summaryrefslogtreecommitdiff
path: root/src/tools/pw-cat.c
blob: 8eee766732642c132c9b1b29d228153d02644944 (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
/* PipeWire - pw-cat
 *
 * Copyright © 2020 Konsulko Group

 * Author: Pantelis Antoniou <pantelis.antoniou@konsulko.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <math.h>
#include <sys/mman.h>
#include <signal.h>
#include <getopt.h>
#include <unistd.h>
#include <assert.h>
#include <ctype.h>

#include <sndfile.h>

#include <spa/param/audio/layout.h>
#include <spa/param/audio/format-utils.h>
#include <spa/param/audio/type-info.h>
#include <spa/param/props.h>
#include <spa/utils/result.h>
#include <spa/debug/types.h>

#include <pipewire/pipewire.h>
#include <pipewire/global.h>

#define DEFAULT_MEDIA_TYPE	"Audio"
#define DEFAULT_MEDIA_CATEGORY_PLAYBACK	"Playback"
#define DEFAULT_MEDIA_CATEGORY_RECORD	"Capture"
#define DEFAULT_MEDIA_ROLE	"Music"
#define DEFAULT_TARGET		"auto"
#define DEFAULT_LATENCY		"100ms"
#define DEFAULT_RATE		48000
#define DEFAULT_CHANNELS	2
#define DEFAULT_FORMAT		"s16"
#define DEFAULT_VOLUME		1.0

enum mode {
	mode_none,
	mode_playback,
	mode_record
};

enum unit {
	unit_none,
	unit_samples,
	unit_sec,
	unit_msec,
	unit_usec,
	unit_nsec,
};

struct data;

typedef int (*fill_fn)(struct data *d, void *dest, unsigned int n_frames);

struct target {
	struct spa_list link;
	uint32_t id;
	char *name;
	char *desc;
	int prio;
};

struct channelmap {
	int n_channels;
	int channels[SPA_AUDIO_MAX_CHANNELS];
};

struct data {
	struct pw_main_loop *loop;
	struct pw_context *context;
	struct pw_core *core;
	struct spa_hook core_listener;
	struct pw_registry *registry;
	struct spa_hook registry_listener;
	struct pw_stream *stream;
	struct spa_hook stream_listener;

	enum mode mode;
	bool verbose;
	const char *remote_name;
	const char *media_type;
	const char *media_category;
	const char *media_role;
	const char *channel_map;
	const char *format;
	const char *target;
	const char *latency;
	struct pw_properties *props;

	const char *filename;
	SNDFILE *file;

	unsigned int rate;
	int channels;
	struct channelmap channelmap;
	unsigned int samplesize;
	unsigned int stride;
	enum unit latency_unit;
	unsigned int latency_value;

	enum spa_audio_format spa_format;

	float volume;
	bool volume_is_set;

	fill_fn fill;

	uint32_t target_id;
	bool list_targets;
	bool targets_listed;
	struct spa_list targets;

	bool drained;
};

static inline int
sf_str_to_fmt(const char *str)
{
	if (!str)
		return -1;

	if (!strcmp(str, "s8"))
		return SF_FORMAT_PCM_S8;
	if (!strcmp(str, "s16"))
		return SF_FORMAT_PCM_16;
	if (!strcmp(str, "s24"))
		return SF_FORMAT_PCM_24;
	if (!strcmp(str, "s32"))
		return SF_FORMAT_PCM_32;
	if (!strcmp(str, "f32"))
		return SF_FORMAT_FLOAT;
	if (!strcmp(str, "f64"))
		return SF_FORMAT_DOUBLE;

	return -1;
}

static inline const char *
sf_fmt_to_str(int format)
{
	int sub_type = (format & SF_FORMAT_SUBMASK);

	if (sub_type == SF_FORMAT_PCM_S8)
		return "s8";
	if (sub_type == SF_FORMAT_PCM_16)
		return "s16";
	if (sub_type == SF_FORMAT_PCM_24)
		return "s24";
	if (sub_type == SF_FORMAT_PCM_32)
		return "s32";
	if (sub_type == SF_FORMAT_FLOAT)
		return "f32";
	if (sub_type == SF_FORMAT_DOUBLE)
		return "f64";
	return "(invalid)";
}

#define STR_FMTS "(s8|s16|s32|f32|f64)"

/* 0 = native, 1 = le, 2 = be */
static inline int
sf_format_endianess(int format)
{
	return 0;		/* native */
}

static inline enum spa_audio_format
sf_format_to_pw(int format)
{
	int endianess;

	endianess = sf_format_endianess(format);
	if (endianess < 0)
		return SPA_AUDIO_FORMAT_UNKNOWN;

	switch (format & SF_FORMAT_SUBMASK) {
	case SF_FORMAT_PCM_S8:
		return SPA_AUDIO_FORMAT_S8;
	case SF_FORMAT_PCM_16:
		return endianess == 1 ? SPA_AUDIO_FORMAT_S16_LE :
		       endianess == 2 ? SPA_AUDIO_FORMAT_S16_BE :
		                        SPA_AUDIO_FORMAT_S16;
	case SF_FORMAT_PCM_24:
	case SF_FORMAT_PCM_32:
		return endianess == 1 ? SPA_AUDIO_FORMAT_S32_LE :
		       endianess == 2 ? SPA_AUDIO_FORMAT_S32_BE :
		                        SPA_AUDIO_FORMAT_S32;
	case SF_FORMAT_DOUBLE:
		return endianess == 1 ? SPA_AUDIO_FORMAT_F64_LE :
		       endianess == 2 ? SPA_AUDIO_FORMAT_F64_BE :
		                        SPA_AUDIO_FORMAT_F64;
	case SF_FORMAT_FLOAT:
	default:
		return endianess == 1 ? SPA_AUDIO_FORMAT_F32_LE :
		       endianess == 2 ? SPA_AUDIO_FORMAT_F32_BE :
		                        SPA_AUDIO_FORMAT_F32;
		break;
	}

	return SPA_AUDIO_FORMAT_UNKNOWN;
}

static inline int
sf_format_samplesize(int format)
{
	int sub_type = (format & SF_FORMAT_SUBMASK);

	switch (sub_type) {
	case SF_FORMAT_PCM_S8:
		return 1;
	case SF_FORMAT_PCM_16:
		return 2;
	case SF_FORMAT_PCM_32:
		return 4;
	case SF_FORMAT_DOUBLE:
		return 8;
	case SF_FORMAT_FLOAT:
	default:
		return 4;
	}
	return -1;
}

static int sf_playback_fill_s8(struct data *d, void *dest, unsigned int n_frames)
{
	sf_count_t rn;

	rn = sf_read_raw(d->file, dest, n_frames);
	return (int)rn;
}

static int sf_playback_fill_s16(struct data *d, void *dest, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(short) == sizeof(int16_t));
	rn = sf_readf_short(d->file, dest, n_frames);
	return (int)rn;
}

