]> git.alsa-project.org Git - alsa-lib.git/blob - test/latency.c
c40b2ae7cb5cb8f97d8b7716e54b0568bde812d2
[alsa-lib.git] / test / latency.c
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 "config.h"
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sched.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <time.h>
38 #include "../include/asoundlib.h"
39 #include <sys/time.h>
40 #include <math.h>
41
42 #ifndef CLOCK_MONOTONIC_RAW
43 #define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
44 #endif
45
46 #if defined(__OpenBSD__)
47 #define sched_getparam(pid, parm) (-1)
48 #define sched_setscheduler(pid, policy, parm) (-1)
49 #endif
50
51 typedef struct timespec timestamp_t;
52
53 char *sched_policy = "rr";
54 char *pdevice = "hw:0,0";
55 char *cdevice = "hw:0,0";
56 snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
57 int rate = 22050;
58 int channels = 2;
59 int buffer_size = 0;            /* auto */
60 int period_size = 0;            /* auto */
61 int latency_min = 32;           /* in frames / 2 */
62 int latency_max = 2048;         /* in frames / 2 */
63 int loop_sec = 30;              /* seconds */
64 int block = 0;                  /* block mode */
65 int use_poll = 0;
66 int usleep_val = 0;
67 int resample = 1;
68 int sys_latency = 0;            /* data I/O: use system timings instead driver wakeups */
69 int pos_dump = 0;               /* dump positions */
70 int realtime_check = 0;
71 unsigned long loop_limit;
72 snd_pcm_uframes_t playback_buffer_size;
73
74 snd_output_t *output = NULL;
75
76 static inline long long frames_to_micro(size_t frames)
77 {
78         return (long long)((frames * 1000000LL) + (rate / 2)) / rate;
79 }
80
81 void timestamp_now(timestamp_t *tstamp)
82 {
83         if (clock_gettime(CLOCK_MONOTONIC_RAW, tstamp))
84                 printf("clock_gettime() failed\n");
85 }
86
87 long long timestamp_diff_micro(timestamp_t *tstamp)
88 {
89         timestamp_t now, diff;
90         timestamp_now(&now);
91         if (tstamp->tv_nsec > now.tv_nsec) {
92                 diff.tv_sec = now.tv_sec - tstamp->tv_sec - 1;
93                 diff.tv_nsec = (now.tv_nsec + 1000000000L) - tstamp->tv_nsec;
94         } else {
95                 diff.tv_sec = now.tv_sec - tstamp->tv_sec;
96                 diff.tv_nsec = now.tv_nsec - tstamp->tv_nsec;
97         }
98         /* microseconds */
99         return (diff.tv_sec * 1000000) + ((diff.tv_nsec + 500L) / 1000L);
100 }
101
102 int setparams_stream(snd_pcm_t *handle,
103                      snd_pcm_hw_params_t *params,
104                      const char *id)
105 {
106         int err;
107         unsigned int rrate;
108
109         err = snd_pcm_hw_params_any(handle, params);
110         if (err < 0) {
111                 printf("Broken configuration for %s PCM: no configurations available: %s\n", snd_strerror(err), id);
112                 return err;
113         }
114         err = snd_pcm_hw_params_set_rate_resample(handle, params, resample);
115         if (err < 0) {
116                 printf("Resample setup failed for %s (val %i): %s\n", id, resample, snd_strerror(err));
117                 return err;
118         }
119         err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
120         if (err < 0) {
121                 printf("Access type not available for %s: %s\n", id, snd_strerror(err));
122                 return err;
123         }
124         err = snd_pcm_hw_params_set_format(handle, params, format);
125         if (err < 0) {
126                 printf("Sample format not available for %s: %s\n", id, snd_strerror(err));
127                 return err;
128         }
129         err = snd_pcm_hw_params_set_channels(handle, params, channels);
130         if (err < 0) {
131                 printf("Channels count (%i) not available for %s: %s\n", channels, id, snd_strerror(err));
132                 return err;
133         }
134         rrate = rate;
135         err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
136         if (err < 0) {
137                 printf("Rate %iHz not available for %s: %s\n", rate, id, snd_strerror(err));
138                 return err;
139         }
140         if ((int)rrate != rate) {
141                 printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
142                 return -EINVAL;
143         }
144         /* we do not want driver wakeups */
145         if (sys_latency > 0 && snd_pcm_hw_params_can_disable_period_wakeup(params)) {
146                 err = snd_pcm_hw_params_set_period_wakeup(handle, params, 0);
147                 if (err < 0) {
148                         printf("Cannot disable period wakeups for %s\n", id);
149                         return err;
150                 }
151         }
152         return 0;
153 }
154
155 int setparams_bufsize(snd_pcm_t *handle,
156                       snd_pcm_hw_params_t *params,
157                       snd_pcm_hw_params_t *tparams,
158                       snd_pcm_uframes_t bufsize,
159                       const char *id)
160 {
161         int err;
162         snd_pcm_uframes_t periodsize;
163
164         snd_pcm_hw_params_copy(params, tparams);
165         periodsize = bufsize * 2;
166         err = snd_pcm_hw_params_set_buffer_size_near(handle, params, &periodsize);
167         if (err < 0) {
168                 printf("Unable to set buffer size %li for %s: %s\n", bufsize * 2, id, snd_strerror(err));
169                 return err;
170         }
171         if (period_size > 0)
172                 periodsize = period_size;
173         else
174                 periodsize /= 2;
175         err = snd_pcm_hw_params_set_period_size_near(handle, params, &periodsize, 0);
176         if (err < 0) {
177                 printf("Unable to set period size %li for %s: %s\n", periodsize, id, snd_strerror(err));
178                 return err;
179         }
180         return 0;
181 }
182
183 int setparams_set(snd_pcm_t *handle,
184                   snd_pcm_hw_params_t *params,
185                   snd_pcm_sw_params_t *swparams,
186                   const char *id)
187 {
188         int err;
189         snd_pcm_uframes_t val;
190
191         err = snd_pcm_hw_params(handle, params);
192         if (err < 0) {
193                 printf("Unable to set hw params for %s: %s\n", id, snd_strerror(err));
194                 return err;
195         }
196         err = snd_pcm_sw_params_current(handle, swparams);
197         if (err < 0) {
198                 printf("Unable to determine current swparams for %s: %s\n", id, snd_strerror(err));
199                 return err;
200         }
201         err = snd_pcm_sw_params_set_start_threshold(handle, swparams, 0x7fffffff);
202         if (err < 0) {
203                 printf("Unable to set start threshold mode for %s: %s\n", id, snd_strerror(err));
204                 return err;
205         }
206         if (!block)
207                 val = 4;
208         else
209                 snd_pcm_hw_params_get_period_size(params, &val, NULL);
210         err = snd_pcm_sw_params_set_avail_min(handle, swparams, val);
211         if (err < 0) {
212                 printf("Unable to set avail min for %s: %s\n", id, snd_strerror(err));
213                 return err;
214         }
215         err = snd_pcm_sw_params(handle, swparams);
216         if (err < 0) {
217                 printf("Unable to set sw params for %s: %s\n", id, snd_strerror(err));
218                 return err;
219         }
220         return 0;
221 }
222
223 int setparams(snd_pcm_t *phandle, snd_pcm_t *chandle, int *bufsize)
224 {
225         int err, last_bufsize = *bufsize;
226         snd_pcm_hw_params_t *pt_params, *ct_params;     /* templates with rate, format and channels */
227         snd_pcm_hw_params_t *p_params, *c_params;
228         snd_pcm_sw_params_t *p_swparams, *c_swparams;
229         snd_pcm_uframes_t p_size, c_size, p_psize, c_psize;
230         unsigned int p_time, c_time;
231         unsigned int val;
232
233         snd_pcm_hw_params_alloca(&p_params);
234         snd_pcm_hw_params_alloca(&c_params);
235         snd_pcm_hw_params_alloca(&pt_params);
236         snd_pcm_hw_params_alloca(&ct_params);
237         snd_pcm_sw_params_alloca(&p_swparams);
238         snd_pcm_sw_params_alloca(&c_swparams);
239         if ((err = setparams_stream(phandle, pt_params, "playback")) < 0) {
240                 printf("Unable to set parameters for playback stream: %s\n", snd_strerror(err));
241                 exit(0);
242         }
243         if ((err = setparams_stream(chandle, ct_params, "capture")) < 0) {
244                 printf("Unable to set parameters for playback stream: %s\n", snd_strerror(err));
245                 exit(0);
246         }
247
248         if (buffer_size > 0) {
249                 *bufsize = buffer_size;
250                 goto __set_it;
251         }
252
253       __again:
254         if (buffer_size > 0)
255                 return -1;
256         if (last_bufsize == *bufsize)
257                 *bufsize += 4;
258         last_bufsize = *bufsize;
259         if (*bufsize > latency_max)
260                 return -1;
261       __set_it:
262         if ((err = setparams_bufsize(phandle, p_params, pt_params, *bufsize, "playback")) < 0) {
263                 printf("Unable to set hw parameters for playback stream: %s\n", snd_strerror(err));
264                 exit(0);
265         }
266         if ((err = setparams_bufsize(chandle, c_params, ct_params, *bufsize, "capture")) < 0) {
267                 printf("Unable to set hw parameters for capture stream: %s\n", snd_strerror(err));
268                 exit(0);
269         }
270
271         snd_pcm_hw_params_get_period_size(p_params, &p_psize, NULL);
272         if (p_psize > (unsigned int)*bufsize)
273                 *bufsize = p_psize;
274         snd_pcm_hw_params_get_period_size(c_params, &c_psize, NULL);
275         if (c_psize > (unsigned int)*bufsize)
276                 *bufsize = c_psize;
277         snd_pcm_hw_params_get_period_time(p_params, &p_time, NULL);
278         snd_pcm_hw_params_get_period_time(c_params, &c_time, NULL);
279         if (p_time != c_time)
280                 goto __again;
281
282         snd_pcm_hw_params_get_buffer_size(p_params, &p_size);
283         playback_buffer_size = p_size;
284         if (p_psize * 2 < p_size) {
285                 snd_pcm_hw_params_get_periods_min(p_params, &val, NULL);
286                 if (val > 2) {
287                         printf("playback device does not support 2 periods per buffer\n");
288                         exit(0);
289                 }
290                 goto __again;
291         }
292         snd_pcm_hw_params_get_buffer_size(c_params, &c_size);
293         if (c_psize * 2 < c_size) {
294                 snd_pcm_hw_params_get_periods_min(c_params, &val, NULL);
295                 if (val > 2 ) {
296                         printf("capture device does not support 2 periods per buffer\n");
297                         exit(0);
298                 }
299                 goto __again;
300         }
301         if ((err = setparams_set(phandle, p_params, p_swparams, "playback")) < 0) {
302                 printf("Unable to set sw parameters for playback stream: %s\n", snd_strerror(err));
303                 exit(0);
304         }
305         if ((err = setparams_set(chandle, c_params, c_swparams, "capture")) < 0) {
306                 printf("Unable to set sw parameters for playback stream: %s\n", snd_strerror(err));
307                 exit(0);
308         }
309
310         if ((err = snd_pcm_prepare(phandle)) < 0) {
311                 printf("Prepare error: %s\n", snd_strerror(err));
312                 exit(0);
313         }
314
315         snd_pcm_dump(phandle, output);
316         snd_pcm_dump(chandle, output);
317         fflush(stdout);
318         return 0;
319 }
320
321 void showstat(snd_pcm_t *handle, size_t frames)
322 {
323         int err;
324         snd_pcm_status_t *status;
325
326         snd_pcm_status_alloca(&status);
327         if ((err = snd_pcm_status(handle, status)) < 0) {
328                 printf("Stream status error: %s\n", snd_strerror(err));
329                 exit(0);
330         }
331         printf("*** frames = %li ***\n", (long)frames);
332         snd_pcm_status_dump(status, output);
333 }
334
335 void showlatency(size_t latency)
336 {
337         double d;
338         latency *= 2;
339         d = (double)latency / (double)rate;
340         printf("Trying latency %li frames, %.3fus, %.6fms (%.4fHz)\n", (long)latency, d * 1000000, d * 1000, (double)1 / d);
341 }
342
343 void showinmax(size_t in_max)
344 {
345         double d;
346
347         printf("Maximum read: %li frames\n", (long)in_max);
348         d = (double)in_max / (double)rate;
349         printf("Maximum read latency: %.3fus, %.6fms (%.4fHz)\n", d * 1000000, d * 1000, (double)1 / d);
350 }
351
352 void gettimestamp(snd_pcm_t *handle, snd_timestamp_t *timestamp)
353 {
354         int err;
355         snd_pcm_status_t *status;
356
357         snd_pcm_status_alloca(&status);
358         if ((err = snd_pcm_status(handle, status)) < 0) {
359                 printf("Stream status error: %s\n", snd_strerror(err));
360                 exit(0);
361         }
362         snd_pcm_status_get_trigger_tstamp(status, timestamp);
363 }
364
365 void setscheduler(void)
366 {
367         struct sched_param sched_param;
368         int policy = SCHED_RR;
369         const char *spolicy = "Round Robin";
370
371         if (strcasecmp(sched_policy, "fifo") == 0) {
372                 policy = SCHED_FIFO;
373                 spolicy = "FIFO";
374         } else if (strcasecmp(sched_policy, "other") == 0) {
375                 policy = SCHED_OTHER;
376                 spolicy = "OTHER";
377         }
378         if (sched_getparam(0, &sched_param) < 0) {
379                 printf("Scheduler getparam failed...\n");
380                 return;
381         }
382         sched_param.sched_priority = sched_get_priority_max(policy);
383         if (!sched_setscheduler(0, policy, &sched_param)) {
384                 printf("Scheduler set to %s with priority %i...\n", spolicy, sched_param.sched_priority);
385                 fflush(stdout);
386                 return;
387         }
388         printf("!!!Scheduler set to %s with priority %i FAILED!!!\n", spolicy, sched_param.sched_priority);
389 }
390
391 long timediff(snd_timestamp_t t1, snd_timestamp_t t2)
392 {
393         signed long l;
394
395         t1.tv_sec -= t2.tv_sec;
396         l = (signed long) t1.tv_usec - (signed long) t2.tv_usec;
397         if (l < 0) {
398                 t1.tv_sec--;
399                 l = 1000000 + l;
400                 l %= 1000000;
401         }
402         return (t1.tv_sec * 1000000) + l;
403 }
404
405 long readbuf(snd_pcm_t *handle, char *buf, long len, size_t *frames, size_t *max)
406 {
407         long r;
408
409         if (!block) {
410                 do {
411                         r = snd_pcm_readi(handle, buf, len);
412                 } while (r == -EAGAIN);
413                 if (r > 0) {
414                         *frames += r;
415                         if ((long)*max < r)
416                                 *max = r;
417                 }
418                 // printf("read = %li\n", r);
419         } else {
420                 int frame_bytes = (snd_pcm_format_physical_width(format) / 8) * channels;
421                 do {
422                         r = snd_pcm_readi(handle, buf, len);
423                         if (r > 0) {
424                                 buf += r * frame_bytes;
425                                 len -= r;
426                                 *frames += r;
427                                 if ((long)*max < r)
428                                         *max = r;
429                         }
430                         // printf("r = %li, len = %li\n", r, len);
431                 } while (r >= 1 && len > 0);
432         }
433         // showstat(handle, 0);
434         return r;
435 }
436
437 long writebuf(snd_pcm_t *handle, char *buf, long len, size_t *frames)
438 {
439         long r;
440         int frame_bytes = (snd_pcm_format_physical_width(format) / 8) * channels;
441
442         while (len > 0) {
443                 r = snd_pcm_writei(handle, buf, len);
444                 if (r == -EAGAIN)
445                         continue;
446                 // printf("write = %li\n", r);
447                 if (r < 0)
448                         return r;
449                 // showstat(handle, 0);
450                 buf += r * frame_bytes;
451                 len -= r;
452                 *frames += r;
453         }
454         return 0;
455 }
456
457 #define FILTERSWEEP_LFO_CENTER 2000.
458 #define FILTERSWEEP_LFO_DEPTH 1800.
459 #define FILTERSWEEP_LFO_FREQ 0.2
460 #define FILTER_BANDWIDTH 50
461
462 /* filter the sweep variables */
463 float lfo,dlfo,fs,fc,BW,C,D,a0,a1,a2,b1,b2,*x[3],*y[3];
464
465 void applyeffect(char* buffer,int r)
466 {
467         short* samples = (short*) buffer;
468         int i;
469         for (i=0;i<r;i++)
470         {
471                 int chn;
472
473                 fc = sin(lfo)*FILTERSWEEP_LFO_DEPTH+FILTERSWEEP_LFO_CENTER;
474                 lfo += dlfo;
475                 if (lfo>2.*M_PI) lfo -= 2.*M_PI;
476                 C = 1./tan(M_PI*BW/fs);
477                 D = 2.*cos(2*M_PI*fc/fs);
478                 a0 = 1./(1.+C);
479                 a1 = 0;
480                 a2 = -a0;
481                 b1 = -C*D*a0;
482                 b2 = (C-1)*a0;
483
484                 for (chn=0;chn<channels;chn++)
485                 {
486                         x[chn][2] = x[chn][1];
487                         x[chn][1] = x[chn][0];
488
489                         y[chn][2] = y[chn][1];
490                         y[chn][1] = y[chn][0];
491
492                         x[chn][0] = samples[i*channels+chn];
493                         y[chn][0] = a0*x[chn][0] + a1*x[chn][1] + a2*x[chn][2] 
494                                 - b1*y[chn][1] - b2*y[chn][2];
495                         samples[i*channels+chn] = y[chn][0];
496                 }
497         }
498 }
499
500 static ssize_t get_avail(snd_pcm_t *pcm)
501 {
502         ssize_t avail;
503
504         while (1) {
505                 avail = snd_pcm_avail(pcm);
506                 if (avail == -EAGAIN)
507                         continue;
508                 break;
509         }
510         return avail;
511 }
512
513 void help(void)
514 {
515         int k;
516         printf(
517 "Usage: latency [OPTION]... [FILE]...\n"
518 "-h,--help      help\n"
519 "-P,--pdevice   playback device\n"
520 "-C,--cdevice   capture device\n"
521 "-m,--min       minimum latency in frames\n"
522 "-M,--max       maximum latency in frames\n"
523 "-U,--updates   I/O updates in milliseconds (0 = off)\n"
524 "-F,--frames    frames to transfer\n"
525 "-f,--format    sample format\n"
526 "-c,--channels  channels\n"
527 "-r,--rate      rate\n"
528 "-B,--buffer    buffer size in frames\n"
529 "-E,--period    period size in frames\n"
530 "-s,--seconds   duration of test in seconds\n"
531 "-b,--block     block mode\n"
532 "-p,--poll      use poll (wait for event - reduces CPU usage)\n"
533 "-y,--usleep    sleep for the specified amount of microseconds between\n"
534 "               stream updates (default 0 - off)\n"
535 "-e,--effect    apply an effect (bandpass filter sweep)\n"
536 "-x,--posdump   dump buffer positions\n"
537 "-X,--realtime  do a realtime check (buffering)\n"
538 "-O,--policy    set scheduler policy (RR, FIFO or OTHER)\n"
539 );
540         printf("Recognized sample formats are:");
541         for (k = 0; k < SND_PCM_FORMAT_LAST; ++k) {
542                 const char *s = snd_pcm_format_name(k);
543                 if (s)
544                         printf(" %s", s);
545         }
546         printf("\n\n");
547         printf(
548 "Tip #1 (usable latency with large periods, non-blocking mode, good CPU usage,\n"
549 "        superb xrun prevention):\n"
550 "  latency -m 8192 -M 8192 -t 1 -p\n"
551 "Tip #2 (superb latency, non-blocking mode, but heavy CPU usage):\n"
552 "  latency -m 128 -M 128\n"
553 );
554 }
555
556 int main(int argc, char *argv[])
557 {
558         struct option long_option[] =
559         {
560                 {"help", 0, NULL, 'h'},
561                 {"pdevice", 1, NULL, 'P'},
562                 {"cdevice", 1, NULL, 'C'},
563                 {"min", 1, NULL, 'm'},
564                 {"max", 1, NULL, 'M'},
565                 {"updates", 1, NULL, 'U'},
566                 {"frames", 1, NULL, 'F'},
567                 {"format", 1, NULL, 'f'},
568                 {"channels", 1, NULL, 'c'},
569                 {"rate", 1, NULL, 'r'},
570                 {"buffer", 1, NULL, 'B'},
571                 {"period", 1, NULL, 'E'},
572                 {"seconds", 1, NULL, 's'},
573                 {"block", 0, NULL, 'b'},
574                 {"poll", 0, NULL, 'p'},
575                 {"usleep", 1, NULL, 'y'},
576                 {"effect", 0, NULL, 'e'},
577                 {"posdump", 0, NULL, 'x'},
578                 {"realtime", 0, NULL, 'X'},
579                 {"policy", 1, NULL, 'O'},
580                 {NULL, 0, NULL, 0},
581         };
582         snd_pcm_t *phandle, *chandle;
583         char *buffer;
584         int err, latency, morehelp;
585         int ok;
586         snd_timestamp_t p_tstamp, c_tstamp;
587         ssize_t r, cap_avail, cap_avail_max, pbk_fill, pbk_fill_min;
588         size_t frames_in, frames_out, in_max;
589         timestamp_t tstamp_start;
590         int effect = 0;
591         morehelp = 0;
592         while (1) {
593                 int c;
594                 if ((c = getopt_long(argc, argv, "hP:C:m:M:U:F:f:c:r:B:E:s:y:O:bpenxX", long_option, NULL)) < 0)
595                         break;
596                 switch (c) {
597                 case 'h':
598                         morehelp++;
599                         break;
600                 case 'P':
601                         pdevice = strdup(optarg);
602                         break;
603                 case 'C':
604                         cdevice = strdup(optarg);
605                         break;
606                 case 'm':
607                         err = atoi(optarg) / 2;
608                         latency_min = err >= 4 ? err : 4;
609                         if (latency_max < latency_min)
610                                 latency_max = latency_min;
611                         break;
612                 case 'M':
613                         err = atoi(optarg) / 2;
614                         latency_max = latency_min > err ? latency_min : err;
615                         break;
616                 case 'U':
617                         err = atoi(optarg);
618                         sys_latency = err <= 0 ? 0 : err;
619                         break;
620                 case 'f':
621                         format = snd_pcm_format_value(optarg);
622                         if (format == SND_PCM_FORMAT_UNKNOWN) {
623                                 printf("Unknown format, setting to default S16_LE\n");
624                                 format = SND_PCM_FORMAT_S16_LE;
625                         }
626                         break;
627                 case 'c':
628                         err = atoi(optarg);
629                         channels = err >= 1 && err < 1024 ? err : 1;
630                         break;
631                 case 'r':
632                         err = atoi(optarg);
633                         rate = err >= 4000 && err < 200000 ? err : 44100;
634                         break;
635                 case 'B':
636                         err = atoi(optarg);
637                         buffer_size = err >= 32 && err < 200000 ? err : 0;
638                         break;
639                 case 'E':
640                         err = atoi(optarg);
641                         period_size = err >= 32 && err < 200000 ? err : 0;
642                         break;
643                 case 's':
644                         err = atoi(optarg);
645                         loop_sec = err >= 1 && err <= 100000 ? err : 30;
646                         break;
647                 case 'b':
648                         block = 1;
649                         break;
650                 case 'p':
651                         use_poll = 1;
652                         break;
653                 case 'y':
654                         usleep_val = atoi(optarg);
655                         break;
656                 case 'e':
657                         effect = 1;
658                         break;
659                 case 'n':
660                         resample = 0;
661                         break;
662                 case 'x':
663                         pos_dump = 1;
664                         break;
665                 case 'X':
666                         realtime_check = 1;
667                         break;
668                 case 'O':
669                         sched_policy = optarg;
670                         break;
671                 }
672         }
673
674         if (morehelp) {
675                 help();
676                 return 0;
677         }
678         err = snd_output_stdio_attach(&output, stdout, 0);
679         if (err < 0) {
680                 printf("Output failed: %s\n", snd_strerror(err));
681                 return 0;
682         }
683
684         loop_limit = loop_sec * rate;
685         latency = latency_min - 4;
686         buffer = malloc((latency_max * 2 * snd_pcm_format_physical_width(format) / 8) * channels);
687
688         /* I/O updates based on a system timer */
689         if (sys_latency > 0) {
690                 block = 0;
691                 use_poll = 0;
692         }
693
694         setscheduler();
695
696         printf("Playback device is %s\n", pdevice);
697         printf("Capture device is %s\n", cdevice);
698         printf("Parameters are %iHz, %s, %i channels, %s mode, use poll %s\n",
699                         rate, snd_pcm_format_name(format),
700                         channels, block ? "blocking" : "non-blocking",
701                         use_poll ? "yes" : "no");
702         printf("Loop limit is %lu frames, minimum latency = %i, maximum latency = %i",
703                         loop_limit, latency_min * 2, latency_max * 2);
704         if (sys_latency > 0)
705                 printf(", I/O updates %ims", sys_latency);
706         else if (!block && !use_poll)
707                 printf(", I/O usleep %ius", usleep_val);
708         printf("\n");
709
710         if ((err = snd_pcm_open(&phandle, pdevice, SND_PCM_STREAM_PLAYBACK, block ? 0 : SND_PCM_NONBLOCK)) < 0) {
711                 printf("Playback open error: %s\n", snd_strerror(err));
712                 return 0;
713         }
714         if ((err = snd_pcm_open(&chandle, cdevice, SND_PCM_STREAM_CAPTURE, block ? 0 : SND_PCM_NONBLOCK)) < 0) {
715                 printf("Record open error: %s\n", snd_strerror(err));
716                 return 0;
717         }
718
719         /* initialize the filter sweep variables */
720         if (effect) {
721                 fs = (float) rate;
722                 BW = FILTER_BANDWIDTH;
723
724                 lfo = 0;
725                 dlfo = 2.*M_PI*FILTERSWEEP_LFO_FREQ/fs;
726
727                 x[0] = (float*) malloc(channels*sizeof(float));         
728                 x[1] = (float*) malloc(channels*sizeof(float));         
729                 x[2] = (float*) malloc(channels*sizeof(float));         
730                 y[0] = (float*) malloc(channels*sizeof(float));         
731                 y[1] = (float*) malloc(channels*sizeof(float));         
732                 y[2] = (float*) malloc(channels*sizeof(float));         
733         }
734
735         cap_avail_max = 0;
736         pbk_fill_min = latency * 2;
737                           
738         while (1) {
739                 frames_in = frames_out = 0;
740                 if (setparams(phandle, chandle, &latency) < 0)
741                         break;
742                 showlatency(latency);
743                 if ((err = snd_pcm_link(chandle, phandle)) < 0) {
744                         printf("Streams link error: %s\n", snd_strerror(err));
745                         exit(0);
746                 }
747                 if (snd_pcm_format_set_silence(format, buffer, latency * channels) < 0) {
748                         fprintf(stderr, "silence error\n");
749                         break;
750                 }
751                 if (writebuf(phandle, buffer, latency, &frames_out) < 0) {
752                         fprintf(stderr, "write error\n");
753                         break;
754                 }
755                 if (writebuf(phandle, buffer, latency, &frames_out) < 0) {
756                         fprintf(stderr, "write error\n");
757                         break;
758                 }
759
760                 if (realtime_check)
761                         timestamp_now(&tstamp_start);
762                 if ((err = snd_pcm_start(chandle)) < 0) {
763                         printf("Go error: %s\n", snd_strerror(err));
764                         exit(0);
765                 }
766                 if (realtime_check)
767                         printf("[%lldus] Stream start\n", timestamp_diff_micro(&tstamp_start));
768                 gettimestamp(phandle, &p_tstamp);
769                 gettimestamp(chandle, &c_tstamp);
770 #if 0
771                 printf("Playback:\n");
772                 showstat(phandle, frames_out);
773                 printf("Capture:\n");
774                 showstat(chandle, frames_in);
775 #endif
776
777                 ok = 1;
778                 in_max = 0;
779                 while (ok && frames_in < loop_limit) {
780                         cap_avail = latency;
781                         if (sys_latency > 0) {
782                                 poll(NULL, 0, sys_latency);
783                                 cap_avail = get_avail(chandle);
784                                 if (cap_avail < 0) {
785                                         printf("Avail failed: %s\n", snd_strerror(cap_avail));
786                                         ok = 0;
787                                         break;
788                                 }
789                         } else if (use_poll) {
790                                 /* use poll to wait for next event */
791                                 snd_pcm_wait(chandle, 1000);
792                         } else if (!block && usleep_val > 0) {
793                                 usleep(usleep_val);
794                         }
795                         if (pos_dump || realtime_check) {
796                                 if (sys_latency <= 0)
797                                         cap_avail = get_avail(chandle);
798                                 pbk_fill = get_avail(phandle);
799                                 if (pbk_fill >= 0)
800                                         pbk_fill = playback_buffer_size - pbk_fill;
801                                 if (cap_avail > cap_avail_max)
802                                         cap_avail_max = cap_avail;
803                                 if (pbk_fill >= 0 && pbk_fill < pbk_fill_min)
804                                         pbk_fill_min = pbk_fill;
805                                 if (realtime_check) {
806                                         long long diff = timestamp_diff_micro(&tstamp_start);
807                                         long long cap_pos = frames_to_micro(frames_in + cap_avail);
808                                         long long pbk_pos = frames_to_micro(frames_out - pbk_fill);
809                                         printf("[%lldus] POS: p=%zd (min=%zd, rt=%lldus) c=%zd (max=%zd, rt=%lldus)\n",
810                                                         diff, pbk_fill, pbk_fill_min, pbk_pos - diff,
811                                                         cap_avail, cap_avail_max, cap_pos - diff);
812                                 } else if (pos_dump) {
813                                         printf("POS: p=%zd (min=%zd), c=%zd (max=%zd)\n",
814                                                         pbk_fill, pbk_fill_min, cap_avail, cap_avail_max);
815                                 }
816                         }
817                         if ((r = readbuf(chandle, buffer, cap_avail, &frames_in, &in_max)) < 0)
818                                 ok = 0;
819                         else {
820                                 if (effect)
821                                         applyeffect(buffer, r);
822                                 if (writebuf(phandle, buffer, r, &frames_out) < 0)
823                                         ok = 0;
824                         }
825                 }
826                 if (ok)
827                         printf("Success\n");
828                 else
829                         printf("Failure\n");
830                 printf("Playback:\n");
831                 showstat(phandle, frames_out);
832                 printf("Capture:\n");
833                 showstat(chandle, frames_in);
834                 showinmax(in_max);
835                 if (p_tstamp.tv_sec == c_tstamp.tv_sec &&
836                     p_tstamp.tv_usec == c_tstamp.tv_usec)
837                         printf("Hardware sync\n");
838                 if (realtime_check) {
839                         long long diff = timestamp_diff_micro(&tstamp_start);
840                         long long mtime = frames_to_micro(frames_in);
841                         printf("Elapsed real time: %lldus\n", diff);
842                         printf("Elapsed device time: %lldus\n", mtime);
843                         printf("Test time diff (device - real): %lldus\n", mtime - diff);
844                 }
845                 snd_pcm_drop(chandle);
846                 snd_pcm_nonblock(phandle, 0);
847                 snd_pcm_drain(phandle);
848                 snd_pcm_nonblock(phandle, !block ? 1 : 0);
849                 if (ok) {
850 #if 1
851                         printf("Playback time = %li.%i, Record time = %li.%i, diff = %li\n",
852                                (long)p_tstamp.tv_sec,
853                                (int)p_tstamp.tv_usec,
854                                (long)c_tstamp.tv_sec,
855                                (int)c_tstamp.tv_usec,
856                                timediff(p_tstamp, c_tstamp));
857 #endif
858                         break;
859                 }
860                 snd_pcm_unlink(chandle);
861                 snd_pcm_hw_free(phandle);
862                 snd_pcm_hw_free(chandle);
863         }
864         snd_pcm_close(phandle);
865         snd_pcm_close(chandle);
866         snd_output_close(output);
867         snd_config_update_free_global();
868         free(buffer);
869         free(pdevice);
870         free(cdevice);
871         return 0;
872 }