]> git.alsa-project.org Git - alsa-utils.git/blob - aplay/aplay.c
20fde77d1d16470eea6efadaf2e3b66155147e4f
[alsa-utils.git] / aplay / aplay.c
1 /*
2  *  aplay.c - plays and records
3  *
4  *      CREATIVE LABS CHANNEL-files
5  *      Microsoft WAVE-files
6  *      SPARC AUDIO .AU-files
7  *      Raw Data
8  *
9  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
10  *  Based on vplay program by Michael Beck
11  *
12  *
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.
17  *
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.
22  *
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
26  *
27  */
28
29 #define _GNU_SOURCE
30 #include "aconfig.h"
31 #include <stdio.h>
32 #include <stdint.h>
33 #if HAVE_MALLOC_H
34 #include <malloc.h>
35 #endif
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <getopt.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <errno.h>
43 #include <limits.h>
44 #include <time.h>
45 #include <locale.h>
46 #include <alsa/asoundlib.h>
47 #include <assert.h>
48 #include <termios.h>
49 #include <signal.h>
50 #include <poll.h>
51 #include <sys/uio.h>
52 #include <sys/time.h>
53 #include <sys/stat.h>
54 #include <endian.h>
55 #include "gettext.h"
56 #include "formats.h"
57 #include "version.h"
58 #include "os_compat.h"
59
60 #define ABS(a)  (a) < 0 ? -(a) : (a)
61
62 #ifdef SND_CHMAP_API_VERSION
63 #define CONFIG_SUPPORT_CHMAP    1
64 #endif
65
66 #ifndef LLONG_MAX
67 #define LLONG_MAX    9223372036854775807LL
68 #endif
69
70 #ifndef le16toh
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)
76 #endif
77
78 #define DEFAULT_FORMAT          SND_PCM_FORMAT_U8
79 #define DEFAULT_SPEED           8000
80
81 #define FORMAT_DEFAULT          -1
82 #define FORMAT_RAW              0
83 #define FORMAT_VOC              1
84 #define FORMAT_WAVE             2
85 #define FORMAT_AU               3
86
87 /* global data */
88
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);
93
94 enum {
95         VUMETER_NONE,
96         VUMETER_MONO,
97         VUMETER_STEREO
98 };
99
100 static char *command;
101 static snd_pcm_t *handle;
102 static struct {
103         snd_pcm_format_t format;
104         snd_pcm_subformat_t subformat;
105         unsigned int channels;
106         unsigned int rate;
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;
146
147 static int fd = -1;
148 static off_t pbrec_count = LLONG_MAX, fdcount;
149 static int vocmajor, vocminor;
150
151 static char *pidfile_name = NULL;
152 FILE *pidf = NULL;
153 static int pidfile_written = 0;
154
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 */
158 #endif
159
160 /* needed prototypes */
161
162 static void done_stdin(void);
163
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);
168
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);
175
176 static void suspend(void);
177
178 static const struct fmt_capture {
179         void (*start) (int fd, size_t count);
180         void (*end) (int fd);
181         char *what;
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 }
189 };
190
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); \
196 } while (0)
197 #else
198 #define error(args...) do {\
199         fprintf(stderr, "%s: %s:%d: ", command, __func__, __LINE__); \
200         fprintf(stderr, ##args); \
201         putc('\n', stderr); \
202 } while (0)
203 #endif  
204
205 static void usage(char *command)
206 {
207         snd_pcm_format_t k;
208         printf(
209 _("Usage: %s [OPTION]... [FILE]...\n"
210 "\n"
211 "-h, --help              help\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"
253   )
254                 , command);
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);
258                 if (s)
259                         printf(" %s", s);
260         }
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"));
266 }
267
268 static void device_list(void)
269 {
270         snd_ctl_t *handle;
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);
276
277         card = -1;
278         if (snd_card_next(&card) < 0 || card < 0) {
279                 error(_("no soundcards found..."));
280                 return;
281         }
282         printf(_("**** List of %s Hardware Devices ****\n"),
283                snd_pcm_stream_name(stream));
284         while (card >= 0) {
285                 char name[32];
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));
289                         goto next_card;
290                 }
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);
294                         goto next_card;
295                 }
296                 dev = -1;
297                 while (1) {
298                         unsigned int count;
299                         if (snd_ctl_pcm_next_device(handle, &dev)<0)
300                                 error("snd_ctl_pcm_next_device");
301                         if (dev < 0)
302                                 break;
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) {
307                                 if (err != -ENOENT)
308                                         error("control digital audio info (%i): %s", card, snd_strerror(err));
309                                 continue;
310                         }
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),
313                                 dev,
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));
323                                 } else {
324                                         printf(_("  Subdevice #%i: %s\n"),
325                                                 idx, snd_pcm_info_get_subdevice_name(pcminfo));
326                                 }
327                         }
328                 }
329                 snd_ctl_close(handle);
330         next_card:
331                 if (snd_card_next(&card) < 0) {
332                         error("snd_card_next");
333                         break;
334                 }
335         }
336 }
337
338 static void pcm_list(void)
339 {
340         void **hints, **n;
341         char *name, *descr, *descr1, *io;
342         const char *filter;
343
344         if (snd_device_name_hint(-1, "pcm", &hints) < 0)
345                 return;
346         n = hints;
347         filter = stream == SND_PCM_STREAM_CAPTURE ? "Input" : "Output";
348         while (*n != NULL) {
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)
353                         goto __end;
354                 printf("%s\n", name);
355                 if ((descr1 = descr) != NULL) {
356                         printf("    ");
357                         while (*descr1) {
358                                 if (*descr1 == '\n')
359                                         printf("\n    ");
360                                 else
361                                         putchar(*descr1);
362                                 descr1++;
363                         }
364                         putchar('\n');
365                 }
366               __end:
367                 if (name != NULL)
368                         free(name);
369                 if (descr != NULL)
370                         free(descr);
371                 if (io != NULL)
372                         free(io);
373                 n++;
374         }
375         snd_device_name_free_hint(hints);
376 }
377
378 static void version(void)
379 {
380         printf("%s: version " SND_UTIL_VERSION_STR " by Jaroslav Kysela <perex@perex.cz>\n", command);
381 }
382
383 /*
384  *      Subroutine to clean up before exit.
385  */
386 static void prg_exit(int code) 
387 {
388         done_stdin();
389         if (handle)
390                 snd_pcm_close(handle);
391         if (pidfile_written)
392                 remove (pidfile_name);
393         exit(code);
394 }
395
396 static void signal_handler(int sig)
397 {
398         if (in_aborting)
399                 return;
400
401         in_aborting = 1;
402         if (verbose==2)
403                 putchar('\n');
404         if (!quiet_mode)
405                 fprintf(stderr, _("Aborted by signal %s...\n"), strsignal(sig));
406         if (handle)
407                 snd_pcm_abort(handle);
408         if (sig == SIGABRT) {
409                 /* do not call snd_pcm_close() and abort immediately */
410                 handle = NULL;
411                 prg_exit(EXIT_FAILURE);
412         }
413         signal(sig, SIG_DFL);
414 }
415
416 /* call on SIGUSR1 signal. */
417 static void signal_handler_recycle(int sig ATTRIBUTE_UNUSED)
418 {
419         /* flag the capture loop to start a new output file */
420         recycle_capture_file = 1;
421 }
422
423 enum {
424         OPT_VERSION = 1,
425         OPT_PERIOD_SIZE,
426         OPT_BUFFER_SIZE,
427         OPT_DISABLE_RESAMPLE,
428         OPT_DISABLE_CHANNELS,
429         OPT_DISABLE_FORMAT,
430         OPT_DISABLE_SOFTVOL,
431         OPT_TEST_POSITION,
432         OPT_TEST_COEF,
433         OPT_TEST_NOWAIT,
434         OPT_MAX_FILE_TIME,
435         OPT_PROCESS_ID_FILE,
436         OPT_USE_STRFTIME,
437         OPT_DUMP_HWPARAMS,
438         OPT_FATAL_ERRORS,
439         OPT_SUBFORMAT,
440 };
441
442 /*
443  * make sure we write all bytes or return an error
444  */
445 static ssize_t xwrite(int fd, const void *buf, size_t count)
446 {
447         ssize_t written;
448         size_t offset = 0;
449
450         while (offset < count) {
451                 written = write(fd, (char *)buf + offset, count - offset);
452                 if (written <= 0)
453                         return written;
454
455                 offset += written;
456         };
457
458         return offset;
459 }
460
461 static long parse_long(const char *str, int *err)
462 {
463         long val;
464         char *endptr;
465
466         errno = 0;
467         val = strtol(str, &endptr, 0);
468
469         if (errno != 0 || *endptr != '\0')
470                 *err = -1;
471         else
472                 *err = 0;
473
474         return val;
475 }
476
477 int main(int argc, char *argv[])
478 {
479         int duration_or_sample = 0;
480         int option_index;
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
483                 "m:"
484 #endif
485                 ;
486         static const struct option long_options[] = {
487                 {"help", 0, 0, 'h'},
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},
498                 {"rate", 1, 0, 'r'},
499                 {"duration", 1, 0 ,'d'},
500                 {"samples", 1, 0, 's'},
501                 {"mmap", 0, 0, 'M'},
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'},
530 #endif
531                 {0, 0, 0, 0}
532         };
533         char *pcm_name = "default";
534         int tmp, err, c;
535         int do_device_list = 0, do_pcm_list = 0, force_sample_format = 0;
536         snd_pcm_info_t *info;
537         FILE *direction;
538
539 #ifdef ENABLE_NLS
540         setlocale(LC_ALL, "");
541         textdomain(PACKAGE);
542 #endif
543
544         snd_pcm_info_alloca(&info);
545
546         err = snd_output_stdio_attach(&log, stderr, 0);
547         assert(err >= 0);
548
549         command = argv[0];
550         file_type = FORMAT_DEFAULT;
551         if (strstr(argv[0], "arecord")) {
552                 stream = SND_PCM_STREAM_CAPTURE;
553                 file_type = FORMAT_WAVE;
554                 command = "arecord";
555                 start_delay = 1;
556                 direction = stdout;
557         } else if (strstr(argv[0], "aplay")) {
558                 stream = SND_PCM_STREAM_PLAYBACK;
559                 command = "aplay";
560                 direction = stdin;
561         } else {
562                 error(_("command should be named either arecord or aplay"));
563                 return 1;
564         }
565
566         if (isatty(fileno(direction)) && (argc == 1)) {
567                 usage(command);
568                 return 1;
569         }
570
571         chunk_size = -1;
572         rhwparams.format = DEFAULT_FORMAT;
573         rhwparams.subformat = SND_PCM_SUBFORMAT_STD;
574         rhwparams.rate = DEFAULT_SPEED;
575         rhwparams.channels = 1;
576
577         while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) {
578                 switch (c) {
579                 case 'h':
580                         usage(command);
581                         return 0;
582                 case OPT_VERSION:
583                         version();
584                         return 0;
585                 case 'l':
586                         do_device_list = 1;
587                         break;
588                 case 'L':
589                         do_pcm_list = 1;
590                         break;
591                 case 'D':
592                         pcm_name = optarg;
593                         break;
594                 case 'q':
595                         quiet_mode = 1;
596                         break;
597                 case 't':
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;
606                         else {
607                                 error(_("unrecognized file format %s"), optarg);
608                                 return 1;
609                         }
610                         break;
611                 case 'c':
612                         rhwparams.channels = parse_long(optarg, &err);
613                         if (err < 0) {
614                                 error(_("invalid channels argument '%s'"), optarg);
615                                 return 1;
616                         }
617                         if (rhwparams.channels < 1 || rhwparams.channels > 256) {
618                                 error(_("value %i for channels is invalid"), rhwparams.channels);
619                                 return 1;
620                         }
621                         break;
622                 case 'f':
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;
627                                 else
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;
635                         } else {
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);
640                                 }
641                         }
642                         break;
643                 case OPT_SUBFORMAT:
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) {
647 #else
648                         if (strcasecmp(optarg, "std") != 0 && strcasecmp(optarg, "standard") != 0) {
649 #endif
650                                 error(_("wrong extended subformat '%s'"), optarg);
651                                 prg_exit(EXIT_FAILURE);
652                         }
653                         break;
654                 case 'r':
655                         tmp = parse_long(optarg, &err);
656                         if (err < 0) {
657                                 error(_("invalid rate argument '%s'"), optarg);
658                                 return 1;
659                         }
660                         if (tmp < 1000)
661                                 tmp *= 1000;
662                         rhwparams.rate = tmp;
663                         if (tmp < 2000 || tmp > 768000) {
664                                 error(_("bad speed value %i"), tmp);
665                                 return 1;
666                         }
667                         break;
668                 case 'd':
669                         if (duration_or_sample) {
670                                 error(_("duration and samples arguments cannot be used together"));
671                                 return 1;
672                         }
673                         timelimit = parse_long(optarg, &err);
674                         if (err < 0) {
675                                 error(_("invalid duration argument '%s'"), optarg);
676                                 return 1;
677                         }
678                         duration_or_sample = 1;
679                         break;
680                 case 's':
681                         if (duration_or_sample) {
682                                 error(_("samples and duration arguments cannot be used together"));
683                                 return 1;
684                         }
685                         sampleslimit = parse_long(optarg, &err);
686                         if (err < 0) {
687                                 error(_("invalid samples argument '%s'"), optarg);
688                                 return 1;
689                         }
690                         duration_or_sample = 1;
691                         break;
692                 case 'N':
693                         nonblock = 1;
694                         open_mode |= SND_PCM_NONBLOCK;
695                         break;
696                 case 'F':
697                         period_time = parse_long(optarg, &err);
698                         if (err < 0) {
699                                 error(_("invalid period time argument '%s'"), optarg);
700                                 return 1;
701                         }
702                         break;
703                 case 'B':
704                         buffer_time = parse_long(optarg, &err);
705                         if (err < 0) {
706                                 error(_("invalid buffer time argument '%s'"), optarg);
707                                 return 1;
708                         }
709                         break;
710                 case OPT_PERIOD_SIZE:
711                         period_frames = parse_long(optarg, &err);
712                         if (err < 0) {
713                                 error(_("invalid period size argument '%s'"), optarg);
714                                 return 1;
715                         }
716                         break;
717                 case OPT_BUFFER_SIZE:
718                         buffer_frames = parse_long(optarg, &err);
719                         if (err < 0) {
720                                 error(_("invalid buffer size argument '%s'"), optarg);
721                                 return 1;
722                         }
723                         break;
724                 case 'A':
725                         avail_min = parse_long(optarg, &err);
726                         if (err < 0) {
727                                 error(_("invalid min available space argument '%s'"), optarg);
728                                 return 1;
729                         }
730                         break;
731                 case 'R':
732                         start_delay = parse_long(optarg, &err);
733                         if (err < 0) {
734                                 error(_("invalid start delay argument '%s'"), optarg);
735                                 return 1;
736                         }
737                         break;
738                 case 'T':
739                         stop_delay = parse_long(optarg, &err);
740                         if (err < 0) {
741                                 error(_("invalid stop delay argument '%s'"), optarg);
742                                 return 1;
743                         }
744                         break;
745                 case 'v':
746                         verbose++;
747                         if (verbose > 1 && !vumeter)
748                                 vumeter = VUMETER_MONO;
749                         break;
750                 case 'V':
751                         if (*optarg == 's')
752                                 vumeter = VUMETER_STEREO;
753                         else if (*optarg == 'm')
754                                 vumeter = VUMETER_MONO;
755                         else
756                                 vumeter = VUMETER_NONE;
757                         break;
758                 case 'M':
759                         mmap_flag = 1;
760                         break;
761                 case 'I':
762                         interleaved = 0;
763                         break;
764                 case 'P':
765                         stream = SND_PCM_STREAM_PLAYBACK;
766                         command = "aplay";
767                         break;
768                 case 'C':
769                         stream = SND_PCM_STREAM_CAPTURE;
770                         command = "arecord";
771                         start_delay = 1;
772                         if (file_type == FORMAT_DEFAULT)
773                                 file_type = FORMAT_WAVE;
774                         break;
775                 case 'i':
776                         interactive = 1;
777                         break;
778                 case OPT_DISABLE_RESAMPLE:
779                         open_mode |= SND_PCM_NO_AUTO_RESAMPLE;
780                         break;
781                 case OPT_DISABLE_CHANNELS:
782                         open_mode |= SND_PCM_NO_AUTO_CHANNELS;
783                         break;
784                 case OPT_DISABLE_FORMAT:
785                         open_mode |= SND_PCM_NO_AUTO_FORMAT;
786                         break;
787                 case OPT_DISABLE_SOFTVOL:
788                         open_mode |= SND_PCM_NO_SOFTVOL;
789                         break;
790                 case OPT_TEST_POSITION:
791                         test_position = 1;
792                         break;
793                 case OPT_TEST_COEF:
794                         test_coef = parse_long(optarg, &err);
795                         if (err < 0) {
796                                 error(_("invalid test coef argument '%s'"), optarg);
797                                 return 1;
798                         }
799                         if (test_coef < 1)
800                                 test_coef = 1;
801                         break;
802                 case OPT_TEST_NOWAIT:
803                         test_nowait = 1;
804                         break;
805                 case OPT_MAX_FILE_TIME:
806                         max_file_time = parse_long(optarg, &err);
807                         if (err < 0) {
808                                 error(_("invalid max file time argument '%s'"), optarg);
809                                 return 1;
810                         }
811                         break;
812                 case OPT_PROCESS_ID_FILE:
813                         pidfile_name = optarg;
814                         break;
815                 case OPT_USE_STRFTIME:
816                         use_strftime = 1;
817                         break;
818                 case OPT_DUMP_HWPARAMS:
819                         dump_hw_params = 1;
820                         break;
821                 case OPT_FATAL_ERRORS:
822                         fatal_errors = 1;
823                         break;
824 #ifdef CONFIG_SUPPORT_CHMAP
825                 case 'm':
826                         channel_map = snd_pcm_chmap_parse_string(optarg);
827                         if (!channel_map) {
828                                 fprintf(stderr, _("Unable to parse channel map string: %s\n"), optarg);
829                                 return 1;
830                         }
831                         break;
832 #endif
833                 default:
834                         fprintf(stderr, _("Try `%s --help' for more information.\n"), command);
835                         return 1;
836                 }
837         }
838
839         if (do_device_list) {
840                 if (do_pcm_list) pcm_list();
841                 device_list();
842                 goto __end;
843         } else if (do_pcm_list) {
844                 pcm_list();
845                 goto __end;
846         }
847
848         err = snd_pcm_open(&handle, pcm_name, stream, open_mode);
849         if (err < 0) {
850                 error(_("audio open error: %s"), snd_strerror(err));
851                 return 1;
852         }
853
854         if ((err = snd_pcm_info(handle, info)) < 0) {
855                 error(_("info error: %s"), snd_strerror(err));
856                 return 1;
857         }
858
859         if (nonblock) {
860                 err = snd_pcm_nonblock(handle, 1);
861                 if (err < 0) {
862                         error(_("nonblock setting error: %s"), snd_strerror(err));
863                         return 1;
864                 }
865         }
866
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");
874
875         chunk_size = 1024;
876         hwparams = rhwparams;
877
878         audiobuf = (uint8_t *)malloc(1024);
879         if (audiobuf == NULL) {
880                 error(_("not enough memory"));
881                 return 1;
882         }
883
884         if (mmap_flag) {
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;
889         } else {
890                 writei_func = snd_pcm_writei;
891                 readi_func = snd_pcm_readi;
892                 writen_func = snd_pcm_writen;
893                 readn_func = snd_pcm_readn;
894         }
895
896         if (pidfile_name) {
897                 errno = 0;
898                 pidf = fopen (pidfile_name, "w");
899                 if (pidf) {
900                         (void)fprintf (pidf, "%d\n", getpid());
901                         fclose(pidf);
902                         pidfile_written = 1;
903                 } else {
904                         error(_("Cannot create process ID file %s: %s"), 
905                                 pidfile_name, strerror (errno));
906                         return 1;
907                 }
908         }
909
910         signal(SIGINT, signal_handler);
911         signal(SIGTERM, signal_handler);
912         signal(SIGABRT, signal_handler);
913         signal(SIGUSR1, signal_handler_recycle);
914         if (interleaved) {
915                 if (optind > argc - 1) {
916                         if (stream == SND_PCM_STREAM_PLAYBACK)
917                                 playback(NULL);
918                         else
919                                 capture(NULL);
920                 } else {
921                         while (optind <= argc - 1) {
922                                 if (stream == SND_PCM_STREAM_PLAYBACK)
923                                         playback(argv[optind++]);
924                                 else
925                                         capture(argv[optind++]);
926                         }
927                 }
928         } else {
929                 if (stream == SND_PCM_STREAM_PLAYBACK)
930                         playbackv(&argv[optind], argc - optind);
931                 else
932                         capturev(&argv[optind], argc - optind);
933         }
934         if (verbose==2)
935                 putchar('\n');
936         snd_pcm_close(handle);
937         handle = NULL;
938         free(audiobuf);
939       __end:
940         snd_output_close(log);
941         snd_config_update_free_global();
942         prg_exit(EXIT_SUCCESS);
943         /* avoid warning */
944         return EXIT_SUCCESS;
945 }
946
947 /*
948  * Safe read (for pipes)
949  */
950  
951 static ssize_t safe_read(int fd, void *buf, size_t count)
952 {
953         ssize_t result = 0, res;
954
955         while (count > 0 && !in_aborting) {
956                 if ((res = read(fd, buf, count)) == 0)
957                         break;
958                 if (res < 0)
959                         return result > 0 ? result : res;
960                 count -= res;
961                 result += res;
962                 buf = (char *)buf + res;
963         }
964         return result;
965 }
966
967 /*
968  * Test, if it is a .VOC file and return >=0 if ok (this is the length of rest)
969  *                                       < 0 if not 
970  */
971 static int test_vocfile(void *buffer)
972 {
973         VocHeader *vp = buffer;
974
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 */
981         }
982         return -1;              /* magic string fail */
983 }
984
985 /*
986  * helper for test_wavefile
987  */
988
989 static size_t test_wavefile_read(int fd, uint8_t *buffer, size_t *size, size_t reqsize, int line)
990 {
991         if (*size >= reqsize)
992                 return *size;
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);
996         }
997         return *size = reqsize;
998 }
999
1000 #define check_wavefile_space(buffer, len, blimit) \
1001         if (len > blimit) { \
1002                 blimit = len; \
1003                 if ((buffer = realloc(buffer, blimit)) == NULL) { \
1004                         error(_("not enough memory"));            \
1005                         prg_exit(EXIT_FAILURE);  \
1006                 } \
1007         }
1008
1009 /*
1010  * test, if it's a .WAV file, > 0 if ok (and set the speed, stereo etc.)
1011  *                            == 0 if not
1012  * Value returned is bytes to be discarded.
1013  */
1014 static ssize_t test_wavefile(int fd, uint8_t *_buffer, size_t size)
1015 {
1016         WaveHeader *h = (WaveHeader *)_buffer;
1017         uint8_t *buffer = NULL;
1018         size_t blimit = 0;
1019         WaveFmtBody *f;
1020         WaveChunkHeader *c;
1021         uint32_t type, len;
1022         unsigned short format, channels;
1023         int big_endian, native_format;
1024         uint8_t vbps = 0;
1025
1026         if (size < sizeof(WaveHeader))
1027                 return -1;
1028         if (h->magic == WAV_RIFF)
1029                 big_endian = 0;
1030         else if (h->magic == WAV_RIFX)
1031                 big_endian = 1;
1032         else
1033                 return -1;
1034         if (h->type != WAV_WAVE)
1035                 return -1;
1036
1037         if (size > sizeof(WaveHeader)) {
1038                 check_wavefile_space(buffer, size - sizeof(WaveHeader), blimit);
1039                 memcpy(buffer, _buffer + sizeof(WaveHeader), size - sizeof(WaveHeader));
1040         }
1041         size -= sizeof(WaveHeader);
1042         while (1) {
1043                 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
1044                 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
1045                 c = (WaveChunkHeader*)buffer;
1046                 type = c->type;
1047                 len = TO_CPU_INT(c->length, big_endian);
1048                 len += len % 2;
1049                 if (size > sizeof(WaveChunkHeader))
1050                         memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
1051                 size -= sizeof(WaveChunkHeader);
1052                 if (type == WAV_FMT)
1053                         break;
1054                 check_wavefile_space(buffer, len, blimit);
1055                 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1056                 if (size > len)
1057                         memmove(buffer, buffer + len, size - len);
1058                 size -= len;
1059         }
1060
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);
1065         }
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);
1076                 }
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);
1080                 }
1081                 vbps = TO_CPU_SHORT(fe->bit_p_spl, big_endian);
1082                 format = TO_CPU_SHORT(fe->guid_format, big_endian);
1083         }
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);
1088         }
1089         channels = TO_CPU_SHORT(f->channels, big_endian);
1090         if (channels < 1) {
1091                 error(_("can't play WAVE-files with %d tracks"), channels);
1092                 prg_exit(EXIT_FAILURE);
1093         }
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);
1098         }
1099         switch (TO_CPU_SHORT(f->bit_p_spl, big_endian)) {
1100         case 8:
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;
1105                 break;
1106         case 16:
1107                 if (big_endian)
1108                         native_format = SND_PCM_FORMAT_S16_BE;
1109                 else
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;
1116                 break;
1117         case 24:
1118                 switch (TO_CPU_SHORT(f->byte_p_spl, big_endian) / hwparams.channels) {
1119                 case 3:
1120                         if (big_endian)
1121                                 native_format = SND_PCM_FORMAT_S24_3BE;
1122                         else
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;
1129                         break;
1130                 case 4:
1131                         if (big_endian)
1132                                 native_format = SND_PCM_FORMAT_S24_BE;
1133                         else
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;
1140                         break;
1141                 default:
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),
1145                               hwparams.channels);
1146                         prg_exit(EXIT_FAILURE);
1147                 }
1148                 break;
1149         case 32:
1150                 if (format == WAV_FMT_PCM) {
1151                         switch (vbps) {
1152                         case 24:
1153                                 if (big_endian)
1154                                         native_format = SND_PCM_FORMAT_S24_BE;
1155                                 else
1156                                         native_format = SND_PCM_FORMAT_S24_LE;
1157                                 break;
1158                         default:
1159                                 if (big_endian)
1160                                         native_format = SND_PCM_FORMAT_S32_BE;
1161                                 else
1162                                         native_format = SND_PCM_FORMAT_S32_LE;
1163                                 break;
1164                         }
1165                         hwparams.format = native_format;
1166                 } else if (format == WAV_FMT_IEEE_FLOAT) {
1167                         if (big_endian)
1168                                 native_format = SND_PCM_FORMAT_FLOAT_BE;
1169                         else
1170                                 native_format = SND_PCM_FORMAT_FLOAT_LE;
1171                         hwparams.format = native_format;
1172                 }
1173                 break;
1174         default:
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);
1178         }
1179         hwparams.rate = TO_CPU_INT(f->sample_fq, big_endian);
1180         
1181         if (size > len)
1182                 memmove(buffer, buffer + len, size - len);
1183         size -= len;
1184         
1185         while (1) {
1186                 uint32_t type, len;
1187
1188                 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
1189                 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
1190                 c = (WaveChunkHeader*)buffer;
1191                 type = c->type;
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)
1198                                 pbrec_count = len;
1199                         if (size > 0)
1200                                 memcpy(_buffer, buffer, size);
1201                         free(buffer);
1202                         return size;
1203                 }
1204                 len += len % 2;
1205                 check_wavefile_space(buffer, len, blimit);
1206                 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1207                 if (size > len)
1208                         memmove(buffer, buffer + len, size - len);
1209                 size -= len;
1210         }
1211
1212         /* shouldn't be reached */
1213         return -1;
1214 }
1215
1216 /*
1217
1218  */
1219
1220 static int test_au(int fd, void *buffer)
1221 {
1222         AuHeader *ap = buffer;
1223
1224         if (ap->magic != AU_MAGIC)
1225                 return -1;
1226         if (BE_INT(ap->hdr_size) > 128 || BE_INT(ap->hdr_size) < 24)
1227                 return -1;
1228         pbrec_count = BE_INT(ap->data_size);
1229         switch (BE_INT(ap->encoding)) {
1230         case AU_FMT_ULAW:
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;
1235                 break;
1236         case AU_FMT_LIN8:
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;
1241                 break;
1242         case AU_FMT_LIN16:
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;
1247                 break;
1248         case AU_FMT_ALAW:
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;
1253                 break;
1254         default:
1255                 return -1;
1256         }
1257         hwparams.rate = BE_INT(ap->sample_rate);
1258         if (hwparams.rate < 2000 || hwparams.rate > 256000)
1259                 return -1;
1260         hwparams.channels = BE_INT(ap->channels);
1261         if (hwparams.channels < 1 || hwparams.channels > 256)
1262                 return -1;
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);
1266         }
1267         return 0;
1268 }
1269
1270 static void show_available_sample_formats(snd_pcm_hw_params_t* params)
1271 {
1272         snd_pcm_format_t format;
1273
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));
1278         }
1279 }
1280
1281 #ifdef CONFIG_SUPPORT_CHMAP
1282 static int setup_chmap(void)
1283 {
1284         snd_pcm_chmap_t *chmap = channel_map;
1285         char mapped[hwparams.channels];
1286         snd_pcm_chmap_t *hw_chmap;
1287         unsigned int ch, i;
1288         int err;
1289
1290         if (!chmap)
1291                 return 0;
1292
1293         if (chmap->channels != hwparams.channels) {
1294                 error(_("Channel numbers don't match between hw_params and channel map"));
1295                 return -1;
1296         }
1297         err = snd_pcm_set_chmap(handle, chmap);
1298         if (!err)
1299                 return 0;
1300
1301         hw_chmap = snd_pcm_get_chmap(handle);
1302         if (!hw_chmap) {
1303                 fprintf(stderr, _("Warning: unable to get channel map\n"));
1304                 return 0;
1305         }
1306
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 */
1310                 free(hw_chmap);
1311                 return 0;
1312         }
1313
1314         hw_map = calloc(hwparams.channels, sizeof(int));
1315         if (!hw_map) {
1316                 error(_("not enough memory"));
1317                 free(hw_chmap);
1318                 return -1;
1319         }
1320
1321         memset(mapped, 0, sizeof(mapped));
1322         for (ch = 0; ch < hw_chmap->channels; ch++) {
1323                 if (chmap->pos[ch] == hw_chmap->pos[ch]) {
1324                         mapped[ch] = 1;
1325                         hw_map[ch] = ch;
1326                         continue;
1327                 }
1328                 for (i = 0; i < hw_chmap->channels; i++) {
1329                         if (!mapped[i] && chmap->pos[ch] == hw_chmap->pos[i]) {
1330                                 mapped[i] = 1;
1331                                 hw_map[ch] = i;
1332                                 break;
1333                         }
1334                 }
1335                 if (i >= hw_chmap->channels) {
1336                         char buf[256];
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);
1340                         free(hw_chmap);
1341                         return -1;
1342                 }
1343         }
1344         free(hw_chmap);
1345         return 0;
1346 }
1347 #else
1348 #define setup_chmap()   0
1349 #endif
1350
1351 static void set_params(void)
1352 {
1353         snd_pcm_hw_params_t *params;
1354         snd_pcm_sw_params_t *swparams;
1355         snd_pcm_uframes_t buffer_size;
1356         int err;
1357         size_t n;
1358         unsigned int rate;
1359         snd_pcm_uframes_t start_threshold, stop_threshold;
1360         snd_pcm_hw_params_alloca(&params);
1361         snd_pcm_sw_params_alloca(&swparams);
1362         err = snd_pcm_hw_params_any(handle, params);
1363         if (err < 0) {
1364                 error(_("Broken configuration for this PCM: no configurations available"));
1365                 prg_exit(EXIT_FAILURE);
1366         }
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");
1373         }
1374         if (mmap_flag) {
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);
1384         else
1385                 err = snd_pcm_hw_params_set_access(handle, params,
1386                                                    SND_PCM_ACCESS_RW_NONINTERLEAVED);
1387         if (err < 0) {
1388                 error(_("Access type not available"));
1389                 prg_exit(EXIT_FAILURE);
1390         }
1391         err = snd_pcm_hw_params_set_format(handle, params, hwparams.format);
1392         if (err < 0) {
1393                 error(_("Sample format non available"));
1394                 show_available_sample_formats(params);
1395                 prg_exit(EXIT_FAILURE);
1396         }
1397         err = snd_pcm_hw_params_set_subformat(handle, params, hwparams.subformat);
1398         if (err < 0) {
1399                 error(_("Sample subformat not available"));
1400                 prg_exit(EXIT_FAILURE);
1401         }
1402         err = snd_pcm_hw_params_set_channels(handle, params, hwparams.channels);
1403         if (err < 0) {
1404                 error(_("Channels count non available"));
1405                 prg_exit(EXIT_FAILURE);
1406         }
1407
1408 #if 0
1409         err = snd_pcm_hw_params_set_periods_min(handle, params, 2);
1410         assert(err >= 0);
1411 #endif
1412         rate = hwparams.rate;
1413         err = snd_pcm_hw_params_set_rate_near(handle, params, &hwparams.rate, 0);
1414         assert(err >= 0);
1415         if ((float)rate * 1.05 < hwparams.rate || (float)rate * 0.95 > hwparams.rate) {
1416                 if (!quiet_mode) {
1417                         char plugex[64];
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), ':'))
1421                                 *plugex = 0;
1422                         else
1423                                 snprintf(plugex, sizeof(plugex), "(-Dplug:%s)",
1424                                          snd_pcm_name(handle));
1425                         fprintf(stderr, _("         please, try the plug plugin %s\n"),
1426                                 plugex);
1427                 }
1428         }
1429         rate = hwparams.rate;
1430         if (buffer_time == 0 && buffer_frames == 0) {
1431                 err = snd_pcm_hw_params_get_buffer_time_max(params,
1432                                                             &buffer_time, 0);
1433                 assert(err >= 0);
1434                 if (buffer_time > 500000)
1435                         buffer_time = 500000;
1436         }
1437         if (period_time == 0 && period_frames == 0) {
1438                 if (buffer_time > 0)
1439                         period_time = buffer_time / 4;
1440                 else
1441                         period_frames = buffer_frames / 4;
1442         }
1443         if (period_time > 0)
1444                 err = snd_pcm_hw_params_set_period_time_near(handle, params,
1445                                                              &period_time, 0);
1446         else
1447                 err = snd_pcm_hw_params_set_period_size_near(handle, params,
1448                                                              &period_frames, 0);
1449         assert(err >= 0);
1450         if (buffer_time > 0) {
1451                 err = snd_pcm_hw_params_set_buffer_time_near(handle, params,
1452                                                              &buffer_time, 0);
1453         } else {
1454                 err = snd_pcm_hw_params_set_buffer_size_near(handle, params,
1455                                                              &buffer_frames);
1456         }
1457         assert(err >= 0);
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);
1461         if (err < 0) {
1462                 error(_("Unable to install hw params:"));
1463                 snd_pcm_hw_params_dump(params, log);
1464                 prg_exit(EXIT_FAILURE);
1465         }
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);
1472         }
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");
1479         }
1480         err = snd_pcm_sw_params_current(handle, swparams);
1481         if (err < 0) {
1482                 error(_("Unable to get current sw params."));
1483                 prg_exit(EXIT_FAILURE);
1484         }
1485         if (avail_min < 0)
1486                 n = chunk_size;
1487         else
1488                 n = (double) rate * avail_min / 1000000;
1489         err = snd_pcm_sw_params_set_avail_min(handle, swparams, n);
1490
1491         /* round up to closest transfer boundary */
1492         n = buffer_size;
1493         if (start_delay <= 0) {
1494                 start_threshold = n + (double) rate * start_delay / 1000000;
1495         } else
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);
1502         assert(err >= 0);
1503         if (stop_delay <= 0) 
1504                 stop_threshold = buffer_size + (double) rate * stop_delay / 1000000;
1505         else
1506                 stop_threshold = (double) rate * stop_delay / 1000000;
1507         err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
1508         assert(err >= 0);
1509
1510         if (verbose) {
1511                 err = snd_pcm_sw_params_set_tstamp_mode(handle, swparams, SND_PCM_TSTAMP_ENABLE);
1512                 assert(err >= 0);
1513
1514                 if (monotonic)
1515                         err = snd_pcm_sw_params_set_tstamp_type(handle, swparams, SND_PCM_TSTAMP_TYPE_MONOTONIC);
1516                 else
1517                         err = snd_pcm_sw_params_set_tstamp_type(handle, swparams, SND_PCM_TSTAMP_TYPE_GETTIMEOFDAY);
1518                 assert(err >= 0);
1519         }
1520
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);
1525         }
1526
1527         if (setup_chmap())
1528                 prg_exit(EXIT_FAILURE);
1529
1530         if (verbose)
1531                 snd_pcm_dump(handle, log);
1532
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);
1541         }
1542         // fprintf(stderr, "real chunk_size = %i, frags = %i, total = %i\n", chunk_size, setup.buf.block.frags, setup.buf.block.frags * chunk_size);
1543
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;
1548         }
1549
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;
1554                 int i;
1555                 err = snd_pcm_mmap_begin(handle, &areas, &offset, &size);
1556                 if (err < 0) {
1557                         error(_("snd_pcm_mmap_begin problem: %s"), snd_strerror(err));
1558                         prg_exit(EXIT_FAILURE);
1559                 }
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);
1564         }
1565
1566         buffer_frames = buffer_size;    /* for position test */
1567 }
1568
1569 static void init_stdin(void)
1570 {
1571         struct termios term;
1572         long flags;
1573
1574         if (!interactive)
1575                 return;
1576         if (!isatty(fileno(stdin))) {
1577                 interactive = 0;
1578                 return;
1579         }
1580         tcgetattr(fileno(stdin), &term);
1581         term_c_lflag = term.c_lflag;
1582         if (fd == fileno(stdin))
1583                 return;
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);
1589 }
1590
1591 static void done_stdin(void)
1592 {
1593         struct termios term;
1594
1595         if (!interactive)
1596                 return;
1597         if (fd == fileno(stdin) || term_c_lflag == -1)
1598                 return;
1599         tcgetattr(fileno(stdin), &term);
1600         term.c_lflag = term_c_lflag;
1601         tcsetattr(fileno(stdin), TCSANOW, &term);
1602 }
1603
1604 static char wait_for_input(void)
1605 {
1606         struct pollfd pfd;
1607         unsigned char b;
1608
1609         do {
1610                 pfd.fd = fileno(stdin);
1611                 pfd.events = POLLIN;
1612                 poll(&pfd, 1, -1);
1613         } while (read(fileno(stdin), &b, 1) != 1);
1614         return b;
1615 }
1616
1617 static void do_pause(void)
1618 {
1619         int err;
1620         unsigned char b;
1621
1622         if (!can_pause) {
1623                 fprintf(stderr, _("\rPAUSE command ignored (no hw support)\n"));
1624                 return;
1625         }
1626         if (snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED)
1627                 suspend();
1628
1629         err = snd_pcm_pause(handle, 1);
1630         if (err < 0) {
1631                 error(_("pause push error: %s"), snd_strerror(err));
1632                 return;
1633         }
1634         fprintf(stderr, _("\r=== PAUSE ===                                                            "));
1635         fflush(stderr);
1636         while (1) {
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)
1641                                 suspend();
1642                         err = snd_pcm_pause(handle, 0);
1643                         if (err < 0)
1644                                 error(_("pause release error: %s"), snd_strerror(err));
1645                         return;
1646                 }
1647         }
1648 }
1649
1650 static void check_stdin(void)
1651 {
1652         unsigned char b;
1653
1654         if (!interactive)
1655                 return;
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);
1660                                 do_pause();
1661                                 fprintf(stderr, "                                                                          \r");
1662                                 fflush(stderr);
1663                         }
1664                 }
1665         }
1666 }
1667
1668 #ifndef timersub
1669 #define timersub(a, b, result) \
1670 do { \
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; \
1676         } \
1677 } while (0)
1678 #endif
1679
1680 #ifndef timermsub
1681 #define timermsub(a, b, result) \
1682 do { \
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; \
1688         } \
1689 } while (0)
1690 #endif
1691
1692 /* I/O error handler */
1693 static void xrun(void)
1694 {
1695         snd_pcm_status_t *status;
1696         int res;
1697         
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);
1702         }
1703         if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) {
1704                 if (monotonic) {
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);
1713 #else
1714                         fprintf(stderr, "%s !!!\n", _("underrun"));
1715 #endif
1716                 } else {
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);
1724                 }
1725                 if (verbose) {
1726                         fprintf(stderr, _("Status:\n"));
1727                         snd_pcm_status_dump(status, log);
1728                 }
1729                 if (fatal_errors) {
1730                         error(_("fatal %s: %s"),
1731                                         stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1732                                         snd_strerror(res));
1733                         prg_exit(EXIT_FAILURE);
1734                 }
1735                 if ((res = snd_pcm_prepare(handle))<0) {
1736                         error(_("xrun: prepare error: %s"), snd_strerror(res));
1737                         prg_exit(EXIT_FAILURE);
1738                 }
1739                 return;         /* ok, data should be accepted again */
1740         }
1741         if (snd_pcm_status_get_state(status) == SND_PCM_STATE_DRAINING) {
1742                 if (verbose) {
1743                         fprintf(stderr, _("Status(DRAINING):\n"));
1744                         snd_pcm_status_dump(status, log);
1745                 }
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);
1751                         }
1752                         return;
1753                 }
1754         }
1755         if (verbose) {
1756                 fprintf(stderr, _("Status(R/W):\n"));
1757                 snd_pcm_status_dump(status, log);
1758         }
1759         error(_("read/write error, state = %s"), snd_pcm_state_name(snd_pcm_status_get_state(status)));
1760         prg_exit(EXIT_FAILURE);
1761 }
1762
1763 /* I/O suspend handler */
1764 static void suspend(void)
1765 {
1766         int res;
1767
1768         if (!quiet_mode) {
1769                 fprintf(stderr, _("Suspended. Trying resume. ")); fflush(stderr);
1770         }
1771         while ((res = snd_pcm_resume(handle)) == -EAGAIN)
1772                 sleep(1);       /* wait until suspend flag is released */
1773         if (res < 0) {
1774                 if (!quiet_mode) {
1775                         fprintf(stderr, _("Failed. Restarting stream. ")); fflush(stderr);
1776                 }
1777                 if ((res = snd_pcm_prepare(handle)) < 0) {
1778                         error(_("suspend: prepare error: %s"), snd_strerror(res));
1779                         prg_exit(EXIT_FAILURE);
1780                 }
1781         }
1782         if (!quiet_mode)
1783                 fprintf(stderr, _("Done.\n"));
1784 }
1785
1786 static void print_vu_meter_mono(int perc, int maxperc)
1787 {
1788         const int bar_length = 50;
1789         char line[80];
1790         int val;
1791
1792         for (val = 0; val <= perc * bar_length / 100 && val < bar_length; val++)
1793                 line[val] = '#';
1794         for (; val <= maxperc * bar_length / 100 && val < bar_length; val++)
1795                 line[val] = ' ';
1796         line[val] = '+';
1797         for (++val; val <= bar_length; val++)
1798                 line[val] = ' ';
1799         if (maxperc > 99)
1800                 sprintf(line + val, "| MAX");
1801         else
1802                 sprintf(line + val, "| %02i%%", maxperc);
1803         fputs(line, stderr);
1804         if (perc > 100)
1805                 fprintf(stderr, _(" !clip  "));
1806 }
1807
1808 static void print_vu_meter_stereo(int *perc, int *maxperc)
1809 {
1810         const int bar_length = 35;
1811         char line[80];
1812         int c;
1813
1814         memset(line, ' ', sizeof(line) - 1);
1815         line[bar_length + 3] = '|';
1816
1817         for (c = 0; c < 2; c++) {
1818                 int p = perc[c] * bar_length / 100;
1819                 char tmp[4];
1820                 if (p > bar_length)
1821                         p = bar_length;
1822                 if (c)
1823                         memset(line + bar_length + 6 + 1, '#', p);
1824                 else
1825                         memset(line + bar_length - p, '#', p);
1826                 p = maxperc[c] * bar_length / 100 - 1;
1827                 if (p < 0)
1828                         p = 0;
1829                 else if (p >= bar_length)
1830                         p = bar_length - 1;
1831                 if (c)
1832                         line[bar_length + 6 + 1 + p] = '+';
1833                 else
1834                         line[bar_length - p - 1] = '+';
1835                 if (ABS(maxperc[c]) > 99)
1836                         sprintf(tmp, "MAX");
1837                 else
1838                         sprintf(tmp, "%02d%%", maxperc[c]);
1839                 if (c)
1840                         memcpy(line + bar_length + 3 + 1, tmp, 3);
1841                 else
1842                         memcpy(line + bar_length, tmp, 3);
1843         }
1844         line[bar_length * 2 + 6 + 2] = 0;
1845         fputs(line, stderr);
1846 }
1847
1848 static void print_vu_meter(signed int *perc, signed int *maxperc)
1849 {
1850         if (vumeter == VUMETER_STEREO)
1851                 print_vu_meter_stereo(perc, maxperc);
1852         else
1853                 print_vu_meter_mono(*perc, *maxperc);
1854 }
1855
1856 /* peak handler */
1857 static void compute_max_peak(uint8_t *data, size_t samples)
1858 {
1859         signed int val, max, perc[2], max_peak[2];
1860         static int run = 0;
1861         size_t osamples = samples;
1862         int format_little_endian = snd_pcm_format_little_endian(hwparams.format);
1863         int ichans, c;
1864
1865         if (vumeter == VUMETER_STEREO)
1866                 ichans = 2;
1867         else
1868                 ichans = 1;
1869
1870         memset(max_peak, 0, sizeof(max_peak));
1871         switch (bits_per_sample) {
1872         case 8: {
1873                 signed char *valp = (signed char *)data;
1874                 signed char mask = snd_pcm_format_silence(hwparams.format);
1875                 c = 0;
1876                 while (samples-- > 0) {
1877                         val = *valp++ ^ mask;
1878                         val = abs(val);
1879                         if (max_peak[c] < val)
1880                                 max_peak[c] = val;
1881                         if (vumeter == VUMETER_STEREO)
1882                                 c = !c;
1883                 }
1884                 break;
1885         }
1886         case 16: {
1887                 signed short *valp = (signed short *)data;
1888                 signed short mask = snd_pcm_format_silence_16(hwparams.format);
1889                 signed short sval;
1890
1891                 c = 0;
1892                 while (samples-- > 0) {
1893                         if (format_little_endian)
1894                                 sval = le16toh(*valp);
1895                         else
1896                                 sval = be16toh(*valp);
1897                         sval ^= mask;
1898                         val = abs(sval);
1899                         if (max_peak[c] < val)
1900                                 max_peak[c] = val;
1901                         valp++;
1902                         if (vumeter == VUMETER_STEREO)
1903                                 c = !c;
1904                 }
1905                 break;
1906         }
1907         case 24: {
1908                 unsigned char *valp = data;
1909                 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1910
1911                 c = 0;
1912                 while (samples-- > 0) {
1913                         if (format_little_endian) {
1914                                 val = valp[0] | (valp[1]<<8) | (valp[2]<<16);
1915                         } else {
1916                                 val = (valp[0]<<16) | (valp[1]<<8) | valp[2];
1917                         }
1918                         val ^= mask;
1919                         /* Correct signed bit in 32-bit value */
1920                         if (val & (1<<(bits_per_sample-1))) {
1921                                 val |= 0xff<<24;        /* Negate upper bits too */
1922                         }
1923                         val = abs(val);
1924                         if (max_peak[c] < val)
1925                                 max_peak[c] = val;
1926                         valp += 3;
1927                         if (vumeter == VUMETER_STEREO)
1928                                 c = !c;
1929                 }
1930                 break;
1931         }
1932         case 32: {
1933                 signed int *valp = (signed int *)data;
1934                 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1935
1936                 c = 0;
1937                 while (samples-- > 0) {
1938                         if (format_little_endian)
1939                                 val = le32toh(*valp);
1940                         else
1941                                 val = be32toh(*valp);
1942                         val ^= mask;
1943                         if ((unsigned int)val == 0x80000000U)
1944                                 val = 0x7fffffff;
1945                         else
1946                                 val = abs(val);
1947                         if (max_peak[c] < val)
1948                                 max_peak[c] = val;
1949                         valp++;
1950                         if (vumeter == VUMETER_STEREO)
1951                                 c = !c;
1952                 }
1953                 break;
1954         }
1955         default:
1956                 if (run == 0) {
1957                         fprintf(stderr, _("Unsupported bit size %d.\n"), (int)bits_per_sample);
1958                         run = 1;
1959                 }
1960                 return;
1961         }
1962         max = 1 << (significant_bits_per_sample-1);
1963         if (max <= 0)
1964                 max = 0x7fffffff;
1965
1966         for (c = 0; c < ichans; c++) {
1967                 if (max_peak[c] > max)
1968                         max_peak[c] = max;
1969                 if (bits_per_sample > 16)
1970                         perc[c] = max_peak[c] / (max / 100);
1971                 else
1972                         perc[c] = max_peak[c] * 100 / max;
1973         }
1974
1975         if (interleaved && verbose <= 2) {
1976                 static int maxperc[2];
1977                 static time_t t=0;
1978                 const time_t tt=time(NULL);
1979                 if(tt>t) {
1980                         t=tt;
1981                         maxperc[0] = 0;
1982                         maxperc[1] = 0;
1983                 }
1984                 for (c = 0; c < ichans; c++)
1985                         if (perc[c] > maxperc[c])
1986                                 maxperc[c] = perc[c];
1987
1988                 putc('\r', stderr);
1989                 print_vu_meter(perc, maxperc);
1990                 fflush(stderr);
1991         }
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)
1996                                 putc('#', stderr);
1997                         else
1998                                 putc(' ', stderr);
1999                 fprintf(stderr, " %i%%\n", perc[0]);
2000                 fflush(stderr);
2001         }
2002 }
2003
2004 static void do_test_position(void)
2005 {
2006         static long counter = 0;
2007         static time_t tmr = -1;
2008         time_t now;
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;
2016         int err;
2017
2018         snd_pcm_status_alloca(&status);
2019         err = snd_pcm_avail_delay(handle, &avail, &delay);
2020         if (err < 0)
2021                 return;
2022         err = snd_pcm_status(handle, status);
2023         if (err < 0)
2024                 return;
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) {
2055                 time(&now);
2056                 if (tmr == (time_t) -1) {
2057                         tmr = now;
2058                         availsum = delaysum = samples = 0;
2059                         maxavail = maxdelay = 0;
2060                         minavail = mindelay = buffer_frames * 16;
2061                 }
2062                 if (avail > maxavail)
2063                         maxavail = avail;
2064                 if (savail > maxavail)
2065                         maxavail = savail;
2066                 if (delay > maxdelay)
2067                         maxdelay = delay;
2068                 if (sdelay > maxdelay)
2069                         maxdelay = sdelay;
2070                 if (avail < minavail)
2071                         minavail = avail;
2072                 if (savail < minavail)
2073                         minavail = savail;
2074                 if (delay < mindelay)
2075                         mindelay = delay;
2076                 if (sdelay < mindelay)
2077                         mindelay = sdelay;
2078                 availsum += avail;
2079                 delaysum += delay;
2080                 samples++;
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);
2090                         tmr = now;
2091                 }
2092         }
2093         if (verbose == 1) {
2094                 fprintf(stderr, _("Status(R/W) (standalone avail=%li delay=%li):\n"), (long)avail, (long)delay);
2095                 snd_pcm_status_dump(status, log);
2096         }
2097 }
2098
2099 /*
2100  */
2101 #ifdef CONFIG_SUPPORT_CHMAP
2102 static uint8_t *remap_data(uint8_t *data, size_t count)
2103 {
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;
2108         size_t chunk_bytes;
2109         unsigned int ch, i;
2110
2111         if (!hw_map)
2112                 return data;
2113
2114         chunk_bytes = count * bits_per_frame / 8;
2115         if (tmp_size < chunk_bytes) {
2116                 free(tmp);
2117                 tmp = malloc(chunk_bytes);
2118                 if (!tmp) {
2119                         error(_("not enough memory"));
2120                         exit(1);
2121                 }
2122                 tmp_size = count;
2123         }
2124
2125         src = data;
2126         dst = tmp;
2127         for (i = 0; i < count; i++) {
2128                 for (ch = 0; ch < hwparams.channels; ch++) {
2129                         memcpy(dst, src + sample_bytes * hw_map[ch],
2130                                sample_bytes);
2131                         dst += sample_bytes;
2132                 }
2133                 src += step;
2134         }
2135         return tmp;
2136 }
2137
2138 static uint8_t **remap_datav(uint8_t **data, size_t count ATTRIBUTE_UNUSED)
2139 {
2140         static uint8_t **tmp;
2141         unsigned int ch;
2142
2143         if (!hw_map)
2144                 return data;
2145
2146         if (!tmp) {
2147                 tmp = malloc(sizeof(*tmp) * hwparams.channels);
2148                 if (!tmp) {
2149                         error(_("not enough memory"));
2150                         exit(1);
2151                 }
2152                 for (ch = 0; ch < hwparams.channels; ch++)
2153                         tmp[ch] = data[hw_map[ch]];
2154         }
2155         return tmp;
2156 }
2157 #else
2158 #define remap_data(data, count)         (data)
2159 #define remap_datav(data, count)        (data)
2160 #endif
2161
2162 /*
2163  *  write function
2164  */
2165
2166 static ssize_t pcm_write(uint8_t *data, size_t count)
2167 {
2168         ssize_t r;
2169         ssize_t result = 0;
2170
2171         if (count < chunk_size) {
2172                 snd_pcm_format_set_silence(hwparams.format, data + count * bits_per_frame / 8, (chunk_size - count) * hwparams.channels);
2173                 count = chunk_size;
2174         }
2175         data = remap_data(data, count);
2176         while (count > 0 && !in_aborting) {
2177                 if (test_position)
2178                         do_test_position();
2179                 check_stdin();
2180                 r = writei_func(handle, data, count);
2181                 if (test_position)
2182                         do_test_position();
2183                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2184                         if (!test_nowait)
2185                                 snd_pcm_wait(handle, 100);
2186                 } else if (r == -EPIPE) {
2187                         xrun();
2188                 } else if (r == -ESTRPIPE) {
2189                         suspend();
2190                 } else if (r < 0) {
2191                         error(_("write error: %s"), snd_strerror(r));
2192                         prg_exit(EXIT_FAILURE);
2193                 }
2194                 if (r > 0) {
2195                         if (vumeter)
2196                                 compute_max_peak(data, r * hwparams.channels);
2197                         result += r;
2198                         count -= r;
2199                         data += r * bits_per_frame / 8;
2200                 }
2201         }
2202         return result;
2203 }
2204
2205 static ssize_t pcm_writev(uint8_t **data, unsigned int channels, size_t count)
2206 {
2207         ssize_t r;
2208         size_t result = 0;
2209
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);
2216                 count = chunk_size;
2217         }
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;
2225                 if (test_position)
2226                         do_test_position();
2227                 check_stdin();
2228                 r = writen_func(handle, bufs, count);
2229                 if (test_position)
2230                         do_test_position();
2231                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2232                         if (!test_nowait)
2233                                 snd_pcm_wait(handle, 100);
2234                 } else if (r == -EPIPE) {
2235                         xrun();
2236                 } else if (r == -ESTRPIPE) {
2237                         suspend();
2238                 } else if (r < 0) {
2239                         error(_("writev error: %s"), snd_strerror(r));
2240                         prg_exit(EXIT_FAILURE);
2241                 }
2242                 if (r > 0) {
2243                         if (vumeter) {
2244                                 for (channel = 0; channel < channels; channel++)
2245                                         compute_max_peak(data[channel], r);
2246                         }
2247                         result += r;
2248                         count -= r;
2249                 }
2250         }
2251         return result;
2252 }
2253
2254 /*
2255  *  read function
2256  */
2257
2258 static ssize_t pcm_read(uint8_t *data, size_t rcount)
2259 {
2260         ssize_t r;
2261         size_t result = 0;
2262         size_t count = rcount;
2263
2264         if (count != chunk_size) {
2265                 count = chunk_size;
2266         }
2267
2268         while (count > 0) {
2269                 if (in_aborting)
2270                         goto abort;
2271                 if (test_position)
2272                         do_test_position();
2273                 check_stdin();
2274                 r = readi_func(handle, data, count);
2275                 if (test_position)
2276                         do_test_position();
2277                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2278                         if (!test_nowait)
2279                                 snd_pcm_wait(handle, 100);
2280                 } else if (r == -EPIPE) {
2281                         xrun();
2282                 } else if (r == -ESTRPIPE) {
2283                         suspend();
2284                 } else if (r < 0) {
2285                         error(_("read error: %s"), snd_strerror(r));
2286                         prg_exit(EXIT_FAILURE);
2287                 }
2288                 if (r > 0) {
2289                         if (vumeter)
2290                                 compute_max_peak(data, r * hwparams.channels);
2291                         result += r;
2292                         count -= r;
2293                         data += r * bits_per_frame / 8;
2294                 }
2295         }
2296 abort:
2297         return result > rcount ? rcount : result;
2298 }
2299
2300 static ssize_t pcm_readv(uint8_t **data, unsigned int channels, size_t rcount)
2301 {
2302         ssize_t r;
2303         size_t result = 0;
2304         size_t count = rcount;
2305
2306         if (count != chunk_size) {
2307                 count = chunk_size;
2308         }
2309
2310         while (count > 0) {
2311                 if (in_aborting)
2312                         goto abort;
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;
2318                 if (test_position)
2319                         do_test_position();
2320                 check_stdin();
2321                 r = readn_func(handle, bufs, count);
2322                 if (test_position)
2323                         do_test_position();
2324                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2325                         if (!test_nowait)
2326                                 snd_pcm_wait(handle, 100);
2327                 } else if (r == -EPIPE) {
2328                         xrun();
2329                 } else if (r == -ESTRPIPE) {
2330                         suspend();
2331                 } else if (r < 0) {
2332                         error(_("readv error: %s"), snd_strerror(r));
2333                         prg_exit(EXIT_FAILURE);
2334                 }
2335                 if (r > 0) {
2336                         if (vumeter) {
2337                                 for (channel = 0; channel < channels; channel++)
2338                                         compute_max_peak(data[channel], r);
2339                         }
2340                         result += r;
2341                         count -= r;
2342                 }
2343         }
2344 abort:
2345         return rcount;
2346 }
2347
2348 /*
2349  *  ok, let's play a .voc file
2350  */
2351
2352 static ssize_t voc_pcm_write(uint8_t *data, size_t count)
2353 {
2354         ssize_t result = count, r;
2355         size_t size;
2356
2357         while (count > 0 && !in_aborting) {
2358                 size = count;
2359                 if (size > chunk_bytes - buffer_pos)
2360                         size = chunk_bytes - buffer_pos;
2361                 memcpy(audiobuf + buffer_pos, data, size);
2362                 data += size;
2363                 count -= size;
2364                 buffer_pos += size;
2365                 if ((size_t)buffer_pos == chunk_bytes) {
2366                         if ((size_t)(r = pcm_write(audiobuf, chunk_size)) != chunk_size)
2367                                 return r;
2368                         buffer_pos = 0;
2369                 }
2370         }
2371         return result;
2372 }
2373
2374 static void voc_write_silence(unsigned x)
2375 {
2376         unsigned l;
2377         uint8_t *buf;
2378
2379         buf = (uint8_t *) malloc(chunk_bytes);
2380         if (buf == NULL) {
2381                 error(_("can't allocate buffer for silence"));
2382                 return;         /* not fatal error */
2383         }
2384         snd_pcm_format_set_silence(hwparams.format, buf, chunk_size * hwparams.channels);
2385         while (x > 0 && !in_aborting) {
2386                 l = x;
2387                 if (l > chunk_size)
2388                         l = chunk_size;
2389                 if (voc_pcm_write(buf, l) != (ssize_t)l) {
2390                         error(_("write error"));
2391                         prg_exit(EXIT_FAILURE);
2392                 }
2393                 x -= l;
2394         }
2395         free(buf);
2396 }
2397
2398 static void voc_pcm_flush(void)
2399 {
2400         if (buffer_pos > 0) {
2401                 size_t b;
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"));
2404                 b = chunk_size;
2405                 if (pcm_write(audiobuf, b) != (ssize_t)b)
2406                         error(_("voc_pcm_flush error"));
2407         }
2408         snd_pcm_nonblock(handle, 0);
2409         snd_pcm_drain(handle);
2410         snd_pcm_nonblock(handle, nonblock);
2411 }
2412
2413 static void voc_play(int fd, int ofs, char *name)
2414 {
2415         int l;
2416         VocBlockType *bp;
2417         VocVoiceData *vd;
2418         VocExtBlock *eb;
2419         size_t nextblock, in_buffer;
2420         uint8_t *data, *buf;
2421         char was_extended = 0, output = 0;
2422         uint16_t *sp, repeat = 0;
2423         off_t filepos = 0;
2424
2425 #define COUNT(x)        nextblock -= x; in_buffer -= x; data += x
2426 #define COUNT1(x)       in_buffer -= x; data += x
2427
2428         data = buf = (uint8_t *)malloc(64 * 1024);
2429         buffer_pos = 0;
2430         if (data == NULL) {
2431                 error(_("malloc error"));
2432                 prg_exit(EXIT_FAILURE);
2433         }
2434         if (!quiet_mode) {
2435                 fprintf(stderr, _("Playing Creative Labs Channel file '%s'...\n"), name);
2436         }
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);
2442                 }
2443                 ofs -= chunk_bytes;
2444         }
2445         if (ofs) {
2446                 if (safe_read(fd, buf, ofs) != ofs) {
2447                         error(_("read error"));
2448                         prg_exit(EXIT_FAILURE);
2449                 }
2450         }
2451         hwparams.format = DEFAULT_FORMAT;
2452         hwparams.subformat = SND_PCM_SUBFORMAT_STD;
2453         hwparams.channels = 1;
2454         hwparams.rate = DEFAULT_SPEED;
2455         set_params();
2456
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 */
2462                         if (in_buffer)
2463                                 memcpy(buf, data, in_buffer);
2464                         data = buf;
2465                         if ((l = safe_read(fd, buf + in_buffer, chunk_bytes - in_buffer)) > 0)
2466                                 in_buffer += l;
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;
2471                                 if (l == -1) {
2472                                         perror(name);
2473                                         prg_exit(EXIT_FAILURE);
2474                                 }
2475                         }
2476                 }
2477                 while (!nextblock) {    /* this is a new block */
2478                         if (in_buffer < sizeof(VocBlockType))
2479                                 goto __end;
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 */
2485                         output = 0;
2486                         switch (bp->type) {
2487                         case 0:
2488 #if 0
2489                                 d_printf("Terminator\n");
2490 #endif
2491                                 return;         /* VOC-file stop */
2492                         case 1:
2493                                 vd = (VocVoiceData *) data;
2494                                 COUNT1(sizeof(VocVoiceData));
2495                                 /* we need a SYNC, before we can set new SPEED, STEREO ... */
2496
2497                                 if (!was_extended) {
2498                                         hwparams.rate = (int) (vd->tc);
2499                                         hwparams.rate = 1000000 / (256 - hwparams.rate);
2500 #if 0
2501                                         d_printf("Channel data %d Hz\n", dsp_speed);
2502 #endif
2503                                         if (vd->pack) {         /* /dev/dsp can't it */
2504                                                 error(_("can't play packed .voc files"));
2505                                                 return;
2506                                         }
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;
2511                                         was_extended = 0;
2512                                 }
2513                                 set_params();
2514                                 break;
2515                         case 2: /* nothing to do, pure data */
2516 #if 0
2517                                 d_printf("Channel continuation\n");
2518 #endif
2519                                 break;
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);
2524                                 COUNT1(1);
2525                                 hwparams.rate = 1000000 / (256 - hwparams.rate);
2526                                 set_params();
2527 #if 0
2528                                 {
2529                                         size_t silence;
2530                                         silence = (((size_t) * sp) * 1000) / hwparams.rate;
2531                                         d_printf("Silence for %d ms\n", (int) silence);
2532                                 }
2533 #endif
2534                                 voc_write_silence(*sp);
2535                                 break;
2536                         case 4: /* a marker for syncronisation, no effect */
2537                                 sp = (uint16_t *) data;
2538                                 COUNT1(sizeof(uint16_t));
2539 #if 0
2540                                 d_printf("Marker %d\n", *sp);
2541 #endif
2542                                 break;
2543                         case 5: /* ASCII text, we copy to stderr */
2544                                 output = 1;
2545 #if 0
2546                                 d_printf("ASCII - text :\n");
2547 #endif
2548                                 break;
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));
2554 #if 0
2555                                 d_printf("Repeat loop %d times\n", repeat);
2556 #endif
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);
2560                                                 repeat = 0;
2561                                         } else {
2562                                                 filepos -= in_buffer;   /* set filepos after repeat */
2563                                         }
2564                                 } else {
2565                                         repeat = 0;
2566                                 }
2567                                 break;
2568                         case 7: /* ok, lets repeat that be rewinding tape */
2569                                 if (repeat) {
2570                                         if (repeat != 0xFFFF) {
2571 #if 0
2572                                                 d_printf("Repeat loop %d\n", repeat);
2573 #endif
2574                                                 --repeat;
2575                                         }
2576 #if 0
2577                                         else
2578                                                 d_printf("Neverending loop\n");
2579 #endif
2580                                         lseek(fd, filepos, 0);
2581                                         in_buffer = 0;  /* clear the buffer */
2582                                         goto Fill_the_buffer;
2583                                 }
2584 #if 0
2585                                 else
2586                                         d_printf("End repeat loop\n");
2587 #endif
2588                                 break;
2589                         case 8: /* the extension to play Stereo, I have SB 1.0 :-( */
2590                                 was_extended = 1;
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"));
2600                                         return;
2601                                 }
2602 #if 0
2603                                 d_printf("Extended block %s %d Hz\n",
2604                                          (eb->mode ? "Stereo" : "Mono"), dsp_speed);
2605 #endif
2606                                 break;
2607                         default:
2608                                 error(_("unknown blocktype %d. terminate."), bp->type);
2609                                 return;
2610                         }       /* switch (bp->type) */
2611                 }               /* while (! nextblock)  */
2612                 /* put nextblock data bytes to dsp */
2613                 l = in_buffer;
2614                 if (nextblock < (size_t)l)
2615                         l = nextblock;
2616                 if (l) {
2617                         if (output && !quiet_mode) {
2618                                 if (xwrite(2, data, l) != l) {  /* to stderr */
2619                                         error(_("write error"));
2620                                         prg_exit(EXIT_FAILURE);
2621                                 }
2622                         } else {
2623                                 if (voc_pcm_write(data, l) != l) {
2624                                         error(_("write error"));
2625                                         prg_exit(EXIT_FAILURE);
2626                                 }
2627                         }
2628                         COUNT(l);
2629                 }
2630         }                       /* while(1) */
2631       __end:
2632         if (!in_aborting) {
2633                 voc_pcm_flush();
2634         }
2635         free(buf);
2636 }
2637 /* that was a big one, perhaps somebody split it :-) */
2638
2639 /* setting the globals for playing raw data */
2640 static void init_raw_data(void)
2641 {
2642         hwparams = rhwparams;
2643 }
2644
2645 /* calculate the data count to read from/to dsp */
2646 static off_t calc_count(void)
2647 {
2648         off_t count;
2649
2650         if (timelimit == 0)
2651                 if (sampleslimit == 0)
2652                         count = pbrec_count;
2653                 else
2654                         count = snd_pcm_format_size(hwparams.format, sampleslimit * hwparams.channels);
2655         else {
2656                 count = snd_pcm_format_size(hwparams.format, hwparams.rate * hwparams.channels);
2657                 count *= (off_t)timelimit;
2658         }
2659         return count < pbrec_count ? count : pbrec_count;
2660 }
2661
2662 /* write a .VOC-header */
2663 static void begin_voc(int fd, size_t cnt)
2664 {
2665         VocHeader vh;
2666         VocBlockType bt;
2667         VocVoiceData vd;
2668         VocExtBlock eb;
2669
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);
2674
2675         if (xwrite(fd, &vh, sizeof(VocHeader)) != sizeof(VocHeader)) {
2676                 error(_("write error"));
2677                 prg_exit(EXIT_FAILURE);
2678         }
2679         if (hwparams.channels > 1) {
2680                 /* write an extended block */
2681                 bt.type = 8;
2682                 bt.datalen = 4;
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);
2687                 }
2688                 eb.tc = LE_SHORT(65536 - 256000000L / (hwparams.rate << 1));
2689                 eb.pack = 0;
2690                 eb.mode = 1;
2691                 if (xwrite(fd, &eb, sizeof(VocExtBlock)) != sizeof(VocExtBlock)) {
2692                         error(_("write error"));
2693                         prg_exit(EXIT_FAILURE);
2694                 }
2695         }
2696         bt.type = 1;
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);
2704         }
2705         vd.tc = (uint8_t) (256 - (1000000 / hwparams.rate));
2706         vd.pack = 0;
2707         if (xwrite(fd, &vd, sizeof(VocVoiceData)) != sizeof(VocVoiceData)) {
2708                 error(_("write error"));
2709                 prg_exit(EXIT_FAILURE);
2710         }
2711 }
2712
2713 /* write a WAVE-header */
2714 static void begin_wave(int fd, size_t cnt)
2715 {
2716         WaveHeader h;
2717         WaveFmtBody f;
2718         WaveChunkHeader cf, cd;
2719         int width, physical_width;
2720         uint32_t tmp;
2721         uint16_t tmp2;
2722
2723         /* WAVE cannot handle greater than 32bit (signed?) int */
2724         if (cnt == (size_t)-2)
2725                 cnt = 0x7fffff00;
2726
2727         width = snd_pcm_format_physical_width(hwparams.format);
2728         physical_width = snd_pcm_format_width(hwparams.format);
2729
2730         if (width < 0 || physical_width < 0)
2731                 goto _format;
2732
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:
2740                 break;
2741         default:
2742 _format:
2743                 error(_("Wave doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2744                 prg_exit(EXIT_FAILURE);
2745         }
2746         h.magic = WAV_RIFF;
2747         tmp = cnt + sizeof(WaveHeader) + sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + sizeof(WaveChunkHeader) - 8;
2748         h.length = LE_INT(tmp);
2749         h.type = WAV_WAVE;
2750
2751         cf.type = WAV_FMT;
2752         cf.length = LE_INT(16);
2753
2754         if (hwparams.format == SND_PCM_FORMAT_FLOAT_LE)
2755                 f.format = LE_SHORT(WAV_FMT_IEEE_FLOAT);
2756         else
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);
2765
2766         cd.type = WAV_DATA;
2767         cd.length = LE_INT(cnt);
2768
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);
2775         }
2776 }
2777
2778 /* write a Au-header */
2779 static void begin_au(int fd, size_t cnt)
2780 {
2781         AuHeader ah;
2782
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);
2789                 break;
2790         case SND_PCM_FORMAT_U8:
2791                 ah.encoding = BE_INT(AU_FMT_LIN8);
2792                 break;
2793         case SND_PCM_FORMAT_S16_BE:
2794                 ah.encoding = BE_INT(AU_FMT_LIN16);
2795                 break;
2796         case SND_PCM_FORMAT_A_LAW:
2797                 ah.encoding = BE_INT(AU_FMT_ALAW);
2798                 break;
2799         default:
2800                 error(_("Sparc Audio doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2801                 prg_exit(EXIT_FAILURE);
2802         }
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);
2808         }
2809 }
2810
2811 /* closing .VOC */
2812 static void end_voc(int fd)
2813 {
2814         off_t length_seek;
2815         VocBlockType bt;
2816         size_t cnt;
2817         char dummy = 0;         /* Write a Terminator */
2818
2819         if (xwrite(fd, &dummy, 1) != 1) {
2820                 error(_("write error"));
2821                 prg_exit(EXIT_FAILURE);
2822         }
2823         length_seek = sizeof(VocHeader);
2824         if (hwparams.channels > 1)
2825                 length_seek += sizeof(VocBlockType) + sizeof(VocExtBlock);
2826         bt.type = 1;
2827         cnt = fdcount;
2828         cnt += sizeof(VocVoiceData);    /* Channel_data block follows */
2829         if (cnt > 0x00ffffff)
2830                 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));
2836 }
2837
2838 static void end_wave(int fd)
2839 {                               /* only close output */
2840         WaveChunkHeader cd;
2841         off_t length_seek;
2842         off_t filelen;
2843         uint32_t rifflen;
2844         
2845         length_seek = sizeof(WaveHeader) +
2846                       sizeof(WaveChunkHeader) +
2847                       sizeof(WaveFmtBody);
2848         cd.type = WAV_DATA;
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));
2856 }
2857
2858 static void end_au(int fd)
2859 {                               /* only close output */
2860         AuHeader ah;
2861         off_t length_seek;
2862         
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));
2867 }
2868
2869 static void header(int rtype, char *name)
2870 {
2871         if (!quiet_mode) {
2872                 if (! 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),
2877                         name);
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"));
2884                 else
2885                         fprintf(stderr, _("Channels %i"), hwparams.channels);
2886                 fprintf(stderr, "\n");
2887         }
2888 }
2889
2890 /* playing raw data */
2891
2892 static void playback_go(int fd, size_t loaded, off_t count, int rtype, char *name)
2893 {
2894         int l, r;
2895         off_t written = 0;
2896         off_t c;
2897
2898         header(rtype, name);
2899         set_params();
2900
2901         while (loaded > chunk_bytes && written < count && !in_aborting) {
2902                 if (pcm_write(audiobuf + written, chunk_size) <= 0)
2903                         return;
2904                 written += chunk_bytes;
2905                 loaded -= chunk_bytes;
2906         }
2907         if (written > 0 && loaded > 0)
2908                 memmove(audiobuf, audiobuf + written, loaded);
2909
2910         l = loaded;
2911         while (written < count && !in_aborting) {
2912                 do {
2913                         c = count - written;
2914                         if (c > (off_t)chunk_bytes)
2915                                 c = chunk_bytes;
2916
2917                         /* c < l, there is more data loaded
2918                          * then we actually need to write
2919                          */
2920                         if (c < l)
2921                                 l = c;
2922
2923                         c -= l;
2924
2925                         if (c == 0)
2926                                 break;
2927                         r = safe_read(fd, audiobuf + l, c);
2928                         if (r < 0) {
2929                                 perror(name);
2930                                 prg_exit(EXIT_FAILURE);
2931                         }
2932                         fdcount += r;
2933                         if (r == 0)
2934                                 break;
2935                         l += r;
2936                 } while ((size_t)l < chunk_bytes);
2937                 l = l * 8 / bits_per_frame;
2938                 r = pcm_write(audiobuf, l);
2939                 if (r != l)
2940                         break;
2941                 r = r * bits_per_frame / 8;
2942                 written += r;
2943                 l = 0;
2944         }
2945         if (!in_aborting) {
2946                 snd_pcm_nonblock(handle, 0);
2947                 snd_pcm_drain(handle);
2948                 snd_pcm_nonblock(handle, nonblock);
2949         }
2950 }
2951
2952 static int read_header(int *loaded, int header_size)
2953 {
2954         int ret;
2955         struct stat buf;
2956
2957         ret = fstat(fd, &buf);
2958         if (ret < 0) {
2959                 perror("fstat");
2960                 prg_exit(EXIT_FAILURE);
2961         }
2962
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)
2967                 return -1;
2968
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);
2975                 }
2976                 *loaded += header_size;
2977         }
2978         return 0;
2979 }
2980
2981 static int playback_au(char *name, int *loaded)
2982 {
2983         if (read_header(loaded, sizeof(AuHeader)) < 0)
2984                 return -1;
2985
2986         if (test_au(fd, audiobuf) < 0)
2987                 return -1;
2988
2989         rhwparams.format = hwparams.format;
2990         pbrec_count = calc_count();
2991         playback_go(fd, *loaded - sizeof(AuHeader), pbrec_count, FORMAT_AU, name);
2992
2993         return 0;
2994 }
2995
2996 static int playback_voc(char *name, int *loaded)
2997 {
2998         int ofs;
2999
3000         if (read_header(loaded, sizeof(VocHeader)) < 0)
3001                 return -1;
3002
3003         if ((ofs = test_vocfile(audiobuf)) < 0)
3004                 return -1;
3005
3006         pbrec_count = calc_count();
3007         voc_play(fd, ofs, name);
3008
3009         return 0;
3010 }
3011
3012 static int playback_wave(char *name, int *loaded)
3013 {
3014         ssize_t dtawave;
3015
3016         if (read_header(loaded, sizeof(WaveHeader)) < 0)
3017                 return -1;
3018
3019         if ((dtawave = test_wavefile(fd, audiobuf, *loaded)) < 0)
3020                 return -1;
3021
3022         pbrec_count = calc_count();
3023         playback_go(fd, dtawave, pbrec_count, FORMAT_WAVE, name);
3024
3025         return 0;
3026 }
3027
3028 static int playback_raw(char *name, int *loaded)
3029 {
3030         init_raw_data();
3031         pbrec_count = calc_count();
3032         playback_go(fd, *loaded, pbrec_count, FORMAT_RAW, name);
3033
3034         return 0;
3035 }
3036
3037 /*
3038  *  let's play or capture it (capture_type says VOC/WAVE/raw)
3039  */
3040
3041 static void playback(char *name)
3042 {
3043         int loaded = 0;
3044
3045         pbrec_count = LLONG_MAX;
3046         fdcount = 0;
3047         if (!name || !strcmp(name, "-")) {
3048                 fd = fileno(stdin);
3049                 name = "stdin";
3050         } else {
3051                 init_stdin();
3052                 if ((fd = open(name, O_RDONLY, 0)) == -1) {
3053                         perror(name);
3054                         prg_exit(EXIT_FAILURE);
3055                 }
3056         }
3057
3058         switch(file_type) {
3059         case FORMAT_AU:
3060                 playback_au(name, &loaded);
3061                 break;
3062         case FORMAT_VOC:
3063                 playback_voc(name, &loaded);
3064                 break;
3065         case FORMAT_WAVE:
3066                 playback_wave(name, &loaded);
3067                 break;
3068         case FORMAT_RAW:
3069                 playback_raw(name, &loaded);
3070                 break;
3071         default:
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 */
3077                 break;
3078         }
3079
3080         if (fd != fileno(stdin))
3081                 close(fd);
3082 }
3083
3084 /**
3085  * mystrftime
3086  *
3087  *   Variant of strftime(3) that supports additional format
3088  *   specifiers in the format string.
3089  *
3090  * Parameters:
3091  *
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
3097  *
3098  * Returns: number of bytes written to the string s
3099  */
3100 size_t mystrftime(char *s, size_t max, const char *userformat,
3101                   const struct tm *tm, const int filenumber)
3102 {
3103         char formatstring[PATH_MAX] = "";
3104         char tempstring[PATH_MAX] = "";
3105         char *format, *tempstr;
3106         const char *pos_userformat;
3107
3108         format = formatstring;
3109
3110         /* if mystrftime is called with userformat = NULL we return a zero length string */
3111         if (userformat == NULL) {
3112                 *s = '\0';
3113                 return 0;
3114         }
3115
3116         for (pos_userformat = userformat; *pos_userformat; ++pos_userformat) {
3117                 if (*pos_userformat == '%') {
3118                         tempstr = tempstring;
3119                         tempstr[0] = '\0';
3120                         switch (*++pos_userformat) {
3121
3122                                 case '\0': // end of string
3123                                         --pos_userformat;
3124                                         break;
3125
3126                                 case 'v': // file number 
3127                                         sprintf(tempstr, "%02d", filenumber);
3128                                         break;
3129
3130                                 default: // All other codes will be handled by strftime
3131                                         *format++ = '%';
3132                                         *format++ = *pos_userformat;
3133                                         continue;
3134                         }
3135
3136                         /* If a format specifier was found and used, copy the result. */
3137                         if (tempstr[0]) {
3138                                 while ((*format = *tempstr++) != '\0')
3139                                         ++format;
3140                                 continue;
3141                         }
3142                 }
3143
3144                 /* For any other character than % we simply copy the character */
3145                 *format++ = *pos_userformat;
3146         }
3147
3148         *format = '\0';
3149         format = formatstring;
3150         return strftime(s, max, format, tm);
3151 }
3152
3153 static int new_capture_file(char *name, char *namebuf, size_t namelen,
3154                             int filecount)
3155 {
3156         char *s;
3157         char buf[PATH_MAX-10];
3158         time_t t;
3159         struct tm *tmp;
3160
3161         if (use_strftime) {
3162                 t = time(NULL);
3163                 tmp = localtime(&t);
3164                 if (tmp == NULL) {
3165                         perror("localtime");
3166                         prg_exit(EXIT_FAILURE);
3167                 }
3168                 if (mystrftime(namebuf, namelen, name, tmp, filecount+1) == 0) {
3169                         fprintf(stderr, "mystrftime returned 0");
3170                         prg_exit(EXIT_FAILURE);
3171                 }
3172                 return filecount;
3173         }
3174
3175         /* get a copy of the original filename */
3176         strncpy(buf, name, sizeof(buf));
3177         buf[sizeof(buf)-1] = '\0';
3178
3179         /* separate extension from filename */
3180         s = buf + strlen(buf);
3181         while (s > buf && *s != '.' && *s != '/')
3182                 --s;
3183         if (*s == '.')
3184                 *s++ = 0;
3185         else if (*s == '/')
3186                 s = buf + strlen(buf);
3187
3188         /* upon first jump to this if block rename the first file */
3189         if (filecount == 1) {
3190                 if (*s)
3191                         snprintf(namebuf, namelen, "%s-01.%s", buf, s);
3192                 else
3193                         snprintf(namebuf, namelen, "%s-01", buf);
3194                 remove(namebuf);
3195                 rename(name, namebuf);
3196                 filecount = 2;
3197         }
3198
3199         /* name of the current file */
3200         if (*s)
3201                 snprintf(namebuf, namelen, "%s-%02i.%s", buf, filecount, s);
3202         else
3203                 snprintf(namebuf, namelen, "%s-%02i", buf, filecount);
3204
3205         return filecount;
3206 }
3207
3208 /**
3209  * create_path
3210  *
3211  *   This function creates a file path, like mkdir -p. 
3212  *
3213  * Parameters:
3214  *
3215  *   path - the path to create
3216  *
3217  * Returns: 0 on success, -1 on failure
3218  * On failure, a message has been printed to stderr.
3219  */
3220 int create_path(const char *path)
3221 {
3222         const char *start;
3223         mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
3224
3225         if (path[0] == '/')
3226                 start = strchr(path + 1, '/');
3227         else
3228                 start = strchr(path, '/');
3229
3230         while (start) {
3231                 char *buffer = strdup(path);
3232                 buffer[start-path] = 0x00;
3233
3234                 if (mkdir(buffer, mode) == -1 && errno != EEXIST) {
3235                         fprintf(stderr, "Problem creating directory %s", buffer);
3236                         perror(" ");
3237                         free(buffer);
3238                         return -1;
3239                 }
3240                 free(buffer);
3241                 start = strchr(start + 1, '/');
3242         }
3243         return 0;
3244 }
3245
3246 static int safe_open(const char *name)
3247 {
3248         int fd;
3249
3250         fd = open(name, O_WRONLY | O_CREAT, 0644);
3251         if (fd == -1) {
3252                 if (errno != ENOENT || !use_strftime)
3253                         return -1;
3254                 if (create_path(name) == 0)
3255                         fd = open(name, O_WRONLY | O_CREAT, 0644);
3256         }
3257         return fd;
3258 }
3259
3260 static void capture(char *orig_name)
3261 {
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;
3268
3269         /* setup sound hardware */
3270         set_params();
3271
3272         /* get number of bytes to capture */
3273         count = calc_count();
3274         if (count == 0)
3275                 count = LLONG_MAX;
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)
3283                 count += count % 2;
3284         else
3285                 count -= count % 2;
3286
3287         /* display verbose output to console */
3288         header(file_type, name);
3289
3290         /* write to stdout? */
3291         if (!name || !strcmp(name, "-")) {
3292                 fd = fileno(stdout);
3293                 name = "stdout";
3294                 tostdout = 1;
3295                 if (count > fmt_rec_table[file_type].max_filesize)
3296                         count = fmt_rec_table[file_type].max_filesize;
3297         }
3298         init_stdin();
3299
3300         do {
3301                 /* open a file to write */
3302                 if (!tostdout) {
3303                         /* upon the second file we start the numbering scheme */
3304                         if (filecount || use_strftime) {
3305                                 filecount = new_capture_file(orig_name, namebuf,
3306                                                              sizeof(namebuf),
3307                                                              filecount);
3308                                 name = namebuf;
3309                         }
3310                         
3311                         /* open a new file */
3312                         if (!lstat(name, &statbuf)) {
3313                                 if (S_ISREG(statbuf.st_mode))
3314                                         remove(name);
3315                         }
3316                         fd = safe_open(name);
3317                         if (fd < 0) {
3318                                 perror(name);
3319                                 prg_exit(EXIT_FAILURE);
3320                         }
3321                         filecount++;
3322                 }
3323
3324                 rest = count;
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;
3329
3330                 /* setup sample header */
3331                 if (fmt_rec_table[file_type].start)
3332                         fmt_rec_table[file_type].start(fd, rest);
3333
3334                 /* capture */
3335                 fdcount = 0;
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);
3341                         size_t save;
3342                         if (read != f)
3343                                 in_aborting = 1;
3344                         save = read * bits_per_frame / 8;
3345                         if (xwrite(fd, audiobuf, save) != (ssize_t)save) {
3346                                 perror(name);
3347                                 in_aborting = 1;
3348                                 break;
3349                         }
3350                         count -= c;
3351                         rest -= c;
3352                         fdcount += save;
3353                 }
3354
3355                 /* re-enable SIGUSR1 signal */
3356                 if (recycle_capture_file) {
3357                         recycle_capture_file = 0;
3358                         signal(SIGUSR1, signal_handler_recycle);
3359                 }
3360
3361                 /* finish sample container */
3362                 if (!tostdout) {
3363                         if (fmt_rec_table[file_type].end)
3364                                 fmt_rec_table[file_type].end(fd);
3365                         close(fd);
3366                         fd = -1;
3367                 }
3368
3369                 if (in_aborting)
3370                         prg_exit(EXIT_FAILURE);
3371
3372                 /* repeat the loop when format is raw without timelimit or
3373                  * requested counts of data are recorded
3374                  */
3375         } while ((file_type == FORMAT_RAW && !timelimit && !sampleslimit) || count > 0);
3376 }
3377
3378 static void playbackv_go(int* fds, unsigned int channels, size_t loaded, off_t count, int rtype, char **names)
3379 {
3380         int r;
3381         size_t vsize;
3382
3383         unsigned int channel;
3384         uint8_t *bufs[channels];
3385
3386         header(rtype, names[0]);
3387         set_params();
3388
3389         vsize = chunk_bytes / channels;
3390
3391         // Not yet implemented
3392         assert(loaded == 0);
3393
3394         for (channel = 0; channel < channels; ++channel)
3395                 bufs[channel] = audiobuf + vsize * channel;
3396
3397         while (count > 0 && !in_aborting) {
3398                 size_t c = 0;
3399                 size_t expected = count / channels;
3400                 if (expected > vsize)
3401                         expected = vsize;
3402                 do {
3403                         r = safe_read(fds[0], bufs[0], expected);
3404                         if (r < 0) {
3405                                 perror(names[0]);
3406                                 prg_exit(EXIT_FAILURE);
3407                         }
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);
3412                                 }
3413                         }
3414                         if (r == 0)
3415                                 break;
3416                         c += r;
3417                 } while (c < expected);
3418                 c = c * 8 / bits_per_sample;
3419                 r = pcm_writev(bufs, channels, c);
3420                 if ((size_t)r != c)
3421                         break;
3422                 r = r * bits_per_frame / 8;
3423                 count -= r;
3424         }
3425         if (!in_aborting) {
3426                 snd_pcm_nonblock(handle, 0);
3427                 snd_pcm_drain(handle);
3428                 snd_pcm_nonblock(handle, nonblock);
3429         }
3430 }
3431
3432 static void capturev_go(int* fds, unsigned int channels, off_t count, int rtype, char **names)
3433 {
3434         size_t c;
3435         ssize_t r;
3436         unsigned int channel;
3437         size_t vsize;
3438         uint8_t *bufs[channels];
3439
3440         header(rtype, names[0]);
3441         set_params();
3442
3443         vsize = chunk_bytes / channels;
3444
3445         for (channel = 0; channel < channels; ++channel)
3446                 bufs[channel] = audiobuf + vsize * channel;
3447
3448         while (count > 0 && !in_aborting) {
3449                 size_t rv;
3450                 c = count;
3451                 if (c > chunk_bytes)
3452                         c = chunk_bytes;
3453                 c = c * 8 / bits_per_frame;
3454                 if ((size_t)(r = pcm_readv(bufs, channels, c)) != c)
3455                         break;
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);
3461                         }
3462                 }
3463                 r = r * bits_per_frame / 8;
3464                 count -= r;
3465                 fdcount += r;
3466         }
3467 }
3468
3469 static void playbackv(char **names, unsigned int count)
3470 {
3471         int ret = 0;
3472         unsigned int channel;
3473         unsigned int channels = rhwparams.channels;
3474         int alloced = 0;
3475         int fds[channels];
3476         for (channel = 0; channel < channels; ++channel)
3477                 fds[channel] = -1;
3478
3479         if (count == 1 && channels > 1) {
3480                 size_t len = strlen(names[0]);
3481                 char buf[len + 1];
3482                 strcpy(buf, names[0]);
3483                 /* 1 for "." + 3 for channel (<= 256) + 1 for null terminator */
3484                 len += 5;
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);
3489                 }
3490                 alloced = 1;
3491         } else if (count != channels) {
3492                 error(_("You need to specify %u files"), channels);
3493                 prg_exit(EXIT_FAILURE);
3494         }
3495
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]);
3500                         ret = EXIT_FAILURE;
3501                         goto __end;
3502                 }
3503         }
3504         /* should be raw data */
3505         init_raw_data();
3506         pbrec_count = calc_count();
3507         playbackv_go(fds, channels, 0, pbrec_count, FORMAT_RAW, names);
3508
3509       __end:
3510         for (channel = 0; channel < channels; ++channel) {
3511                 if (fds[channel] >= 0)
3512                         close(fds[channel]);
3513                 if (alloced)
3514                         free(names[channel]);
3515         }
3516         if (alloced)
3517                 free(names);
3518         if (ret)
3519                 prg_exit(ret);
3520 }
3521
3522 static void capturev(char **names, unsigned int count)
3523 {
3524         int ret = 0;
3525         unsigned int channel;
3526         unsigned int channels = rhwparams.channels;
3527         int alloced = 0;
3528         int fds[channels];
3529         for (channel = 0; channel < channels; ++channel)
3530                 fds[channel] = -1;
3531
3532         if (count == 1) {
3533                 size_t len = strlen(names[0]);
3534                 char buf[len + 1];
3535                 strcpy(buf, names[0]);
3536                 /* 1 for "." + 3 for channel (<= 256) + 1 for null terminator */
3537                 len += 5;
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);
3542                 }
3543                 alloced = 1;
3544         } else if (count != channels) {
3545                 error(_("You need to specify %d files"), channels);
3546                 prg_exit(EXIT_FAILURE);
3547         }
3548
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]);
3553                         ret = EXIT_FAILURE;
3554                         goto __end;
3555                 }
3556         }
3557         /* should be raw data */
3558         init_raw_data();
3559         pbrec_count = calc_count();
3560         capturev_go(fds, channels, pbrec_count, FORMAT_RAW, names);
3561
3562       __end:
3563         for (channel = 0; channel < channels; ++channel) {
3564                 if (fds[channel] >= 0)
3565                         close(fds[channel]);
3566                 if (alloced)
3567                         free(names[channel]);
3568         }
3569         if (alloced)
3570                 free(names);
3571         if (ret)
3572                 prg_exit(ret);
3573 }