summaryrefslogtreecommitdiff
path: root/alsaloop/alsaloop.c
blob: 4192712ed52da320347d5f68fcbf0bac0e88bfac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
/*
 *  A simple PCM loopback utility with adaptive sample rate support
 *
 *     Author: Jaroslav Kysela <perex@perex.cz>
 *
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <errno.h>
#include <getopt.h>
#include <alsa/asoundlib.h>
#include <sys/time.h>
#include <math.h>
#include <pthread.h>
#include <syslog.h>
#include <signal.h>
#include "alsaloop.h"

struct loopback_thread {
	int threaded;
	pthread_t thread;
	int exitcode;
	struct loopback **loopbacks;
	int loopbacks_count;
	snd_output_t *output;
};

int quit = 0;
int verbose = 0;
int workarounds = 0;
int daemonize = 0;
int use_syslog = 0;
struct loopback **loopbacks = NULL;
int loopbacks_count = 0;
char **my_argv = NULL;
int my_argc = 0;
struct loopback_thread *threads;
int threads_count = 0;
pthread_t main_job;
int arg_default_xrun = 0;
int arg_default_wake = 0;

static void my_exit(struct loopback_thread *thread, int exitcode)
{
	int i;

	for (i = 0; i < thread->loopbacks_count; i++)
		pcmjob_done(thread->loopbacks[i]);
	if (thread->threaded) {
		thread->exitcode = exitcode;
		pthread_exit(0);
	}
	exit(exitcode);
}

static int create_loopback_handle(struct loopback_handle **_handle,
				  const char *device,
				  const char *ctldev,
				  const char *id)
{
	char idbuf[1024];
	struct loopback_handle *handle;

	handle = calloc(1, sizeof(*handle));
	if (handle == NULL)
		return -ENOMEM;
	if (device == NULL)
		device = "hw:0,0";
	handle->device = strdup(device);
	if (handle->device == NULL) {
		free(handle);
		return -ENOMEM;
	}
	if (ctldev) {
		handle->ctldev = strdup(ctldev);
		if (handle->ctldev == NULL) {
			free(handle->device);
			free(handle);
			return -ENOMEM;
		}
	} else {
		handle->ctldev = NULL;
	}
	snprintf(idbuf, sizeof(idbuf)-1, "%s %s", id, device);
	idbuf[sizeof(idbuf)-1] = '\0';
	handle->id = strdup(idbuf);
	handle->access = SND_PCM_ACCESS_RW_INTERLEAVED;
	handle->format = SND_PCM_FORMAT_S16_LE;
	handle->rate = handle->rate_req = 48000;
	handle->channels = 2;
	handle->resample = 0;
	*_handle = handle;
	return 0;
}

static int create_loopback(struct loopback **_handle,
			   struct loopback_handle *play,
			   struct loopback_handle *capt,
			   snd_output_t *output)
{
	struct loopback *handle;

	handle = calloc(1, sizeof(*handle));
	if (handle == NULL)
		return -ENOMEM;
	handle->play = play;
	handle->capt = capt;
	play->loopback = handle;
	capt->loopback = handle;
	handle->latency_req = 0;
	handle->latency_reqtime = 10000;
	handle->loop_time = ~0UL;
	handle->loop_limit = ~0ULL;
	handle->output = output;
	handle->state = output;
#ifdef USE_SAMPLERATE
	handle->src_enable = 1;
	handle->src_converter_type = SRC_SINC_BEST_QUALITY;
#endif
	*_handle = handle;
	return 0;
}

static void set_loop_time(struct loopback *loop, unsigned long loop_time)
{
	loop->loop_time = loop_time;
	loop->loop_limit = loop->capt->rate * loop_time;
}

static void setscheduler(void)
{
	struct sched_param sched_param;

	if (sched_getparam(0, &sched_param) < 0) {
		logit(LOG_WARNING, "Scheduler getparam failed.\n");
		return;
	}
	sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
	if (!sched_setscheduler(0, SCHED_RR, &sched_param)) {
		if (verbose)
			logit(LOG_WARNING, "Scheduler set to Round Robin with priority %i\n", sched_param.sched_priority);
		return;
	}
	if (verbose)
		logit(LOG_INFO, "!!!Scheduler set to Round Robin with priority %i FAILED!\n", sched_param.sched_priority);
}

void help(void)
{
	int k;
	printf(
"Usage: alsaloop [OPTION]...\n\n"
"-h,--help      help\n"
"-g,--config    configuration file (one line = one job specified)\n"
"-d,--daemonize daemonize the main process and use syslog for errors\n"
"-P,--pdevice   playback device\n"
"-C,--cdevice   capture device\n"
"-X,--pctl      playback ctl device\n"
"-Y,--cctl      capture ctl device\n"
"-x,--prateshift playback 'PCM Rate Shift 100000' ascii ctl name\n"
"-l,--latency   requested latency in frames\n"
"-t,--tlatency  requested latency in usec (1/1000000sec)\n"
"-f,--format    sample format\n"
"-c,--channels  channels\n"
"-r,--rate      rate\n"
"-n,--resample  resample in alsa-lib\n"
"-A,--samplerate use converter (0=sincbest,1=sincmedium,2=sincfastest,\n"
"                               3=zerohold,4=linear)\n"
"-B,--buffer    buffer size in frames\n"
"-E,--period    period size in frames\n"
"-s,--seconds   duration of loop in seconds\n"
"-b,--nblock    non-block mode (very early process wakeup)\n"
"-S,--sync      sync mode(0=none,1=simple,2=captshift,3=playshift,4=samplerate,\n"
"                         5=auto)\n"
"-a,--slave     stream parameters slave mode (0=auto, 1=on, 2=off)\n"
"-T,--thread    thread number (-1 = create unique)\n"
"-m,--mixer	redirect mixer, argument is:\n"
"		    SRC_SLAVE_ID(PLAYBACK)[@DST_SLAVE_ID(CAPTURE)]\n"
"-O,--ossmixer	rescan and redirect oss mixer, argument is:\n"
"		    ALSA_ID@OSS_ID  (for example: \"Master@VOLUME\")\n"
"-e,--effect    apply an effect (bandpass filter sweep)\n"
"-v,--verbose   verbose mode (more -v means more verbose)\n"
"-w,--workaround use workaround (serialopen)\n"
"-U,--xrun      xrun profiling\n"
"-W,--wake      process wake timeout in ms\n"
"-z,--syslog    use syslog for errors\n"
);
	printf("\nRecognized sample formats are:");
	for (k = 0; k < SND_PCM_FORMAT_LAST; ++k) {
		const char *s = snd_pcm_format_name(k);
		if (s)
			printf(" %s", s);
	}
	printf("\n\n");
	printf(
"Tip #1 (usable 500ms latency, good CPU usage, superb xrun prevention):\n"
"  alsaloop -t 500000\n"
"Tip #2 (superb 1ms latency, but heavy CPU usage):\n"
"  alsaloop -t 1000\n"
);
}

static long timediff(struct timeval t1, struct timeval t2)
{
	signed long l;

	t1.tv_sec -= t2.tv_sec;
	l = (signed long) t1.tv_usec - (signed long) t2.tv_usec;
	if (l < 0) {
		t1.tv_sec--;
		l = 1000000 + l;
		l %= 1000000;
	}
	return (t1.tv_sec * 1000000) + l;
}

static void add_loop(struct loopback *loop)
{
	loopbacks = realloc(loopbacks, (loopbacks_count + 1) *
						sizeof(struct loopback *));
	if (loopbacks == NULL) {
		logit(LOG_CRIT, "No enough memory\n");
		exit(EXIT_FAILURE);
	}
	loopbacks[loopbacks_count++] = loop;
}

static int init_mixer_control(struct loopback_control *control,
			      char *id)
{
	int err;

	err = snd_ctl_elem_id_malloc(&control->id);
	if (err < 0)
		return err;
	err = snd_ctl_elem_info_malloc(&control->info);
	if (err < 0)
		return err;
	err = snd_ctl_elem_value_malloc(&control->value);
	if (err < 0)
		return err;
	err = control_parse_id(id, control->id);
	if (err < 0)
		return err;
	return 0;
}

static int add_mixers(struct loopback *loop,
		      char **mixers,
		      int mixers_count)
{
	struct loopback_mixer *mixer, *last = NULL;
	char *str1;
	int err;

	while (mixers_count > 0) {
		mixer = calloc(1, sizeof(*mixer));
		if (mixer == NULL)
			return -ENOMEM;
		if (last)
			last->next = mixer;
		else
			loop->controls = mixer;
		last = mixer;
		str1 = strchr(*mixers, '@');
		if (str1)
			*str1 = '\0';
		err = init_mixer_control(&mixer->src, *mixers);
		if (err < 0) {
			logit(LOG_CRIT, "Wrong mixer control ID syntax '%s'\n", *mixers);
			return -EINVAL;
		}
		err = init_mixer_control(&mixer->dst, str1 ? str1 + 1 : *mixers);
		if (err < 0) {
			logit(LOG_CRIT, "Wrong mixer control ID syntax '%s'\n", str1 ? str1 + 1 : *mixers);
			return -EINVAL;
		}
		if (str1)
			*str1 = '@';
		mixers++;
		mixers_count--;
	}
	return 0;
}

static int add_oss_mixers(struct loopback *loop,
			  char **mixers,
			  int mixers_count)
{
	struct loopback_ossmixer *mixer, *last = NULL;
	char *str1, *str2;

	while (mixers_count > 0) {
		mixer = calloc(1, sizeof(*mixer));
		if (mixer == NULL)
			return -ENOMEM;
		if (last)
			last->next = mixer;
		else
			loop->oss_controls = mixer;
		last = mixer;
		str1 = strchr(*mixers, ',');
		if (str1)
			*str1 = '\0';
		str2 = strchr(str1 ? str1 + 1 : *mixers, '@');
		if (str2)
			*str2 = '\0';
		mixer->alsa_id = strdup(*mixers);
		if (str1)
			mixer->alsa_index = atoi(str1);
		mixer->oss_id = strdup(str2 ? str2 + 1 : *mixers);
		if (mixer->alsa_id == NULL || mixer->oss_id == NULL) {
			logit(LOG_CRIT, "Not enough memory");
			return -ENOMEM;
		}
		if (str1)
			*str1 = ',';
		if (str2)
			*str2 = ',';
		mixers++;
		mixers_count--;
	}
	return 0;
}

static void enable_syslog(void)
{
	if (!use_syslog) {
		use_syslog = 1;
		openlog("alsaloop", LOG_NDELAY|LOG_PID, LOG_DAEMON);
	}
}

static int parse_config_file(const char *file, snd_output_t *output);

static int parse_config(int argc, char *argv[], snd_output_t *output,
			int cmdline)
{
	struct option long_option[] =
	{
		{"help", 0, NULL, 'h'},
		{"config", 1, NULL, 'g'},
		{"daemonize", 0, NULL, 'd'},
		{"pdevice", 1, NULL, 'P'},
		{"cdevice", 1, NULL, 'C'},
		{"pctl", 1, NULL, 'X'},
		{"cctl", 1, NULL, 'Y'},
		{"prateshift", 1, NULL, 'x'},
		{"latency", 1, NULL, 'l'},
		{"tlatency", 1, NULL, 't'},
		{"format", 1, NULL, 'f'},
		{"channels", 1, NULL, 'c'},
		{"rate", 1, NULL, 'r'},
		{"buffer", 1, NULL, 'B'},
		{"period", 1, NULL, 'E'},
		{"seconds", 1, NULL, 's'},
		{"nblock", 0, NULL, 'b'},
		{"effect", 0, NULL, 'e'},
		{"verbose", 0, NULL, 'v'},
		{"resample", 0, NULL, 'n'},
		{"samplerate", 1, NULL, 'A'},
		{"sync", 1, NULL, 'S'},
		{"slave", 1, NULL, 'a'},
		{"thread", 1, NULL, 'T'},
		{"mixer", 1, NULL, 'm'},
		{"ossmixer", 1, NULL, 'O'},
		{"workaround", 1, NULL, 'w'},
		{"xrun", 0, NULL, 'U'},
		{"syslog", 0, NULL, 'z'},
		{NULL, 0, NULL, 0},
	};
	int err, morehelp;
	char *arg_config = NULL;
	char *arg_pdevice = NULL;
	char *arg_cdevice = NULL;
	char *arg_pctl = NULL;
	char *arg_cctl = NULL;
	char *arg_prateshift = NULL;
	unsigned int arg_latency_req = 0;
	unsigned int arg_latency_reqtime = 10000;
	snd_pcm_format_t arg_format = SND_PCM_FORMAT_S16_LE;
	unsigned int arg_channels = 2;
	unsigned int arg_rate = 48000;
	snd_pcm_uframes_t arg_buffer_size = 0;
	snd_pcm_uframes_t arg_period_size = 0;
	unsigned long arg_loop_time = ~0UL;
	int arg_nblock = 0;
	int arg_effect = 0;
	int arg_resample = 0;
#ifdef USE_SAMPLERATE
	int arg_samplerate = SRC_SINC_FASTEST + 1;
#endif
	int arg_sync = SYNC_TYPE_AUTO;
	int arg_slave = SLAVE_TYPE_AUTO;
	int arg_thread = 0;
	struct loopback *loop = NULL;
	char *arg_mixers[MAX_MIXERS];
	int arg_mixers_count = 0;
	char *arg_ossmixers[MAX_MIXERS];
	int arg_ossmixers_count = 0;
	int arg_xrun = arg_default_xrun;
	int arg_wake = arg_default_wake;

	morehelp = 0;
	while (1) {
		int c;
		if ((c = getopt_long(argc, argv,
				"hdg:P:C:X:Y:x:l:t:F:f:c:r:s:benvA:S:a:m:T:O:w:UW:z",
				long_option, NULL)) < 0)
			break;
		switch (c) {
		case 'h':
			morehelp++;
			break;
		case 'g':
			arg_config = strdup(optarg);
			break;
		case 'd':
			daemonize = 1;
			enable_syslog();
			break;
		case 'P':
			arg_pdevice = strdup(optarg);
			break;
		case 'C':
			arg_cdevice = strdup(optarg);
			break;
		case 'X':
			arg_pctl = strdup(optarg);
			break;
		case 'Y':
			arg_cctl = strdup(optarg);
			break;
		case 'x':
			arg_prateshift = strdup(optarg);
			break;
		case 'l':
			err = atoi(optarg);
			arg_latency_req = err >= 4 ? err : 4;
			break;
		case 't':
			err = atoi(optarg);
			arg_latency_reqtime = err >= 500 ? err : 500;
			break;
		case 'f':
			arg_format = snd_pcm_format_value(optarg);
			if (arg_format == SND_PCM_FORMAT_UNKNOWN) {
				logit(LOG_WARNING, "Unknown format, setting to default S16_LE\n");
				arg_format = SND_PCM_FORMAT_S16_LE;
			}
			break;
		case 'c':
			err = atoi(optarg);
			arg_channels = err >= 1 && err < 1024 ? err : 1;
			break;
		case 'r':
			err = atoi(optarg);
			arg_rate = err >= 4000 && err < 200000 ? err : 44100;
			break;
		case 'B':
			err = atoi(optarg);
			arg_buffer_size = err >= 32 && err < 200000 ? err : 0;
			break;
		case 'E':
			err = atoi(optarg);
			arg_period_size = err >= 32 && err < 200000 ? err : 0;
			break;
		case 's':
			err = atoi(optarg);
			arg_loop_time = err >= 1 && err <= 100000 ? err : 30;
			break;
		case 'b':
			arg_nblock = 1;
			break;
		case 'e':
			arg_effect = 1;
			break;
		case 'n':
			arg_resample = 1;
			break;
#ifdef USE_SAMPLERATE
		case 'A':
			if (strcasecmp(optarg, "sincbest") == 0)
				arg_samplerate = SRC_SINC_BEST_QUALITY;
			else if (strcasecmp(optarg, "sincmedium") == 0)
				arg_samplerate = SRC_SINC_MEDIUM_QUALITY;
			else if (strcasecmp(optarg, "sincfastest") == 0)
				arg_samplerate = SRC_SINC_FASTEST;
			else if (strcasecmp(optarg, "zerohold") == 0)
				arg_samplerate = SRC_ZERO_ORDER_HOLD;
			else if (strcasecmp(optarg, "linear") == 0)
				arg_samplerate = SRC_LINEAR;
			else
				arg_samplerate = atoi(optarg);
			if (arg_samplerate < 0 || arg_samplerate > SRC_LINEAR)
				arg_sync = SRC_SINC_FASTEST;
			arg_samplerate += 1;
			break;
#endif
		case 'S':
			if (strcasecmp(optarg, "samplerate") == 0)
				arg_sync = SYNC_TYPE_SAMPLERATE;
			else if (optarg[0] == 'n')
				arg_sync = SYNC_TYPE_NONE;
			else if (optarg[0] == 's')
				arg_sync = SYNC_TYPE_SIMPLE;
			else if (optarg[0] == 'c')
				arg_sync = SYNC_TYPE_CAPTRATESHIFT;
			else if (optarg[0] == 'p')
				arg_sync = SYNC_TYPE_PLAYRATESHIFT;
			else if (optarg[0] == 'r')
				arg_sync = SYNC_TYPE_SAMPLERATE;
			else
				arg_sync = atoi(optarg);
			if (arg_sync < 0 || arg_sync > SYNC_TYPE_LAST)
				arg_sync = SYNC_TYPE_AUTO;
			break;
		case 'a':
			if (optarg[0] == 'a')
				arg_slave = SLAVE_TYPE_AUTO;
			else if (strcasecmp(optarg, "on") == 0)
				arg_slave = SLAVE_TYPE_ON;
			else if (strcasecmp(optarg, "off") == 0)
				arg_slave = SLAVE_TYPE_OFF;
			else
				arg_slave = atoi(optarg);
			if (arg_slave < 0 || arg_slave > SLAVE_TYPE_LAST)
				arg_slave = SLAVE_TYPE_AUTO;
			break;
		case 'T':
			arg_thread = atoi(optarg);
			if (arg_thread < 0)
				arg_thread = 10000000 + loopbacks_count;
			break;
		case 'm':
			if (arg_mixers_count >= MAX_MIXERS) {
				logit(LOG_CRIT, "Maximum redirected mixer controls reached (max %i)\n", (int)MAX_MIXERS);
				exit(EXIT_FAILURE);
			}
			arg_mixers[arg_mixers_count++] = optarg;
			break;
		case 'O':
			if (arg_ossmixers_count >= MAX_MIXERS) {
				logit(LOG_CRIT, "Maximum redirected mixer controls reached (max %i)\n", (int)MAX_MIXERS);
				exit(EXIT_FAILURE);
			}
			arg_ossmixers[arg_ossmixers_count++] = optarg;
			break;
		case 'v':
			verbose++;
			break;
		case 'w':
			if (strcasecmp(optarg, "serialopen") == 0)
				workarounds |= WORKAROUND_SERIALOPEN;
			break;
		case 'U':
			arg_xrun = 1;
			if (cmdline)
				arg_default_xrun = 1;
			break;
		case 'W':
			arg_wake = atoi(optarg);
			if (cmdline)
				arg_default_wake = arg_wake;
			break;
		case 'z':
			enable_syslog();
			break;
		}
	}

	if (morehelp) {
		help();
		exit(EXIT_SUCCESS);
	}
	if (arg_config == NULL) {
		struct loopback_handle *play;
		struct loopback_handle *capt;
		err = create_loopback_handle(&play, arg_pdevice, arg_pctl, "playback");
		if (err < 0) {
			logit(LOG_CRIT, "Unable to create playback handle.\n");
			exit(EXIT_FAILURE);
		}
		err = create_loopback_handle(&capt, arg_cdevice, arg_cctl, "capture");
		if (err < 0) {
			logit(LOG_CRIT, "Unable to create capture handle.\n");
			exit(EXIT_FAILURE);
		}
		err = create_loopback(&loop, play, capt, output);
		if (err < 0) {
			logit(LOG_CRIT, "Unable to create loopback handle.\n");
			exit(EXIT_FAILURE);
		}
		play->format = capt->format = arg_format;
		play->rate = play->rate_req = capt->rate = capt->rate_req = arg_rate;
		play->channels = capt->channels = arg_channels;
		play->buffer_size_req = capt->buffer_size_req = arg_buffer_size;
		play->period_size_req = capt->period_size_req = arg_period_size;
		play->resample = capt->resample = arg_resample;
		play->nblock = capt->nblock = arg_nblock ? 1 : 0;
		loop->latency_req = arg_latency_req;
		loop->latency_reqtime = arg_latency_reqtime;
		loop->sync = arg_sync;
		loop->slave = arg_slave;
		loop->thread = arg_thread;
		loop->xrun = arg_xrun;
		loop->wake = arg_wake;
		err = add_mixers(loop, arg_mixers, arg_mixers_count);
		if (err < 0) {
			logit(LOG_CRIT, "Unable to add mixer controls.\n");
			exit(EXIT_FAILURE);
		}
		err = add_oss_mixers(loop, arg_ossmixers, arg_ossmixers_count);
		if (err < 0) {
			logit(LOG_CRIT, "Unable to add ossmixer controls.\n");
			exit(EXIT_FAILURE);
		}
		if (arg_prateshift)
			play->prateshift_name = arg_prateshift;

#ifdef USE_SAMPLERATE
		loop->src_enable = arg_samplerate > 0;
		if (loop->src_enable)
			loop->src_converter_type = arg_samplerate - 1;
#endif
		set_loop_time(loop, arg_loop_time);
		add_loop(loop);
		return 0;
	}

	return parse_config_file(arg_config, output);
}

static int parse_config_file(const char *file, snd_output_t *output)
{
	FILE *fp;
	char line[2048], word[2048];
	char *str, *ptr;
	int argc, c, err = 0;
	char **argv;

	fp = fopen(file, "r");
	if (fp == NULL) {
		logit(LOG_CRIT, "Unable to open file '%s': %s\n", file, strerror(errno));
		return -EIO;
	}
	while (!feof(fp)) {
		if (fgets(line, sizeof(line)-1, fp) == NULL)
			break;
		line[sizeof(line)-1] = '\0';
		my_argv = realloc(my_argv, my_argc + MAX_ARGS * sizeof(char *));
		if (my_argv == NULL)
			return -ENOMEM;
		argv = my_argv + my_argc;
		argc = 0;
		argv[argc++] = strdup("<prog>");
		my_argc++;
		str = line;
		while (*str) {
			ptr = word;
			while (*str && (*str == ' ' || *str < ' '))
				str++;
			if (*str == '#')
				goto __next;
			if (*str == '\'' || *str == '\"') {
				c = *str++;
				while (*str && *str != c)
					*ptr++ = *str++;
				if (*str == c)
					str++;
			} else {
				while (*str && *str != ' ' && *str != '\t')
					*ptr++ = *str++;
			}
			if (ptr != word) {
				if (*(ptr-1) == '\n')
					ptr--;
				*ptr = '\0';
				if (argc >= MAX_ARGS) {
					logit(LOG_CRIT, "Too many arguments.");
					goto __error;
				}
				argv[argc++] = strdup(word);
				my_argc++;
			}
		}
		/* erase runtime variables for getopt */
		optarg = NULL;
		optind = opterr = 1;
		optopt = '?';

		err = parse_config(argc, argv, output, 0);
	      __next:
		if (err < 0)
			break;
		err = 0;
	}
      __error:
	fclose(fp);

	return err;
}