static int sf_playback_fill_s32(struct data *d, void *dest, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(int) == sizeof(int32_t));
	rn = sf_readf_int(d->file, dest, n_frames);
	return (int)rn;
}

static int sf_playback_fill_f32(struct data *d, void *dest, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(float) == 4);
	rn = sf_readf_float(d->file, dest, n_frames);
	return (int)rn;
}

static int sf_playback_fill_f64(struct data *d, void *dest, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(double) == 8);
	rn = sf_readf_double(d->file, dest, n_frames);
	return (int)rn;
}

static inline fill_fn
sf_fmt_playback_fill_fn(int format)
{
	enum spa_audio_format fmt = sf_format_to_pw(format);

	switch (fmt) {
	case SPA_AUDIO_FORMAT_S8:
		return sf_playback_fill_s8;
	case SPA_AUDIO_FORMAT_S16_LE:
	case SPA_AUDIO_FORMAT_S16_BE:
		/* sndfile check */
		if (sizeof(int16_t) != sizeof(short))
			return NULL;
		return sf_playback_fill_s16;
	case SPA_AUDIO_FORMAT_S32_LE:
	case SPA_AUDIO_FORMAT_S32_BE:
		/* sndfile check */
		if (sizeof(int32_t) != sizeof(int))
			return NULL;
		return sf_playback_fill_s32;
	case SPA_AUDIO_FORMAT_F32_LE:
	case SPA_AUDIO_FORMAT_F32_BE:
		/* sndfile check */
		if (sizeof(float) != 4)
			return NULL;
		return sf_playback_fill_f32;
	case SPA_AUDIO_FORMAT_F64_LE:
	case SPA_AUDIO_FORMAT_F64_BE:
		if (sizeof(double) != 8)
			return NULL;
		return sf_playback_fill_f64;
	default:
		break;
	}
	return NULL;
}

static int sf_record_fill_s8(struct data *d, void *src, unsigned int n_frames)
{
	sf_count_t rn;

	rn = sf_write_raw(d->file, src, n_frames);
	return (int)rn;
}

static int sf_record_fill_s16(struct data *d, void *src, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(short) == sizeof(int16_t));
	rn = sf_writef_short(d->file, src, n_frames);
	return (int)rn;
}

static int sf_record_fill_s32(struct data *d, void *src, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(int) == sizeof(int32_t));
	rn = sf_writef_int(d->file, src, n_frames);
	return (int)rn;
}

static int sf_record_fill_f32(struct data *d, void *src, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(float) == 4);
	rn = sf_writef_float(d->file, src, n_frames);
	return (int)rn;
}

static int sf_record_fill_f64(struct data *d, void *src, unsigned int n_frames)
{
	sf_count_t rn;

	assert(sizeof(double) == 8);
	rn = sf_writef_double(d->file, src, n_frames);
	return (int)rn;
}

static inline fill_fn
sf_fmt_record_fill_fn(int format)
{
	enum spa_audio_format fmt = sf_format_to_pw(format);

	switch (fmt) {
	case SPA_AUDIO_FORMAT_S8:
		return sf_record_fill_s8;
	case SPA_AUDIO_FORMAT_S16_LE:
	case SPA_AUDIO_FORMAT_S16_BE:
		/* sndfile check */
		if (sizeof(int16_t) != sizeof(short))
			return NULL;
		return sf_record_fill_s16;
	case SPA_AUDIO_FORMAT_S32_LE:
	case SPA_AUDIO_FORMAT_S32_BE:
		/* sndfile check */
		if (sizeof(int32_t) != sizeof(int))
			return NULL;
		return sf_record_fill_s32;
	case SPA_AUDIO_FORMAT_F32_LE:
	case SPA_AUDIO_FORMAT_F32_BE:
		/* sndfile check */
		if (sizeof(float) != 4)
			return NULL;
		return sf_record_fill_f32;
	case SPA_AUDIO_FORMAT_F64_LE:
	case SPA_AUDIO_FORMAT_F64_BE:
		/* sndfile check */
		if (sizeof(double) != 8)
			return NULL;
		return sf_record_fill_f64;
	default:
		break;
	}
	return NULL;
}

