1 /*
2  *  Latency test program
3  *
4  *     Author: Jaroslav Kysela <perex@perex.cz>
5  *
6  *     Author of bandpass filter sweep effect:
7  *	       Maarten de Boer <mdeboer@iua.upf.es>
8  *
9  *  This small demo program can be used for measuring latency between
10  *  capture and playback. This latency is measured from driver (diff when
11  *  playback and capture was started). Scheduler is set to SCHED_RR.
12  *
13  *
14  *   This program is free software; you can redistribute it and/or modify
15  *   it under the terms of the GNU General Public License as published by
16  *   the Free Software Foundation; either version 2 of the License, or
17  *   (at your option) any later version.
18  *
19  *   This program is distributed in the hope that it will be useful,
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   GNU General Public License for more details.
23  *
24  *   You should have received a copy of the GNU General Public License
25  *   along with this program; if not, write to the Free Software
26  *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
27  *
28  */
29 
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sched.h>
34 #include <errno.h>
35 #include <getopt.h>
36 #include "../include/asoundlib.h"
37 #include <sys/time.h>
38 #include <math.h>
39 
40 char *pdevice = "hw:0,0";
41 char *cdevice = "hw:0,0";
42 snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
43 int rate = 22050;
44 int channels = 2;
45 int buffer_size = 0;		/* auto */
46 int period_size = 0;		/* auto */
47 int latency_min = 32;		/* in frames / 2 */
48 int latency_max = 2048;		/* in frames / 2 */
49 int loop_sec = 30;		/* seconds */
50 int block = 0;			/* block mode */
51 int use_poll = 0;
52 int resample = 1;
53 unsigned long loop_limit;
54 
55 snd_output_t *output = NULL;
56 
setparams_stream(snd_pcm_t * handle,snd_pcm_hw_params_t * params,const char * id)57 int setparams_stream(snd_pcm_t *handle,
58 		     snd_pcm_hw_params_t *params,
59 		     const char *id)
60 {
61 	int err;
62 	unsigned int rrate;
63 
64 	err = snd_pcm_hw_params_any(handle, params);
65 	if (err < 0) {
66 		printf("Broken configuration for %s PCM: no configurations available: %s\n", snd_strerror(err), id);
67 		return err;
68 	}
69 	err = snd_pcm_hw_params_set_rate_resample(handle, params, resample);
70 	if (err < 0) {
71 		printf("Resample setup failed for %s (val %i): %s\n", id, resample, snd_strerror(err));
72 		return err;
73 	}
74 	err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
75 	if (err < 0) {
76 		printf("Access type not available for %s: %s\n", id, snd_strerror(err));
77 		return err;
78 	}
79 	err = snd_pcm_hw_params_set_format(handle, params, format);
80 	if (err < 0) {
81 		printf("Sample format not available for %s: %s\n", id, snd_strerror(err));
82 		return err;
83 	}
84 	err = snd_pcm_hw_params_set_channels(handle, params, channels);
85 	if (err < 0) {
86 		printf("Channels count (%i) not available for %s: %s\n", channels, id, snd_strerror(err));
87 		return err;
88 	}
89 	rrate = rate;
90 	err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
91 	if (err < 0) {
92 		printf("Rate %iHz not available for %s: %s\n", rate, id, snd_strerror(err));
93 		return err;
94 	}
95 	if ((int)rrate != rate) {
96 		printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
97 		return -EINVAL;
98 	}
99 	return 0;
100 }
101 
setparams_bufsize(snd_pcm_t * handle,snd_pcm_hw_params_t * params,snd_pcm_hw_params_t * tparams,snd_pcm_uframes_t bufsize,const char * id)102 int setparams_bufsize(snd_pcm_t *handle,
103 		      snd_pcm_hw_params_t *params,
104 		      snd_pcm_hw_params_t *tparams,
105 		      snd_pcm_uframes_t bufsize,
106 		      const char *id)
107 {
108 	int err;
109 	snd_pcm_uframes_t periodsize;
110 
111 	snd_pcm_hw_params_copy(params, tparams);
112 	periodsize = bufsize * 2;
113 	err = snd_pcm_hw_params_set_buffer_size_near(handle, params, &periodsize);
114 	if (err < 0) {
115 		printf("Unable to set buffer size %li for %s: %s\n", bufsize * 2, id, snd_strerror(err));
116 		return err;
117 	}
118 	if (period_size > 0)
119 		periodsize = period_size;
120 	else
121 		periodsize /= 2;
122 	err = snd_pcm_hw_params_set_period_size_near(handle, params, &periodsize, 0);
123 	if (err < 0) {
124 		printf("Unable to set period size %li for %s: %s\n", periodsize, id, snd_strerror(err));
125 		return err;
126 	}
127 	return 0;
128 }
129 
setparams_set(snd_pcm_t * handle,snd_pcm_hw_params_t * params,snd_pcm_sw_params_t * swparams,const char * id)130 int setparams_set(snd_pcm_t *handle,
131 		  snd_pcm_hw_params_t *params,
132 		  snd_pcm_sw_params_t *swparams,
133 		  const char *id)
134 {
135 	int err;
136 	snd_pcm_uframes_t val;
137 
138 	err = snd_pcm_hw_params(handle, params);
139 	if (err < 0) {
140 		printf("Unable to set hw params for %s: %s\n", id, snd_strerror(err));
141 		return err;
142 	}
143 	err = snd_pcm_sw_params_current(handle, swparams);
144 	if (err < 0) {
145 		printf("Unable to determine current swparams for %s: %s\n", id, snd_strerror(err));
146 		return err;
147 	}
148 	err = snd_pcm_sw_params_set_start_threshold(handle, swparams, 0x7fffffff);
149 	if (err < 0) {
150 		printf("Unable to set start threshold mode for %s: %s\n", id, snd_strerror(err));
151 		return err;
152 	}
153 	if (!block)
154 		val = 4;
155 	else
156 		snd_pcm_hw_params_get_period_size(params, &val, NULL);
157 	err = snd_pcm_sw_params_set_avail_min(handle, swparams, val);
158 	if (err < 0) {
159 		printf("Unable to set avail min for %s: %s\n", id, snd_strerror(err));
160 		return err;
161 	}
162 	err = snd_pcm_sw_params(handle, swparams);
163 	if (err < 0) {
164 		printf("Unable to set sw params for %s: %s\n", id, snd_strerror(err));
165 		return err;
166 	}
167 	return 0;
168 }
169 
setparams(snd_pcm_t * phandle,snd_pcm_t * chandle,int * bufsize)170 int setparams(snd_pcm_t *phandle, snd_pcm_t *chandle, int *bufsize)
171 {
172 	int err, last_bufsize = *bufsize;
173 	snd_pcm_hw_params_t *pt_params, *ct_params;	/* templates with rate, format and channels */
174 	snd_pcm_hw_params_t *p_params, *c_params;
175 	snd_pcm_sw_params_t *p_swparams, *c_swparams;
176 	snd_pcm_uframes_t p_size, c_size, p_psize, c_psize;
177 	unsigned int p_time, c_time;
178 	unsigned int val;
179 
180 	snd_pcm_hw_params_alloca(&p_params);
181 	snd_pcm_hw_params_alloca(&c_params);
182 	snd_pcm_hw_params_alloca(&pt_params);
183 	snd_pcm_hw_params_alloca(&ct_params);
184 	snd_pcm_sw_params_alloca(&p_swparams);
185 	snd_pcm_sw_params_alloca(&c_swparams);
186 	if ((err = setparams_stream(phandle, pt_params, "playback")) < 0) {
187 		printf("Unable to set parameters for playback stream: %s\n", snd_strerror(err));
188 		exit(0);
189 	}
190 	if ((err = setparams_stream(chandle, ct_params, "capture")) < 0) {
191 		printf("Unable to set parameters for playback stream: %s\n", snd_strerror(err));
192 		exit(0);
193 	}
194 
195 	if (buffer_size > 0) {
196 		*bufsize = buffer_size;
197 		goto __set_it;
198 	}
199 
200       __again:
201       	if (buffer_size > 0)
202       		return -1;
203       	if (last_bufsize == *bufsize)
204 		*bufsize += 4;
205 	last_bufsize = *bufsize;
206 	if (*bufsize > latency_max)
207 		return -1;
208       __set_it:
209 	if ((err = setparams_bufsize(phandle, p_params, pt_params, *bufsize, "playback")) < 0) {
210 		printf("Unable to set sw parameters for playback stream: %s\n", snd_strerror(err));
211 		exit(0);
212 	}
213 	if ((err = setparams_bufsize(chandle, c_params, ct_params, *bufsize, "capture")) < 0) {
214 		printf("Unable to set sw parameters for playback stream: %s\n", snd_strerror(err));
215 		exit(0);
216 	}
217 
218 	snd_pcm_hw_params_get_period_size(p_params, &p_psize, NULL);
219 	if (p_psize > (unsigned int)*bufsize)
220 		*bufsize = p_psize;
221 	snd_pcm_hw_params_get_period_size(c_params, &c_psize, NULL);
222 	if (c_psize > (unsigned int)*bufsize)
223 		*bufsize = c_psize;
224 	snd_pcm_hw_params_get_period_time(p_params, &p_time, NULL);
225 	snd_pcm_hw_params_get_period_time(c_params, &c_time, NULL);
226 	if (p_time != c_time)
227 		goto __again;
228 
229 	snd_pcm_hw_params_get_buffer_size(p_params, &p_size);
230 	if (p_psize * 2 < p_size) {
231                 snd_pcm_hw_params_get_periods_min(p_params, &val, NULL);
232                 if (val > 2) {
233 			printf("playback device does not support 2 periods per buffer\n");
234 			exit(0);
235 		}
236 		goto __again;
237 	}
238 	snd_pcm_hw_params_get_buffer_size(c_params, &c_size);
239 	if (c_psize * 2 < c_size) {
240                 snd_pcm_hw_params_get_periods_min(c_params, &val, NULL);
241 		if (val > 2 ) {
242 			printf("capture device does not support 2 periods per buffer\n");
243 			exit(0);
244 		}
245 		goto __again;
246 	}
247 	if ((err = setparams_set(phandle, p_params, p_swparams, "playback")) < 0) {
248 		printf("Unable to set sw parameters for playback stream: %s\n", snd_strerror(err));
249 		exit(0);
250 	}
251 	if ((err = setparams_set(chandle, c_params, c_swparams, "capture")) < 0) {
252 		printf("Unable to set sw parameters for playback stream: %s\n", snd_strerror(err));
253 		exit(0);
254 	}
255 
256 	if ((err = snd_pcm_prepare(phandle)) < 0) {
257 		printf("Prepare error: %s\n", snd_strerror(err));
258 		exit(0);
259 	}
260 
261 	snd_pcm_dump(phandle, output);
262 	snd_pcm_dump(chandle, output);
263 	fflush(stdout);
264 	return 0;
265 }
266 
showstat(snd_pcm_t * handle,size_t frames)267 void showstat(snd_pcm_t *handle, size_t frames)
268 {
269 	int err;
270 	snd_pcm_status_t *status;
271 
272 	snd_pcm_status_alloca(&status);
273 	if ((err = snd_pcm_status(handle, status)) < 0) {
274 		printf("Stream status error: %s\n", snd_strerror(err));
275 		exit(0);
276 	}
277 	printf("*** frames = %li ***\n", (long)frames);
278 	snd_pcm_status_dump(status, output);
279 }
280 
showlatency(size_t latency)281 void showlatency(size_t latency)
282 {
283 	double d;
284 	latency *= 2;
285 	d = (double)latency / (double)rate;
286 	printf("Trying latency %li frames, %.3fus, %.6fms (%.4fHz)\n", (long)latency, d * 1000000, d * 1000, (double)1 / d);
287 }
288 
showinmax(size_t in_max)289 void showinmax(size_t in_max)
290 {
291 	double d;
292 
293 	printf("Maximum read: %li frames\n", (long)in_max);
294 	d = (double)in_max / (double)rate;
295 	printf("Maximum read latency: %.3fus, %.6fms (%.4fHz)\n", d * 1000000, d * 1000, (double)1 / d);
296 }
297 
gettimestamp(snd_pcm_t * handle,snd_timestamp_t * timestamp)298 void gettimestamp(snd_pcm_t *handle, snd_timestamp_t *timestamp)
299 {
300 	int err;
301 	snd_pcm_status_t *status;
302 
303 	snd_pcm_status_alloca(&status);
304 	if ((err = snd_pcm_status(handle, status)) < 0) {
305 		printf("Stream status error: %s\n", snd_strerror(err));
306 		exit(0);
307 	}
308 	snd_pcm_status_get_trigger_tstamp(status, timestamp);
309 }
310 
setscheduler(void)311 void setscheduler(void)
312 {
313 	struct sched_param sched_param;
314 
315 	if (sched_getparam(0, &sched_param) < 0) {
316 		printf("Scheduler getparam failed...\n");
317 		return;
318 	}
319 	sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
320 	if (!sched_setscheduler(0, SCHED_RR, &sched_param)) {
321 		printf("Scheduler set to Round Robin with priority %i...\n", sched_param.sched_priority);
322 		fflush(stdout);
323 		return;
324 	}
325 	printf("!!!Scheduler set to Round Robin with priority %i FAILED!!!\n", sched_param.sched_priority);
326 }
327 
timediff(snd_timestamp_t t1,snd_timestamp_t t2)328 long timediff(snd_timestamp_t t1, snd_timestamp_t t2)
329 {
330 	signed long l;
331 
332 	t1.tv_sec -= t2.tv_sec;
333 	l = (signed long) t1.tv_usec - (signed long) t2.tv_usec;
334 	if (l < 0) {
335 		t1.tv_sec--;
336 		l = 1000000 + l;
337 		l %= 1000000;
338 	}
339 	return (t1.tv_sec * 1000000) + l;
340 }
341 
readbuf(snd_pcm_t * handle,char * buf,long len,size_t * frames,size_t * max)342 long readbuf(snd_pcm_t *handle, char *buf, long len, size_t *frames, size_t *max)
343 {
344 	long r;
345 
346 	if (!block) {
347 		do {
348 			r = snd_pcm_readi(handle, buf, len);
349 		} while (r == -EAGAIN);
350 		if (r > 0) {
351 			*frames += r;
352 			if ((long)*max < r)
353 				*max = r;
354 		}
355 		// printf("read = %li\n", r);
356 	} else {
357 		int frame_bytes = (snd_pcm_format_width(format) / 8) * channels;
358 		do {
359 			r = snd_pcm_readi(handle, buf, len);
360 			if (r > 0) {
361 				buf += r * frame_bytes;
362 				len -= r;
363 				*frames += r;
364 				if ((long)*max < r)
365 					*max = r;
366 			}
367 			// printf("r = %li, len = %li\n", r, len);
368 		} while (r >= 1 && len > 0);
369 	}
370 	// showstat(handle, 0);
371 	return r;
372 }
373 
writebuf(snd_pcm_t * handle,char * buf,long len,size_t * frames)374 long writebuf(snd_pcm_t *handle, char *buf, long len, size_t *frames)
375 {
376 	long r;
377 	int frame_bytes = (snd_pcm_format_width(format) / 8) * channels;
378 
379 	while (len > 0) {
380 		r = snd_pcm_writei(handle, buf, len);
381 		if (r == -EAGAIN)
382 			continue;
383 		// printf("write = %li\n", r);
384 		if (r < 0)
385 			return r;
386 		// showstat(handle, 0);
387 		buf += r * frame_bytes;
388 		len -= r;
389 		*frames += r;
390 	}
391 	return 0;
392 }
393 
394 #define FILTERSWEEP_LFO_CENTER 2000.
395 #define FILTERSWEEP_LFO_DEPTH 1800.
396 #define FILTERSWEEP_LFO_FREQ 0.2
397 #define FILTER_BANDWIDTH 50
398 
399 /* filter the sweep variables */
400 float lfo,dlfo,fs,fc,BW,C,D,a0,a1,a2,b1,b2,*x[3],*y[3];
401 
applyeffect(char * buffer,int r)402 void applyeffect(char* buffer,int r)
403 {
404 	short* samples = (short*) buffer;
405 	int i;
406 	for (i=0;i<r;i++)
407 	{
408 		int chn;
409 
410 		fc = sin(lfo)*FILTERSWEEP_LFO_DEPTH+FILTERSWEEP_LFO_CENTER;
411 		lfo += dlfo;
412 		if (lfo>2.*M_PI) lfo -= 2.*M_PI;
413 		C = 1./tan(M_PI*BW/fs);
414 		D = 2.*cos(2*M_PI*fc/fs);
415 		a0 = 1./(1.+C);
416 		a1 = 0;
417 		a2 = -a0;
418 		b1 = -C*D*a0;
419 		b2 = (C-1)*a0;
420 
421 		for (chn=0;chn<channels;chn++)
422 		{
423 			x[chn][2] = x[chn][1];
424 			x[chn][1] = x[chn][0];
425 
426 			y[chn][2] = y[chn][1];
427 			y[chn][1] = y[chn][0];
428 
429 			x[chn][0] = samples[i*channels+chn];
430 			y[chn][0] = a0*x[chn][0] + a1*x[chn][1] + a2*x[chn][2]
431 				- b1*y[chn][1] - b2*y[chn][2];
432 			samples[i*channels+chn] = y[chn][0];
433 		}
434 	}
435 }
436 
help(void)437 void help(void)
438 {
439 	int k;
440 	printf(
441 "Usage: latency [OPTION]... [FILE]...\n"
442 "-h,--help      help\n"
443 "-P,--pdevice   playback device\n"
444 "-C,--cdevice   capture device\n"
445 "-m,--min       minimum latency in frames\n"
446 "-M,--max       maximum latency in frames\n"
447 "-F,--frames    frames to transfer\n"
448 "-f,--format    sample format\n"
449 "-c,--channels  channels\n"
450 "-r,--rate      rate\n"
451 "-B,--buffer    buffer size in frames\n"
452 "-E,--period    period size in frames\n"
453 "-s,--seconds   duration of test in seconds\n"
454 "-b,--block     block mode\n"
455 "-p,--poll      use poll (wait for event - reduces CPU usage)\n"
456 "-e,--effect    apply an effect (bandpass filter sweep)\n"
457 );
458         printf("Recognized sample formats are:");
459         for (k = 0; k < SND_PCM_FORMAT_LAST; ++k) {
460                 const char *s = snd_pcm_format_name(k);
461                 if (s)
462                         printf(" %s", s);
463         }
464         printf("\n\n");
465         printf(
466 "Tip #1 (usable latency with large periods, non-blocking mode, good CPU usage,\n"
467 "        superb xrun prevention):\n"
468 "  latency -m 8192 -M 8192 -t 1 -p\n"
469 "Tip #2 (superb latency, non-blocking mode, but heavy CPU usage):\n"
470 "  latency -m 128 -M 128\n"
471 );
472 }
473 
main(int argc,char * argv[])474 int main(int argc, char *argv[])
475 {
476 	struct option long_option[] =
477 	{
478 		{"help", 0, NULL, 'h'},
479 		{"pdevice", 1, NULL, 'P'},
480 		{"cdevice", 1, NULL, 'C'},
481 		{"min", 1, NULL, 'm'},
482 		{"max", 1, NULL, 'M'},
483 		{"frames", 1, NULL, 'F'},
484 		{"format", 1, NULL, 'f'},
485 		{"channels", 1, NULL, 'c'},
486 		{"rate", 1, NULL, 'r'},
487 		{"buffer", 1, NULL, 'B'},
488 		{"period", 1, NULL, 'E'},
489 		{"seconds", 1, NULL, 's'},
490 		{"block", 0, NULL, 'b'},
491 		{"poll", 0, NULL, 'p'},
492 		{"effect", 0, NULL, 'e'},
493 		{NULL, 0, NULL, 0},
494 	};
495 	snd_pcm_t *phandle, *chandle;
496 	char *buffer;
497 	int err, latency, morehelp;
498 	int ok;
499 	snd_timestamp_t p_tstamp, c_tstamp;
500 	ssize_t r;
501 	size_t frames_in, frames_out, in_max;
502 	int effect = 0;
503 	morehelp = 0;
504 	while (1) {
505 		int c;
506 		if ((c = getopt_long(argc, argv, "hP:C:m:M:F:f:c:r:B:E:s:bpen", long_option, NULL)) < 0)
507 			break;
508 		switch (c) {
509 		case 'h':
510 			morehelp++;
511 			break;
512 		case 'P':
513 			pdevice = strdup(optarg);
514 			break;
515 		case 'C':
516 			cdevice = strdup(optarg);
517 			break;
518 		case 'm':
519 			err = atoi(optarg) / 2;
520 			latency_min = err >= 4 ? err : 4;
521 			if (latency_max < latency_min)
522 				latency_max = latency_min;
523 			break;
524 		case 'M':
525 			err = atoi(optarg) / 2;
526 			latency_max = latency_min > err ? latency_min : err;
527 			break;
528 		case 'f':
529 			format = snd_pcm_format_value(optarg);
530 			if (format == SND_PCM_FORMAT_UNKNOWN) {
531 				printf("Unknown format, setting to default S16_LE\n");
532 				format = SND_PCM_FORMAT_S16_LE;
533 			}
534 			break;
535 		case 'c':
536 			err = atoi(optarg);
537 			channels = err >= 1 && err < 1024 ? err : 1;
538 			break;
539 		case 'r':
540 			err = atoi(optarg);
541 			rate = err >= 4000 && err < 200000 ? err : 44100;
542 			break;
543 		case 'B':
544 			err = atoi(optarg);
545 			buffer_size = err >= 32 && err < 200000 ? err : 0;
546 			break;
547 		case 'E':
548 			err = atoi(optarg);
549 			period_size = err >= 32 && err < 200000 ? err : 0;
550 			break;
551 		case 's':
552 			err = atoi(optarg);
553 			loop_sec = err >= 1 && err <= 100000 ? err : 30;
554 			break;
555 		case 'b':
556 			block = 1;
557 			break;
558 		case 'p':
559 			use_poll = 1;
560 			break;
561 		case 'e':
562 			effect = 1;
563 			break;
564 		case 'n':
565 			resample = 0;
566 			break;
567 		}
568 	}
569 
570 	if (morehelp) {
571 		help();
572 		return 0;
573 	}
574 	err = snd_output_stdio_attach(&output, stdout, 0);
575 	if (err < 0) {
576 		printf("Output failed: %s\n", snd_strerror(err));
577 		return 0;
578 	}
579 
580 	loop_limit = loop_sec * rate;
581 	latency = latency_min - 4;
582 	buffer = malloc((latency_max * snd_pcm_format_width(format) / 8) * 2);
583 
584 	setscheduler();
585 
586 	printf("Playback device is %s\n", pdevice);
587 	printf("Capture device is %s\n", cdevice);
588 	printf("Parameters are %iHz, %s, %i channels, %s mode\n", rate, snd_pcm_format_name(format), channels, block ? "blocking" : "non-blocking");
589 	printf("Poll mode: %s\n", use_poll ? "yes" : "no");
590 	printf("Loop limit is %lu frames, minimum latency = %i, maximum latency = %i\n", loop_limit, latency_min * 2, latency_max * 2);
591 
592 	if ((err = snd_pcm_open(&phandle, pdevice, SND_PCM_STREAM_PLAYBACK, block ? 0 : SND_PCM_NONBLOCK)) < 0) {
593 		printf("Playback open error: %s\n", snd_strerror(err));
594 		return 0;
595 	}
596 	if ((err = snd_pcm_open(&chandle, cdevice, SND_PCM_STREAM_CAPTURE, block ? 0 : SND_PCM_NONBLOCK)) < 0) {
597 		printf("Record open error: %s\n", snd_strerror(err));
598 		return 0;
599 	}
600 
601 	/* initialize the filter sweep variables */
602 	if (effect) {
603 		fs = (float) rate;
604 		BW = FILTER_BANDWIDTH;
605 
606 		lfo = 0;
607 		dlfo = 2.*M_PI*FILTERSWEEP_LFO_FREQ/fs;
608 
609 		x[0] = (float*) malloc(channels*sizeof(float));
610 		x[1] = (float*) malloc(channels*sizeof(float));
611 		x[2] = (float*) malloc(channels*sizeof(float));
612 		y[0] = (float*) malloc(channels*sizeof(float));
613 		y[1] = (float*) malloc(channels*sizeof(float));
614 		y[2] = (float*) malloc(channels*sizeof(float));
615 	}
616 
617 	while (1) {
618 		frames_in = frames_out = 0;
619 		if (setparams(phandle, chandle, &latency) < 0)
620 			break;
621 		showlatency(latency);
622 		if ((err = snd_pcm_link(chandle, phandle)) < 0) {
623 			printf("Streams link error: %s\n", snd_strerror(err));
624 			exit(0);
625 		}
626 		if (snd_pcm_format_set_silence(format, buffer, latency*channels) < 0) {
627 			fprintf(stderr, "silence error\n");
628 			break;
629 		}
630 		if (writebuf(phandle, buffer, latency, &frames_out) < 0) {
631 			fprintf(stderr, "write error\n");
632 			break;
633 		}
634 		if (writebuf(phandle, buffer, latency, &frames_out) < 0) {
635 			fprintf(stderr, "write error\n");
636 			break;
637 		}
638 
639 		if ((err = snd_pcm_start(chandle)) < 0) {
640 			printf("Go error: %s\n", snd_strerror(err));
641 			exit(0);
642 		}
643 		gettimestamp(phandle, &p_tstamp);
644 		gettimestamp(chandle, &c_tstamp);
645 #if 0
646 		printf("Playback:\n");
647 		showstat(phandle, frames_out);
648 		printf("Capture:\n");
649 		showstat(chandle, frames_in);
650 #endif
651 
652 		ok = 1;
653 		in_max = 0;
654 		while (ok && frames_in < loop_limit) {
655 			if (use_poll) {
656 				/* use poll to wait for next event */
657 				snd_pcm_wait(chandle, 1000);
658 			}
659 			if ((r = readbuf(chandle, buffer, latency, &frames_in, &in_max)) < 0)
660 				ok = 0;
661 			else {
662 				if (effect)
663 					applyeffect(buffer,r);
664 			 	if (writebuf(phandle, buffer, r, &frames_out) < 0)
665 					ok = 0;
666 			}
667 		}
668 		if (ok)
669 			printf("Success\n");
670 		else
671 			printf("Failure\n");
672 		printf("Playback:\n");
673 		showstat(phandle, frames_out);
674 		printf("Capture:\n");
675 		showstat(chandle, frames_in);
676 		showinmax(in_max);
677 		if (p_tstamp.tv_sec == c_tstamp.tv_sec &&
678 		    p_tstamp.tv_usec == c_tstamp.tv_usec)
679 			printf("Hardware sync\n");
680 		snd_pcm_drop(chandle);
681 		snd_pcm_nonblock(phandle, 0);
682 		snd_pcm_drain(phandle);
683 		snd_pcm_nonblock(phandle, !block ? 1 : 0);
684 		if (ok) {
685 #if 1
686 			printf("Playback time = %li.%i, Record time = %li.%i, diff = %li\n",
687 			       p_tstamp.tv_sec,
688 			       (int)p_tstamp.tv_usec,
689 			       c_tstamp.tv_sec,
690 			       (int)c_tstamp.tv_usec,
691 			       timediff(p_tstamp, c_tstamp));
692 #endif
693 			break;
694 		}
695 		snd_pcm_unlink(chandle);
696 		snd_pcm_hw_free(phandle);
697 		snd_pcm_hw_free(chandle);
698 	}
699 	snd_pcm_close(phandle);
700 	snd_pcm_close(chandle);
701 	return 0;
702 }
703