static void thread_job1(void *_data)
{
	struct loopback_thread *thread = _data;
	snd_output_t *output = thread->output;
	struct pollfd *pfds = NULL;
	int pfds_count = 0;
	int i, j, err, wake = 1000000;

	setscheduler();

	for (i = 0; i < thread->loopbacks_count; i++) {
		err = pcmjob_init(thread->loopbacks[i]);
		if (err < 0) {
			logit(LOG_CRIT, "Loopback initialization failure.\n");
			my_exit(thread, EXIT_FAILURE);
		}
	}
	for (i = 0; i < thread->loopbacks_count; i++) {
		err = pcmjob_start(thread->loopbacks[i]);
		if (err < 0) {
			logit(LOG_CRIT, "Loopback start failure.\n");
			my_exit(thread, EXIT_FAILURE);
		}
		pfds_count += thread->loopbacks[i]->pollfd_count;
		j = thread->loopbacks[i]->wake;
		if (j > 0 && j < wake)
			wake = j;
	}
	if (wake >= 1000000)
		wake = -1;
	pfds = calloc(pfds_count, sizeof(struct pollfd));
	if (pfds == NULL || pfds_count <= 0) {
		logit(LOG_CRIT, "Poll FDs allocation failed.\n");
		my_exit(thread, EXIT_FAILURE);
	}
	while (!quit) {
		struct timeval tv1, tv2;
		for (i = j = 0; i < thread->loopbacks_count; i++) {
			err = pcmjob_pollfds_init(thread->loopbacks[i], &pfds[j]);
			if (err < 0) {
				logit(LOG_CRIT, "Poll FD initialization failed.\n");
				my_exit(thread, EXIT_FAILURE);
			}
			j += err;
		}
		if (verbose > 10)
			gettimeofday(&tv1, NULL);
		err = poll(pfds, j, wake);
		if (err < 0)
			err = -errno;
		if (verbose > 10) {
			gettimeofday(&tv2, NULL);
			snd_output_printf(output, "pool took %lius\n", timediff(tv2, tv1));
		}
		if (err < 0) {
			if (err == -EINTR || err == -ERESTART)
				continue;
			logit(LOG_CRIT, "Poll failed: %s\n", strerror(-err));
			my_exit(thread, EXIT_FAILURE);
		}
		for (i = j = 0; i < thread->loopbacks_count; i++) {
			struct loopback *loop = thread->loopbacks[i];
			if (j < loop->active_pollfd_count) {
				err = pcmjob_pollfds_handle(loop, &pfds[j]);
				if (err < 0) {
					logit(LOG_CRIT, "pcmjob failed.\n");
					exit(EXIT_FAILURE);
				}
			}
			j += loop->active_pollfd_count;
		}
	}

	my_exit(thread, EXIT_SUCCESS);
}