static int channelmap_from_sf(struct channelmap *map)
{
	static const enum spa_audio_channel table[] = {
		[SF_CHANNEL_MAP_MONO] =                  SPA_AUDIO_CHANNEL_MONO,
		[SF_CHANNEL_MAP_LEFT] =                  SPA_AUDIO_CHANNEL_FL, /* libsndfile distinguishes left and front-left, which we don't */
		[SF_CHANNEL_MAP_RIGHT] =                 SPA_AUDIO_CHANNEL_FR,
		[SF_CHANNEL_MAP_CENTER] =                SPA_AUDIO_CHANNEL_FC,
		[SF_CHANNEL_MAP_FRONT_LEFT] =            SPA_AUDIO_CHANNEL_FL,
		[SF_CHANNEL_MAP_FRONT_RIGHT] =           SPA_AUDIO_CHANNEL_FR,
		[SF_CHANNEL_MAP_FRONT_CENTER] =          SPA_AUDIO_CHANNEL_FC,
		[SF_CHANNEL_MAP_REAR_CENTER] =           SPA_AUDIO_CHANNEL_RC,
		[SF_CHANNEL_MAP_REAR_LEFT] =             SPA_AUDIO_CHANNEL_RL,
		[SF_CHANNEL_MAP_REAR_RIGHT] =            SPA_AUDIO_CHANNEL_RR,
		[SF_CHANNEL_MAP_LFE] =                   SPA_AUDIO_CHANNEL_LFE,
		[SF_CHANNEL_MAP_FRONT_LEFT_OF_CENTER] =  SPA_AUDIO_CHANNEL_FLC,
		[SF_CHANNEL_MAP_FRONT_RIGHT_OF_CENTER] = SPA_AUDIO_CHANNEL_FRC,
		[SF_CHANNEL_MAP_SIDE_LEFT] =             SPA_AUDIO_CHANNEL_SL,
		[SF_CHANNEL_MAP_SIDE_RIGHT] =            SPA_AUDIO_CHANNEL_SR,
		[SF_CHANNEL_MAP_TOP_CENTER] =            SPA_AUDIO_CHANNEL_TC,
		[SF_CHANNEL_MAP_TOP_FRONT_LEFT] =        SPA_AUDIO_CHANNEL_TFL,
		[SF_CHANNEL_MAP_TOP_FRONT_RIGHT] =       SPA_AUDIO_CHANNEL_TFR,
		[SF_CHANNEL_MAP_TOP_FRONT_CENTER] =      SPA_AUDIO_CHANNEL_TFC,
		[SF_CHANNEL_MAP_TOP_REAR_LEFT] =         SPA_AUDIO_CHANNEL_TRL,
		[SF_CHANNEL_MAP_TOP_REAR_RIGHT] =        SPA_AUDIO_CHANNEL_TRR,
		[SF_CHANNEL_MAP_TOP_REAR_CENTER] =       SPA_AUDIO_CHANNEL_TRC
	};
	int i;

	for (i = 0; i < map->n_channels; i++) {
		if (map->channels[i] >= 0 && map->channels[i] < (int) SPA_N_ELEMENTS(table))
			map->channels[i] = table[map->channels[i]];
		else
			map->channels[i] = SPA_AUDIO_CHANNEL_UNKNOWN;
	}
	return 0;
}
struct mapping {
	const char *name;
	unsigned int channels;
	unsigned int values[32];
};

static const struct mapping maps[] =
{
	{ "mono",         SPA_AUDIO_LAYOUT_Mono },
	{ "stereo",       SPA_AUDIO_LAYOUT_Stereo },
	{ "surround-21",  SPA_AUDIO_LAYOUT_2_1 },
	{ "quad",         SPA_AUDIO_LAYOUT_Quad },
	{ "surround-22",  SPA_AUDIO_LAYOUT_2_2 },
	{ "surround-40",  SPA_AUDIO_LAYOUT_4_0 },
	{ "surround-31",  SPA_AUDIO_LAYOUT_3_1 },
	{ "surround-41",  SPA_AUDIO_LAYOUT_4_1 },
	{ "surround-50",  SPA_AUDIO_LAYOUT_5_0 },
	{ "surround-51",  SPA_AUDIO_LAYOUT_5_1 },
	{ "surround-51r", SPA_AUDIO_LAYOUT_5_1R },
	{ "surround-70",  SPA_AUDIO_LAYOUT_7_0 },
	{ "surround-71",  SPA_AUDIO_LAYOUT_7_1 },
};

static unsigned int find_channel(const char *name)
{
	int i;

	for (i = 0; spa_type_audio_channel[i].name; i++) {
		if (strcmp(name, rindex(spa_type_audio_channel[i].name, ':')+1) == 0)
			return i;
	}
	return SPA_AUDIO_CHANNEL_UNKNOWN;
}

static int parse_channelmap(const char *channel_map, struct channelmap *map)
{
	int i, nch;
	char **ch;

	for (i = 0; i < (int) SPA_N_ELEMENTS(maps); i++) {
		if (strcmp(maps[i].name, channel_map) == 0) {
			map->n_channels = maps[i].channels;
			spa_memcpy(map->channels, &maps[i].values,
					map->n_channels * sizeof(unsigned int));
			return 0;
		}
	}

	ch = pw_split_strv(channel_map, ",", SPA_AUDIO_MAX_CHANNELS, &nch);
	if (ch == NULL)
		return -1;

	map->n_channels = nch;
	for (i = 0; i < map->n_channels; i++) {
		int c = find_channel(ch[i]);
		if (c == SPA_AUDIO_CHANNEL_UNKNOWN)
			return -1;
		map->channels[i] = c;
	}
	return 0;
}

