summaryrefslogtreecommitdiff
path: root/libhfp/soundio-alsa.cpp
blob: a41a937ea7ee0dbf42fb8a3b8d643e0724b9be5c (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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
/*
 * Software Bluetooth Hands-Free Implementation
 *
 * Copyright (C) 2006-2008 Sam Revitch <samr7@cs.washington.edu>
 *
 * 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, 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 St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <libhfp/soundio.h>
#include <libhfp/soundio-buf.h>

/*
 * ALSA backend SoundIo implementation, including support for procedural
 * and mmap access.
 */

#if defined(USE_ALSA_SOUNDIO)
#include <alsa/asoundlib.h>

namespace libhfp {

/*
 * Linux ALSA sound I/O base class.
 * There are more specific ALSA classes for low-level procedural
 * and MMAP interfaces.
 *
 * Nomenclature clash alert!
 * One sample group -- N bytes per sample, M channels, NxM bytes
 *	ALSA: "frame"
 *	Us:   "record"
 *
 * Hardware sample batch size -- the interrupt interval
 *	ALSA: "period"
 *	Us:   "packet"
 */

class AlsaIoBase {
public:
	struct AlsaChannelProps {
		snd_pcm_uframes_t	packetsize;
		snd_pcm_uframes_t	bufsize;
		snd_pcm_uframes_t	min_avail;
	};

	SoundIoFormat			m_format;

	DispatchInterface		*m_ei;

	snd_pcm_t			*m_play_handle;
	char				*m_play_devspec;
	AlsaChannelProps		m_play_props;
	int				m_play_not_count;
	SocketNotifier			**m_play_not;
	bool				m_play_async;
	bool				m_play_xrun;

	snd_pcm_t			*m_rec_handle;
	char				*m_rec_devspec;
	AlsaChannelProps		m_rec_props;
	int				m_rec_not_count;
	SocketNotifier			**m_rec_not;
	bool				m_rec_async;
	bool				m_rec_xrun;

	AlsaIoBase(DispatchInterface *eip,
		   const char *output_devspec, const char *input_devspec)
		: m_ei(eip), 
		  m_play_handle(NULL), m_play_not_count(0), m_play_not(NULL),
		  m_play_async(false), m_rec_handle(NULL), m_rec_not_count(0),
		  m_rec_not(NULL), m_rec_async(false) {
		m_play_devspec = strdup(output_devspec);
		m_rec_devspec = m_play_devspec;
		if (input_devspec &&
		    strcmp(input_devspec, output_devspec)) {
			m_rec_devspec = strdup(input_devspec);
		}
		memset(&m_play_props, 0, sizeof(m_play_props));
		memset(&m_rec_props, 0, sizeof(m_rec_props));

		/* Set a default format */
		memset(&m_format, 0, sizeof(m_format));
		m_format.sampletype = SIO_PCM_S16_LE;
		m_format.samplerate = 8000;
		m_format.packet_samps = 128;
		m_format.nchannels = 1;
		m_format.bytes_per_record = 2;
	}

	~AlsaIoBase() {
		CloseDevice();
		if (m_play_devspec) {
			free(m_play_devspec);
		}
		if (m_rec_devspec && (m_rec_devspec != m_play_devspec)) {
			free(m_rec_devspec);
		}
	}

	snd_pcm_sframes_t GetPacketSize(void) const {
		if (m_rec_handle) return m_rec_props.packetsize;
		if (m_play_handle) return m_play_props.packetsize;
		return m_format.packet_samps;
	}

	snd_pcm_sframes_t GetSampleBytes(void) const
		{ return m_format.bytes_per_record; }

	bool OpenDevice(snd_pcm_access_t pcm_access, bool play, bool rec) {
		int err;
		if (m_play_handle || m_rec_handle) { return false; }

		if (play) {
			err = snd_pcm_open(&m_play_handle, m_play_devspec,
					   SND_PCM_STREAM_PLAYBACK, 0);
			if (err < 0) {
				m_ei->LogWarn("Could not open playback "
					      "device \"%s\": %d\n",
					      m_play_devspec, err);
				return false;
			}

			if (!ConfigurePcm(m_play_handle, m_format, pcm_access,
					  m_play_props)) {
				m_ei->LogWarn("Error configuring playback "
					      "device \"%s\"\n",
					      m_play_devspec);
				CloseDevice();
				return false;
			}
		}

		if (rec) {
			err = snd_pcm_open(&m_rec_handle, m_rec_devspec,
					   SND_PCM_STREAM_CAPTURE, 0);
			if (err < 0) {
				m_ei->LogWarn("Could not open record "
					      "device \"%s\": %d\n",
					      m_rec_devspec, err);
				CloseDevice();
				return false;
			}

			if (!ConfigurePcm(m_rec_handle, m_format, pcm_access,
					  m_rec_props)) {
				m_ei->LogWarn("Error configuring record "
					      "device \"%s\"\n",
					      m_rec_devspec);
				CloseDevice();
				return false;
			}
		}

		return true;
	}

	void CloseDevice(void) {
		if (m_play_handle) {
			snd_pcm_close(m_play_handle);
			m_play_handle = NULL;
		}
		if (m_rec_handle) {
			snd_pcm_close(m_rec_handle);
			m_rec_handle = NULL;
		}
	}

	void GetProps(SoundIoProps &props) const {
		props.has_clock = true;
		props.does_source = (m_rec_handle != NULL);
		props.does_sink = (m_play_handle != NULL);
		props.does_loop = false;
		props.remove_on_exhaust = false;
		props.outbuf_size = m_play_props.bufsize;
	}

	/*
	 * Register file handle notification callbacks.
	 * Start recording if requested.
	 */
	bool CreatePcmNotifiers(bool playback, bool capture,
				Callback<void, SocketNotifier*, int> &tmpl) {
		int err;
		bool do_playback = playback;

		if (!playback && !capture) {
			return true;
		}
		if (playback && (m_play_handle == NULL)) {
			return false;
		}
		if (capture && (m_rec_handle == NULL)) {
			return false;
		}

		if (playback && capture) {
			/*
			 * We could save some resources and register
			 * a single notifier here, but what the heck.
			 */
			/* do_playback = false; */
		}

		m_play_xrun = false;
		m_rec_xrun = false;

		if (do_playback &&
		    (m_play_not == NULL) &&
		    !CreateNotifiers(m_play_handle, m_ei, tmpl, m_play_not,
				     m_play_not_count)) {
			return false;
		}

		if (capture && (m_rec_not == NULL)) {
			if (!CreateNotifiers(m_rec_handle, m_ei, tmpl,
					     m_rec_not, m_rec_not_count)) {
				CleanupPcmNotifiers();
				return false;
			}

			err = snd_pcm_start(m_rec_handle);
			if (err == -EBADFD) {
				/* ???  Try again! */
				snd_pcm_drop(m_rec_handle);
				snd_pcm_prepare(m_rec_handle);
				err = snd_pcm_start(m_rec_handle);
			}

			if (err < 0) {
				m_ei->LogDebug("ALSA pcm start: %d\n", err);
				CleanupPcmNotifiers();
				return false;
			}
		}

		if (!do_playback && (m_play_not != NULL)) {
			CleanupNotifiers(m_play_not, m_play_not_count);
		}

		m_play_async = playback;
		m_rec_async = capture;
		return true;
	}

	void CleanupPcmNotifiers(void) {
		m_play_async = m_rec_async = false;
		CleanupNotifiers(m_play_not, m_play_not_count);
		CleanupNotifiers(m_rec_not, m_rec_not_count);
	}

	bool Reconfigure(SoundIoFormat *formatp,
			 snd_pcm_access_t pcm_access) {
		SoundIoFormat format;

		if (formatp) { format = *formatp; } else { format = m_format; }

		if (m_play_handle) {
			m_ei->LogDebug("ALSA play state: %d\n",
				       snd_pcm_state(m_play_handle));
			snd_pcm_drop(m_play_handle);
			if (!ConfigurePcm(m_play_handle, format, pcm_access,
					  m_play_props)) {
				return false;
			}
			m_ei->LogDebug("ALSA play state: %d\n",
				       snd_pcm_state(m_play_handle));
		}

		if (m_rec_handle) {
			m_ei->LogDebug("ALSA rec state: %d\n",
				       snd_pcm_state(m_rec_handle));
			snd_pcm_drop(m_rec_handle);
			if (!ConfigurePcm(m_rec_handle, format, pcm_access,
					  m_rec_props)) {
				return false;
			}
			m_ei->LogDebug("ALSA rec state: %d\n",
				       snd_pcm_state(m_rec_handle));
		}

		if (!m_play_handle && !m_rec_handle) {
			m_rec_props.packetsize = m_play_props.packetsize =
				format.packet_samps;
		}

		m_format = format;
		return true;
	}

	static snd_pcm_format_t AlsaPcmFormat(sio_sampletype_t st) {
		switch (st) {
		case SIO_PCM_U8:
			return SND_PCM_FORMAT_U8;
		case SIO_PCM_S16_LE:
			return SND_PCM_FORMAT_S16_LE;
		case SIO_PCM_A_LAW:
			return SND_PCM_FORMAT_A_LAW;
		case SIO_PCM_MU_LAW:
			return SND_PCM_FORMAT_MU_LAW;
		default:
			return SND_PCM_FORMAT_UNKNOWN;
		}
	}

	bool SetAvailMin(snd_pcm_t *pcmp, snd_pcm_uframes_t amin) {
		int err;
		snd_pcm_sw_params_t *swp;

		snd_pcm_sw_params_alloca(&swp);

		err = snd_pcm_sw_params_current(pcmp, swp);
		if (err < 0) {
			m_ei->LogWarn("ALSA sw_params_current failed: %d\n",
				      err);
			return false;
		}

		err = snd_pcm_sw_params_set_avail_min(pcmp, swp, amin);
		if (err < 0) {
			m_ei->LogWarn("ALSA sw_params_set_avail_min "
				      "failed: %d\n", err);
			return false;
		}

		err = snd_pcm_sw_params(pcmp, swp);
		if (err < 0) {
			m_ei->LogWarn("ALSA sw_params failed: %d\n", err);
			return false;
		}

		return true;
	}

	bool ConfigurePcm(snd_pcm_t *pcmp, SoundIoFormat &format,
			  snd_pcm_access_t pcm_access,
			  AlsaChannelProps &props) {
		snd_pcm_hw_params_t *hwp;
		snd_pcm_sw_params_t *swp;
		snd_pcm_uframes_t buffersize, packetsize, amin;
		snd_pcm_format_t sampfmt;
		int err;

		sampfmt = AlsaPcmFormat(format.sampletype);
		if (sampfmt == SND_PCM_FORMAT_UNKNOWN) {
			m_ei->LogWarn("Unrecognized sample type %d\n",
				      format.sampletype);
			return false;
		}

		snd_pcm_hw_params_alloca(&hwp);
		snd_pcm_sw_params_alloca(&swp);

		err = snd_pcm_hw_params_any(pcmp, hwp);
		if (err) {
			m_ei->LogWarn("ALSA hw_params_any failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_hw_params_set_access(pcmp, hwp, pcm_access);
		if (err) {
			m_ei->LogWarn("ALSA set_access failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_hw_params_set_format(pcmp, hwp, sampfmt);
		if (err) {
			m_ei->LogWarn("ALSA set_format failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_hw_params_set_rate(pcmp, hwp,
						 format.samplerate, 0);
		if (err) {
			m_ei->LogWarn("ALSA set_rate failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_hw_params_set_channels(pcmp, hwp,
						     format.nchannels);
		if (err) {
			m_ei->LogWarn("ALSA set_channels failed: %d\n", err);
			goto failed;
		}

		packetsize = format.packet_samps;

		err = snd_pcm_hw_params_set_period_size_near(pcmp, hwp,
							     &packetsize, 0);
		if (err) {
			m_ei->LogWarn("ALSA set_period failed: %d\n", err);
			goto failed;
		}

		buffersize = props.bufsize ? props.bufsize : 0;
		if (buffersize < packetsize)
			/* Default create a buffer sixteen packets deep */
			buffersize = packetsize * 16;

		err = snd_pcm_hw_params_set_buffer_size_near(pcmp, hwp,
							     &buffersize);
		if (err) {
			m_ei->LogWarn("ALSA set_buffer_size failed: %d\n",
				      err);
			goto failed;
		}

		err = snd_pcm_hw_params(pcmp, hwp);
		if (err < 0) {
			m_ei->LogWarn("ALSA hw_params failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_hw_params_current(pcmp, hwp);
		if (err < 0) {
			m_ei->LogWarn("ALSA hw_params_current failed: %d\n",
				      err);
			goto failed;
		}

		err = snd_pcm_hw_params_get_buffer_size(hwp, &buffersize);
		if (err) {
			m_ei->LogWarn("ALSA get_buffer_size failed: %d\n",
				      err);
			goto failed;
		}
		err = snd_pcm_hw_params_get_period_size(hwp, &packetsize, 0);
		if (err) {
			m_ei->LogWarn("ALSA get_period_size failed: %d\n",
				      err);
			goto failed;
		}

		err = snd_pcm_sw_params_current(pcmp, swp);
		if (err < 0) {
			m_ei->LogWarn("ALSA sw_params failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_sw_params_get_avail_min(swp, &amin);
		if (err < 0) {
			m_ei->LogWarn("ALSA sw_params_get_avail_min "
				      "failed: %d\n", err);
			goto failed;
		}

		err = snd_pcm_prepare(pcmp);
		if (err < 0) {
			m_ei->LogWarn("ALSA prepare failed: %d\n", err);
			goto failed;
		}

		props.packetsize = packetsize;
		props.bufsize = buffersize;
		props.min_avail = amin;
		return true;

	failed:
		return false;
	}

	bool Prepare(bool playback, bool capture) {
		if (playback) {
			assert(m_play_handle);
			m_ei->LogDebug("ALSA play state: %d\n",
				       snd_pcm_state(m_play_handle));
		}
		if (capture) {
			assert(m_rec_handle);
			m_ei->LogDebug("ALSA rec state: %d\n",
				       snd_pcm_state(m_rec_handle));
		}
		return true;
	}

	bool CreateNotifiers(snd_pcm_t *pcm_handle,
			     DispatchInterface *eip,
			     Callback<void, SocketNotifier*, int> &cbtemplate,
			     SocketNotifier **&table, int &count) {
		struct pollfd *polldesc;
		int i, j, nfds, nnot;
		int err;

		nfds = snd_pcm_poll_descriptors_count(pcm_handle);
		polldesc = (struct pollfd*) alloca(nfds * sizeof(*polldesc));
		err = snd_pcm_poll_descriptors(pcm_handle, polldesc, nfds);
		if (err < 0) {
			m_ei->LogWarn("ALSA get poll descriptors: %d\n", err);
			return false;
		}

		/* Determine how many notifiers we need */
		nnot = 0;
		for (i = 0; i < nfds; i++) {
			if (polldesc[i].events & POLLIN)
				nnot++;
			if (polldesc[i].events & POLLOUT)
				nnot++;
		}

		table = (SocketNotifier**)
			malloc(nnot * sizeof(SocketNotifier*));

		for (i = 0, j = 0; i < nfds; i++) {
			if (polldesc[i].events & POLLIN) {
				assert(j < nnot);
				table[j] = eip->NewSocket(polldesc[i].fd,
							  false);
				table[j]->Register(cbtemplate);
				j++;
			}
			if (polldesc[i].events & POLLOUT) {
				assert(j < nnot);
				table[j] = eip->NewSocket(polldesc[i].fd,
							  true);
				table[j]->Register(cbtemplate);
				j++;
			}
		}
		assert(j == nnot);
		count = nnot;
		return true;
	}

	bool HasNotifiers(void) const {
		return (m_play_not != 0) || (m_rec_not != 0);
	}

	static void CleanupNotifiers(SocketNotifier **&table, int &count) {
		int i;
		if (count) {
			for (i = 0; i < count; i++) {
				delete table[i];
			}
			free(table);
			table = NULL;
			count = 0;
		}
	}

	/*
	 * This is quite ugly.  We don't control the real event loop,
	 * so we call poll() ourselves and let ALSA process the result.
	 * Depending on how the alsa-lib PCM device stack is built, this
	 * function can do some really interesting things.
	 */
	bool CheckNotifications(void) {
		struct pollfd *pollfds;
		unsigned short revents;
		int ndesc = 0, nused = 0, play_first;

		if (m_rec_handle)
			ndesc = snd_pcm_poll_descriptors_count(m_rec_handle);
		if (m_play_handle)
			ndesc += snd_pcm_poll_descriptors_count(m_play_handle);
		if (!ndesc)
			return false;
		pollfds = (struct pollfd*) alloca(ndesc * sizeof(*pollfds));
		if (m_rec_handle) {
			nused = snd_pcm_poll_descriptors(m_rec_handle,
							 pollfds, ndesc);
			assert(nused <= ndesc);
		}
		play_first = nused;
		if (m_play_handle) {
			nused += snd_pcm_poll_descriptors(m_play_handle,
							  &pollfds[nused],
							  ndesc - nused);
			assert(nused <= ndesc);
		}
		if (!nused)
			return false;
		poll(pollfds, nused, 0);
		if (m_rec_handle && play_first) {
			if (snd_pcm_poll_descriptors_revents(m_rec_handle,
							     pollfds,
							     play_first,
							     &revents) < 0) {
			m_ei->LogWarn("ALSA pcm_poll_descriptors_revents "
				      "for rec: %d\n", errno);
			}
			else if (revents & POLLIN)
				return true;
		}
		if (m_play_handle && (nused - play_first)) {
			if (snd_pcm_poll_descriptors_revents(m_play_handle,
						     &pollfds[play_first],
						     nused - play_first,
						     &revents) < 0) {
			m_ei->LogWarn("ALSA pcm_poll_descriptors_revents "
				      "for play: %d\n", errno);
			}
			else if (revents & POLLOUT)
				return true;
		}

		return false;
	}

	bool HandleInterruption(snd_pcm_t *pcmp, snd_pcm_sframes_t res) {
		int err;
		const char *streamtype;
		bool *xrun;

		if (snd_pcm_stream(pcmp) == SND_PCM_STREAM_PLAYBACK) {
			streamtype = "playback";
			xrun = &m_play_xrun;
		} else {
			streamtype = "capture";
			xrun = &m_rec_xrun;
		}

	restart:
		switch (snd_pcm_state(pcmp)) {
		case SND_PCM_STATE_XRUN:
			/* buffer overrun/underrun, treat like setup */
			m_ei->LogDebug("**** ALSA %s xrun ****\n", streamtype);
			*xrun = true;

		case SND_PCM_STATE_SETUP:
			err = snd_pcm_prepare(pcmp);
			if (err < 0) {
				m_ei->LogWarn("ALSA %s prepare: %d\n",
					      streamtype, err);
				return false;
			}

			assert(snd_pcm_state(pcmp) == SND_PCM_STATE_PREPARED);
			/* fall-thru */

		case SND_PCM_STATE_PREPARED:
			if (snd_pcm_stream(pcmp) == SND_PCM_STREAM_CAPTURE) {
				err = snd_pcm_start(pcmp);
				if (err < 0) {
					m_ei->LogWarn("ALSA %s start: %d\n",
						      streamtype, err);
					return false;
				}
			}
			return true;

		case SND_PCM_STATE_SUSPENDED:
			/* hardware was suspended? huh? */
			m_ei->LogWarn("ALSA %s suspended\n", streamtype);

			err = snd_pcm_resume(pcmp);
			if (err < 0) {
				m_ei->LogWarn("ALSA %s resume: %d\n",
					      streamtype, err);
				return false;
			}
			if (snd_pcm_state(pcmp) == SND_PCM_STATE_SUSPENDED) {
				m_ei->LogWarn("ALSA %s resume succeeded, but "
					      "still in suspended state\n",
					      streamtype);
				return false;
			}
			goto restart;

		case SND_PCM_STATE_RUNNING:
			return true;

		case SND_PCM_STATE_DISCONNECTED:
			m_ei->LogDebug("ALSA %s is disconnected, "
				       "shutting down\n", streamtype);
			return false;

		default:
			m_ei->LogWarn("ALSA %s in strange state %d\n",
				      streamtype, snd_pcm_state(pcmp));
			return false;
		}
	}
};


class SoundIoAlsaProc : public SoundIoBufferBase {
	AlsaIoBase		m_alsa;

	bool			m_play_nonblock;
	bool			m_rec_nonblock;

	void OpenBuf(void) {
		BufOpen(m_alsa.GetPacketSize(),
			m_alsa.m_format.bytes_per_record);
	}

public:
	SoundIoAlsaProc(DispatchInterface *eip,
			const char *output_devspec, const char *input_devspec)
		: m_alsa(eip, output_devspec, input_devspec) {}
	virtual ~SoundIoAlsaProc() {}

	virtual bool SndOpen(bool play, bool capture) {
		if (m_alsa.OpenDevice(SND_PCM_ACCESS_RW_INTERLEAVED,
				      play, capture)) {
			m_play_nonblock = false;
			m_rec_nonblock = false;
			OpenBuf();
			return true;
		}
		return false;
	}
	virtual void SndClose(void) {
		SndAsyncStop();
		BufClose();
		m_alsa.CloseDevice();
	}

	virtual void SndGetFormat(SoundIoFormat &format) const {
		format = m_alsa.m_format;
		format.packet_samps = m_alsa.GetPacketSize();
	}

	virtual bool SndSetFormat(SoundIoFormat &format) {
		SndAsyncStop();
		if (m_alsa.Reconfigure(&format,
				       SND_PCM_ACCESS_RW_INTERLEAVED)) {
			OpenBuf();
			return true;
		}
		return false;
	}

	virtual void SndGetProps(SoundIoProps &props) const {
		m_alsa.GetProps(props);
	}

	virtual void SndGetQueueState(SoundIoQueueState &qs) {
		snd_pcm_sframes_t err, exp;

		if (m_alsa.m_play_handle) {
			(void) snd_pcm_avail_update(m_alsa.m_play_handle);
			err = snd_pcm_delay(m_alsa.m_play_handle, &exp);
			if (err < 0) {
				exp = 0;
			}
			if (exp < 0) {
				/* WTF?  Die broken alsa-lib plugins! */
				exp = 0;
			}
			m_hw_outq = exp;
		}
		SoundIoBufferBase::SndGetQueueState(qs);
	}

	virtual void SndPushInput(bool nonblock) {
		unsigned int nsamples;
		uint8_t *buf;
		snd_pcm_sframes_t exp, err;

		if (m_abort)
			return;		/* Don't bother */

		if (m_rec_nonblock != nonblock) {
			err = snd_pcm_nonblock(m_alsa.m_rec_handle, nonblock);
			if (err < 0) {
				m_alsa.m_ei->LogWarn("ALSA set nonblock: "
						     "%ld\n", err);
			}
			m_rec_nonblock = nonblock;
		}

		/*
		 * For some reason, if we're dealing directly with a
		 * hardware device, nonblocking mode is busted here.
		 * We need to deal with hw:X devices in order to
		 * achieve low latency.
		 *
		 * We won't even bother to set it, and will emulate it by
		 * only calling pcm_readi if we're sure the number of
		 * samples we want is available.
		 */
	restart_me:
		exp = snd_pcm_avail_update(m_alsa.m_rec_handle);
		if (exp < 0) {
			err = exp;
			goto do_interruption;
		}
		while (1) {
			nsamples = 0;
			m_input.GetUnfilled(buf, nsamples);
			assert(nsamples);
			if (exp < (snd_pcm_sframes_t) nsamples)
				break;

			err = snd_pcm_readi(m_alsa.m_rec_handle, buf,nsamples);
			if (err < 0) {
				if (err == -EAGAIN) { break; }
			do_interruption:
				if (m_alsa.HandleInterruption(
					    m_alsa.m_rec_handle, err)) {
					goto restart_me;
				}
				m_alsa.m_ei->LogWarn("ALSA capture failed: "
						     "%ld\n", err);
				BufAbort(m_alsa.m_ei);
				break;
			}
			if (!err) { break; }

			m_input.PutUnfilled(err);
			exp -= err;
		}
	}

	virtual void SndPushOutput(bool nonblock) {
		unsigned int nsamples;
		uint8_t *buf;
		ssize_t err;

		if (m_abort)
			return;		/* Don't bother */

		if (!m_alsa.m_play_handle)
			return;

		if (m_play_nonblock != nonblock) {
			err = snd_pcm_nonblock(m_alsa.m_play_handle, nonblock);
			if (err < 0) {
				m_alsa.m_ei->LogWarn("ALSA set nonblock: "
						     "%zd\n", err);
			}
			m_play_nonblock = nonblock;
		}

		(void) snd_pcm_avail_update(m_alsa.m_play_handle);
		while (1) {
			nsamples = 0;
			m_output.Peek(buf, nsamples);
			if (!nsamples) { break; }

		restart_me:
			err = snd_pcm_writei(m_alsa.m_play_handle,
					     buf, nsamples);
			if (err < 0) {
				if (err == -EAGAIN) {
					m_alsa.m_ei->LogWarn("ALSA: playback "
							     "buffer full\n");
					break;
				}
				if (m_alsa.HandleInterruption(
					    m_alsa.m_play_handle, err)) {
					goto restart_me;
				}
				m_alsa.m_ei->LogWarn("ALSA playback failed: "
						     "%zd\n", err);
				BufAbort(m_alsa.m_ei);
				break;
			}
			if (!err) {
				m_alsa.m_ei->LogWarn("ALSA pcm_writei "
						     "result is 0?\n");
				break;
			}

			m_output.Dequeue(err);
			m_hw_outq += err;
		}
	}

	void AsyncProcess(SocketNotifier *notp, int fh) {
		bool overrun = false, underrun = false;
		int err;
		snd_pcm_sframes_t exp = 0;

		/*
		 * We will explicitly test for xruns here.
		 */

		if (m_abort)
			goto do_abort;

		if (!m_alsa.CheckNotifications())
			return;

		if (m_alsa.m_rec_async) {
			if (!m_alsa.m_rec_xrun) {
				/*
				 * We will read as much input as we can
				 * into our buffer
				 */
				SndPushInput(true);
			}

			overrun = m_alsa.m_rec_xrun;
			m_alsa.m_rec_xrun = false;
			if (!overrun) {
				overrun = (snd_pcm_state(m_alsa.
							 m_rec_handle) ==
					   SND_PCM_STATE_XRUN);
				if (overrun &&
				    !m_alsa.HandleInterruption(m_alsa.
							       m_rec_handle,
							       -EPIPE)) {
					goto do_abort;
				}
			}
		}

		if (m_alsa.m_play_async) {
			(void) snd_pcm_avail_update(m_alsa.m_play_handle);
			underrun = m_alsa.m_play_xrun;
			m_alsa.m_play_xrun = false;
			if (!underrun) {
				underrun = (snd_pcm_state(m_alsa.
							  m_play_handle) ==
					    SND_PCM_STATE_XRUN);
				if (underrun &&
				    !m_alsa.HandleInterruption(m_alsa.
							       m_play_handle,
							       -EPIPE)) {
					goto do_abort;
				}
			}

			err = snd_pcm_delay(m_alsa.m_play_handle, &exp);
			if (err < 0) {
				if (!underrun || (err != -EPIPE))
					m_alsa.m_ei->LogWarn(
						"ALSA playback: "
						"snd_pcm_delay: %d\n", err);
				exp = 0;
			}
			if (exp < 0) {
				/* WTF?  Die broken alsa-lib plugins! */
				exp = 0;
			}
		}

		if (!BufProcess(exp, overrun, underrun))
			return;

		if (m_alsa.m_play_not &&
		    (m_hw_outq < m_alsa.m_play_props.bufsize)) {
			/*
			 * ALSA wants to alert us whenever our output
			 * buffer free space increases above some level.
			 * We just want to know whenever pktsize samples
			 * have been processed.
			 */
			exp = ((m_alsa.m_play_props.bufsize - m_hw_outq) +
			       m_alsa.m_play_props.packetsize);

			m_alsa.SetAvailMin(m_alsa.m_play_handle, exp);
		}
		return;

	do_abort:
		SndHandleAbort();
	}

	virtual bool SndAsyncStart(bool playback, bool capture) {
		Callback<void, SocketNotifier*, int> tmpl;
		if (playback) {
			m_alsa.SetAvailMin(m_alsa.m_play_handle,
					   m_alsa.m_play_props.bufsize -
					   m_alsa.m_play_props.packetsize);
		}
		tmpl.Register(this, &SoundIoAlsaProc::AsyncProcess);
		if (!m_alsa.Prepare(playback, capture))
			return false;
		return m_alsa.CreatePcmNotifiers(playback, capture, tmpl);
	}

	virtual void SndAsyncStop(void) {
		BufClose();
		m_alsa.CleanupPcmNotifiers();
	}

	virtual bool SndIsAsyncStarted(void) const {
		return m_alsa.HasNotifiers();
	}
};

class SoundIoAlsaMmap : public SoundIo {
	AlsaIoBase		m_alsa;

	const snd_pcm_channel_area_t	*m_play_areas;
	snd_pcm_uframes_t		m_play_off, m_play_size;
	const snd_pcm_channel_area_t	*m_rec_areas;
	snd_pcm_uframes_t		m_rec_off, m_rec_size;
	int				m_packetbytes;
	SoundIoQueueState		m_qs;
	bool				m_abort;

public:
	SoundIoAlsaMmap(DispatchInterface *eip,
			const char *output_devspec, const char *input_devspec)
		: m_alsa(eip, output_devspec, input_devspec),
		  m_play_areas(NULL), m_rec_areas(NULL), m_abort(false) {}
	virtual ~SoundIoAlsaMmap() {}

	bool SetPacketSize(void) {
		if (m_alsa.m_rec_props.packetsize !=
		    m_alsa.m_play_props.packetsize) {
			m_alsa.m_ei->LogWarn("ALSA packet size mismatch: "
					     "%ld capture, %ld playback\n",
					     m_alsa.m_rec_props.packetsize,
					     m_alsa.m_play_props.packetsize);
			return false;
		}
		m_packetbytes = m_alsa.GetPacketSize() *
			m_alsa.GetSampleBytes();

		return true;
	}

	void CommitMappings(void) {
		if (m_play_areas) {
			snd_pcm_mmap_commit(m_alsa.m_play_handle,
					    m_play_off, 0);
			m_play_areas = NULL;
		}
		if (m_rec_areas) {
			snd_pcm_mmap_commit(m_alsa.m_rec_handle,
					    m_rec_off, 0);
			m_rec_areas = NULL;
		}
	}

	virtual bool SndOpen(bool play, bool capture) {
		return m_alsa.OpenDevice(SND_PCM_ACCESS_MMAP_INTERLEAVED,
					 play, capture) &&
			SetPacketSize();
	}
	virtual void SndClose(void) {
		SndAsyncStop();
		m_alsa.CloseDevice();
	}

	virtual void SndGetProps(SoundIoProps &props) const {
		m_alsa.GetProps(props);
	}

	virtual void SndGetFormat(SoundIoFormat &format) const {
		format = m_alsa.m_format;
		format.packet_samps = m_alsa.GetPacketSize();
	}

	virtual bool SndSetFormat(SoundIoFormat &format) {
		SndAsyncStop();
		if (!m_alsa.Reconfigure(&format,
					SND_PCM_ACCESS_MMAP_INTERLEAVED)) {
			return false;
		}
		if (!SetPacketSize()) {
			return false;
		}
		return true;
	}

	virtual void SndGetIBuf(SoundIoBuffer &fillme) {
		int err;

		if (m_rec_areas &&
		    (!fillme.m_size || (fillme.m_size < m_rec_size))) {
			/* Use the existing buffer */
			fillme.m_data = (((uint8_t *) m_rec_areas[0].addr) +
				 (m_rec_off * m_alsa.GetSampleBytes()));
			return;
		}

		if (m_rec_areas) {
			(void) snd_pcm_mmap_commit(m_alsa.m_rec_handle,
						   m_rec_off, 0);
			m_rec_areas = NULL;
		}

		m_rec_size = fillme.m_size;
		if (!m_rec_size) { m_rec_size = m_alsa.GetPacketSize(); }
	retry:
		(void) snd_pcm_avail_update(m_alsa.m_rec_handle);
		err = snd_pcm_mmap_begin(m_alsa.m_rec_handle,
					 &m_rec_areas,
					 &m_rec_off,
					 &m_rec_size);
		if (err < 0) {
			if (m_alsa.HandleInterruption(m_alsa.m_rec_handle,
						      err))
				goto retry;

			m_alsa.m_ei->LogWarn("ALSA rec mmap_begin: %d\n", err);
			m_abort = true;
			fillme.m_size = 0;
			return;
		}
		if (!m_rec_size) {
			(void) snd_pcm_mmap_commit(m_alsa.m_rec_handle,
						   m_rec_off, 0);
			m_rec_areas = NULL;
			fillme.m_size = 0;
			return;
		}

		fillme.m_data = (((uint8_t *) m_rec_areas[0].addr) +
				 (m_rec_off * m_alsa.GetSampleBytes()));
		fillme.m_size = m_rec_size;
	}

	virtual void SndDequeueIBuf(sio_sampnum_t deqme) {
		int err;

		if (m_rec_areas) {
			if (deqme < m_rec_size) {
				m_rec_size -= deqme;
				m_rec_off += deqme;
				return;
			}

			m_rec_areas = NULL;
			err = snd_pcm_mmap_commit(m_alsa.m_rec_handle,
						  m_rec_off, m_rec_size);
			if (err != (int) m_rec_size) {
				if (!m_alsa.HandleInterruption(m_alsa.
							       m_rec_handle,
							       err)) {
					m_alsa.m_ei->LogWarn(
						"ALSA rec mmap_commit: %d\n",
						err);
					m_abort = true;
					return;
				}
			}

			deqme -= m_rec_size;
		}

		if (deqme) {
			/*
			 * The caller wants us to dequeue more frames than
			 * were ever mapped.  Fine.
			 */
			err = snd_pcm_forward(m_alsa.m_rec_handle, deqme);
		}
	}

	virtual void SndGetOBuf(SoundIoBuffer &fillme) {
		int err;

		if (m_play_areas &&
		    (!fillme.m_size || (fillme.m_size < m_play_size))) {
			/* Use the existing buffer */
			fillme.m_data = (((uint8_t *) m_play_areas[0].addr) +
				 (m_play_off * m_alsa.GetSampleBytes()));
			return;
		}

		if (m_play_areas) {
			(void) snd_pcm_mmap_commit(m_alsa.m_play_handle,
						   m_play_off, 0);
			m_play_areas = NULL;
		}

		m_play_size = fillme.m_size;
		if (!m_play_size) { m_play_size = m_alsa.GetPacketSize(); }
	retry:
		(void) snd_pcm_avail_update(m_alsa.m_play_handle);
		err = snd_pcm_mmap_begin(m_alsa.m_play_handle,
					 &m_play_areas,
					 &m_play_off,
					 &m_play_size);
		if (err < 0) {
			if (m_alsa.HandleInterruption(m_alsa.m_play_handle,
						      err))
				goto retry;
			m_alsa.m_ei->LogWarn("ALSA play mmap_begin: %d\n",
					     err);
			m_abort = true;
			fillme.m_size = 0;
			return;
		}
		if (!m_play_size) {
			(void) snd_pcm_mmap_commit(m_alsa.m_play_handle,
						   m_play_off, 0);
			m_play_areas = NULL;
			fillme.m_size = 0;
			return;
		}

		fillme.m_data = (((uint8_t *) m_play_areas[0].addr) +
				 (m_play_off * m_alsa.GetSampleBytes()));
		fillme.m_size = m_play_size;
	}

	virtual void SndQueueOBuf(sio_sampnum_t qcount) {
		int err;

		/*
		 * We permit callers to remove record buffer data
		 * without ever examining it, but we don't do the
		 * same for playback buffers.
		 */

		assert(m_play_areas);
		assert(qcount <= m_play_size);

		m_play_areas = NULL;
		err = snd_pcm_mmap_commit(m_alsa.m_play_handle,
					  m_play_off, qcount);
		if (err != (int) qcount) {
			m_alsa.m_ei->LogWarn("ALSA play mmap_commit: %d\n",
					     err);
			m_alsa.HandleInterruption(m_alsa.m_play_handle, err);
		}

		else if (snd_pcm_state(m_alsa.m_play_handle) ==
			 SND_PCM_STATE_PREPARED) {
			err = snd_pcm_start(m_alsa.m_play_handle);
			if (err) {
				m_alsa.m_ei->LogWarn("ALSA play start: %d\n",
						     err);
			}
		}

	}

	virtual void SndGetQueueState(SoundIoQueueState &qs) {
		snd_pcm_sframes_t val;

		m_qs.in_queued = 0;
		m_qs.out_queued = 0;

		if (m_alsa.m_rec_handle) {
			val = snd_pcm_avail_update(m_alsa.m_rec_handle);
			if (val > 0)
				m_qs.in_queued = val;
		}
		if (m_alsa.m_play_handle) {
			snd_pcm_avail_update(m_alsa.m_play_handle);
			if (!snd_pcm_delay(m_alsa.m_play_handle, &val)) {
				if (val < 0) {
					/* WTF? */
					val = 0;
				}
				m_qs.out_queued = val;
			}
		}

		qs = m_qs;
	}

	void SndHandleAbort(void) {
		m_abort = false;
		CommitMappings();
		m_alsa.CleanupPcmNotifiers();
		if (cb_NotifyPacket.Registered())
			cb_NotifyPacket(this, NULL);
	}

	void AsyncProcess(SocketNotifier *notp, int fh) {
		SoundIoQueueState qs;
		bool overrun, underrun;

		/*
		 * We will explicitly test for xruns here.
		 */

		if (m_abort) {
			SndHandleAbort();
			return;
		}

		if (!m_alsa.CheckNotifications())
			return;

		SndGetQueueState(qs);

		underrun = m_alsa.m_play_xrun;
		m_alsa.m_play_xrun = false;
		if (!underrun && m_alsa.m_play_async) {
			underrun = (snd_pcm_state(m_alsa.m_play_handle) ==
				    SND_PCM_STATE_XRUN);
			if (underrun &&
			    !m_alsa.HandleInterruption(m_alsa.m_play_handle,
						       -EPIPE)) {
				SndHandleAbort();
				return;
			}
		}

		overrun = m_alsa.m_rec_xrun;
		m_alsa.m_rec_xrun = false;
		if (!overrun && m_alsa.m_rec_async) {
			overrun = (snd_pcm_state(m_alsa.m_rec_handle) ==
				   SND_PCM_STATE_XRUN);
			if (overrun &&
			    !m_alsa.HandleInterruption(m_alsa.m_rec_handle,
						       -EPIPE)) {
				SndHandleAbort();
				return;
			}
		}

		if (cb_NotifyPacket.Registered())
			cb_NotifyPacket(this, &qs);

		if (m_abort)
			SndHandleAbort();
	}

	virtual bool SndAsyncStart(bool playback, bool capture) {
		Callback<void, SocketNotifier*, int> tmpl;
		tmpl.Register(this, &SoundIoAlsaMmap::AsyncProcess);
		return m_alsa.CreatePcmNotifiers(playback, capture, tmpl);
	}

	virtual void SndAsyncStop(void) {
		CommitMappings();
		m_alsa.CleanupPcmNotifiers();
		m_abort = false;
	}

	virtual bool SndIsAsyncStarted(void) const {
		return m_alsa.HasNotifiers();
	}
};

#define trim_leading_ws(X) do { 					\
	while (*(X) && ((*(X) == ' ') || (*(X) == '\t'))) { (X)++; }	\
	} while (0)

#define trim_trailing_ws(X) do {					\
		size_t siz = strlen(X);					\
		while (siz && (((X)[siz - 1] == ' ') ||			\
			       ((X)[siz - 1] == '\t'))) {		\
			(X)[--siz] = '\0';				\
		} } while(0)

static inline SoundIo *
DoAlsaConfig(DispatchInterface *dip, const char *driveropts)
{
	char *opts = 0, *tok = 0, *save = 0, *tmp;
	const char *ind, *outd;
	bool do_mmap = false;
	SoundIo *alsap = 0;

	ind = "default";
	outd = "default";

	if (driveropts) {
		opts = strdup(driveropts);
		if (!opts)
			return 0;
		tok = strtok_r(opts, "&", &save);
	}

	while (tok) {
		trim_leading_ws(tok);
		if (!strncmp(tok, "in=", 3)) {
			tmp = &tok[3];
			trim_leading_ws(tmp);
			trim_trailing_ws(tmp);
			ind = tmp;
		}
		else if (!strncmp(tok, "out=", 4)) {
			tmp = &tok[4];
			trim_leading_ws(tmp);
			trim_trailing_ws(tmp);
			outd = tmp;
		}
		else if (!strncmp(tok, "dev=", 4)) {
			tmp = &tok[4];
			trim_leading_ws(tmp);
			trim_trailing_ws(tmp);
			ind = outd = tmp;
		}
		else if (!strncmp(tok, "mmap=", 5)) {
			tmp = &tok[5];
			trim_leading_ws(tmp);
			trim_trailing_ws(tmp);
			if (!strcmp(tmp, "on")) {
				do_mmap = true;
			}
			else if (!strcmp(tmp, "off")) {
				do_mmap = false;
			}
			else {
				dip->LogWarn("ALSA: unrecognized mmap "
					     "value \"%s\"\n", tmp);
			}
		}
		else if (strchr(tok, '=')) {
			dip->LogWarn("ALSA: unrecognized option \"%s\"\n",
				     tok);
		}
		else {
			tmp = tok;
			trim_leading_ws(tmp);
			trim_trailing_ws(tmp);
			ind = outd = tmp;
		}

		tok = strtok_r(NULL, "&", &save);
	}

	if (do_mmap)
		alsap = new SoundIoAlsaMmap(dip, outd, ind);
	else
		alsap = new SoundIoAlsaProc(dip, outd, ind);

	if (opts)
		free(opts);
	return alsap;
}

#else  /* defined(USE_ALSA_SOUNDIO) */
static inline SoundIo *
DoAlsaConfig(DispatchInterface *dip, const char *devspec)
{
	return NULL;
}
#endif  /* defined(USE_ALSA_SOUNDIO) */


SoundIo *
SoundIoCreateAlsa(DispatchInterface *dip, const char *devspec)
{
	return DoAlsaConfig(dip, devspec);
}

} /* namespace libhfp */