Imported Upstream version 1.0.28
[platform/upstream/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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
26  *
27  */
28
29 #define _GNU_SOURCE
30 #include <stdio.h>
31 #include <malloc.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <fcntl.h>
37 #include <ctype.h>
38 #include <errno.h>
39 #include <limits.h>
40 #include <time.h>
41 #include <locale.h>
42 #include <alsa/asoundlib.h>
43 #include <assert.h>
44 #include <termios.h>
45 #include <signal.h>
46 #include <sys/poll.h>
47 #include <sys/uio.h>
48 #include <sys/time.h>
49 #include <sys/stat.h>
50 #include <sys/types.h>
51 #include <endian.h>
52 #include "aconfig.h"
53 #include "gettext.h"
54 #include "formats.h"
55 #include "version.h"
56
57 #ifdef SND_CHMAP_API_VERSION
58 #define CONFIG_SUPPORT_CHMAP    1
59 #endif
60
61 #ifndef LLONG_MAX
62 #define LLONG_MAX    9223372036854775807LL
63 #endif
64
65 #ifndef le16toh
66 #include <asm/byteorder.h>
67 #define le16toh(x) __le16_to_cpu(x)
68 #define be16toh(x) __be16_to_cpu(x)
69 #define le32toh(x) __le32_to_cpu(x)
70 #define be32toh(x) __be32_to_cpu(x)
71 #endif
72
73 #define DEFAULT_FORMAT          SND_PCM_FORMAT_U8
74 #define DEFAULT_SPEED           8000
75
76 #define FORMAT_DEFAULT          -1
77 #define FORMAT_RAW              0
78 #define FORMAT_VOC              1
79 #define FORMAT_WAVE             2
80 #define FORMAT_AU               3
81
82 /* global data */
83
84 static snd_pcm_sframes_t (*readi_func)(snd_pcm_t *handle, void *buffer, snd_pcm_uframes_t size);
85 static snd_pcm_sframes_t (*writei_func)(snd_pcm_t *handle, const void *buffer, snd_pcm_uframes_t size);
86 static snd_pcm_sframes_t (*readn_func)(snd_pcm_t *handle, void **bufs, snd_pcm_uframes_t size);
87 static snd_pcm_sframes_t (*writen_func)(snd_pcm_t *handle, void **bufs, snd_pcm_uframes_t size);
88
89 enum {
90         VUMETER_NONE,
91         VUMETER_MONO,
92         VUMETER_STEREO
93 };
94
95 static char *command;
96 static snd_pcm_t *handle;
97 static struct {
98         snd_pcm_format_t format;
99         unsigned int channels;
100         unsigned int rate;
101 } hwparams, rhwparams;
102 static int timelimit = 0;
103 static int quiet_mode = 0;
104 static int file_type = FORMAT_DEFAULT;
105 static int open_mode = 0;
106 static snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
107 static int mmap_flag = 0;
108 static int interleaved = 1;
109 static int nonblock = 0;
110 static int in_aborting = 0;
111 static u_char *audiobuf = NULL;
112 static snd_pcm_uframes_t chunk_size = 0;
113 static unsigned period_time = 0;
114 static unsigned buffer_time = 0;
115 static snd_pcm_uframes_t period_frames = 0;
116 static snd_pcm_uframes_t buffer_frames = 0;
117 static int avail_min = -1;
118 static int start_delay = 0;
119 static int stop_delay = 0;
120 static int monotonic = 0;
121 static int interactive = 0;
122 static int can_pause = 0;
123 static int fatal_errors = 0;
124 static int verbose = 0;
125 static int vumeter = VUMETER_NONE;
126 static int buffer_pos = 0;
127 static size_t bits_per_sample, bits_per_frame;
128 static size_t chunk_bytes;
129 static int test_position = 0;
130 static int test_coef = 8;
131 static int test_nowait = 0;
132 static snd_output_t *log;
133 static long long max_file_size = 0;
134 static int max_file_time = 0;
135 static int use_strftime = 0;
136 volatile static int recycle_capture_file = 0;
137 static long term_c_lflag = -1;
138 static int dump_hw_params = 0;
139
140 static int fd = -1;
141 static off64_t pbrec_count = LLONG_MAX, fdcount;
142 static int vocmajor, vocminor;
143
144 static char *pidfile_name = NULL;
145 FILE *pidf = NULL;
146 static int pidfile_written = 0;
147
148 #ifdef CONFIG_SUPPORT_CHMAP
149 static snd_pcm_chmap_t *channel_map = NULL; /* chmap to override */
150 static unsigned int *hw_map = NULL; /* chmap to follow */
151 #endif
152
153 /* needed prototypes */
154
155 static void done_stdin(void);
156
157 static void playback(char *filename);
158 static void capture(char *filename);
159 static void playbackv(char **filenames, unsigned int count);
160 static void capturev(char **filenames, unsigned int count);
161
162 static void begin_voc(int fd, size_t count);
163 static void end_voc(int fd);
164 static void begin_wave(int fd, size_t count);
165 static void end_wave(int fd);
166 static void begin_au(int fd, size_t count);
167 static void end_au(int fd);
168
169 static const struct fmt_capture {
170         void (*start) (int fd, size_t count);
171         void (*end) (int fd);
172         char *what;
173         long long max_filesize;
174 } fmt_rec_table[] = {
175         {       NULL,           NULL,           N_("raw data"),         LLONG_MAX },
176         {       begin_voc,      end_voc,        N_("VOC"),              16000000LL },
177         /* FIXME: can WAV handle exactly 2GB or less than it? */
178         {       begin_wave,     end_wave,       N_("WAVE"),             2147483648LL },
179         {       begin_au,       end_au,         N_("Sparc Audio"),      LLONG_MAX }
180 };
181
182 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
183 #define error(...) do {\
184         fprintf(stderr, "%s: %s:%d: ", command, __FUNCTION__, __LINE__); \
185         fprintf(stderr, __VA_ARGS__); \
186         putc('\n', stderr); \
187 } while (0)
188 #else
189 #define error(args...) do {\
190         fprintf(stderr, "%s: %s:%d: ", command, __FUNCTION__, __LINE__); \
191         fprintf(stderr, ##args); \
192         putc('\n', stderr); \
193 } while (0)
194 #endif  
195
196 static void usage(char *command)
197 {
198         snd_pcm_format_t k;
199         printf(
200 _("Usage: %s [OPTION]... [FILE]...\n"
201 "\n"
202 "-h, --help              help\n"
203 "    --version           print current version\n"
204 "-l, --list-devices      list all soundcards and digital audio devices\n"
205 "-L, --list-pcms         list device names\n"
206 "-D, --device=NAME       select PCM by name\n"
207 "-q, --quiet             quiet mode\n"
208 "-t, --file-type TYPE    file type (voc, wav, raw or au)\n"
209 "-c, --channels=#        channels\n"
210 "-f, --format=FORMAT     sample format (case insensitive)\n"
211 "-r, --rate=#            sample rate\n"
212 "-d, --duration=#        interrupt after # seconds\n"
213 "-M, --mmap              mmap stream\n"
214 "-N, --nonblock          nonblocking mode\n"
215 "-F, --period-time=#     distance between interrupts is # microseconds\n"
216 "-B, --buffer-time=#     buffer duration is # microseconds\n"
217 "    --period-size=#     distance between interrupts is # frames\n"
218 "    --buffer-size=#     buffer duration is # frames\n"
219 "-A, --avail-min=#       min available space for wakeup is # microseconds\n"
220 "-R, --start-delay=#     delay for automatic PCM start is # microseconds \n"
221 "                        (relative to buffer size if <= 0)\n"
222 "-T, --stop-delay=#      delay for automatic PCM stop is # microseconds from xrun\n"
223 "-v, --verbose           show PCM structure and setup (accumulative)\n"
224 "-V, --vumeter=TYPE      enable VU meter (TYPE: mono or stereo)\n"
225 "-I, --separate-channels one file for each channel\n"
226 "-i, --interactive       allow interactive operation from stdin\n"
227 "-m, --chmap=ch1,ch2,..  Give the channel map to override or follow\n"
228 "    --disable-resample  disable automatic rate resample\n"
229 "    --disable-channels  disable automatic channel conversions\n"
230 "    --disable-format    disable automatic format conversions\n"
231 "    --disable-softvol   disable software volume control (softvol)\n"
232 "    --test-position     test ring buffer position\n"
233 "    --test-coef=#       test coefficient for ring buffer position (default 8)\n"
234 "                        expression for validation is: coef * (buffer_size / 2)\n"
235 "    --test-nowait       do not wait for ring buffer - eats whole CPU\n"
236 "    --max-file-time=#   start another output file when the old file has recorded\n"
237 "                        for this many seconds\n"
238 "    --process-id-file   write the process ID here\n"
239 "    --use-strftime      apply the strftime facility to the output file name\n"
240 "    --dump-hw-params    dump hw_params of the device\n"
241 "    --fatal-errors      treat all errors as fatal\n"
242   )
243                 , command);
244         printf(_("Recognized sample formats are:"));
245         for (k = 0; k <= SND_PCM_FORMAT_LAST; ++k) {
246                 const char *s = snd_pcm_format_name(k);
247                 if (s)
248                         printf(" %s", s);
249         }
250         printf(_("\nSome of these may not be available on selected hardware\n"));
251         printf(_("The available format shortcuts are:\n"));
252         printf(_("-f cd (16 bit little endian, 44100, stereo)\n"));
253         printf(_("-f cdr (16 bit big endian, 44100, stereo)\n"));
254         printf(_("-f dat (16 bit little endian, 48000, stereo)\n"));
255 }
256
257 static void device_list(void)
258 {
259         snd_ctl_t *handle;
260         int card, err, dev, idx;
261         snd_ctl_card_info_t *info;
262         snd_pcm_info_t *pcminfo;
263         snd_ctl_card_info_alloca(&info);
264         snd_pcm_info_alloca(&pcminfo);
265
266         card = -1;
267         if (snd_card_next(&card) < 0 || card < 0) {
268                 error(_("no soundcards found..."));
269                 return;
270         }
271         printf(_("**** List of %s Hardware Devices ****\n"),
272                snd_pcm_stream_name(stream));
273         while (card >= 0) {
274                 char name[32];
275                 sprintf(name, "hw:%d", card);
276                 if ((err = snd_ctl_open(&handle, name, 0)) < 0) {
277                         error("control open (%i): %s", card, snd_strerror(err));
278                         goto next_card;
279                 }
280                 if ((err = snd_ctl_card_info(handle, info)) < 0) {
281                         error("control hardware info (%i): %s", card, snd_strerror(err));
282                         snd_ctl_close(handle);
283                         goto next_card;
284                 }
285                 dev = -1;
286                 while (1) {
287                         unsigned int count;
288                         if (snd_ctl_pcm_next_device(handle, &dev)<0)
289                                 error("snd_ctl_pcm_next_device");
290                         if (dev < 0)
291                                 break;
292                         snd_pcm_info_set_device(pcminfo, dev);
293                         snd_pcm_info_set_subdevice(pcminfo, 0);
294                         snd_pcm_info_set_stream(pcminfo, stream);
295                         if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
296                                 if (err != -ENOENT)
297                                         error("control digital audio info (%i): %s", card, snd_strerror(err));
298                                 continue;
299                         }
300                         printf(_("card %i: %s [%s], device %i: %s [%s]\n"),
301                                 card, snd_ctl_card_info_get_id(info), snd_ctl_card_info_get_name(info),
302                                 dev,
303                                 snd_pcm_info_get_id(pcminfo),
304                                 snd_pcm_info_get_name(pcminfo));
305                         count = snd_pcm_info_get_subdevices_count(pcminfo);
306                         printf( _("  Subdevices: %i/%i\n"),
307                                 snd_pcm_info_get_subdevices_avail(pcminfo), count);
308                         for (idx = 0; idx < (int)count; idx++) {
309                                 snd_pcm_info_set_subdevice(pcminfo, idx);
310                                 if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
311                                         error("control digital audio playback info (%i): %s", card, snd_strerror(err));
312                                 } else {
313                                         printf(_("  Subdevice #%i: %s\n"),
314                                                 idx, snd_pcm_info_get_subdevice_name(pcminfo));
315                                 }
316                         }
317                 }
318                 snd_ctl_close(handle);
319         next_card:
320                 if (snd_card_next(&card) < 0) {
321                         error("snd_card_next");
322                         break;
323                 }
324         }
325 }
326
327 static void pcm_list(void)
328 {
329         void **hints, **n;
330         char *name, *descr, *descr1, *io;
331         const char *filter;
332
333         if (snd_device_name_hint(-1, "pcm", &hints) < 0)
334                 return;
335         n = hints;
336         filter = stream == SND_PCM_STREAM_CAPTURE ? "Input" : "Output";
337         while (*n != NULL) {
338                 name = snd_device_name_get_hint(*n, "NAME");
339                 descr = snd_device_name_get_hint(*n, "DESC");
340                 io = snd_device_name_get_hint(*n, "IOID");
341                 if (io != NULL && strcmp(io, filter) != 0)
342                         goto __end;
343                 printf("%s\n", name);
344                 if ((descr1 = descr) != NULL) {
345                         printf("    ");
346                         while (*descr1) {
347                                 if (*descr1 == '\n')
348                                         printf("\n    ");
349                                 else
350                                         putchar(*descr1);
351                                 descr1++;
352                         }
353                         putchar('\n');
354                 }
355               __end:
356                 if (name != NULL)
357                         free(name);
358                 if (descr != NULL)
359                         free(descr);
360                 if (io != NULL)
361                         free(io);
362                 n++;
363         }
364         snd_device_name_free_hint(hints);
365 }
366
367 static void version(void)
368 {
369         printf("%s: version " SND_UTIL_VERSION_STR " by Jaroslav Kysela <perex@perex.cz>\n", command);
370 }
371
372 /*
373  *      Subroutine to clean up before exit.
374  */
375 static void prg_exit(int code) 
376 {
377         done_stdin();
378         if (handle)
379                 snd_pcm_close(handle);
380         if (pidfile_written)
381                 remove (pidfile_name);
382         exit(code);
383 }
384
385 static void signal_handler(int sig)
386 {
387         if (in_aborting)
388                 return;
389
390         in_aborting = 1;
391         if (verbose==2)
392                 putchar('\n');
393         if (!quiet_mode)
394                 fprintf(stderr, _("Aborted by signal %s...\n"), strsignal(sig));
395         if (handle)
396                 snd_pcm_abort(handle);
397         if (sig == SIGABRT) {
398                 /* do not call snd_pcm_close() and abort immediately */
399                 handle = NULL;
400                 prg_exit(EXIT_FAILURE);
401         }
402         signal(sig, signal_handler);
403 }
404
405 /* call on SIGUSR1 signal. */
406 static void signal_handler_recycle (int sig)
407 {
408         /* flag the capture loop to start a new output file */
409         recycle_capture_file = 1;
410 }
411
412 enum {
413         OPT_VERSION = 1,
414         OPT_PERIOD_SIZE,
415         OPT_BUFFER_SIZE,
416         OPT_DISABLE_RESAMPLE,
417         OPT_DISABLE_CHANNELS,
418         OPT_DISABLE_FORMAT,
419         OPT_DISABLE_SOFTVOL,
420         OPT_TEST_POSITION,
421         OPT_TEST_COEF,
422         OPT_TEST_NOWAIT,
423         OPT_MAX_FILE_TIME,
424         OPT_PROCESS_ID_FILE,
425         OPT_USE_STRFTIME,
426         OPT_DUMP_HWPARAMS,
427         OPT_FATAL_ERRORS,
428 };
429
430 int main(int argc, char *argv[])
431 {
432         int option_index;
433         static const char short_options[] = "hnlLD:qt:c:f:r:d:MNF:A:R:T:B:vV:IPCi"
434 #ifdef CONFIG_SUPPORT_CHMAP
435                 "m:"
436 #endif
437                 ;
438         static const struct option long_options[] = {
439                 {"help", 0, 0, 'h'},
440                 {"version", 0, 0, OPT_VERSION},
441                 {"list-devnames", 0, 0, 'n'},
442                 {"list-devices", 0, 0, 'l'},
443                 {"list-pcms", 0, 0, 'L'},
444                 {"device", 1, 0, 'D'},
445                 {"quiet", 0, 0, 'q'},
446                 {"file-type", 1, 0, 't'},
447                 {"channels", 1, 0, 'c'},
448                 {"format", 1, 0, 'f'},
449                 {"rate", 1, 0, 'r'},
450                 {"duration", 1, 0 ,'d'},
451                 {"mmap", 0, 0, 'M'},
452                 {"nonblock", 0, 0, 'N'},
453                 {"period-time", 1, 0, 'F'},
454                 {"period-size", 1, 0, OPT_PERIOD_SIZE},
455                 {"avail-min", 1, 0, 'A'},
456                 {"start-delay", 1, 0, 'R'},
457                 {"stop-delay", 1, 0, 'T'},
458                 {"buffer-time", 1, 0, 'B'},
459                 {"buffer-size", 1, 0, OPT_BUFFER_SIZE},
460                 {"verbose", 0, 0, 'v'},
461                 {"vumeter", 1, 0, 'V'},
462                 {"separate-channels", 0, 0, 'I'},
463                 {"playback", 0, 0, 'P'},
464                 {"capture", 0, 0, 'C'},
465                 {"disable-resample", 0, 0, OPT_DISABLE_RESAMPLE},
466                 {"disable-channels", 0, 0, OPT_DISABLE_CHANNELS},
467                 {"disable-format", 0, 0, OPT_DISABLE_FORMAT},
468                 {"disable-softvol", 0, 0, OPT_DISABLE_SOFTVOL},
469                 {"test-position", 0, 0, OPT_TEST_POSITION},
470                 {"test-coef", 1, 0, OPT_TEST_COEF},
471                 {"test-nowait", 0, 0, OPT_TEST_NOWAIT},
472                 {"max-file-time", 1, 0, OPT_MAX_FILE_TIME},
473                 {"process-id-file", 1, 0, OPT_PROCESS_ID_FILE},
474                 {"use-strftime", 0, 0, OPT_USE_STRFTIME},
475                 {"interactive", 0, 0, 'i'},
476                 {"dump-hw-params", 0, 0, OPT_DUMP_HWPARAMS},
477                 {"fatal-errors", 0, 0, OPT_FATAL_ERRORS},
478 #ifdef CONFIG_SUPPORT_CHMAP
479                 {"chmap", 1, 0, 'm'},
480 #endif
481                 {0, 0, 0, 0}
482         };
483         char *pcm_name = "default";
484         int tmp, err, c;
485         int do_device_list = 0, do_pcm_list = 0;
486         snd_pcm_info_t *info;
487         FILE *direction;
488
489 #ifdef ENABLE_NLS
490         setlocale(LC_ALL, "");
491         textdomain(PACKAGE);
492 #endif
493
494         snd_pcm_info_alloca(&info);
495
496         err = snd_output_stdio_attach(&log, stderr, 0);
497         assert(err >= 0);
498
499         command = argv[0];
500         file_type = FORMAT_DEFAULT;
501         if (strstr(argv[0], "arecord")) {
502                 stream = SND_PCM_STREAM_CAPTURE;
503                 file_type = FORMAT_WAVE;
504                 command = "arecord";
505                 start_delay = 1;
506                 direction = stdout;
507         } else if (strstr(argv[0], "aplay")) {
508                 stream = SND_PCM_STREAM_PLAYBACK;
509                 command = "aplay";
510                 direction = stdin;
511         } else {
512                 error(_("command should be named either arecord or aplay"));
513                 return 1;
514         }
515
516         if (isatty(fileno(direction)) && (argc == 1)) {
517                 usage(command);
518                 return 1;
519         }
520
521         chunk_size = -1;
522         rhwparams.format = DEFAULT_FORMAT;
523         rhwparams.rate = DEFAULT_SPEED;
524         rhwparams.channels = 1;
525
526         while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) {
527                 switch (c) {
528                 case 'h':
529                         usage(command);
530                         return 0;
531                 case OPT_VERSION:
532                         version();
533                         return 0;
534                 case 'l':
535                         do_device_list = 1;
536                         break;
537                 case 'L':
538                         do_pcm_list = 1;
539                         break;
540                 case 'D':
541                         pcm_name = optarg;
542                         break;
543                 case 'q':
544                         quiet_mode = 1;
545                         break;
546                 case 't':
547                         if (strcasecmp(optarg, "raw") == 0)
548                                 file_type = FORMAT_RAW;
549                         else if (strcasecmp(optarg, "voc") == 0)
550                                 file_type = FORMAT_VOC;
551                         else if (strcasecmp(optarg, "wav") == 0)
552                                 file_type = FORMAT_WAVE;
553                         else if (strcasecmp(optarg, "au") == 0 || strcasecmp(optarg, "sparc") == 0)
554                                 file_type = FORMAT_AU;
555                         else {
556                                 error(_("unrecognized file format %s"), optarg);
557                                 return 1;
558                         }
559                         break;
560                 case 'c':
561                         rhwparams.channels = strtol(optarg, NULL, 0);
562                         if (rhwparams.channels < 1 || rhwparams.channels > 256) {
563                                 error(_("value %i for channels is invalid"), rhwparams.channels);
564                                 return 1;
565                         }
566                         break;
567                 case 'f':
568                         if (strcasecmp(optarg, "cd") == 0 || strcasecmp(optarg, "cdr") == 0) {
569                                 if (strcasecmp(optarg, "cdr") == 0)
570                                         rhwparams.format = SND_PCM_FORMAT_S16_BE;
571                                 else
572                                         rhwparams.format = file_type == FORMAT_AU ? SND_PCM_FORMAT_S16_BE : SND_PCM_FORMAT_S16_LE;
573                                 rhwparams.rate = 44100;
574                                 rhwparams.channels = 2;
575                         } else if (strcasecmp(optarg, "dat") == 0) {
576                                 rhwparams.format = file_type == FORMAT_AU ? SND_PCM_FORMAT_S16_BE : SND_PCM_FORMAT_S16_LE;
577                                 rhwparams.rate = 48000;
578                                 rhwparams.channels = 2;
579                         } else {
580                                 rhwparams.format = snd_pcm_format_value(optarg);
581                                 if (rhwparams.format == SND_PCM_FORMAT_UNKNOWN) {
582                                         error(_("wrong extended format '%s'"), optarg);
583                                         prg_exit(EXIT_FAILURE);
584                                 }
585                         }
586                         break;
587                 case 'r':
588                         tmp = strtol(optarg, NULL, 0);
589                         if (tmp < 300)
590                                 tmp *= 1000;
591                         rhwparams.rate = tmp;
592                         if (tmp < 2000 || tmp > 192000) {
593                                 error(_("bad speed value %i"), tmp);
594                                 return 1;
595                         }
596                         break;
597                 case 'd':
598                         timelimit = strtol(optarg, NULL, 0);
599                         break;
600                 case 'N':
601                         nonblock = 1;
602                         open_mode |= SND_PCM_NONBLOCK;
603                         break;
604                 case 'F':
605                         period_time = strtol(optarg, NULL, 0);
606                         break;
607                 case 'B':
608                         buffer_time = strtol(optarg, NULL, 0);
609                         break;
610                 case OPT_PERIOD_SIZE:
611                         period_frames = strtol(optarg, NULL, 0);
612                         break;
613                 case OPT_BUFFER_SIZE:
614                         buffer_frames = strtol(optarg, NULL, 0);
615                         break;
616                 case 'A':
617                         avail_min = strtol(optarg, NULL, 0);
618                         break;
619                 case 'R':
620                         start_delay = strtol(optarg, NULL, 0);
621                         break;
622                 case 'T':
623                         stop_delay = strtol(optarg, NULL, 0);
624                         break;
625                 case 'v':
626                         verbose++;
627                         if (verbose > 1 && !vumeter)
628                                 vumeter = VUMETER_MONO;
629                         break;
630                 case 'V':
631                         if (*optarg == 's')
632                                 vumeter = VUMETER_STEREO;
633                         else if (*optarg == 'm')
634                                 vumeter = VUMETER_MONO;
635                         else
636                                 vumeter = VUMETER_NONE;
637                         break;
638                 case 'M':
639                         mmap_flag = 1;
640                         break;
641                 case 'I':
642                         interleaved = 0;
643                         break;
644                 case 'P':
645                         stream = SND_PCM_STREAM_PLAYBACK;
646                         command = "aplay";
647                         break;
648                 case 'C':
649                         stream = SND_PCM_STREAM_CAPTURE;
650                         command = "arecord";
651                         start_delay = 1;
652                         if (file_type == FORMAT_DEFAULT)
653                                 file_type = FORMAT_WAVE;
654                         break;
655                 case 'i':
656                         interactive = 1;
657                         break;
658                 case OPT_DISABLE_RESAMPLE:
659                         open_mode |= SND_PCM_NO_AUTO_RESAMPLE;
660                         break;
661                 case OPT_DISABLE_CHANNELS:
662                         open_mode |= SND_PCM_NO_AUTO_CHANNELS;
663                         break;
664                 case OPT_DISABLE_FORMAT:
665                         open_mode |= SND_PCM_NO_AUTO_FORMAT;
666                         break;
667                 case OPT_DISABLE_SOFTVOL:
668                         open_mode |= SND_PCM_NO_SOFTVOL;
669                         break;
670                 case OPT_TEST_POSITION:
671                         test_position = 1;
672                         break;
673                 case OPT_TEST_COEF:
674                         test_coef = strtol(optarg, NULL, 0);
675                         if (test_coef < 1)
676                                 test_coef = 1;
677                         break;
678                 case OPT_TEST_NOWAIT:
679                         test_nowait = 1;
680                         break;
681                 case OPT_MAX_FILE_TIME:
682                         max_file_time = strtol(optarg, NULL, 0);
683                         break;
684                 case OPT_PROCESS_ID_FILE:
685                         pidfile_name = optarg;
686                         break;
687                 case OPT_USE_STRFTIME:
688                         use_strftime = 1;
689                         break;
690                 case OPT_DUMP_HWPARAMS:
691                         dump_hw_params = 1;
692                         break;
693                 case OPT_FATAL_ERRORS:
694                         fatal_errors = 1;
695                         break;
696 #ifdef CONFIG_SUPPORT_CHMAP
697                 case 'm':
698                         channel_map = snd_pcm_chmap_parse_string(optarg);
699                         if (!channel_map) {
700                                 fprintf(stderr, _("Unable to parse channel map string: %s\n"), optarg);
701                                 return 1;
702                         }
703                         break;
704 #endif
705                 default:
706                         fprintf(stderr, _("Try `%s --help' for more information.\n"), command);
707                         return 1;
708                 }
709         }
710
711         if (do_device_list) {
712                 if (do_pcm_list) pcm_list();
713                 device_list();
714                 goto __end;
715         } else if (do_pcm_list) {
716                 pcm_list();
717                 goto __end;
718         }
719
720         err = snd_pcm_open(&handle, pcm_name, stream, open_mode);
721         if (err < 0) {
722                 error(_("audio open error: %s"), snd_strerror(err));
723                 return 1;
724         }
725
726         if ((err = snd_pcm_info(handle, info)) < 0) {
727                 error(_("info error: %s"), snd_strerror(err));
728                 return 1;
729         }
730
731         if (nonblock) {
732                 err = snd_pcm_nonblock(handle, 1);
733                 if (err < 0) {
734                         error(_("nonblock setting error: %s"), snd_strerror(err));
735                         return 1;
736                 }
737         }
738
739         chunk_size = 1024;
740         hwparams = rhwparams;
741
742         audiobuf = (u_char *)malloc(1024);
743         if (audiobuf == NULL) {
744                 error(_("not enough memory"));
745                 return 1;
746         }
747
748         if (mmap_flag) {
749                 writei_func = snd_pcm_mmap_writei;
750                 readi_func = snd_pcm_mmap_readi;
751                 writen_func = snd_pcm_mmap_writen;
752                 readn_func = snd_pcm_mmap_readn;
753         } else {
754                 writei_func = snd_pcm_writei;
755                 readi_func = snd_pcm_readi;
756                 writen_func = snd_pcm_writen;
757                 readn_func = snd_pcm_readn;
758         }
759
760         if (pidfile_name) {
761                 errno = 0;
762                 pidf = fopen (pidfile_name, "w");
763                 if (pidf) {
764                         (void)fprintf (pidf, "%d\n", getpid());
765                         fclose(pidf);
766                         pidfile_written = 1;
767                 } else {
768                         error(_("Cannot create process ID file %s: %s"), 
769                                 pidfile_name, strerror (errno));
770                         return 1;
771                 }
772         }
773
774         signal(SIGINT, signal_handler);
775         signal(SIGTERM, signal_handler);
776         signal(SIGABRT, signal_handler);
777         signal(SIGUSR1, signal_handler_recycle);
778         if (interleaved) {
779                 if (optind > argc - 1) {
780                         if (stream == SND_PCM_STREAM_PLAYBACK)
781                                 playback(NULL);
782                         else
783                                 capture(NULL);
784                 } else {
785                         while (optind <= argc - 1) {
786                                 if (stream == SND_PCM_STREAM_PLAYBACK)
787                                         playback(argv[optind++]);
788                                 else
789                                         capture(argv[optind++]);
790                         }
791                 }
792         } else {
793                 if (stream == SND_PCM_STREAM_PLAYBACK)
794                         playbackv(&argv[optind], argc - optind);
795                 else
796                         capturev(&argv[optind], argc - optind);
797         }
798         if (verbose==2)
799                 putchar('\n');
800         snd_pcm_close(handle);
801         handle = NULL;
802         free(audiobuf);
803       __end:
804         snd_output_close(log);
805         snd_config_update_free_global();
806         prg_exit(EXIT_SUCCESS);
807         /* avoid warning */
808         return EXIT_SUCCESS;
809 }
810
811 /*
812  * Safe read (for pipes)
813  */
814  
815 static ssize_t safe_read(int fd, void *buf, size_t count)
816 {
817         ssize_t result = 0, res;
818
819         while (count > 0 && !in_aborting) {
820                 if ((res = read(fd, buf, count)) == 0)
821                         break;
822                 if (res < 0)
823                         return result > 0 ? result : res;
824                 count -= res;
825                 result += res;
826                 buf = (char *)buf + res;
827         }
828         return result;
829 }
830
831 /*
832  * Test, if it is a .VOC file and return >=0 if ok (this is the length of rest)
833  *                                       < 0 if not 
834  */
835 static int test_vocfile(void *buffer)
836 {
837         VocHeader *vp = buffer;
838
839         if (!memcmp(vp->magic, VOC_MAGIC_STRING, 20)) {
840                 vocminor = LE_SHORT(vp->version) & 0xFF;
841                 vocmajor = LE_SHORT(vp->version) / 256;
842                 if (LE_SHORT(vp->version) != (0x1233 - LE_SHORT(vp->coded_ver)))
843                         return -2;      /* coded version mismatch */
844                 return LE_SHORT(vp->headerlen) - sizeof(VocHeader);     /* 0 mostly */
845         }
846         return -1;              /* magic string fail */
847 }
848
849 /*
850  * helper for test_wavefile
851  */
852
853 static size_t test_wavefile_read(int fd, u_char *buffer, size_t *size, size_t reqsize, int line)
854 {
855         if (*size >= reqsize)
856                 return *size;
857         if ((size_t)safe_read(fd, buffer + *size, reqsize - *size) != reqsize - *size) {
858                 error(_("read error (called from line %i)"), line);
859                 prg_exit(EXIT_FAILURE);
860         }
861         return *size = reqsize;
862 }
863
864 #define check_wavefile_space(buffer, len, blimit) \
865         if (len > blimit) { \
866                 blimit = len; \
867                 if ((buffer = realloc(buffer, blimit)) == NULL) { \
868                         error(_("not enough memory"));            \
869                         prg_exit(EXIT_FAILURE);  \
870                 } \
871         }
872
873 /*
874  * test, if it's a .WAV file, > 0 if ok (and set the speed, stereo etc.)
875  *                            == 0 if not
876  * Value returned is bytes to be discarded.
877  */
878 static ssize_t test_wavefile(int fd, u_char *_buffer, size_t size)
879 {
880         WaveHeader *h = (WaveHeader *)_buffer;
881         u_char *buffer = NULL;
882         size_t blimit = 0;
883         WaveFmtBody *f;
884         WaveChunkHeader *c;
885         u_int type, len;
886         unsigned short format, channels;
887         int big_endian, native_format;
888
889         if (size < sizeof(WaveHeader))
890                 return -1;
891         if (h->magic == WAV_RIFF)
892                 big_endian = 0;
893         else if (h->magic == WAV_RIFX)
894                 big_endian = 1;
895         else
896                 return -1;
897         if (h->type != WAV_WAVE)
898                 return -1;
899
900         if (size > sizeof(WaveHeader)) {
901                 check_wavefile_space(buffer, size - sizeof(WaveHeader), blimit);
902                 memcpy(buffer, _buffer + sizeof(WaveHeader), size - sizeof(WaveHeader));
903         }
904         size -= sizeof(WaveHeader);
905         while (1) {
906                 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
907                 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
908                 c = (WaveChunkHeader*)buffer;
909                 type = c->type;
910                 len = TO_CPU_INT(c->length, big_endian);
911                 len += len % 2;
912                 if (size > sizeof(WaveChunkHeader))
913                         memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
914                 size -= sizeof(WaveChunkHeader);
915                 if (type == WAV_FMT)
916                         break;
917                 check_wavefile_space(buffer, len, blimit);
918                 test_wavefile_read(fd, buffer, &size, len, __LINE__);
919                 if (size > len)
920                         memmove(buffer, buffer + len, size - len);
921                 size -= len;
922         }
923
924         if (len < sizeof(WaveFmtBody)) {
925                 error(_("unknown length of 'fmt ' chunk (read %u, should be %u at least)"),
926                       len, (u_int)sizeof(WaveFmtBody));
927                 prg_exit(EXIT_FAILURE);
928         }
929         check_wavefile_space(buffer, len, blimit);
930         test_wavefile_read(fd, buffer, &size, len, __LINE__);
931         f = (WaveFmtBody*) buffer;
932         format = TO_CPU_SHORT(f->format, big_endian);
933         if (format == WAV_FMT_EXTENSIBLE) {
934                 WaveFmtExtensibleBody *fe = (WaveFmtExtensibleBody*)buffer;
935                 if (len < sizeof(WaveFmtExtensibleBody)) {
936                         error(_("unknown length of extensible 'fmt ' chunk (read %u, should be %u at least)"),
937                                         len, (u_int)sizeof(WaveFmtExtensibleBody));
938                         prg_exit(EXIT_FAILURE);
939                 }
940                 if (memcmp(fe->guid_tag, WAV_GUID_TAG, 14) != 0) {
941                         error(_("wrong format tag in extensible 'fmt ' chunk"));
942                         prg_exit(EXIT_FAILURE);
943                 }
944                 format = TO_CPU_SHORT(fe->guid_format, big_endian);
945         }
946         if (format != WAV_FMT_PCM &&
947             format != WAV_FMT_IEEE_FLOAT) {
948                 error(_("can't play WAVE-file format 0x%04x which is not PCM or FLOAT encoded"), format);
949                 prg_exit(EXIT_FAILURE);
950         }
951         channels = TO_CPU_SHORT(f->channels, big_endian);
952         if (channels < 1) {
953                 error(_("can't play WAVE-files with %d tracks"), channels);
954                 prg_exit(EXIT_FAILURE);
955         }
956         hwparams.channels = channels;
957         switch (TO_CPU_SHORT(f->bit_p_spl, big_endian)) {
958         case 8:
959                 if (hwparams.format != DEFAULT_FORMAT &&
960                     hwparams.format != SND_PCM_FORMAT_U8)
961                         fprintf(stderr, _("Warning: format is changed to U8\n"));
962                 hwparams.format = SND_PCM_FORMAT_U8;
963                 break;
964         case 16:
965                 if (big_endian)
966                         native_format = SND_PCM_FORMAT_S16_BE;
967                 else
968                         native_format = SND_PCM_FORMAT_S16_LE;
969                 if (hwparams.format != DEFAULT_FORMAT &&
970                     hwparams.format != native_format)
971                         fprintf(stderr, _("Warning: format is changed to %s\n"),
972                                 snd_pcm_format_name(native_format));
973                 hwparams.format = native_format;
974                 break;
975         case 24:
976                 switch (TO_CPU_SHORT(f->byte_p_spl, big_endian) / hwparams.channels) {
977                 case 3:
978                         if (big_endian)
979                                 native_format = SND_PCM_FORMAT_S24_3BE;
980                         else
981                                 native_format = SND_PCM_FORMAT_S24_3LE;
982                         if (hwparams.format != DEFAULT_FORMAT &&
983                             hwparams.format != native_format)
984                                 fprintf(stderr, _("Warning: format is changed to %s\n"),
985                                         snd_pcm_format_name(native_format));
986                         hwparams.format = native_format;
987                         break;
988                 case 4:
989                         if (big_endian)
990                                 native_format = SND_PCM_FORMAT_S24_BE;
991                         else
992                                 native_format = SND_PCM_FORMAT_S24_LE;
993                         if (hwparams.format != DEFAULT_FORMAT &&
994                             hwparams.format != native_format)
995                                 fprintf(stderr, _("Warning: format is changed to %s\n"),
996                                         snd_pcm_format_name(native_format));
997                         hwparams.format = native_format;
998                         break;
999                 default:
1000                         error(_(" can't play WAVE-files with sample %d bits in %d bytes wide (%d channels)"),
1001                               TO_CPU_SHORT(f->bit_p_spl, big_endian),
1002                               TO_CPU_SHORT(f->byte_p_spl, big_endian),
1003                               hwparams.channels);
1004                         prg_exit(EXIT_FAILURE);
1005                 }
1006                 break;
1007         case 32:
1008                 if (format == WAV_FMT_PCM) {
1009                         if (big_endian)
1010                                 native_format = SND_PCM_FORMAT_S32_BE;
1011                         else
1012                                 native_format = SND_PCM_FORMAT_S32_LE;
1013                         hwparams.format = native_format;
1014                 } else if (format == WAV_FMT_IEEE_FLOAT) {
1015                         if (big_endian)
1016                                 native_format = SND_PCM_FORMAT_FLOAT_BE;
1017                         else
1018                                 native_format = SND_PCM_FORMAT_FLOAT_LE;
1019                         hwparams.format = native_format;
1020                 }
1021                 break;
1022         default:
1023                 error(_(" can't play WAVE-files with sample %d bits wide"),
1024                       TO_CPU_SHORT(f->bit_p_spl, big_endian));
1025                 prg_exit(EXIT_FAILURE);
1026         }
1027         hwparams.rate = TO_CPU_INT(f->sample_fq, big_endian);
1028         
1029         if (size > len)
1030                 memmove(buffer, buffer + len, size - len);
1031         size -= len;
1032         
1033         while (1) {
1034                 u_int type, len;
1035
1036                 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
1037                 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
1038                 c = (WaveChunkHeader*)buffer;
1039                 type = c->type;
1040                 len = TO_CPU_INT(c->length, big_endian);
1041                 if (size > sizeof(WaveChunkHeader))
1042                         memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
1043                 size -= sizeof(WaveChunkHeader);
1044                 if (type == WAV_DATA) {
1045                         if (len < pbrec_count && len < 0x7ffffffe)
1046                                 pbrec_count = len;
1047                         if (size > 0)
1048                                 memcpy(_buffer, buffer, size);
1049                         free(buffer);
1050                         return size;
1051                 }
1052                 len += len % 2;
1053                 check_wavefile_space(buffer, len, blimit);
1054                 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1055                 if (size > len)
1056                         memmove(buffer, buffer + len, size - len);
1057                 size -= len;
1058         }
1059
1060         /* shouldn't be reached */
1061         return -1;
1062 }
1063
1064 /*
1065
1066  */
1067
1068 static int test_au(int fd, void *buffer)
1069 {
1070         AuHeader *ap = buffer;
1071
1072         if (ap->magic != AU_MAGIC)
1073                 return -1;
1074         if (BE_INT(ap->hdr_size) > 128 || BE_INT(ap->hdr_size) < 24)
1075                 return -1;
1076         pbrec_count = BE_INT(ap->data_size);
1077         switch (BE_INT(ap->encoding)) {
1078         case AU_FMT_ULAW:
1079                 if (hwparams.format != DEFAULT_FORMAT &&
1080                     hwparams.format != SND_PCM_FORMAT_MU_LAW)
1081                         fprintf(stderr, _("Warning: format is changed to MU_LAW\n"));
1082                 hwparams.format = SND_PCM_FORMAT_MU_LAW;
1083                 break;
1084         case AU_FMT_LIN8:
1085                 if (hwparams.format != DEFAULT_FORMAT &&
1086                     hwparams.format != SND_PCM_FORMAT_U8)
1087                         fprintf(stderr, _("Warning: format is changed to U8\n"));
1088                 hwparams.format = SND_PCM_FORMAT_U8;
1089                 break;
1090         case AU_FMT_LIN16:
1091                 if (hwparams.format != DEFAULT_FORMAT &&
1092                     hwparams.format != SND_PCM_FORMAT_S16_BE)
1093                         fprintf(stderr, _("Warning: format is changed to S16_BE\n"));
1094                 hwparams.format = SND_PCM_FORMAT_S16_BE;
1095                 break;
1096         default:
1097                 return -1;
1098         }
1099         hwparams.rate = BE_INT(ap->sample_rate);
1100         if (hwparams.rate < 2000 || hwparams.rate > 256000)
1101                 return -1;
1102         hwparams.channels = BE_INT(ap->channels);
1103         if (hwparams.channels < 1 || hwparams.channels > 256)
1104                 return -1;
1105         if ((size_t)safe_read(fd, buffer + sizeof(AuHeader), BE_INT(ap->hdr_size) - sizeof(AuHeader)) != BE_INT(ap->hdr_size) - sizeof(AuHeader)) {
1106                 error(_("read error"));
1107                 prg_exit(EXIT_FAILURE);
1108         }
1109         return 0;
1110 }
1111
1112 static void show_available_sample_formats(snd_pcm_hw_params_t* params)
1113 {
1114         snd_pcm_format_t format;
1115
1116         fprintf(stderr, "Available formats:\n");
1117         for (format = 0; format <= SND_PCM_FORMAT_LAST; format++) {
1118                 if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
1119                         fprintf(stderr, "- %s\n", snd_pcm_format_name(format));
1120         }
1121 }
1122
1123 #ifdef CONFIG_SUPPORT_CHMAP
1124 static int setup_chmap(void)
1125 {
1126         snd_pcm_chmap_t *chmap = channel_map;
1127         char mapped[hwparams.channels];
1128         snd_pcm_chmap_t *hw_chmap;
1129         unsigned int ch, i;
1130         int err;
1131
1132         if (!chmap)
1133                 return 0;
1134
1135         if (chmap->channels != hwparams.channels) {
1136                 error(_("Channel numbers don't match between hw_params and channel map"));
1137                 return -1;
1138         }
1139         err = snd_pcm_set_chmap(handle, chmap);
1140         if (!err)
1141                 return 0;
1142
1143         hw_chmap = snd_pcm_get_chmap(handle);
1144         if (!hw_chmap) {
1145                 fprintf(stderr, _("Warning: unable to get channel map\n"));
1146                 return 0;
1147         }
1148
1149         if (hw_chmap->channels == chmap->channels &&
1150             !memcmp(hw_chmap, chmap, 4 * (chmap->channels + 1))) {
1151                 /* maps are identical, so no need to convert */
1152                 free(hw_chmap);
1153                 return 0;
1154         }
1155
1156         hw_map = calloc(hwparams.channels, sizeof(int));
1157         if (!hw_map) {
1158                 error(_("not enough memory"));
1159                 return -1;
1160         }
1161
1162         memset(mapped, 0, sizeof(mapped));
1163         for (ch = 0; ch < hw_chmap->channels; ch++) {
1164                 if (chmap->pos[ch] == hw_chmap->pos[ch]) {
1165                         mapped[ch] = 1;
1166                         hw_map[ch] = ch;
1167                         continue;
1168                 }
1169                 for (i = 0; i < hw_chmap->channels; i++) {
1170                         if (!mapped[i] && chmap->pos[ch] == hw_chmap->pos[i]) {
1171                                 mapped[i] = 1;
1172                                 hw_map[ch] = i;
1173                                 break;
1174                         }
1175                 }
1176                 if (i >= hw_chmap->channels) {
1177                         char buf[256];
1178                         error(_("Channel %d doesn't match with hw_parmas"), ch);
1179                         snd_pcm_chmap_print(hw_chmap, sizeof(buf), buf);
1180                         fprintf(stderr, "hardware chmap = %s\n", buf);
1181                         return -1;
1182                 }
1183         }
1184         free(hw_chmap);
1185         return 0;
1186 }
1187 #else
1188 #define setup_chmap()   0
1189 #endif
1190
1191 static void set_params(void)
1192 {
1193         snd_pcm_hw_params_t *params;
1194         snd_pcm_sw_params_t *swparams;
1195         snd_pcm_uframes_t buffer_size;
1196         int err;
1197         size_t n;
1198         unsigned int rate;
1199         snd_pcm_uframes_t start_threshold, stop_threshold;
1200         snd_pcm_hw_params_alloca(&params);
1201         snd_pcm_sw_params_alloca(&swparams);
1202         err = snd_pcm_hw_params_any(handle, params);
1203         if (err < 0) {
1204                 error(_("Broken configuration for this PCM: no configurations available"));
1205                 prg_exit(EXIT_FAILURE);
1206         }
1207         if (dump_hw_params) {
1208                 fprintf(stderr, _("HW Params of device \"%s\":\n"),
1209                         snd_pcm_name(handle));
1210                 fprintf(stderr, "--------------------\n");
1211                 snd_pcm_hw_params_dump(params, log);
1212                 fprintf(stderr, "--------------------\n");
1213         }
1214         if (mmap_flag) {
1215                 snd_pcm_access_mask_t *mask = alloca(snd_pcm_access_mask_sizeof());
1216                 snd_pcm_access_mask_none(mask);
1217                 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_INTERLEAVED);
1218                 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_NONINTERLEAVED);
1219                 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_COMPLEX);
1220                 err = snd_pcm_hw_params_set_access_mask(handle, params, mask);
1221         } else if (interleaved)
1222                 err = snd_pcm_hw_params_set_access(handle, params,
1223                                                    SND_PCM_ACCESS_RW_INTERLEAVED);
1224         else
1225                 err = snd_pcm_hw_params_set_access(handle, params,
1226                                                    SND_PCM_ACCESS_RW_NONINTERLEAVED);
1227         if (err < 0) {
1228                 error(_("Access type not available"));
1229                 prg_exit(EXIT_FAILURE);
1230         }
1231         err = snd_pcm_hw_params_set_format(handle, params, hwparams.format);
1232         if (err < 0) {
1233                 error(_("Sample format non available"));
1234                 show_available_sample_formats(params);
1235                 prg_exit(EXIT_FAILURE);
1236         }
1237         err = snd_pcm_hw_params_set_channels(handle, params, hwparams.channels);
1238         if (err < 0) {
1239                 error(_("Channels count non available"));
1240                 prg_exit(EXIT_FAILURE);
1241         }
1242
1243 #if 0
1244         err = snd_pcm_hw_params_set_periods_min(handle, params, 2);
1245         assert(err >= 0);
1246 #endif
1247         rate = hwparams.rate;
1248         err = snd_pcm_hw_params_set_rate_near(handle, params, &hwparams.rate, 0);
1249         assert(err >= 0);
1250         if ((float)rate * 1.05 < hwparams.rate || (float)rate * 0.95 > hwparams.rate) {
1251                 if (!quiet_mode) {
1252                         char plugex[64];
1253                         const char *pcmname = snd_pcm_name(handle);
1254                         fprintf(stderr, _("Warning: rate is not accurate (requested = %iHz, got = %iHz)\n"), rate, hwparams.rate);
1255                         if (! pcmname || strchr(snd_pcm_name(handle), ':'))
1256                                 *plugex = 0;
1257                         else
1258                                 snprintf(plugex, sizeof(plugex), "(-Dplug:%s)",
1259                                          snd_pcm_name(handle));
1260                         fprintf(stderr, _("         please, try the plug plugin %s\n"),
1261                                 plugex);
1262                 }
1263         }
1264         rate = hwparams.rate;
1265         if (buffer_time == 0 && buffer_frames == 0) {
1266                 err = snd_pcm_hw_params_get_buffer_time_max(params,
1267                                                             &buffer_time, 0);
1268                 assert(err >= 0);
1269                 if (buffer_time > 500000)
1270                         buffer_time = 500000;
1271         }
1272         if (period_time == 0 && period_frames == 0) {
1273                 if (buffer_time > 0)
1274                         period_time = buffer_time / 4;
1275                 else
1276                         period_frames = buffer_frames / 4;
1277         }
1278         if (period_time > 0)
1279                 err = snd_pcm_hw_params_set_period_time_near(handle, params,
1280                                                              &period_time, 0);
1281         else
1282                 err = snd_pcm_hw_params_set_period_size_near(handle, params,
1283                                                              &period_frames, 0);
1284         assert(err >= 0);
1285         if (buffer_time > 0) {
1286                 err = snd_pcm_hw_params_set_buffer_time_near(handle, params,
1287                                                              &buffer_time, 0);
1288         } else {
1289                 err = snd_pcm_hw_params_set_buffer_size_near(handle, params,
1290                                                              &buffer_frames);
1291         }
1292         assert(err >= 0);
1293         monotonic = snd_pcm_hw_params_is_monotonic(params);
1294         can_pause = snd_pcm_hw_params_can_pause(params);
1295         err = snd_pcm_hw_params(handle, params);
1296         if (err < 0) {
1297                 error(_("Unable to install hw params:"));
1298                 snd_pcm_hw_params_dump(params, log);
1299                 prg_exit(EXIT_FAILURE);
1300         }
1301         snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
1302         snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
1303         if (chunk_size == buffer_size) {
1304                 error(_("Can't use period equal to buffer size (%lu == %lu)"),
1305                       chunk_size, buffer_size);
1306                 prg_exit(EXIT_FAILURE);
1307         }
1308         snd_pcm_sw_params_current(handle, swparams);
1309         if (avail_min < 0)
1310                 n = chunk_size;
1311         else
1312                 n = (double) rate * avail_min / 1000000;
1313         err = snd_pcm_sw_params_set_avail_min(handle, swparams, n);
1314
1315         /* round up to closest transfer boundary */
1316         n = buffer_size;
1317         if (start_delay <= 0) {
1318                 start_threshold = n + (double) rate * start_delay / 1000000;
1319         } else
1320                 start_threshold = (double) rate * start_delay / 1000000;
1321         if (start_threshold < 1)
1322                 start_threshold = 1;
1323         if (start_threshold > n)
1324                 start_threshold = n;
1325         err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
1326         assert(err >= 0);
1327         if (stop_delay <= 0) 
1328                 stop_threshold = buffer_size + (double) rate * stop_delay / 1000000;
1329         else
1330                 stop_threshold = (double) rate * stop_delay / 1000000;
1331         err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
1332         assert(err >= 0);
1333
1334         if (snd_pcm_sw_params(handle, swparams) < 0) {
1335                 error(_("unable to install sw params:"));
1336                 snd_pcm_sw_params_dump(swparams, log);
1337                 prg_exit(EXIT_FAILURE);
1338         }
1339
1340         if (setup_chmap())
1341                 prg_exit(EXIT_FAILURE);
1342
1343         if (verbose)
1344                 snd_pcm_dump(handle, log);
1345
1346         bits_per_sample = snd_pcm_format_physical_width(hwparams.format);
1347         bits_per_frame = bits_per_sample * hwparams.channels;
1348         chunk_bytes = chunk_size * bits_per_frame / 8;
1349         audiobuf = realloc(audiobuf, chunk_bytes);
1350         if (audiobuf == NULL) {
1351                 error(_("not enough memory"));
1352                 prg_exit(EXIT_FAILURE);
1353         }
1354         // fprintf(stderr, "real chunk_size = %i, frags = %i, total = %i\n", chunk_size, setup.buf.block.frags, setup.buf.block.frags * chunk_size);
1355
1356         /* stereo VU-meter isn't always available... */
1357         if (vumeter == VUMETER_STEREO) {
1358                 if (hwparams.channels != 2 || !interleaved || verbose > 2)
1359                         vumeter = VUMETER_MONO;
1360         }
1361
1362         /* show mmap buffer arragment */
1363         if (mmap_flag && verbose) {
1364                 const snd_pcm_channel_area_t *areas;
1365                 snd_pcm_uframes_t offset, size = chunk_size;
1366                 int i;
1367                 err = snd_pcm_mmap_begin(handle, &areas, &offset, &size);
1368                 if (err < 0) {
1369                         error(_("snd_pcm_mmap_begin problem: %s"), snd_strerror(err));
1370                         prg_exit(EXIT_FAILURE);
1371                 }
1372                 for (i = 0; i < hwparams.channels; i++)
1373                         fprintf(stderr, "mmap_area[%i] = %p,%u,%u (%u)\n", i, areas[i].addr, areas[i].first, areas[i].step, snd_pcm_format_physical_width(hwparams.format));
1374                 /* not required, but for sure */
1375                 snd_pcm_mmap_commit(handle, offset, 0);
1376         }
1377
1378         buffer_frames = buffer_size;    /* for position test */
1379 }
1380
1381 static void init_stdin(void)
1382 {
1383         struct termios term;
1384         long flags;
1385
1386         if (!interactive)
1387                 return;
1388         if (!isatty(fileno(stdin))) {
1389                 interactive = 0;
1390                 return;
1391         }
1392         tcgetattr(fileno(stdin), &term);
1393         term_c_lflag = term.c_lflag;
1394         if (fd == fileno(stdin))
1395                 return;
1396         flags = fcntl(fileno(stdin), F_GETFL);
1397         if (flags < 0 || fcntl(fileno(stdin), F_SETFL, flags|O_NONBLOCK) < 0)
1398                 fprintf(stderr, _("stdin O_NONBLOCK flag setup failed\n"));
1399         term.c_lflag &= ~ICANON;
1400         tcsetattr(fileno(stdin), TCSANOW, &term);
1401 }
1402
1403 static void done_stdin(void)
1404 {
1405         struct termios term;
1406
1407         if (!interactive)
1408                 return;
1409         if (fd == fileno(stdin) || term_c_lflag == -1)
1410                 return;
1411         tcgetattr(fileno(stdin), &term);
1412         term.c_lflag = term_c_lflag;
1413         tcsetattr(fileno(stdin), TCSANOW, &term);
1414 }
1415
1416 static void do_pause(void)
1417 {
1418         int err;
1419         unsigned char b;
1420
1421         if (!can_pause) {
1422                 fprintf(stderr, _("\rPAUSE command ignored (no hw support)\n"));
1423                 return;
1424         }
1425         err = snd_pcm_pause(handle, 1);
1426         if (err < 0) {
1427                 error(_("pause push error: %s"), snd_strerror(err));
1428                 return;
1429         }
1430         while (1) {
1431                 while (read(fileno(stdin), &b, 1) != 1);
1432                 if (b == ' ' || b == '\r') {
1433                         while (read(fileno(stdin), &b, 1) == 1);
1434                         err = snd_pcm_pause(handle, 0);
1435                         if (err < 0)
1436                                 error(_("pause release error: %s"), snd_strerror(err));
1437                         return;
1438                 }
1439         }
1440 }
1441
1442 static void check_stdin(void)
1443 {
1444         unsigned char b;
1445
1446         if (!interactive)
1447                 return;
1448         if (fd != fileno(stdin)) {
1449                 while (read(fileno(stdin), &b, 1) == 1) {
1450                         if (b == ' ' || b == '\r') {
1451                                 while (read(fileno(stdin), &b, 1) == 1);
1452                                 fprintf(stderr, _("\r=== PAUSE ===                                                            "));
1453                                 fflush(stderr);
1454                         do_pause();
1455                                 fprintf(stderr, "                                                                          \r");
1456                                 fflush(stderr);
1457                         }
1458                 }
1459         }
1460 }
1461
1462 #ifndef timersub
1463 #define timersub(a, b, result) \
1464 do { \
1465         (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
1466         (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
1467         if ((result)->tv_usec < 0) { \
1468                 --(result)->tv_sec; \
1469                 (result)->tv_usec += 1000000; \
1470         } \
1471 } while (0)
1472 #endif
1473
1474 #ifndef timermsub
1475 #define timermsub(a, b, result) \
1476 do { \
1477         (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
1478         (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
1479         if ((result)->tv_nsec < 0) { \
1480                 --(result)->tv_sec; \
1481                 (result)->tv_nsec += 1000000000L; \
1482         } \
1483 } while (0)
1484 #endif
1485
1486 /* I/O error handler */
1487 static void xrun(void)
1488 {
1489         snd_pcm_status_t *status;
1490         int res;
1491         
1492         snd_pcm_status_alloca(&status);
1493         if ((res = snd_pcm_status(handle, status))<0) {
1494                 error(_("status error: %s"), snd_strerror(res));
1495                 prg_exit(EXIT_FAILURE);
1496         }
1497         if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) {
1498                 if (fatal_errors) {
1499                         error(_("fatal %s: %s"),
1500                                         stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1501                                         snd_strerror(res));
1502                         prg_exit(EXIT_FAILURE);
1503                 }
1504                 if (monotonic) {
1505 #ifdef HAVE_CLOCK_GETTIME
1506                         struct timespec now, diff, tstamp;
1507                         clock_gettime(CLOCK_MONOTONIC, &now);
1508                         snd_pcm_status_get_trigger_htstamp(status, &tstamp);
1509                         timermsub(&now, &tstamp, &diff);
1510                         fprintf(stderr, _("%s!!! (at least %.3f ms long)\n"),
1511                                 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1512                                 diff.tv_sec * 1000 + diff.tv_nsec / 1000000.0);
1513 #else
1514                         fprintf(stderr, "%s !!!\n", _("underrun"));
1515 #endif
1516                 } else {
1517                         struct timeval now, diff, tstamp;
1518                         gettimeofday(&now, 0);
1519                         snd_pcm_status_get_trigger_tstamp(status, &tstamp);
1520                         timersub(&now, &tstamp, &diff);
1521                         fprintf(stderr, _("%s!!! (at least %.3f ms long)\n"),
1522                                 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1523                                 diff.tv_sec * 1000 + diff.tv_usec / 1000.0);
1524                 }
1525                 if (verbose) {
1526                         fprintf(stderr, _("Status:\n"));
1527                         snd_pcm_status_dump(status, log);
1528                 }
1529                 if ((res = snd_pcm_prepare(handle))<0) {
1530                         error(_("xrun: prepare error: %s"), snd_strerror(res));
1531                         prg_exit(EXIT_FAILURE);
1532                 }
1533                 return;         /* ok, data should be accepted again */
1534         } if (snd_pcm_status_get_state(status) == SND_PCM_STATE_DRAINING) {
1535                 if (verbose) {
1536                         fprintf(stderr, _("Status(DRAINING):\n"));
1537                         snd_pcm_status_dump(status, log);
1538                 }
1539                 if (stream == SND_PCM_STREAM_CAPTURE) {
1540                         fprintf(stderr, _("capture stream format change? attempting recover...\n"));
1541                         if ((res = snd_pcm_prepare(handle))<0) {
1542                                 error(_("xrun(DRAINING): prepare error: %s"), snd_strerror(res));
1543                                 prg_exit(EXIT_FAILURE);
1544                         }
1545                         return;
1546                 }
1547         }
1548         if (verbose) {
1549                 fprintf(stderr, _("Status(R/W):\n"));
1550                 snd_pcm_status_dump(status, log);
1551         }
1552         error(_("read/write error, state = %s"), snd_pcm_state_name(snd_pcm_status_get_state(status)));
1553         prg_exit(EXIT_FAILURE);
1554 }
1555
1556 /* I/O suspend handler */
1557 static void suspend(void)
1558 {
1559         int res;
1560
1561         if (!quiet_mode)
1562                 fprintf(stderr, _("Suspended. Trying resume. ")); fflush(stderr);
1563         while ((res = snd_pcm_resume(handle)) == -EAGAIN)
1564                 sleep(1);       /* wait until suspend flag is released */
1565         if (res < 0) {
1566                 if (!quiet_mode)
1567                         fprintf(stderr, _("Failed. Restarting stream. ")); fflush(stderr);
1568                 if ((res = snd_pcm_prepare(handle)) < 0) {
1569                         error(_("suspend: prepare error: %s"), snd_strerror(res));
1570                         prg_exit(EXIT_FAILURE);
1571                 }
1572         }
1573         if (!quiet_mode)
1574                 fprintf(stderr, _("Done.\n"));
1575 }
1576
1577 static void print_vu_meter_mono(int perc, int maxperc)
1578 {
1579         const int bar_length = 50;
1580         char line[80];
1581         int val;
1582
1583         for (val = 0; val <= perc * bar_length / 100 && val < bar_length; val++)
1584                 line[val] = '#';
1585         for (; val <= maxperc * bar_length / 100 && val < bar_length; val++)
1586                 line[val] = ' ';
1587         line[val] = '+';
1588         for (++val; val <= bar_length; val++)
1589                 line[val] = ' ';
1590         if (maxperc > 99)
1591                 sprintf(line + val, "| MAX");
1592         else
1593                 sprintf(line + val, "| %02i%%", maxperc);
1594         fputs(line, stderr);
1595         if (perc > 100)
1596                 fprintf(stderr, _(" !clip  "));
1597 }
1598
1599 static void print_vu_meter_stereo(int *perc, int *maxperc)
1600 {
1601         const int bar_length = 35;
1602         char line[80];
1603         int c;
1604
1605         memset(line, ' ', sizeof(line) - 1);
1606         line[bar_length + 3] = '|';
1607
1608         for (c = 0; c < 2; c++) {
1609                 int p = perc[c] * bar_length / 100;
1610                 char tmp[4];
1611                 if (p > bar_length)
1612                         p = bar_length;
1613                 if (c)
1614                         memset(line + bar_length + 6 + 1, '#', p);
1615                 else
1616                         memset(line + bar_length - p - 1, '#', p);
1617                 p = maxperc[c] * bar_length / 100;
1618                 if (p > bar_length)
1619                         p = bar_length;
1620                 if (c)
1621                         line[bar_length + 6 + 1 + p] = '+';
1622                 else
1623                         line[bar_length - p - 1] = '+';
1624                 if (maxperc[c] > 99)
1625                         sprintf(tmp, "MAX");
1626                 else
1627                         sprintf(tmp, "%02d%%", maxperc[c]);
1628                 if (c)
1629                         memcpy(line + bar_length + 3 + 1, tmp, 3);
1630                 else
1631                         memcpy(line + bar_length, tmp, 3);
1632         }
1633         line[bar_length * 2 + 6 + 2] = 0;
1634         fputs(line, stderr);
1635 }
1636
1637 static void print_vu_meter(signed int *perc, signed int *maxperc)
1638 {
1639         if (vumeter == VUMETER_STEREO)
1640                 print_vu_meter_stereo(perc, maxperc);
1641         else
1642                 print_vu_meter_mono(*perc, *maxperc);
1643 }
1644
1645 /* peak handler */
1646 static void compute_max_peak(u_char *data, size_t count)
1647 {
1648         signed int val, max, perc[2], max_peak[2];
1649         static  int     run = 0;
1650         size_t ocount = count;
1651         int     format_little_endian = snd_pcm_format_little_endian(hwparams.format);   
1652         int ichans, c;
1653
1654         if (vumeter == VUMETER_STEREO)
1655                 ichans = 2;
1656         else
1657                 ichans = 1;
1658
1659         memset(max_peak, 0, sizeof(max_peak));
1660         switch (bits_per_sample) {
1661         case 8: {
1662                 signed char *valp = (signed char *)data;
1663                 signed char mask = snd_pcm_format_silence(hwparams.format);
1664                 c = 0;
1665                 while (count-- > 0) {
1666                         val = *valp++ ^ mask;
1667                         val = abs(val);
1668                         if (max_peak[c] < val)
1669                                 max_peak[c] = val;
1670                         if (vumeter == VUMETER_STEREO)
1671                                 c = !c;
1672                 }
1673                 break;
1674         }
1675         case 16: {
1676                 signed short *valp = (signed short *)data;
1677                 signed short mask = snd_pcm_format_silence_16(hwparams.format);
1678                 signed short sval;
1679
1680                 count /= 2;
1681                 c = 0;
1682                 while (count-- > 0) {
1683                         if (format_little_endian)
1684                                 sval = le16toh(*valp);
1685                         else
1686                                 sval = be16toh(*valp);
1687                         sval = abs(sval) ^ mask;
1688                         if (max_peak[c] < sval)
1689                                 max_peak[c] = sval;
1690                         valp++;
1691                         if (vumeter == VUMETER_STEREO)
1692                                 c = !c;
1693                 }
1694                 break;
1695         }
1696         case 24: {
1697                 unsigned char *valp = data;
1698                 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1699
1700                 count /= 3;
1701                 c = 0;
1702                 while (count-- > 0) {
1703                         if (format_little_endian) {
1704                                 val = valp[0] | (valp[1]<<8) | (valp[2]<<16);
1705                         } else {
1706                                 val = (valp[0]<<16) | (valp[1]<<8) | valp[2];
1707                         }
1708                         /* Correct signed bit in 32-bit value */
1709                         if (val & (1<<(bits_per_sample-1))) {
1710                                 val |= 0xff<<24;        /* Negate upper bits too */
1711                         }
1712                         val = abs(val) ^ mask;
1713                         if (max_peak[c] < val)
1714                                 max_peak[c] = val;
1715                         valp += 3;
1716                         if (vumeter == VUMETER_STEREO)
1717                                 c = !c;
1718                 }
1719                 break;
1720         }
1721         case 32: {
1722                 signed int *valp = (signed int *)data;
1723                 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1724
1725                 count /= 4;
1726                 c = 0;
1727                 while (count-- > 0) {
1728                         if (format_little_endian)
1729                                 val = le32toh(*valp);
1730                         else
1731                                 val = be32toh(*valp);
1732                         val = abs(val) ^ mask;
1733                         if (max_peak[c] < val)
1734                                 max_peak[c] = val;
1735                         valp++;
1736                         if (vumeter == VUMETER_STEREO)
1737                                 c = !c;
1738                 }
1739                 break;
1740         }
1741         default:
1742                 if (run == 0) {
1743                         fprintf(stderr, _("Unsupported bit size %d.\n"), (int)bits_per_sample);
1744                         run = 1;
1745                 }
1746                 return;
1747         }
1748         max = 1 << (bits_per_sample-1);
1749         if (max <= 0)
1750                 max = 0x7fffffff;
1751
1752         for (c = 0; c < ichans; c++) {
1753                 if (bits_per_sample > 16)
1754                         perc[c] = max_peak[c] / (max / 100);
1755                 else
1756                         perc[c] = max_peak[c] * 100 / max;
1757         }
1758
1759         if (interleaved && verbose <= 2) {
1760                 static int maxperc[2];
1761                 static time_t t=0;
1762                 const time_t tt=time(NULL);
1763                 if(tt>t) {
1764                         t=tt;
1765                         maxperc[0] = 0;
1766                         maxperc[1] = 0;
1767                 }
1768                 for (c = 0; c < ichans; c++)
1769                         if (perc[c] > maxperc[c])
1770                                 maxperc[c] = perc[c];
1771
1772                 putc('\r', stderr);
1773                 print_vu_meter(perc, maxperc);
1774                 fflush(stderr);
1775         }
1776         else if(verbose==3) {
1777                 fprintf(stderr, _("Max peak (%li samples): 0x%08x "), (long)ocount, max_peak[0]);
1778                 for (val = 0; val < 20; val++)
1779                         if (val <= perc[0] / 5)
1780                                 putc('#', stderr);
1781                         else
1782                                 putc(' ', stderr);
1783                 fprintf(stderr, " %i%%\n", perc[0]);
1784                 fflush(stderr);
1785         }
1786 }
1787
1788 static void do_test_position(void)
1789 {
1790         static long counter = 0;
1791         static time_t tmr = -1;
1792         time_t now;
1793         static float availsum, delaysum, samples;
1794         static snd_pcm_sframes_t maxavail, maxdelay;
1795         static snd_pcm_sframes_t minavail, mindelay;
1796         static snd_pcm_sframes_t badavail = 0, baddelay = 0;
1797         snd_pcm_sframes_t outofrange;
1798         snd_pcm_sframes_t avail, delay;
1799         int err;
1800
1801         err = snd_pcm_avail_delay(handle, &avail, &delay);
1802         if (err < 0)
1803                 return;
1804         outofrange = (test_coef * (snd_pcm_sframes_t)buffer_frames) / 2;
1805         if (avail > outofrange || avail < -outofrange ||
1806             delay > outofrange || delay < -outofrange) {
1807           badavail = avail; baddelay = delay;
1808           availsum = delaysum = samples = 0;
1809           maxavail = maxdelay = 0;
1810           minavail = mindelay = buffer_frames * 16;
1811           fprintf(stderr, _("Suspicious buffer position (%li total): "
1812                 "avail = %li, delay = %li, buffer = %li\n"),
1813                 ++counter, (long)avail, (long)delay, (long)buffer_frames);
1814         } else if (verbose) {
1815                 time(&now);
1816                 if (tmr == (time_t) -1) {
1817                         tmr = now;
1818                         availsum = delaysum = samples = 0;
1819                         maxavail = maxdelay = 0;
1820                         minavail = mindelay = buffer_frames * 16;
1821                 }
1822                 if (avail > maxavail)
1823                         maxavail = avail;
1824                 if (delay > maxdelay)
1825                         maxdelay = delay;
1826                 if (avail < minavail)
1827                         minavail = avail;
1828                 if (delay < mindelay)
1829                         mindelay = delay;
1830                 availsum += avail;
1831                 delaysum += delay;
1832                 samples++;
1833                 if (avail != 0 && now != tmr) {
1834                         fprintf(stderr, "BUFPOS: avg%li/%li "
1835                                 "min%li/%li max%li/%li (%li) (%li:%li/%li)\n",
1836                                 (long)(availsum / samples),
1837                                 (long)(delaysum / samples),
1838                                 (long)minavail, (long)mindelay,
1839                                 (long)maxavail, (long)maxdelay,
1840                                 (long)buffer_frames,
1841                                 counter, badavail, baddelay);
1842                         tmr = now;
1843                 }
1844         }
1845 }
1846
1847 /*
1848  */
1849 #ifdef CONFIG_SUPPORT_CHMAP
1850 static u_char *remap_data(u_char *data, size_t count)
1851 {
1852         static u_char *tmp, *src, *dst;
1853         static size_t tmp_size;
1854         size_t sample_bytes = bits_per_sample / 8;
1855         size_t step = bits_per_frame / 8;
1856         size_t chunk_bytes;
1857         unsigned int ch, i;
1858
1859         if (!hw_map)
1860                 return data;
1861
1862         chunk_bytes = count * bits_per_frame / 8;
1863         if (tmp_size < chunk_bytes) {
1864                 free(tmp);
1865                 tmp = malloc(chunk_bytes);
1866                 if (!tmp) {
1867                         error(_("not enough memory"));
1868                         exit(1);
1869                 }
1870                 tmp_size = count;
1871         }
1872
1873         src = data;
1874         dst = tmp;
1875         for (i = 0; i < count; i++) {
1876                 for (ch = 0; ch < hwparams.channels; ch++) {
1877                         memcpy(dst, src + sample_bytes * hw_map[ch],
1878                                sample_bytes);
1879                         dst += sample_bytes;
1880                 }
1881                 src += step;
1882         }
1883         return tmp;
1884 }
1885
1886 static u_char **remap_datav(u_char **data, size_t count)
1887 {
1888         static u_char **tmp;
1889         unsigned int ch;
1890
1891         if (!hw_map)
1892                 return data;
1893
1894         if (!tmp) {
1895                 tmp = malloc(sizeof(*tmp) * hwparams.channels);
1896                 if (!tmp) {
1897                         error(_("not enough memory"));
1898                         exit(1);
1899                 }
1900                 for (ch = 0; ch < hwparams.channels; ch++)
1901                         tmp[ch] = data[hw_map[ch]];
1902         }
1903         return tmp;
1904 }
1905 #else
1906 #define remap_data(data, count)         (data)
1907 #define remap_datav(data, count)        (data)
1908 #endif
1909
1910 /*
1911  *  write function
1912  */
1913
1914 static ssize_t pcm_write(u_char *data, size_t count)
1915 {
1916         ssize_t r;
1917         ssize_t result = 0;
1918
1919         if (count < chunk_size) {
1920                 snd_pcm_format_set_silence(hwparams.format, data + count * bits_per_frame / 8, (chunk_size - count) * hwparams.channels);
1921                 count = chunk_size;
1922         }
1923         data = remap_data(data, count);
1924         while (count > 0 && !in_aborting) {
1925                 if (test_position)
1926                         do_test_position();
1927                 check_stdin();
1928                 r = writei_func(handle, data, count);
1929                 if (test_position)
1930                         do_test_position();
1931                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
1932                         if (!test_nowait)
1933                                 snd_pcm_wait(handle, 100);
1934                 } else if (r == -EPIPE) {
1935                         xrun();
1936                 } else if (r == -ESTRPIPE) {
1937                         suspend();
1938                 } else if (r < 0) {
1939                         error(_("write error: %s"), snd_strerror(r));
1940                         prg_exit(EXIT_FAILURE);
1941                 }
1942                 if (r > 0) {
1943                         if (vumeter)
1944                                 compute_max_peak(data, r * hwparams.channels);
1945                         result += r;
1946                         count -= r;
1947                         data += r * bits_per_frame / 8;
1948                 }
1949         }
1950         return result;
1951 }
1952
1953 static ssize_t pcm_writev(u_char **data, unsigned int channels, size_t count)
1954 {
1955         ssize_t r;
1956         size_t result = 0;
1957
1958         if (count != chunk_size) {
1959                 unsigned int channel;
1960                 size_t offset = count;
1961                 size_t remaining = chunk_size - count;
1962                 for (channel = 0; channel < channels; channel++)
1963                         snd_pcm_format_set_silence(hwparams.format, data[channel] + offset * bits_per_sample / 8, remaining);
1964                 count = chunk_size;
1965         }
1966         data = remap_datav(data, count);
1967         while (count > 0 && !in_aborting) {
1968                 unsigned int channel;
1969                 void *bufs[channels];
1970                 size_t offset = result;
1971                 for (channel = 0; channel < channels; channel++)
1972                         bufs[channel] = data[channel] + offset * bits_per_sample / 8;
1973                 if (test_position)
1974                         do_test_position();
1975                 check_stdin();
1976                 r = writen_func(handle, bufs, count);
1977                 if (test_position)
1978                         do_test_position();
1979                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
1980                         if (!test_nowait)
1981                                 snd_pcm_wait(handle, 100);
1982                 } else if (r == -EPIPE) {
1983                         xrun();
1984                 } else if (r == -ESTRPIPE) {
1985                         suspend();
1986                 } else if (r < 0) {
1987                         error(_("writev error: %s"), snd_strerror(r));
1988                         prg_exit(EXIT_FAILURE);
1989                 }
1990                 if (r > 0) {
1991                         if (vumeter) {
1992                                 for (channel = 0; channel < channels; channel++)
1993                                         compute_max_peak(data[channel], r);
1994                         }
1995                         result += r;
1996                         count -= r;
1997                 }
1998         }
1999         return result;
2000 }
2001
2002 /*
2003  *  read function
2004  */
2005
2006 static ssize_t pcm_read(u_char *data, size_t rcount)
2007 {
2008         ssize_t r;
2009         size_t result = 0;
2010         size_t count = rcount;
2011
2012         if (count != chunk_size) {
2013                 count = chunk_size;
2014         }
2015
2016         while (count > 0 && !in_aborting) {
2017                 if (test_position)
2018                         do_test_position();
2019                 check_stdin();
2020                 r = readi_func(handle, data, count);
2021                 if (test_position)
2022                         do_test_position();
2023                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2024                         if (!test_nowait)
2025                                 snd_pcm_wait(handle, 100);
2026                 } else if (r == -EPIPE) {
2027                         xrun();
2028                 } else if (r == -ESTRPIPE) {
2029                         suspend();
2030                 } else if (r < 0) {
2031                         error(_("read error: %s"), snd_strerror(r));
2032                         prg_exit(EXIT_FAILURE);
2033                 }
2034                 if (r > 0) {
2035                         if (vumeter)
2036                                 compute_max_peak(data, r * hwparams.channels);
2037                         result += r;
2038                         count -= r;
2039                         data += r * bits_per_frame / 8;
2040                 }
2041         }
2042         return result;
2043 }
2044
2045 static ssize_t pcm_readv(u_char **data, unsigned int channels, size_t rcount)
2046 {
2047         ssize_t r;
2048         size_t result = 0;
2049         size_t count = rcount;
2050
2051         if (count != chunk_size) {
2052                 count = chunk_size;
2053         }
2054
2055         while (count > 0 && !in_aborting) {
2056                 unsigned int channel;
2057                 void *bufs[channels];
2058                 size_t offset = result;
2059                 for (channel = 0; channel < channels; channel++)
2060                         bufs[channel] = data[channel] + offset * bits_per_sample / 8;
2061                 if (test_position)
2062                         do_test_position();
2063                 check_stdin();
2064                 r = readn_func(handle, bufs, count);
2065                 if (test_position)
2066                         do_test_position();
2067                 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2068                         if (!test_nowait)
2069                                 snd_pcm_wait(handle, 100);
2070                 } else if (r == -EPIPE) {
2071                         xrun();
2072                 } else if (r == -ESTRPIPE) {
2073                         suspend();
2074                 } else if (r < 0) {
2075                         error(_("readv error: %s"), snd_strerror(r));
2076                         prg_exit(EXIT_FAILURE);
2077                 }
2078                 if (r > 0) {
2079                         if (vumeter) {
2080                                 for (channel = 0; channel < channels; channel++)
2081                                         compute_max_peak(data[channel], r);
2082                         }
2083                         result += r;
2084                         count -= r;
2085                 }
2086         }
2087         return result;
2088 }
2089
2090 /*
2091  *  ok, let's play a .voc file
2092  */
2093
2094 static ssize_t voc_pcm_write(u_char *data, size_t count)
2095 {
2096         ssize_t result = count, r;
2097         size_t size;
2098
2099         while (count > 0) {
2100                 size = count;
2101                 if (size > chunk_bytes - buffer_pos)
2102                         size = chunk_bytes - buffer_pos;
2103                 memcpy(audiobuf + buffer_pos, data, size);
2104                 data += size;
2105                 count -= size;
2106                 buffer_pos += size;
2107                 if ((size_t)buffer_pos == chunk_bytes) {
2108                         if ((size_t)(r = pcm_write(audiobuf, chunk_size)) != chunk_size)
2109                                 return r;
2110                         buffer_pos = 0;
2111                 }
2112         }
2113         return result;
2114 }
2115
2116 static void voc_write_silence(unsigned x)
2117 {
2118         unsigned l;
2119         u_char *buf;
2120
2121         buf = (u_char *) malloc(chunk_bytes);
2122         if (buf == NULL) {
2123                 error(_("can't allocate buffer for silence"));
2124                 return;         /* not fatal error */
2125         }
2126         snd_pcm_format_set_silence(hwparams.format, buf, chunk_size * hwparams.channels);
2127         while (x > 0 && !in_aborting) {
2128                 l = x;
2129                 if (l > chunk_size)
2130                         l = chunk_size;
2131                 if (voc_pcm_write(buf, l) != (ssize_t)l) {
2132                         error(_("write error"));
2133                         prg_exit(EXIT_FAILURE);
2134                 }
2135                 x -= l;
2136         }
2137         free(buf);
2138 }
2139
2140 static void voc_pcm_flush(void)
2141 {
2142         if (buffer_pos > 0) {
2143                 size_t b;
2144                 if (snd_pcm_format_set_silence(hwparams.format, audiobuf + buffer_pos, chunk_bytes - buffer_pos * 8 / bits_per_sample) < 0)
2145                         fprintf(stderr, _("voc_pcm_flush - silence error"));
2146                 b = chunk_size;
2147                 if (pcm_write(audiobuf, b) != (ssize_t)b)
2148                         error(_("voc_pcm_flush error"));
2149         }
2150         snd_pcm_nonblock(handle, 0);
2151         snd_pcm_drain(handle);
2152         snd_pcm_nonblock(handle, nonblock);
2153 }
2154
2155 static void voc_play(int fd, int ofs, char *name)
2156 {
2157         int l;
2158         VocBlockType *bp;
2159         VocVoiceData *vd;
2160         VocExtBlock *eb;
2161         size_t nextblock, in_buffer;
2162         u_char *data, *buf;
2163         char was_extended = 0, output = 0;
2164         u_short *sp, repeat = 0;
2165         off64_t filepos = 0;
2166
2167 #define COUNT(x)        nextblock -= x; in_buffer -= x; data += x
2168 #define COUNT1(x)       in_buffer -= x; data += x
2169
2170         data = buf = (u_char *)malloc(64 * 1024);
2171         buffer_pos = 0;
2172         if (data == NULL) {
2173                 error(_("malloc error"));
2174                 prg_exit(EXIT_FAILURE);
2175         }
2176         if (!quiet_mode) {
2177                 fprintf(stderr, _("Playing Creative Labs Channel file '%s'...\n"), name);
2178         }
2179         /* first we waste the rest of header, ugly but we don't need seek */
2180         while (ofs > (ssize_t)chunk_bytes) {
2181                 if ((size_t)safe_read(fd, buf, chunk_bytes) != chunk_bytes) {
2182                         error(_("read error"));
2183                         prg_exit(EXIT_FAILURE);
2184                 }
2185                 ofs -= chunk_bytes;
2186         }
2187         if (ofs) {
2188                 if (safe_read(fd, buf, ofs) != ofs) {
2189                         error(_("read error"));
2190                         prg_exit(EXIT_FAILURE);
2191                 }
2192         }
2193         hwparams.format = DEFAULT_FORMAT;
2194         hwparams.channels = 1;
2195         hwparams.rate = DEFAULT_SPEED;
2196         set_params();
2197
2198         in_buffer = nextblock = 0;
2199         while (!in_aborting) {
2200               Fill_the_buffer:  /* need this for repeat */
2201                 if (in_buffer < 32) {
2202                         /* move the rest of buffer to pos 0 and fill the buf up */
2203                         if (in_buffer)
2204                                 memcpy(buf, data, in_buffer);
2205                         data = buf;
2206                         if ((l = safe_read(fd, buf + in_buffer, chunk_bytes - in_buffer)) > 0)
2207                                 in_buffer += l;
2208                         else if (!in_buffer) {
2209                                 /* the file is truncated, so simulate 'Terminator' 
2210                                    and reduce the datablock for safe landing */
2211                                 nextblock = buf[0] = 0;
2212                                 if (l == -1) {
2213                                         perror(name);
2214                                         prg_exit(EXIT_FAILURE);
2215                                 }
2216                         }
2217                 }
2218                 while (!nextblock) {    /* this is a new block */
2219                         if (in_buffer < sizeof(VocBlockType))
2220                                 goto __end;
2221                         bp = (VocBlockType *) data;
2222                         COUNT1(sizeof(VocBlockType));
2223                         nextblock = VOC_DATALEN(bp);
2224                         if (output && !quiet_mode)
2225                                 fprintf(stderr, "\n");  /* write /n after ASCII-out */
2226                         output = 0;
2227                         switch (bp->type) {
2228                         case 0:
2229 #if 0
2230                                 d_printf("Terminator\n");
2231 #endif
2232                                 return;         /* VOC-file stop */
2233                         case 1:
2234                                 vd = (VocVoiceData *) data;
2235                                 COUNT1(sizeof(VocVoiceData));
2236                                 /* we need a SYNC, before we can set new SPEED, STEREO ... */
2237
2238                                 if (!was_extended) {
2239                                         hwparams.rate = (int) (vd->tc);
2240                                         hwparams.rate = 1000000 / (256 - hwparams.rate);
2241 #if 0
2242                                         d_printf("Channel data %d Hz\n", dsp_speed);
2243 #endif
2244                                         if (vd->pack) {         /* /dev/dsp can't it */
2245                                                 error(_("can't play packed .voc files"));
2246                                                 return;
2247                                         }
2248                                         if (hwparams.channels == 2)             /* if we are in Stereo-Mode, switch back */
2249                                                 hwparams.channels = 1;
2250                                 } else {        /* there was extended block */
2251                                         hwparams.channels = 2;
2252                                         was_extended = 0;
2253                                 }
2254                                 set_params();
2255                                 break;
2256                         case 2: /* nothing to do, pure data */
2257 #if 0
2258                                 d_printf("Channel continuation\n");
2259 #endif
2260                                 break;
2261                         case 3: /* a silence block, no data, only a count */
2262                                 sp = (u_short *) data;
2263                                 COUNT1(sizeof(u_short));
2264                                 hwparams.rate = (int) (*data);
2265                                 COUNT1(1);
2266                                 hwparams.rate = 1000000 / (256 - hwparams.rate);
2267                                 set_params();
2268 #if 0
2269                                 {
2270                                         size_t silence;
2271                                         silence = (((size_t) * sp) * 1000) / hwparams.rate;
2272                                         d_printf("Silence for %d ms\n", (int) silence);
2273                                 }
2274 #endif
2275                                 voc_write_silence(*sp);
2276                                 break;
2277                         case 4: /* a marker for syncronisation, no effect */
2278                                 sp = (u_short *) data;
2279                                 COUNT1(sizeof(u_short));
2280 #if 0
2281                                 d_printf("Marker %d\n", *sp);
2282 #endif
2283                                 break;
2284                         case 5: /* ASCII text, we copy to stderr */
2285                                 output = 1;
2286 #if 0
2287                                 d_printf("ASCII - text :\n");
2288 #endif
2289                                 break;
2290                         case 6: /* repeat marker, says repeatcount */
2291                                 /* my specs don't say it: maybe this can be recursive, but
2292                                    I don't think somebody use it */
2293                                 repeat = *(u_short *) data;
2294                                 COUNT1(sizeof(u_short));
2295 #if 0
2296                                 d_printf("Repeat loop %d times\n", repeat);
2297 #endif
2298                                 if (filepos >= 0) {     /* if < 0, one seek fails, why test another */
2299                                         if ((filepos = lseek64(fd, 0, 1)) < 0) {
2300                                                 error(_("can't play loops; %s isn't seekable\n"), name);
2301                                                 repeat = 0;
2302                                         } else {
2303                                                 filepos -= in_buffer;   /* set filepos after repeat */
2304                                         }
2305                                 } else {
2306                                         repeat = 0;
2307                                 }
2308                                 break;
2309                         case 7: /* ok, lets repeat that be rewinding tape */
2310                                 if (repeat) {
2311                                         if (repeat != 0xFFFF) {
2312 #if 0
2313                                                 d_printf("Repeat loop %d\n", repeat);
2314 #endif
2315                                                 --repeat;
2316                                         }
2317 #if 0
2318                                         else
2319                                                 d_printf("Neverending loop\n");
2320 #endif
2321                                         lseek64(fd, filepos, 0);
2322                                         in_buffer = 0;  /* clear the buffer */
2323                                         goto Fill_the_buffer;
2324                                 }
2325 #if 0
2326                                 else
2327                                         d_printf("End repeat loop\n");
2328 #endif
2329                                 break;
2330                         case 8: /* the extension to play Stereo, I have SB 1.0 :-( */
2331                                 was_extended = 1;
2332                                 eb = (VocExtBlock *) data;
2333                                 COUNT1(sizeof(VocExtBlock));
2334                                 hwparams.rate = (int) (eb->tc);
2335                                 hwparams.rate = 256000000L / (65536 - hwparams.rate);
2336                                 hwparams.channels = eb->mode == VOC_MODE_STEREO ? 2 : 1;
2337                                 if (hwparams.channels == 2)
2338                                         hwparams.rate = hwparams.rate >> 1;
2339                                 if (eb->pack) {         /* /dev/dsp can't it */
2340                                         error(_("can't play packed .voc files"));
2341                                         return;
2342                                 }
2343 #if 0
2344                                 d_printf("Extended block %s %d Hz\n",
2345                                          (eb->mode ? "Stereo" : "Mono"), dsp_speed);
2346 #endif
2347                                 break;
2348                         default:
2349                                 error(_("unknown blocktype %d. terminate."), bp->type);
2350                                 return;
2351                         }       /* switch (bp->type) */
2352                 }               /* while (! nextblock)  */
2353                 /* put nextblock data bytes to dsp */
2354                 l = in_buffer;
2355                 if (nextblock < (size_t)l)
2356                         l = nextblock;
2357                 if (l) {
2358                         if (output && !quiet_mode) {
2359                                 if (write(2, data, l) != l) {   /* to stderr */
2360                                         error(_("write error"));
2361                                         prg_exit(EXIT_FAILURE);
2362                                 }
2363                         } else {
2364                                 if (voc_pcm_write(data, l) != l) {
2365                                         error(_("write error"));
2366                                         prg_exit(EXIT_FAILURE);
2367                                 }
2368                         }
2369                         COUNT(l);
2370                 }
2371         }                       /* while(1) */
2372       __end:
2373         voc_pcm_flush();
2374         free(buf);
2375 }
2376 /* that was a big one, perhaps somebody split it :-) */
2377
2378 /* setting the globals for playing raw data */
2379 static void init_raw_data(void)
2380 {
2381         hwparams = rhwparams;
2382 }
2383
2384 /* calculate the data count to read from/to dsp */
2385 static off64_t calc_count(void)
2386 {
2387         off64_t count;
2388
2389         if (timelimit == 0) {
2390                 count = pbrec_count;
2391         } else {
2392                 count = snd_pcm_format_size(hwparams.format, hwparams.rate * hwparams.channels);
2393                 count *= (off64_t)timelimit;
2394         }
2395         return count < pbrec_count ? count : pbrec_count;
2396 }
2397
2398 /* write a .VOC-header */
2399 static void begin_voc(int fd, size_t cnt)
2400 {
2401         VocHeader vh;
2402         VocBlockType bt;
2403         VocVoiceData vd;
2404         VocExtBlock eb;
2405
2406         memcpy(vh.magic, VOC_MAGIC_STRING, 20);
2407         vh.headerlen = LE_SHORT(sizeof(VocHeader));
2408         vh.version = LE_SHORT(VOC_ACTUAL_VERSION);
2409         vh.coded_ver = LE_SHORT(0x1233 - VOC_ACTUAL_VERSION);
2410
2411         if (write(fd, &vh, sizeof(VocHeader)) != sizeof(VocHeader)) {
2412                 error(_("write error"));
2413                 prg_exit(EXIT_FAILURE);
2414         }
2415         if (hwparams.channels > 1) {
2416                 /* write an extended block */
2417                 bt.type = 8;
2418                 bt.datalen = 4;
2419                 bt.datalen_m = bt.datalen_h = 0;
2420                 if (write(fd, &bt, sizeof(VocBlockType)) != sizeof(VocBlockType)) {
2421                         error(_("write error"));
2422                         prg_exit(EXIT_FAILURE);
2423                 }
2424                 eb.tc = LE_SHORT(65536 - 256000000L / (hwparams.rate << 1));
2425                 eb.pack = 0;
2426                 eb.mode = 1;
2427                 if (write(fd, &eb, sizeof(VocExtBlock)) != sizeof(VocExtBlock)) {
2428                         error(_("write error"));
2429                         prg_exit(EXIT_FAILURE);
2430                 }
2431         }
2432         bt.type = 1;
2433         cnt += sizeof(VocVoiceData);    /* Channel_data block follows */
2434         bt.datalen = (u_char) (cnt & 0xFF);
2435         bt.datalen_m = (u_char) ((cnt & 0xFF00) >> 8);
2436         bt.datalen_h = (u_char) ((cnt & 0xFF0000) >> 16);
2437         if (write(fd, &bt, sizeof(VocBlockType)) != sizeof(VocBlockType)) {
2438                 error(_("write error"));
2439                 prg_exit(EXIT_FAILURE);
2440         }
2441         vd.tc = (u_char) (256 - (1000000 / hwparams.rate));
2442         vd.pack = 0;
2443         if (write(fd, &vd, sizeof(VocVoiceData)) != sizeof(VocVoiceData)) {
2444                 error(_("write error"));
2445                 prg_exit(EXIT_FAILURE);
2446         }
2447 }
2448
2449 /* write a WAVE-header */
2450 static void begin_wave(int fd, size_t cnt)
2451 {
2452         WaveHeader h;
2453         WaveFmtBody f;
2454         WaveChunkHeader cf, cd;
2455         int bits;
2456         u_int tmp;
2457         u_short tmp2;
2458
2459         /* WAVE cannot handle greater than 32bit (signed?) int */
2460         if (cnt == (size_t)-2)
2461                 cnt = 0x7fffff00;
2462
2463         bits = 8;
2464         switch ((unsigned long) hwparams.format) {
2465         case SND_PCM_FORMAT_U8:
2466                 bits = 8;
2467                 break;
2468         case SND_PCM_FORMAT_S16_LE:
2469                 bits = 16;
2470                 break;
2471         case SND_PCM_FORMAT_S32_LE:
2472         case SND_PCM_FORMAT_FLOAT_LE:
2473                 bits = 32;
2474                 break;
2475         case SND_PCM_FORMAT_S24_LE:
2476         case SND_PCM_FORMAT_S24_3LE:
2477                 bits = 24;
2478                 break;
2479         default:
2480                 error(_("Wave doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2481                 prg_exit(EXIT_FAILURE);
2482         }
2483         h.magic = WAV_RIFF;
2484         tmp = cnt + sizeof(WaveHeader) + sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + sizeof(WaveChunkHeader) - 8;
2485         h.length = LE_INT(tmp);
2486         h.type = WAV_WAVE;
2487
2488         cf.type = WAV_FMT;
2489         cf.length = LE_INT(16);
2490
2491         if (hwparams.format == SND_PCM_FORMAT_FLOAT_LE)
2492                 f.format = LE_SHORT(WAV_FMT_IEEE_FLOAT);
2493         else
2494                 f.format = LE_SHORT(WAV_FMT_PCM);
2495         f.channels = LE_SHORT(hwparams.channels);
2496         f.sample_fq = LE_INT(hwparams.rate);
2497 #if 0
2498         tmp2 = (samplesize == 8) ? 1 : 2;
2499         f.byte_p_spl = LE_SHORT(tmp2);
2500         tmp = dsp_speed * hwparams.channels * (u_int) tmp2;
2501 #else
2502         tmp2 = hwparams.channels * snd_pcm_format_physical_width(hwparams.format) / 8;
2503         f.byte_p_spl = LE_SHORT(tmp2);
2504         tmp = (u_int) tmp2 * hwparams.rate;
2505 #endif
2506         f.byte_p_sec = LE_INT(tmp);
2507         f.bit_p_spl = LE_SHORT(bits);
2508
2509         cd.type = WAV_DATA;
2510         cd.length = LE_INT(cnt);
2511
2512         if (write(fd, &h, sizeof(WaveHeader)) != sizeof(WaveHeader) ||
2513             write(fd, &cf, sizeof(WaveChunkHeader)) != sizeof(WaveChunkHeader) ||
2514             write(fd, &f, sizeof(WaveFmtBody)) != sizeof(WaveFmtBody) ||
2515             write(fd, &cd, sizeof(WaveChunkHeader)) != sizeof(WaveChunkHeader)) {
2516                 error(_("write error"));
2517                 prg_exit(EXIT_FAILURE);
2518         }
2519 }
2520
2521 /* write a Au-header */
2522 static void begin_au(int fd, size_t cnt)
2523 {
2524         AuHeader ah;
2525
2526         ah.magic = AU_MAGIC;
2527         ah.hdr_size = BE_INT(24);
2528         ah.data_size = BE_INT(cnt);
2529         switch ((unsigned long) hwparams.format) {
2530         case SND_PCM_FORMAT_MU_LAW:
2531                 ah.encoding = BE_INT(AU_FMT_ULAW);
2532                 break;
2533         case SND_PCM_FORMAT_U8:
2534                 ah.encoding = BE_INT(AU_FMT_LIN8);
2535                 break;
2536         case SND_PCM_FORMAT_S16_BE:
2537                 ah.encoding = BE_INT(AU_FMT_LIN16);
2538                 break;
2539         default:
2540                 error(_("Sparc Audio doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2541                 prg_exit(EXIT_FAILURE);
2542         }
2543         ah.sample_rate = BE_INT(hwparams.rate);
2544         ah.channels = BE_INT(hwparams.channels);
2545         if (write(fd, &ah, sizeof(AuHeader)) != sizeof(AuHeader)) {
2546                 error(_("write error"));
2547                 prg_exit(EXIT_FAILURE);
2548         }
2549 }
2550
2551 /* closing .VOC */
2552 static void end_voc(int fd)
2553 {
2554         off64_t length_seek;
2555         VocBlockType bt;
2556         size_t cnt;
2557         char dummy = 0;         /* Write a Terminator */
2558
2559         if (write(fd, &dummy, 1) != 1) {
2560                 error(_("write error"));
2561                 prg_exit(EXIT_FAILURE);
2562         }
2563         length_seek = sizeof(VocHeader);
2564         if (hwparams.channels > 1)
2565                 length_seek += sizeof(VocBlockType) + sizeof(VocExtBlock);
2566         bt.type = 1;
2567         cnt = fdcount;
2568         cnt += sizeof(VocVoiceData);    /* Channel_data block follows */
2569         if (cnt > 0x00ffffff)
2570                 cnt = 0x00ffffff;
2571         bt.datalen = (u_char) (cnt & 0xFF);
2572         bt.datalen_m = (u_char) ((cnt & 0xFF00) >> 8);
2573         bt.datalen_h = (u_char) ((cnt & 0xFF0000) >> 16);
2574         if (lseek64(fd, length_seek, SEEK_SET) == length_seek)
2575                 write(fd, &bt, sizeof(VocBlockType));
2576         if (fd != 1)
2577                 close(fd);
2578 }
2579
2580 static void end_wave(int fd)
2581 {                               /* only close output */
2582         WaveChunkHeader cd;
2583         off64_t length_seek;
2584         off64_t filelen;
2585         u_int rifflen;
2586         
2587         length_seek = sizeof(WaveHeader) +
2588                       sizeof(WaveChunkHeader) +
2589                       sizeof(WaveFmtBody);
2590         cd.type = WAV_DATA;
2591         cd.length = fdcount > 0x7fffffff ? LE_INT(0x7fffffff) : LE_INT(fdcount);
2592         filelen = fdcount + 2*sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + 4;
2593         rifflen = filelen > 0x7fffffff ? LE_INT(0x7fffffff) : LE_INT(filelen);
2594         if (lseek64(fd, 4, SEEK_SET) == 4)
2595                 write(fd, &rifflen, 4);
2596         if (lseek64(fd, length_seek, SEEK_SET) == length_seek)
2597                 write(fd, &cd, sizeof(WaveChunkHeader));
2598         if (fd != 1)
2599                 close(fd);
2600 }
2601
2602 static void end_au(int fd)
2603 {                               /* only close output */
2604         AuHeader ah;
2605         off64_t length_seek;
2606         
2607         length_seek = (char *)&ah.data_size - (char *)&ah;
2608         ah.data_size = fdcount > 0xffffffff ? 0xffffffff : BE_INT(fdcount);
2609         if (lseek64(fd, length_seek, SEEK_SET) == length_seek)
2610                 write(fd, &ah.data_size, sizeof(ah.data_size));
2611         if (fd != 1)
2612                 close(fd);
2613 }
2614
2615 static void header(int rtype, char *name)
2616 {
2617         if (!quiet_mode) {
2618                 if (! name)
2619                         name = (stream == SND_PCM_STREAM_PLAYBACK) ? "stdout" : "stdin";
2620                 fprintf(stderr, "%s %s '%s' : ",
2621                         (stream == SND_PCM_STREAM_PLAYBACK) ? _("Playing") : _("Recording"),
2622                         gettext(fmt_rec_table[rtype].what),
2623                         name);
2624                 fprintf(stderr, "%s, ", snd_pcm_format_description(hwparams.format));
2625                 fprintf(stderr, _("Rate %d Hz, "), hwparams.rate);
2626                 if (hwparams.channels == 1)
2627                         fprintf(stderr, _("Mono"));
2628                 else if (hwparams.channels == 2)
2629                         fprintf(stderr, _("Stereo"));
2630                 else
2631                         fprintf(stderr, _("Channels %i"), hwparams.channels);
2632                 fprintf(stderr, "\n");
2633         }
2634 }
2635
2636 /* playing raw data */
2637
2638 static void playback_go(int fd, size_t loaded, off64_t count, int rtype, char *name)
2639 {
2640         int l, r;
2641         off64_t written = 0;
2642         off64_t c;
2643
2644         header(rtype, name);
2645         set_params();
2646
2647         while (loaded > chunk_bytes && written < count && !in_aborting) {
2648                 if (pcm_write(audiobuf + written, chunk_size) <= 0)
2649                         return;
2650                 written += chunk_bytes;
2651                 loaded -= chunk_bytes;
2652         }
2653         if (written > 0 && loaded > 0)
2654                 memmove(audiobuf, audiobuf + written, loaded);
2655
2656         l = loaded;
2657         while (written < count && !in_aborting) {
2658                 do {
2659                         c = count - written;
2660                         if (c > chunk_bytes)
2661                                 c = chunk_bytes;
2662                         c -= l;
2663
2664                         if (c == 0)
2665                                 break;
2666                         r = safe_read(fd, audiobuf + l, c);
2667                         if (r < 0) {
2668                                 perror(name);
2669                                 prg_exit(EXIT_FAILURE);
2670                         }
2671                         fdcount += r;
2672                         if (r == 0)
2673                                 break;
2674                         l += r;
2675                 } while ((size_t)l < chunk_bytes);
2676                 l = l * 8 / bits_per_frame;
2677                 r = pcm_write(audiobuf, l);
2678                 if (r != l)
2679                         break;
2680                 r = r * bits_per_frame / 8;
2681                 written += r;
2682                 l = 0;
2683         }
2684         snd_pcm_nonblock(handle, 0);
2685         snd_pcm_drain(handle);
2686         snd_pcm_nonblock(handle, nonblock);
2687 }
2688
2689
2690 /*
2691  *  let's play or capture it (capture_type says VOC/WAVE/raw)
2692  */
2693
2694 static void playback(char *name)
2695 {
2696         int ofs;
2697         size_t dta;
2698         ssize_t dtawave;
2699
2700         pbrec_count = LLONG_MAX;
2701         fdcount = 0;
2702         if (!name || !strcmp(name, "-")) {
2703                 fd = fileno(stdin);
2704                 name = "stdin";
2705         } else {
2706                 init_stdin();
2707                 if ((fd = open(name, O_RDONLY, 0)) == -1) {
2708                         perror(name);
2709                         prg_exit(EXIT_FAILURE);
2710                 }
2711         }
2712         /* read the file header */
2713         dta = sizeof(AuHeader);
2714         if ((size_t)safe_read(fd, audiobuf, dta) != dta) {
2715                 error(_("read error"));
2716                 prg_exit(EXIT_FAILURE);
2717         }
2718         if (test_au(fd, audiobuf) >= 0) {
2719                 rhwparams.format = hwparams.format;
2720                 pbrec_count = calc_count();
2721                 playback_go(fd, 0, pbrec_count, FORMAT_AU, name);
2722                 goto __end;
2723         }
2724         dta = sizeof(VocHeader);
2725         if ((size_t)safe_read(fd, audiobuf + sizeof(AuHeader),
2726                  dta - sizeof(AuHeader)) != dta - sizeof(AuHeader)) {
2727                 error(_("read error"));
2728                 prg_exit(EXIT_FAILURE);;
2729         }
2730         if ((ofs = test_vocfile(audiobuf)) >= 0) {
2731                 pbrec_count = calc_count();
2732                 voc_play(fd, ofs, name);
2733                 goto __end;
2734         }
2735         /* read bytes for WAVE-header */
2736         if ((dtawave = test_wavefile(fd, audiobuf, dta)) >= 0) {
2737                 pbrec_count = calc_count();
2738                 playback_go(fd, dtawave, pbrec_count, FORMAT_WAVE, name);
2739         } else {
2740                 /* should be raw data */
2741                 init_raw_data();
2742                 pbrec_count = calc_count();
2743                 playback_go(fd, dta, pbrec_count, FORMAT_RAW, name);
2744         }
2745       __end:
2746         if (fd != 0)
2747                 close(fd);
2748 }
2749
2750 /**
2751  * mystrftime
2752  *
2753  *   Variant of strftime(3) that supports additional format
2754  *   specifiers in the format string.
2755  *
2756  * Parameters:
2757  *
2758  *   s    - destination string
2759  *   max        - max number of bytes to write
2760  *   userformat - format string
2761  *   tm  - time information
2762  *   filenumber - the number of the file, starting at 1
2763  *
2764  * Returns: number of bytes written to the string s
2765  */
2766 size_t mystrftime(char *s, size_t max, const char *userformat,
2767                   const struct tm *tm, const int filenumber)
2768 {
2769         char formatstring[PATH_MAX] = "";
2770         char tempstring[PATH_MAX] = "";
2771         char *format, *tempstr;
2772         const char *pos_userformat;
2773
2774         format = formatstring;
2775
2776         /* if mystrftime is called with userformat = NULL we return a zero length string */
2777         if (userformat == NULL) {
2778                 *s = '\0';
2779                 return 0;
2780         }
2781
2782         for (pos_userformat = userformat; *pos_userformat; ++pos_userformat) {
2783                 if (*pos_userformat == '%') {
2784                         tempstr = tempstring;
2785                         tempstr[0] = '\0';
2786                         switch (*++pos_userformat) {
2787
2788                                 case '\0': // end of string
2789                                         --pos_userformat;
2790                                         break;
2791
2792                                 case 'v': // file number 
2793                                         sprintf(tempstr, "%02d", filenumber);
2794                                         break;
2795
2796                                 default: // All other codes will be handled by strftime
2797                                         *format++ = '%';
2798                                         *format++ = *pos_userformat;
2799                                         continue;
2800                         }
2801
2802                         /* If a format specifier was found and used, copy the result. */
2803                         if (tempstr[0]) {
2804                                 while ((*format = *tempstr++) != '\0')
2805                                         ++format;
2806                                 continue;
2807                         }
2808                 }
2809
2810                 /* For any other character than % we simply copy the character */
2811                 *format++ = *pos_userformat;
2812         }
2813
2814         *format = '\0';
2815         format = formatstring;
2816         return strftime(s, max, format, tm);
2817 }
2818
2819 static int new_capture_file(char *name, char *namebuf, size_t namelen,
2820                             int filecount)
2821 {
2822         char *s;
2823         char buf[PATH_MAX+1];
2824         time_t t;
2825         struct tm *tmp;
2826
2827         if (use_strftime) {
2828                 t = time(NULL);
2829                 tmp = localtime(&t);
2830                 if (tmp == NULL) {
2831                         perror("localtime");
2832                         prg_exit(EXIT_FAILURE);
2833                 }
2834                 if (mystrftime(namebuf, namelen, name, tmp, filecount+1) == 0) {
2835                         fprintf(stderr, "mystrftime returned 0");
2836                         prg_exit(EXIT_FAILURE);
2837                 }
2838                 return filecount;
2839         }
2840
2841         /* get a copy of the original filename */
2842         strncpy(buf, name, sizeof(buf));
2843
2844         /* separate extension from filename */
2845         s = buf + strlen(buf);
2846         while (s > buf && *s != '.' && *s != '/')
2847                 --s;
2848         if (*s == '.')
2849                 *s++ = 0;
2850         else if (*s == '/')
2851                 s = buf + strlen(buf);
2852
2853         /* upon first jump to this if block rename the first file */
2854         if (filecount == 1) {
2855                 if (*s)
2856                         snprintf(namebuf, namelen, "%s-01.%s", buf, s);
2857                 else
2858                         snprintf(namebuf, namelen, "%s-01", buf);
2859                 remove(namebuf);
2860                 rename(name, namebuf);
2861                 filecount = 2;
2862         }
2863
2864         /* name of the current file */
2865         if (*s)
2866                 snprintf(namebuf, namelen, "%s-%02i.%s", buf, filecount, s);
2867         else
2868                 snprintf(namebuf, namelen, "%s-%02i", buf, filecount);
2869
2870         return filecount;
2871 }
2872
2873 /**
2874  * create_path
2875  *
2876  *   This function creates a file path, like mkdir -p. 
2877  *
2878  * Parameters:
2879  *
2880  *   path - the path to create
2881  *
2882  * Returns: 0 on success, -1 on failure
2883  * On failure, a message has been printed to stderr.
2884  */
2885 int create_path(const char *path)
2886 {
2887         char *start;
2888         mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
2889
2890         if (path[0] == '/')
2891                 start = strchr(path + 1, '/');
2892         else
2893                 start = strchr(path, '/');
2894
2895         while (start) {
2896                 char *buffer = strdup(path);
2897                 buffer[start-path] = 0x00;
2898
2899                 if (mkdir(buffer, mode) == -1 && errno != EEXIST) {
2900                         fprintf(stderr, "Problem creating directory %s", buffer);
2901                         perror(" ");
2902                         free(buffer);
2903                         return -1;
2904                 }
2905                 free(buffer);
2906                 start = strchr(start + 1, '/');
2907         }
2908         return 0;
2909 }
2910
2911 static int safe_open(const char *name)
2912 {
2913         int fd;
2914
2915         fd = open(name, O_WRONLY | O_CREAT, 0644);
2916         if (fd == -1) {
2917                 if (errno != ENOENT || !use_strftime)
2918                         return -1;
2919                 if (create_path(name) == 0)
2920                         fd = open(name, O_WRONLY | O_CREAT, 0644);
2921         }
2922         return fd;
2923 }
2924
2925 static void capture(char *orig_name)
2926 {
2927         int tostdout=0;         /* boolean which describes output stream */
2928         int filecount=0;        /* number of files written */
2929         char *name = orig_name; /* current filename */
2930         char namebuf[PATH_MAX+1];
2931         off64_t count, rest;            /* number of bytes to capture */
2932
2933         /* get number of bytes to capture */
2934         count = calc_count();
2935         if (count == 0)
2936                 count = LLONG_MAX;
2937         /* compute the number of bytes per file */
2938         max_file_size = max_file_time *
2939                 snd_pcm_format_size(hwparams.format,
2940                                     hwparams.rate * hwparams.channels);
2941         /* WAVE-file should be even (I'm not sure), but wasting one byte
2942            isn't a problem (this can only be in 8 bit mono) */
2943         if (count < LLONG_MAX)
2944                 count += count % 2;
2945         else
2946                 count -= count % 2;
2947
2948         /* display verbose output to console */
2949         header(file_type, name);
2950
2951         /* setup sound hardware */
2952         set_params();
2953
2954         /* write to stdout? */
2955         if (!name || !strcmp(name, "-")) {
2956                 fd = fileno(stdout);
2957                 name = "stdout";
2958                 tostdout=1;
2959                 if (count > fmt_rec_table[file_type].max_filesize)
2960                         count = fmt_rec_table[file_type].max_filesize;
2961         }
2962         init_stdin();
2963
2964         do {
2965                 /* open a file to write */
2966                 if(!tostdout) {
2967                         /* upon the second file we start the numbering scheme */
2968                         if (filecount || use_strftime) {
2969                                 filecount = new_capture_file(orig_name, namebuf,
2970                                                              sizeof(namebuf),
2971                                                              filecount);
2972                                 name = namebuf;
2973                         }
2974                         
2975                         /* open a new file */
2976                         remove(name);
2977                         fd = safe_open(name);
2978                         if (fd < 0) {
2979                                 perror(name);
2980                                 prg_exit(EXIT_FAILURE);
2981                         }
2982                         filecount++;
2983                 }
2984
2985                 rest = count;
2986                 if (rest > fmt_rec_table[file_type].max_filesize)
2987                         rest = fmt_rec_table[file_type].max_filesize;
2988                 if (max_file_size && (rest > max_file_size)) 
2989                         rest = max_file_size;
2990
2991                 /* setup sample header */
2992                 if (fmt_rec_table[file_type].start)
2993                         fmt_rec_table[file_type].start(fd, rest);
2994
2995                 /* capture */
2996                 fdcount = 0;
2997                 while (rest > 0 && recycle_capture_file == 0 && !in_aborting) {
2998                         size_t c = (rest <= (off64_t)chunk_bytes) ?
2999                                 (size_t)rest : chunk_bytes;
3000                         size_t f = c * 8 / bits_per_frame;
3001                         if (pcm_read(audiobuf, f) != f)
3002                                 break;
3003                         if (write(fd, audiobuf, c) != c) {
3004                                 perror(name);
3005                                 prg_exit(EXIT_FAILURE);
3006                         }
3007                         count -= c;
3008                         rest -= c;
3009                         fdcount += c;
3010                 }
3011
3012                 /* re-enable SIGUSR1 signal */
3013                 if (recycle_capture_file) {
3014                         recycle_capture_file = 0;
3015                         signal(SIGUSR1, signal_handler_recycle);
3016                 }
3017
3018                 /* finish sample container */
3019                 if (fmt_rec_table[file_type].end && !tostdout) {
3020                         fmt_rec_table[file_type].end(fd);
3021                         fd = -1;
3022                 }
3023
3024                 if (in_aborting)
3025                         break;
3026
3027                 /* repeat the loop when format is raw without timelimit or
3028                  * requested counts of data are recorded
3029                  */
3030         } while ((file_type == FORMAT_RAW && !timelimit) || count > 0);
3031 }
3032
3033 static void playbackv_go(int* fds, unsigned int channels, size_t loaded, off64_t count, int rtype, char **names)
3034 {
3035         int r;
3036         size_t vsize;
3037
3038         unsigned int channel;
3039         u_char *bufs[channels];
3040
3041         header(rtype, names[0]);
3042         set_params();
3043
3044         vsize = chunk_bytes / channels;
3045
3046         // Not yet implemented
3047         assert(loaded == 0);
3048
3049         for (channel = 0; channel < channels; ++channel)
3050                 bufs[channel] = audiobuf + vsize * channel;
3051
3052         while (count > 0 && !in_aborting) {
3053                 size_t c = 0;
3054                 size_t expected = count / channels;
3055                 if (expected > vsize)
3056                         expected = vsize;
3057                 do {
3058                         r = safe_read(fds[0], bufs[0], expected);
3059                         if (r < 0) {
3060                                 perror(names[channel]);
3061                                 prg_exit(EXIT_FAILURE);
3062                         }
3063                         for (channel = 1; channel < channels; ++channel) {
3064                                 if (safe_read(fds[channel], bufs[channel], r) != r) {
3065                                         perror(names[channel]);
3066                                         prg_exit(EXIT_FAILURE);
3067                                 }
3068                         }
3069                         if (r == 0)
3070                                 break;
3071                         c += r;
3072                 } while (c < expected);
3073                 c = c * 8 / bits_per_sample;
3074                 r = pcm_writev(bufs, channels, c);
3075                 if ((size_t)r != c)
3076                         break;
3077                 r = r * bits_per_frame / 8;
3078                 count -= r;
3079         }
3080         snd_pcm_nonblock(handle, 0);
3081         snd_pcm_drain(handle);
3082         snd_pcm_nonblock(handle, nonblock);
3083 }
3084
3085 static void capturev_go(int* fds, unsigned int channels, off64_t count, int rtype, char **names)
3086 {
3087         size_t c;
3088         ssize_t r;
3089         unsigned int channel;
3090         size_t vsize;
3091         u_char *bufs[channels];
3092
3093         header(rtype, names[0]);
3094         set_params();
3095
3096         vsize = chunk_bytes / channels;
3097
3098         for (channel = 0; channel < channels; ++channel)
3099                 bufs[channel] = audiobuf + vsize * channel;
3100
3101         while (count > 0 && !in_aborting) {
3102                 size_t rv;
3103                 c = count;
3104                 if (c > chunk_bytes)
3105                         c = chunk_bytes;
3106                 c = c * 8 / bits_per_frame;
3107                 if ((size_t)(r = pcm_readv(bufs, channels, c)) != c)
3108                         break;
3109                 rv = r * bits_per_sample / 8;
3110                 for (channel = 0; channel < channels; ++channel) {
3111                         if ((size_t)write(fds[channel], bufs[channel], rv) != rv) {
3112                                 perror(names[channel]);
3113                                 prg_exit(EXIT_FAILURE);
3114                         }
3115                 }
3116                 r = r * bits_per_frame / 8;
3117                 count -= r;
3118                 fdcount += r;
3119         }
3120 }
3121
3122 static void playbackv(char **names, unsigned int count)
3123 {
3124         int ret = 0;
3125         unsigned int channel;
3126         unsigned int channels = rhwparams.channels;
3127         int alloced = 0;
3128         int fds[channels];
3129         for (channel = 0; channel < channels; ++channel)
3130                 fds[channel] = -1;
3131
3132         if (count == 1 && channels > 1) {
3133                 size_t len = strlen(names[0]);
3134                 char format[1024];
3135                 memcpy(format, names[0], len);
3136                 strcpy(format + len, ".%d");
3137                 len += 4;
3138                 names = malloc(sizeof(*names) * channels);
3139                 for (channel = 0; channel < channels; ++channel) {
3140                         names[channel] = malloc(len);
3141                         sprintf(names[channel], format, channel);
3142                 }
3143                 alloced = 1;
3144         } else if (count != channels) {
3145                 error(_("You need to specify %d files"), channels);
3146                 prg_exit(EXIT_FAILURE);
3147         }
3148
3149         for (channel = 0; channel < channels; ++channel) {
3150                 fds[channel] = open(names[channel], O_RDONLY, 0);
3151                 if (fds[channel] < 0) {
3152                         perror(names[channel]);
3153                         ret = EXIT_FAILURE;
3154                         goto __end;
3155                 }
3156         }
3157         /* should be raw data */
3158         init_raw_data();
3159         pbrec_count = calc_count();
3160         playbackv_go(fds, channels, 0, pbrec_count, FORMAT_RAW, names);
3161
3162       __end:
3163         for (channel = 0; channel < channels; ++channel) {
3164                 if (fds[channel] >= 0)
3165                         close(fds[channel]);
3166                 if (alloced)
3167                         free(names[channel]);
3168         }
3169         if (alloced)
3170                 free(names);
3171         if (ret)
3172                 prg_exit(ret);
3173 }
3174
3175 static void capturev(char **names, unsigned int count)
3176 {
3177         int ret = 0;
3178         unsigned int channel;
3179         unsigned int channels = rhwparams.channels;
3180         int alloced = 0;
3181         int fds[channels];
3182         for (channel = 0; channel < channels; ++channel)
3183                 fds[channel] = -1;
3184
3185         if (count == 1) {
3186                 size_t len = strlen(names[0]);
3187                 char format[1024];
3188                 memcpy(format, names[0], len);
3189                 strcpy(format + len, ".%d");
3190                 len += 4;
3191                 names = malloc(sizeof(*names) * channels);
3192                 for (channel = 0; channel < channels; ++channel) {
3193                         names[channel] = malloc(len);
3194                         sprintf(names[channel], format, channel);
3195                 }
3196                 alloced = 1;
3197         } else if (count != channels) {
3198                 error(_("You need to specify %d files"), channels);
3199                 prg_exit(EXIT_FAILURE);
3200         }
3201
3202         for (channel = 0; channel < channels; ++channel) {
3203                 fds[channel] = open(names[channel], O_WRONLY + O_CREAT, 0644);
3204                 if (fds[channel] < 0) {
3205                         perror(names[channel]);
3206                         ret = EXIT_FAILURE;
3207                         goto __end;
3208                 }
3209         }
3210         /* should be raw data */
3211         init_raw_data();
3212         pbrec_count = calc_count();
3213         capturev_go(fds, channels, pbrec_count, FORMAT_RAW, names);
3214
3215       __end:
3216         for (channel = 0; channel < channels; ++channel) {
3217                 if (fds[channel] >= 0)
3218                         close(fds[channel]);
3219                 if (alloced)
3220                         free(names[channel]);
3221         }
3222         if (alloced)
3223                 free(names);
3224         if (ret)
3225                 prg_exit(ret);
3226 }