static int channelmap_default(struct channelmap *map, int n_channels)
{
	switch(n_channels) {
	case 1:
		parse_channelmap("mono", map);
		break;
	case 2:
		parse_channelmap("stereo", map);
		break;
	case 3:
		parse_channelmap("surround-21", map);
		break;
	case 4:
		parse_channelmap("quad", map);
		break;
	case 5:
		parse_channelmap("surround-50", map);
		break;
	case 6:
		parse_channelmap("surround-51", map);
		break;
	case 7:
		parse_channelmap("surround-70", map);
		break;
	case 8:
		parse_channelmap("surround-71", map);
		break;
	default:
		n_channels = 0;
		break;
	}
	map->n_channels = n_channels;
	return 0;
}

static void channelmap_print(struct channelmap *map)
{
	int i;

	for (i = 0; i < map->n_channels; i++) {
		const char *name = spa_debug_type_find_name(spa_type_audio_channel, map->channels[i]);
		if (name == NULL)
			name = ":UNK";
		printf("%s%s", rindex(name, ':')+1, i + 1 < map->n_channels ? "," : "");
	}
}

static void
target_destroy(struct target *target)
{
	if (!target)
		return;
	if (target->name)
		free(target->name);
	if (target->desc)
		free(target->desc);
	free(target);
}

static struct target *
target_create(uint32_t id, const char *name, const char *desc, int prio)
{
	struct target *target;

	target = malloc(sizeof(*target));
	if (!target)
		return NULL;
	target->id = id;
	target->name = strdup(name);
	target->desc = strdup(desc ? : "");
	target->prio = prio;

	if (!target->name || !target->desc) {
		target_destroy(target);
		return NULL;
	}
	return target;
}

static void on_core_info(void *userdata, const struct pw_core_info *info)
{
	struct data *data = userdata;

	if (data->verbose)
		fprintf(stdout, "remote %"PRIu32" is named \"%s\"\n",
				info->id, info->name);
}

static void on_core_done(void *userdata, uint32_t id, int seq)
{
	struct data *data = userdata;

	if (data->verbose)
		printf("core done\n");

	/* if we're listing targets just exist */
	if (data->list_targets) {
		data->targets_listed = true;
		pw_main_loop_quit(data->loop);
	}
}

static void on_core_error(void *userdata, uint32_t id, int seq, int res, const char *message)
{
	struct data *data = userdata;

	fprintf(stderr, "remote error: id=%"PRIu32" seq:%d res:%d (%s): %s",
			id, seq, res, spa_strerror(res), message);

	pw_main_loop_quit(data->loop);
}

static const struct pw_core_events core_events = {
	PW_VERSION_CORE_EVENTS,
	.info = on_core_info,
	.done = on_core_done,
	.error = on_core_error,
};

static void registry_event_global(void *userdata, uint32_t id,
		uint32_t permissions, const char *type, uint32_t version,
		const struct spa_dict *props)
{
	struct data *data = userdata;
	const struct spa_dict_item *item;
	const char *name, *desc, *media_class, *prio_session;
	int prio;
	enum mode mode = mode_none;
	struct target *target;

	/* only once */
	if (data->targets_listed)
		return;

	/* must be listing targets and interface must be a node */
	if (!data->list_targets || strcmp(type, PW_TYPE_INTERFACE_Node))
		return;

	name = spa_dict_lookup(props, PW_KEY_NODE_NAME);
	desc = spa_dict_lookup(props, PW_KEY_NODE_DESCRIPTION);
	media_class = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
	prio_session = spa_dict_lookup(props, PW_KEY_PRIORITY_SESSION);

	/* name and media class must exist */
	if (!name || !media_class)
		return;

	/* get allowed mode from the media class */
	/* TODO extend to something else besides Audio/Source|Sink */
	if (!strcmp(media_class, "Audio/Source"))
		mode = mode_record;
	else if (!strcmp(media_class, "Audio/Sink"))
		mode = mode_playback;

	/* modes must match */
	if (mode != data->mode)
		return;

	prio = prio_session ? atoi(prio_session) : -1;

	if (data->verbose) {
		printf("registry: id=%"PRIu32" type=%s name=\"%s\" media_class=\"%s\" desc=\"%s\" prio=%d\n",
				id, type, name, media_class, desc ? : "", prio);

		spa_dict_for_each(item, props) {
			fprintf(stdout, "\t\t%s = \"%s\"\n", item->key, item->value);
		}
	}

	target = target_create(id, name, desc, prio);
	if (target)
		spa_list_append(&data->targets, &target->link);
}

static void registry_event_global_remove(void *userdata, uint32_t id)
{
	struct data *data = userdata;

	if (data->verbose)
		printf("registry: remove id=%"PRIu32"\n", id);
}

static const struct pw_registry_events registry_events = {
	PW_VERSION_REGISTRY_EVENTS,
	.global = registry_event_global,
	.global_remove = registry_event_global_remove,
};

static void
on_state_changed(void *userdata, enum pw_stream_state old,
		 enum pw_stream_state state, const char *error)
{
	struct data *data = userdata;
	int ret;

	if (data->verbose)
		printf("stream state changed %s -> %s\n",
				pw_stream_state_as_string(old),
				pw_stream_state_as_string(state));

	if (state == PW_STREAM_STATE_STREAMING && !data->volume_is_set) {

		ret = pw_stream_set_control(data->stream,
				SPA_PROP_volume, 1, &data->volume,
				0);
		if (data->verbose)
			printf("set stream volume to %.3f - %s\n", data->volume,
					ret == 0 ? "success" : "FAILED");

		data->volume_is_set = true;

	}