static void thread_job(struct loopback_thread *thread)
{
	if (!thread->threaded) {
		thread_job1(thread);
		return;
	}
	pthread_create(&thread->thread, NULL, (void *) &thread_job1,
					      (void *) thread);
}

static void send_to_all(int sig)
{
	struct loopback_thread *thread;
	int i;

	for (i = 0; i < threads_count; i++) {
		thread = &threads[i];
		if (thread->threaded)
			pthread_kill(thread->thread, sig);
	}
}

static void signal_handler(int sig)
{
	quit = 1;
	send_to_all(SIGUSR2);
}

static void signal_handler_state(int sig)
{
	pthread_t self = pthread_self();
	struct loopback_thread *thread;
	int i, j;

	if (pthread_equal(main_job, self))
		send_to_all(SIGUSR1);
	for (i = 0; i < threads_count; i++) {
		thread = &threads[i];
		if (thread->thread == self) {
			for (j = 0; j < thread->loopbacks_count; j++)
				pcmjob_state(thread->loopbacks[j]);
		}
	}
	signal(sig, signal_handler_state);
}

static void signal_handler_ignore(int sig)
{
	signal(sig, signal_handler_ignore);
}

int main(int argc, char *argv[])
{
	snd_output_t *output;
	int i, j, k, l, err;

	err = snd_output_stdio_attach(&output, stdout, 0);
	if (err < 0) {
		logit(LOG_CRIT, "Output failed: %s\n", snd_strerror(err));
		exit(EXIT_FAILURE);
	}
	err = parse_config(argc, argv, output, 1);
	if (err < 0) {
		logit(LOG_CRIT, "Unable to parse arguments or configuration...\n");
		exit(EXIT_FAILURE);
	}
	while (my_argc > 0)
		free(my_argv[--my_argc]);
	free(my_argv);

	if (loopbacks_count <= 0) {
		logit(LOG_CRIT, "No loopback defined...\n");
		exit(EXIT_FAILURE);
	}

	if (daemonize) {
		if (daemon(0, 0) < 0) {
			logit(LOG_CRIT, "daemon() failed: %s\n", strerror(errno));
			exit(EXIT_FAILURE);
		}
		i = fork();
		if (i < 0) {
			logit(LOG_CRIT, "fork() failed: %s\n", strerror(errno));
			exit(EXIT_FAILURE);
		}
		if (i > 0) {
			/* wait(&i); */
			exit(EXIT_SUCCESS);
		}
	}

	/* we must sort thread IDs */
	j = -1;
	do {
		k = 0x7fffffff;
		for (i = 0; i < loopbacks_count; i++) {
			if (loopbacks[i]->thread < k &&
			    loopbacks[i]->thread > j)
				k = loopbacks[i]->thread;
		}
		j++;
		for (i = 0; i < loopbacks_count; i++) {
			if (loopbacks[i]->thread == k)
				loopbacks[i]->thread = j;
		}
	} while (k != 0x7fffffff);
	/* fix maximum thread id */
	for (i = 0, j = -1; i < loopbacks_count; i++) {
		if (loopbacks[i]->thread > j)
			j = loopbacks[i]->thread;
	}
	j += 1;
	threads = calloc(1, sizeof(struct loopback_thread) * j);
	if (threads == NULL) {
		logit(LOG_CRIT, "No enough memory\n");
		exit(EXIT_FAILURE);
	}
	/* sort all threads */
	for (k = 0; k < j; k++) {
		for (i = l = 0; i < loopbacks_count; i++)
			if (loopbacks[i]->thread == k)
				l++;
		threads[k].loopbacks = malloc(l * sizeof(struct loopback *));
		threads[k].loopbacks_count = l;
		threads[k].output = output;
		threads[k].threaded = j > 1;
		for (i = l = 0; i < loopbacks_count; i++)
			if (loopbacks[i]->thread == k)
				threads[k].loopbacks[l++] = loopbacks[i];
	}
	threads_count = j;
	main_job = pthread_self();
 
	signal(SIGINT, signal_handler);
	signal(SIGTERM, signal_handler);
	signal(SIGABRT, signal_handler);
	signal(SIGUSR1, signal_handler_state);
	signal(SIGUSR2, signal_handler_ignore);

	for (k = 0; k < threads_count; k++)
		thread_job(&threads[k]);

	if (j > 1) {
		for (k = 0; k < threads_count; k++)
			pthread_join(threads[k].thread, NULL);
	}

	if (use_syslog)
		closelog();
	exit(EXIT_SUCCESS);
}