xref: /openbsd/regress/lib/libsndio/rec/rec.c (revision 404b540a)
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <poll.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include "sndio.h"
9 
10 #define BUFSZ 0x1000
11 unsigned char buf[BUFSZ];
12 struct sio_par par;
13 char *xstr[] = SIO_XSTRINGS;
14 
15 long long pos = 0;
16 int rlat = 0;
17 
18 void
19 cb(void *addr, int delta)
20 {
21 	pos += delta;
22 	rlat += delta;
23 	fprintf(stderr,
24 	    "cb: delta = %+7d, rlat = %+7d, pos = %+7lld\n",
25 	    delta, rlat, pos);
26 }
27 
28 void
29 usage(void) {
30 	fprintf(stderr, "usage: rec [-r rate] [-c nchan] [-e enc]\n");
31 }
32 
33 int
34 main(int argc, char **argv) {
35 	int ch;
36 	struct sio_hdl *hdl;
37 	ssize_t n;
38 
39 	/*
40 	 * defaults parameters
41 	 */
42 	sio_initpar(&par);
43 	par.sig = 1;
44 	par.bits = 16;
45 	par.rchan = 2;
46 	par.rate = 44100;
47 
48 	while ((ch = getopt(argc, argv, "r:c:e:b:x:")) != -1) {
49 		switch(ch) {
50 		case 'r':
51 			if (sscanf(optarg, "%u", &par.rate) != 1) {
52 				fprintf(stderr, "%s: bad rate\n", optarg);
53 				exit(1);
54 			}
55 			break;
56 		case 'c':
57 			if (sscanf(optarg, "%u", &par.rchan) != 1) {
58 				fprintf(stderr, "%s: channels number\n", optarg);
59 				exit(1);
60 			}
61 			break;
62 		case 'e':
63 			if (!sio_strtoenc(&par, optarg)) {
64 				fprintf(stderr, "%s: unknown encoding\n", optarg);
65 				exit(1);
66 			}
67 			break;
68 		case 'x':
69 			for (par.xrun = 0;; par.xrun++) {
70 				if (par.xrun == sizeof(xstr) / sizeof(char *)) {
71 					fprintf(stderr,
72 					    "%s: bad xrun mode\n", optarg);
73 					exit(1);
74 				}
75 				if (strcmp(xstr[par.xrun], optarg) == 0)
76 					break;
77 			}
78 			break;
79 		default:
80 			usage();
81 			exit(1);
82 			break;
83 		}
84 	}
85 
86 	hdl = sio_open(NULL, SIO_REC, 0);
87 	if (hdl == NULL) {
88 		fprintf(stderr, "sio_open() failed\n");
89 		exit(1);
90 	}
91 	sio_onmove(hdl, cb, NULL);
92 	if (!sio_setpar(hdl, &par)) {
93 		fprintf(stderr, "sio_setpar() failed\n");
94 		exit(1);
95 	}
96 	if (!sio_getpar(hdl, &par)) {
97 		fprintf(stderr, "sio_getpar() failed\n");
98 		exit(1);
99 	}
100 	if (!sio_start(hdl)) {
101 		fprintf(stderr, "sio_start() failed\n");
102 		exit(1);
103 	}
104 	for (;;) {
105 		n = sio_read(hdl, buf, BUFSZ);
106 		if (n == 0) {
107 			fprintf(stderr, "sio_write: failed\n");
108 			exit(1);
109 		}
110 		rlat -= n / (int)(par.bps * par.rchan);
111 		if (write(STDOUT_FILENO, buf, n) < 0) {
112 			perror("stdout");
113 			exit(1);
114 		}
115 	}
116 	sio_close(hdl);
117 	return 0;
118 }
119