	if (state == PW_STREAM_STATE_STREAMING) {
		if (data->verbose)
			printf("stream node %"PRIu32"\n",
				pw_stream_get_node_id(data->stream));
	}
}

static void
on_param_changed(void *userdata, uint32_t id, const struct spa_pod *format)
{
	struct data *data = userdata;

	if (data->verbose)
		printf("stream param change: id=%"PRIu32"\n",
				id);
}

static void on_process(void *userdata)
{
	struct data *data = userdata;
	struct pw_buffer *b;
	struct spa_buffer *buf;
	struct spa_data *d;
	int n_frames, n_fill_frames;
	uint8_t *p;
	bool have_data;
	uint32_t offset, size;

	if ((b = pw_stream_dequeue_buffer(data->stream)) == NULL)
		return;

	buf = b->buffer;
	d = &buf->datas[0];

	have_data = false;

	if ((p = d->data) == NULL)
		return;

	if (data->mode == mode_playback) {

		n_frames = d->maxsize / data->stride;

		n_fill_frames = data->fill(data, p, n_frames);

		if (n_fill_frames > 0) {
			d->chunk->offset = 0;
			d->chunk->stride = data->stride;
			d->chunk->size = n_fill_frames * data->stride;
			have_data = true;
		} else if (n_fill_frames < 0)
			fprintf(stderr, "fill error %d\n", n_fill_frames);
	} else {
		offset = SPA_MIN(d->chunk->offset, d->maxsize);
		size = SPA_MIN(d->chunk->size, d->maxsize - offset);

		p += offset;

		n_frames = size / data->stride;

		n_fill_frames = data->fill(data, p, n_frames);

		have_data = true;
	}

	if (have_data) {
		pw_stream_queue_buffer(data->stream, b);
		return;
	}

	if (data->mode == mode_playback)
		pw_stream_flush(data->stream, true);
}

static void on_drained(void *userdata)
{
	struct data *data = userdata;

	if (data->verbose)
		printf("stream drained\n");

	data->drained = true;
	pw_main_loop_quit(data->loop);
}

static const struct pw_stream_events stream_events = {
	PW_VERSION_STREAM_EVENTS,
	.state_changed = on_state_changed,
	.param_changed = on_param_changed,
	.process = on_process,
	.drained = on_drained
};

static void do_quit(void *userdata, int signal_number)
{
	struct data *data = userdata;
	pw_main_loop_quit(data->loop);
}

enum {
	OPT_VERSION = 1000,
	OPT_MEDIA_TYPE,
	OPT_MEDIA_CATEGORY,
	OPT_MEDIA_ROLE,
	OPT_TARGET,
	OPT_LATENCY,
	OPT_RATE,
	OPT_CHANNELS,
	OPT_CHANNELMAP,
	OPT_FORMAT,
	OPT_VOLUME,
	OPT_LIST_TARGETS,
};

static const struct option long_options[] = {
	{"help",	no_argument,	   NULL, 'h'},
	{"version",	no_argument,	   NULL, OPT_VERSION},
	{"verbose",	no_argument,	   NULL, 'v'},

	{"record",	no_argument,	   NULL, 'r'},
	{"playback",	no_argument,	   NULL, 's'},

	{"remote",	required_argument, NULL, 'R'},

	{"media-type",		required_argument, NULL, OPT_MEDIA_TYPE },
	{"media-category",	required_argument, NULL, OPT_MEDIA_CATEGORY },
	{"media-role",		required_argument, NULL, OPT_MEDIA_ROLE },
	{"target",		required_argument, NULL, OPT_TARGET },
	{"latency",		required_argument, NULL, OPT_LATENCY },

	{"rate",		required_argument, NULL, OPT_RATE },
	{"channels",		required_argument, NULL, OPT_CHANNELS },
	{"channel-map",		required_argument, NULL, OPT_CHANNELMAP },
	{"format",		required_argument, NULL, OPT_FORMAT },

	{"volume",		required_argument, NULL, OPT_VOLUME },
	{"list-targets",	no_argument, NULL, OPT_LIST_TARGETS },

	{NULL, 0, NULL, 0 }
};

static void show_usage(const char *name, bool is_error)
{
	FILE *fp;

	fp = is_error ? stderr : stdout;

        fprintf(fp, "%s [options] <file>\n", name);

	fprintf(fp,
             "  -h, --help                            Show this help\n"
             "      --version                         Show version\n"
	     "\n");

	fprintf(fp,
             "  -R, --remote                          Remote daemon name\n"
             "      --media-type                      Set media type (default %s)\n"
             "      --media-category                  Set media category (default %s)\n"
             "      --media-role                      Set media role (default %s)\n"
             "      --target                          Set node target (default %s)\n"
	     "                                          0 means don't link\n"
             "      --latency                         Set node latency (default %s)\n"
	     "                                          Xunit (unit = s, ms, us, ns)\n"
	     "                                          or direct samples (256)\n"
	     "                                          the rate is the one of the source file\n"
	     "      --list-targets                    List available targets for --target\n"
	     "\n",
	     DEFAULT_MEDIA_TYPE,
	     DEFAULT_MEDIA_CATEGORY_PLAYBACK,
	     DEFAULT_MEDIA_ROLE,
	     DEFAULT_TARGET, DEFAULT_LATENCY);

	fprintf(fp,
             "      --rate                            Sample rate (req. for rec) (default %u)\n"
             "      --channels                        Number of channels (req. for rec) (default %u)\n"
             "      --channel-map                     Channel map\n"
	     "                                            one of: \"stereo\", \"surround-51\",... or\n"
	     "                                            comma separated list of channel names: eg. \"FL,FR\"\n"
             "      --format                          Sample format %s (req. for rec) (default %s)\n"
	     "      --volume                          Stream volume 0-1.0 (default %.3f)\n"
	     "\n",
	     DEFAULT_RATE, DEFAULT_CHANNELS, STR_FMTS, DEFAULT_FORMAT, DEFAULT_VOLUME);

	if (!strcmp(name, "pw-cat")) {
		fprintf(fp,
		     "  -p, --playback                        Playback mode\n"
		     "  -r, --record                          Recording mode\n"
		     "\n");
	}

        fprintf(fp,
             "  -v, --verbose                         Enable verbose operations\n"
	     "\n");
}

static int setup_sndfile(struct data *data)
{
	SF_INFO info;
	const char *s;
	unsigned int nom = 0;

	/* for record, you fill in the info first */
	if (data->mode == mode_record) {
		if (data->format == NULL)
			data->format = DEFAULT_FORMAT;
		if (data->channels == 0)
			data->channels = DEFAULT_CHANNELS;
		if (data->rate == 0)
			data->rate = DEFAULT_RATE;

		memset(&info, 0, sizeof(info));
		info.samplerate = data->rate;
		info.channels = data->channels;
		info.format = sf_str_to_fmt(data->format);
		if (info.format == -1) {
			fprintf(stderr, "error: unknown format \"%s\"\n", data->format);
			return -EINVAL;
		}
		info.format |= SF_FORMAT_WAV;
#if __BYTE_ORDER == __BIG_ENDIAN
		info.format |= SF_ENDIAN_BIG;
#else
		info.format |= SF_ENDIAN_LITTLE;
#endif
	}

	data->file = sf_open(data->filename,
			data->mode == mode_playback ? SFM_READ : SFM_WRITE,
			&info);
	if (!data->file) {
		fprintf(stderr, "error: failed to open audio file \"%s\": %s\n",
				data->filename, sf_strerror(NULL));
		return -EIO;
	}

	if (data->verbose)
		printf("opened file \"%s\" format %08x channels:%d rate:%d\n",
				data->filename, info.format, info.channels, info.samplerate);
	if (data->channels > 0 && info.channels != data->channels) {
		printf("given channels (%u) don't match file channels (%d)\n",
				data->channels, info.channels);
		return -EINVAL;
	}

	data->rate = info.samplerate;
	data->channels = info.channels;

	if (data->mode == mode_playback) {
		if (data->channelmap.n_channels == 0) {
			bool def = false;

			if (sf_command(data->file, SFC_GET_CHANNEL_MAP_INFO,
					data->channelmap.channels,
					sizeof(data->channelmap.channels[0]) * data->channels)) {
				data->channelmap.n_channels = data->channels;
				if (channelmap_from_sf(&data->channelmap) < 0)
					data->channelmap.n_channels = 0;
			}
			if (data->channelmap.n_channels == 0) {
				channelmap_default(&data->channelmap, data->channels);
				def = true;
			}
			if (data->verbose) {
				printf("using %s channel map: ", def ? "default" : "file");
				channelmap_print(&data->channelmap);
				printf("\n");
			}
		}
	}
	data->samplesize = sf_format_samplesize(info.format);
	data->stride = data->samplesize * data->channels;
	data->spa_format = sf_format_to_pw(info.format);
	data->fill = data->mode == mode_playback ?
			sf_fmt_playback_fill_fn(info.format) :
			sf_fmt_record_fill_fn(info.format);

	data->latency_unit = unit_none;

	s = data->latency;
	while (*s && isdigit(*s))
		s++;
	if (!*s)
		data->latency_unit = unit_samples;
	else if (!strcmp(s, "none"))
		data->latency_unit = unit_none;
	else if (!strcmp(s, "s") || !strcmp(s, "sec") || !strcmp(s, "secs"))
		data->latency_unit = unit_sec;
	else if (!strcmp(s, "ms") || !strcmp(s, "msec") || !strcmp(s, "msecs"))
		data->latency_unit = unit_msec;
	else if (!strcmp(s, "us") || !strcmp(s, "usec") || !strcmp(s, "usecs"))
		data->latency_unit = unit_usec;
	else if (!strcmp(s, "ns") || !strcmp(s, "nsec") || !strcmp(s, "nsecs"))
		data->latency_unit = unit_nsec;
	else {
		fprintf(stderr, "error: bad latency value %s (bad unit)\n", data->latency);
		return -EINVAL;
	}
	data->latency_value = atoi(data->latency);
	if (!data->latency_value) {
		fprintf(stderr, "error: bad latency value %s (is zero)\n", data->latency);
		return -EINVAL;
	}

	switch (data->latency_unit) {
	case unit_sec:
		nom = data->latency_value * data->rate;
		break;
	case unit_msec:
		nom = nearbyint((data->latency_value * data->rate) / 1000.0);
		break;
	case unit_usec:
		nom = nearbyint((data->latency_value * data->rate) / 1000000.0);
		break;
	case unit_nsec:
		nom = nearbyint((data->latency_value * data->rate) / 1000000000.0);
		break;
	case unit_samples:
		nom = data->latency_value;
		break;
	default:
		nom = 0;
		break;
	}

	if (data->verbose)
		printf("rate=%u channels=%u fmt=%s samplesize=%u stride=%u latency=%u (%.3fs)\n",
				data->rate, data->channels,
				sf_fmt_to_str(info.format),
				data->samplesize,
				data->stride, nom, (double)nom/data->rate);
	if (nom)
		pw_properties_setf(data->props, PW_KEY_NODE_LATENCY, "%u/%u", nom, data->rate);

	return 0;
}

int main(int argc, char *argv[])
{
	struct data data = { 0, };
	struct pw_loop *l;
	const struct spa_pod *params[1];
	uint8_t buffer[1024];
	struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));
	const char *prog;
	int exit_code = EXIT_FAILURE, c, ret;
	struct target *target, *target_default;
	enum pw_stream_flags flags = 0;

	pw_init(&argc, &argv);

	flags |= PW_STREAM_FLAG_AUTOCONNECT;

	prog = argv[0];
	if ((prog = strrchr(argv[0], '/')) != NULL)
		prog++;
	else
		prog = argv[0];

	/* prime the mode from the program name */
	if (!strcmp(prog, "pw-play"))
		data.mode = mode_playback;
	else if (!strcmp(prog, "pw-record"))
		data.mode = mode_record;
	else
		data.mode = mode_none;

	/* negative means no volume adjustment */
	data.volume = -1.0;

	/* initialize list everytime */
	spa_list_init(&data.targets);

	while ((c = getopt_long(argc, argv, "hvprR:", long_options, NULL)) != -1) {

		switch (c) {

		case 'h':
			show_usage(prog, false);
			return EXIT_SUCCESS;

		case OPT_VERSION:
			fprintf(stdout, "%s\n"
				"Compiled with libpipewire %s\n"
				"Linked with libpipewire %s\n",
				prog,
				pw_get_headers_version(),
				pw_get_library_version());
			return 0;

		case 'v':
			data.verbose = true;
			break;

		case 'p':
			data.mode = mode_playback;
			break;

		case 'r':
			data.mode = mode_record;
			break;

		case 'R':
			data.remote_name = optarg;
			break;

		case OPT_MEDIA_TYPE:
			data.media_type = optarg;
			break;

		case OPT_MEDIA_CATEGORY:
			data.media_category = optarg;
			break;

		case OPT_MEDIA_ROLE:
			data.media_role = optarg;
			break;

		case OPT_TARGET:
			data.target = optarg;
			if (!strcmp(optarg, "auto")) {
				data.target_id = PW_ID_ANY;
				break;
			}
			if (!isdigit(optarg[0])) {
				fprintf(stderr, "error: bad target option \"%s\"\n", optarg);
				goto error_usage;
			}
			data.target_id = atoi(optarg);
			if (data.target_id == 0) {
				data.target_id = PW_ID_ANY;
				flags &= ~PW_STREAM_FLAG_AUTOCONNECT;
			}
			break;

		case OPT_LATENCY:
			data.latency = optarg;
			break;

		case OPT_RATE:
			ret = atoi(optarg);
			if (ret <= 0) {
				fprintf(stderr, "error: bad rate %d\n", ret);
				goto error_usage;
			}
			data.rate = (unsigned int)ret;
			break;

		case OPT_CHANNELS:
			ret = atoi(optarg);
			if (ret <= 0) {
				fprintf(stderr, "error: bad channels %d\n", ret);
				goto error_usage;
			}
			data.channels = (unsigned int)ret;
			break;

		case OPT_CHANNELMAP:
			data.channel_map = optarg;
			break;

		case OPT_FORMAT:
			data.format = optarg;
			break;

		case OPT_VOLUME:
			data.volume = atof(optarg);
			break;

		case OPT_LIST_TARGETS:
			data.list_targets = true;
			break;

		default:
			fprintf(stderr, "error: unknown option '%c'\n", c);
			goto error_usage;
		}
	}

	if (data.mode == mode_none) {
		fprintf(stderr, "error: one of the playback/record options must be provided\n");
		goto error_usage;
	}

	if (!data.media_type)
		data.media_type = DEFAULT_MEDIA_TYPE;
	if (!data.media_category)
		data.media_category = data.mode == mode_playback ?
					DEFAULT_MEDIA_CATEGORY_PLAYBACK :
					DEFAULT_MEDIA_CATEGORY_RECORD;
	if (!data.media_role)
		data.media_role = DEFAULT_MEDIA_ROLE;
	if (!data.target) {
		data.target = DEFAULT_TARGET;
		data.target_id = PW_ID_ANY;
	}
	if (!data.latency)
		data.latency = DEFAULT_LATENCY;
	if (data.channel_map != NULL) {
		if (parse_channelmap(data.channel_map, &data.channelmap) < 0) {
			fprintf(stderr, "error: can parse channel-map \"%s\"\n", data.channel_map);
			goto error_usage;

		} else {
			if (data.channels > 0 && data.channelmap.n_channels != data.channels) {
				fprintf(stderr, "error: channels and channel-map incompatible\n");
				goto error_usage;
			}
			data.channels = data.channelmap.n_channels;
		}
	}
	if (data.volume < 0)
		data.volume = DEFAULT_VOLUME;

	if (!data.list_targets && optind >= argc) {
		fprintf(stderr, "error: filename argument missing\n");
		goto error_usage;
	}
	data.filename = argv[optind++];

	data.props = pw_properties_new(
			PW_KEY_MEDIA_TYPE, data.media_type,
			PW_KEY_MEDIA_CATEGORY, data.media_category,
			PW_KEY_MEDIA_ROLE, data.media_role,
			PW_KEY_APP_NAME, prog,
			PW_KEY_MEDIA_NAME, data.filename,
			PW_KEY_NODE_NAME, prog,
			NULL);

	if (data.props == NULL) {
		fprintf(stderr, "error: pw_properties_new() failed: %m\n");
		goto error_no_props;
	}

	/* make a main loop. If you already have another main loop, you can add
	 * the fd of this pipewire mainloop to it. */
	data.loop = pw_main_loop_new(NULL);
	if (!data.loop) {
		fprintf(stderr, "error: pw_main_loop_new() failed: %m\n");
		goto error_no_main_loop;
	}

	l = pw_main_loop_get_loop(data.loop);
	pw_loop_add_signal(l, SIGINT, do_quit, &data);
	pw_loop_add_signal(l, SIGTERM, do_quit, &data);

	data.context = pw_context_new(l, NULL, 0);
	if (!data.context) {
		fprintf(stderr, "error: pw_context_new() failed: %m\n");
		goto error_no_context;
	}

	data.core = pw_context_connect(data.context,
			pw_properties_new(
				PW_KEY_REMOTE_NAME, data.remote_name,
				NULL),
			0);
	if (!data.core) {
		fprintf(stderr, "error: pw_context_connect() failed: %m\n");
		goto error_ctx_connect_failed;
	}
	pw_core_add_listener(data.core, &data.core_listener, &core_events, &data);

	data.registry = pw_core_get_registry(data.core, PW_VERSION_REGISTRY, 0);
	if (!data.registry) {
		fprintf(stderr, "error: pw_core_get_registry() failed: %m\n");
		goto error_no_registry;
	}
	pw_registry_add_listener(data.registry, &data.registry_listener, &registry_events, &data);

	pw_core_sync(data.core, 0, 0);

	if (!data.list_targets) {
		struct spa_audio_info_raw info;

		ret = setup_sndfile(&data);
		if (ret < 0) {
			fprintf(stderr, "error: open failed: %s\n", spa_strerror(ret));
			switch (ret) {
			case -EIO:
				goto error_bad_file;
			case -EINVAL:
			default:
				goto error_usage;
			}
		}
		info = SPA_AUDIO_INFO_RAW_INIT(
			.flags = data.channelmap.n_channels ? 0 : SPA_AUDIO_FLAG_UNPOSITIONED,
			.format = data.spa_format,
			.rate = data.rate,
			.channels = data.channels);

		if (data.channelmap.n_channels)
			memcpy(info.position, data.channelmap.channels, data.channels * sizeof(int));

		params[0] = spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &info);

		data.stream = pw_stream_new(data.core, prog, data.props);
		data.props = NULL;

		if (data.stream == NULL) {
			fprintf(stderr, "error: failed to create stream: %m\n");
			goto error_no_stream;
		}
		pw_stream_add_listener(data.stream, &data.stream_listener, &stream_events, &data);

		if (data.verbose)
			printf("connecting %s stream; target_id=%"PRIu32"\n",
					data.mode == mode_playback ? "playback" : "record",
					data.target_id);

		ret = pw_stream_connect(data.stream,
				  data.mode == mode_playback ? PW_DIRECTION_OUTPUT : PW_DIRECTION_INPUT,
				  data.target_id,
				  flags |
				  PW_STREAM_FLAG_MAP_BUFFERS,
				  params, 1);
		if (ret < 0) {
			fprintf(stderr, "error: failed connect: %s\n", spa_strerror(ret));
			goto error_connect_fail;
		}

		if (data.verbose) {
			const struct pw_properties *props;
			void *pstate;
			const char *key, *val;

			if ((props = pw_stream_get_properties(data.stream)) != NULL) {
				printf("stream properties:\n");
				pstate = NULL;
				while ((key = pw_properties_iterate(props, &pstate)) != NULL &&
					(val = pw_properties_get(props, key)) != NULL) {
					printf("\t%s = \"%s\"\n", key, val);
				}
			}
		}
	}

	/* and wait while we let things run */
	pw_main_loop_run(data.loop);

	/* we're returning OK only if got to the point to drain */
	if (!data.list_targets) {
		if (data.drained)
			exit_code = EXIT_SUCCESS;
	} else {
		if (data.targets_listed) {
			exit_code = EXIT_SUCCESS;

			/* first find the highest priority */
			target_default = NULL;
			spa_list_for_each(target, &data.targets, link) {
				if (!target_default) {
					target_default = target;
					continue;
				}
				if (target->prio > target_default->prio)
					target_default = target;
			}

			printf("Available targets (\"*\" denotes default):\n");
			spa_list_for_each(target, &data.targets, link) {
				printf("%s\t%"PRIu32": name=\"%s\" description=\"%s\" prio=%d\n",
				       target == target_default ? "*" : "",
				       target->id, target->name, target->desc, target->prio);
			}
		}
	}

	/* destroy targets */
	while (!spa_list_is_empty(&data.targets)) {
		target = spa_list_last(&data.targets, struct target, link);
		spa_list_remove(&target->link);
		target_destroy(target);
	}

error_connect_fail:
	if (data.stream)
		pw_stream_destroy(data.stream);
error_no_stream:
error_no_registry:
	pw_core_disconnect(data.core);
error_ctx_connect_failed:
	pw_context_destroy(data.context);
error_no_context:
	pw_main_loop_destroy(data.loop);
error_no_props:
error_no_main_loop:
error_bad_file:
	if (data.props)
		pw_properties_free(data.props);
	if (data.file)
		sf_close(data.file);
	return exit_code;

error_usage:
	show_usage(prog, true);
	return EXIT_FAILURE;
}