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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
package main

import (
	"encoding/binary"
	"fmt"
	"os"
	"path/filepath"
	"syscall"

	"golang.org/x/sys/unix"
)

// Message header is 16 bytes
type MessageHeader struct {
	ID        uint32 // Object ID (0 for core)
	Opcode    uint8  // Method/event opcode
	Size      uint32 // Size of payload (24 bits, but we use uint32)
	HeaderSeq uint32 // Message sequence counter (no semantic meaning, just increments)
	NFds      uint32 // Number of file descriptors
}

// EncodeHeader encodes the message header to 16 bytes
func (h *MessageHeader) Encode() []byte {
	buf := make([]byte, 16)
	binary.LittleEndian.PutUint32(buf[0:4], h.ID)

	// Pack opcode (high byte) and size (low 24 bits) into one uint32
	// opcode in bits 24-31, size in bits 0-23
	packed := (uint32(h.Opcode) << 24) | (h.Size & 0xFFFFFF)
	binary.LittleEndian.PutUint32(buf[4:8], packed)

	binary.LittleEndian.PutUint32(buf[8:12], h.HeaderSeq)
	binary.LittleEndian.PutUint32(buf[12:16], h.NFds)
	return buf
}

// DecodeHeader decodes 16 bytes into a message header
func DecodeHeader(data []byte) (*MessageHeader, error) {
	if len(data) < 16 {
		return nil, fmt.Errorf("insufficient data for header: need 16, got %d", len(data))
	}

	h := &MessageHeader{}
	h.ID = binary.LittleEndian.Uint32(data[0:4])

	// Extract opcode and size from the packed field
	// opcode in bits 24-31, size in bits 0-23
	packed := binary.LittleEndian.Uint32(data[4:8])
	h.Opcode = uint8(packed >> 24)
	h.Size = packed & 0xFFFFFF

	h.HeaderSeq = binary.LittleEndian.Uint32(data[8:12])
	h.NFds = binary.LittleEndian.Uint32(data[12:16])

	return h, nil
}

// SendMessage sends a complete message (header + payload) using sendmsg
func SendMessage(fd int, header *MessageHeader, payload []byte) error {
	headerBytes := header.Encode()

	// Combine header and payload into a single buffer
	msg := make([]byte, len(headerBytes)+len(payload))
	copy(msg, headerBytes)
	copy(msg[len(headerBytes):], payload)

	// Use sendmsg like pw-cli does
	err := syscall.Sendmsg(fd, msg, nil, nil, syscall.MSG_DONTWAIT|syscall.MSG_NOSIGNAL)
	if err != nil {
		return fmt.Errorf("failed to sendmsg: %w", err)
	}

	return nil
}

// Message represents a complete PipeWire message
type Message struct {
	Header  *MessageHeader
	Payload []byte
}

// ReceiveMessages receives ALL messages from one recvmsg call
func ReceiveMessages(fd int) ([]*Message, error) {
	// Allocate a large buffer like pw-cli does (98304 bytes to match what we saw in strace)
	buf := make([]byte, 98304)

	// Do a BLOCKING read - wait until data arrives
	n, _, _, _, err := syscall.Recvmsg(fd, buf, nil, syscall.MSG_CMSG_CLOEXEC)
	if err != nil {
		return nil, fmt.Errorf("failed to recvmsg: %w", err)
	}

	// Parse all messages from the buffer
	messages := make([]*Message, 0)
	offset := 0

	for offset < n {
		if n-offset < 16 {
			// Not enough data for a header
			break
		}

		// Parse header
		header, err := DecodeHeader(buf[offset : offset+16])
		if err != nil {
			return nil, fmt.Errorf("failed to decode header at offset %d: %w", offset, err)
		}

		// Check if we have the complete payload
		messageSize := 16 + int(header.Size)
		if offset+messageSize > n {
			return nil, fmt.Errorf("incomplete message at offset %d: need %d bytes, have %d", offset, messageSize, n-offset)
		}

		// Extract payload
		var payload []byte
		if header.Size > 0 {
			payload = make([]byte, header.Size)
			copy(payload, buf[offset+16:offset+messageSize])
		}

		messages = append(messages, &Message{
			Header:  header,
			Payload: payload,
		})

		offset += messageSize
	}

	return messages, nil
}

// SendCoreHello sends a Core::Hello message with version 3
func SendCoreHello(fd int, seq uint32) error {
	// Create payload: Struct(Int: 3)
	// According to protocol, version = 3
	versionPod := NewInt(3)
	structPod := NewStruct(versionPod)
	payload := structPod.Encode()

	header := &MessageHeader{
		ID:        0, // Core object ID
		Opcode:    1, // Core::Hello opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// ParseCoreInfo parses a Core::Info response
func ParseCoreInfo(payload []byte) error {
	pod, _, err := DecodePOD(payload)
	if err != nil {
		return fmt.Errorf("failed to decode POD: %w", err)
	}

	if pod.Type != TypeStruct {
		return fmt.Errorf("expected Struct, got type %d", pod.Type)
	}

	children, err := pod.GetStructChildren()
	if err != nil {
		return fmt.Errorf("failed to get struct children: %w", err)
	}

	fmt.Printf("Core::Info received with %d fields:\n", len(children))

	// Parse the fields according to the protocol spec
	// Struct(Int: id, Int: cookie, String: user_name, String: host_name,
	//        String: version, String: name, Long: change_mask, Struct: props)

	if len(children) >= 1 {
		id, err := children[0].GetInt()
		if err == nil {
			fmt.Printf("  id: %d\n", id)
		}
	}

	if len(children) >= 2 {
		cookie, err := children[1].GetInt()
		if err == nil {
			fmt.Printf("  cookie: %d\n", cookie)
		}
	}

	if len(children) >= 3 {
		userName, err := children[2].GetString()
		if err == nil {
			fmt.Printf("  user_name: %s\n", userName)
		}
	}

	if len(children) >= 4 {
		hostName, err := children[3].GetString()
		if err == nil {
			fmt.Printf("  host_name: %s\n", hostName)
		}
	}

	if len(children) >= 5 {
		version, err := children[4].GetString()
		if err == nil {
			fmt.Printf("  version: %s\n", version)
		}
	}

	if len(children) >= 6 {
		name, err := children[5].GetString()
		if err == nil {
			fmt.Printf("  name: %s\n", name)
		}
	}

	if len(children) >= 7 {
		changeMask, err := children[6].GetLong()
		if err == nil {
			fmt.Printf("  change_mask: %d\n", changeMask)
		}
	}

	// Properties are in child 7 if change_mask has (1<<0)
	if len(children) >= 8 {
		fmt.Printf("  properties (struct with %d total children)\n", len(children))
	}

	return nil
}

// SendCoreGetRegistry sends Core::GetRegistry to bind to the registry
// Returns the new_id that will receive Registry events
func SendCoreGetRegistry(fd int, seq uint32, newID uint32) error {
	// Create payload: Struct(Int: version, Int: new_id)
	versionPod := NewInt(3) // Registry version 3
	newIDPod := NewInt(int32(newID))
	structPod := NewStruct(versionPod, newIDPod)
	payload := structPod.Encode()

	header := &MessageHeader{
		ID:        0, // Core object ID
		Opcode:    5, // Core::GetRegistry opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// SendCoreSync sends Core::Sync to mark a synchronization point
func SendCoreSync(fd int, id uint32, seq uint32) error {
	// Create payload: Struct(Int: id, Int: seq)
	idPod := NewInt(int32(id))
	seqPod := NewInt(int32(seq))
	structPod := NewStruct(idPod, seqPod)
	payload := structPod.Encode()

	header := &MessageHeader{
		ID:        0, // Core object ID
		Opcode:    2, // Core::Sync opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// SendClientUpdateProperties sends Client::UpdateProperties
func SendClientUpdateProperties(fd int, clientID uint32, seq uint32, props map[string]string) error {
	// Create properties dict: Struct(Int: n_items, String: key1, String: val1, ...)
	propFields := make([]*POD, 0)
	propFields = append(propFields, NewInt(int32(len(props)))) // n_items

	for key, val := range props {
		propFields = append(propFields, NewString(key))
		propFields = append(propFields, NewString(val))
	}

	propsStruct := NewStruct(propFields...)
	outerStruct := NewStruct(propsStruct)
	payload := outerStruct.Encode()

	header := &MessageHeader{
		ID:        clientID, // Client object ID
		Opcode:    2,        // Client::UpdateProperties opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// SendCoreCreateObject sends Core::CreateObject to create a new object from a factory
func SendCoreCreateObject(fd int, seq uint32, factoryName string, typeName string, version uint32, props map[string]string, newID uint32) error {
	// Create properties dict: Struct(Int: n_items, String: key1, String: val1, ...)
	propFields := make([]*POD, 0)
	propFields = append(propFields, NewInt(int32(len(props)))) // n_items

	for key, val := range props {
		propFields = append(propFields, NewString(key))
		propFields = append(propFields, NewString(val))
	}

	propsStruct := NewStruct(propFields...)

	// Create payload: Struct(String: factory_name, String: type, Int: version, Struct: props, Int: new_id)
	payload := NewStruct(
		NewString(factoryName),
		NewString(typeName),
		NewInt(int32(version)),
		propsStruct,
		NewInt(int32(newID)),
	).Encode()

	header := &MessageHeader{
		ID:        0, // Core object ID
		Opcode:    6, // Core::CreateObject opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// SendRegistryBind sends Registry::Bind to bind to a global object
func SendRegistryBind(fd int, registryID uint32, seq uint32, globalID uint32, typeName string, version uint32, newID uint32) error {
	// Create payload: Struct(Int: id, String: type, Int: version, Int: new_id)
	payload := NewStruct(
		NewInt(int32(globalID)),
		NewString(typeName),
		NewInt(int32(version)),
		NewInt(int32(newID)),
	).Encode()

	header := &MessageHeader{
		ID:        registryID, // Registry object ID
		Opcode:    1,          // Registry::Bind opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// SPA parameter type constants
const (
	SPA_PARAM_Invalid        = 0
	SPA_PARAM_PropInfo       = 1
	SPA_PARAM_Props          = 2
	SPA_PARAM_EnumFormat     = 3
	SPA_PARAM_Format         = 4
	SPA_PARAM_Buffers        = 5
	SPA_PARAM_Meta           = 6
	SPA_PARAM_IO             = 7
	SPA_PARAM_EnumProfile    = 8
	SPA_PARAM_Profile        = 9
	SPA_PARAM_EnumPortConfig = 10
	SPA_PARAM_PortConfig     = 11
	SPA_PARAM_EnumRoute      = 12
	SPA_PARAM_Route          = 13
	SPA_PARAM_Control        = 14
	SPA_PARAM_Latency        = 15
	SPA_PARAM_ProcessLatency = 16
)

// SendDeviceEnumParams sends Device::EnumParams to enumerate parameters
func SendDeviceEnumParams(fd int, deviceProxyID uint32, seq uint32, enumSeq uint32, paramID uint32) error {
	// Create payload: Struct(Int: seq, Id: id, Int: index, Int: num, Pod: filter)
	// filter is None (null) to get all params
	payload := NewStruct(
		NewInt(int32(enumSeq)), // seq for matching responses
		NewId(paramID),         // param type to enumerate
		NewInt(0),              // index: start at 0
		NewInt(-1),             // num: -1 means all
		NewNone(),              // filter: null/none
	).Encode()

	header := &MessageHeader{
		ID:        deviceProxyID, // Device proxy ID
		Opcode:    2,             // Device::EnumParams opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// SendDeviceSetParam sends Device::SetParam to set a parameter
func SendDeviceSetParam(fd int, deviceProxyID uint32, seq uint32, paramID uint32, paramPod *POD) error {
	// Create payload: Struct(Id: id, Int: flags, Pod: param)
	payload := NewStruct(
		NewId(paramID), // param type (e.g. SPA_PARAM_Profile)
		NewInt(0),      // flags
		paramPod,       // the actual parameter POD
	).Encode()

	header := &MessageHeader{
		ID:        deviceProxyID, // Device proxy ID
		Opcode:    3,             // Device::SetParam opcode
		Size:      uint32(len(payload)),
		HeaderSeq: seq,
		NFds:      0,
	}

	return SendMessage(fd, header, payload)
}

// GlobalObject represents a global object from Registry::Global event
type GlobalObject struct {
	ID          uint32
	Permissions uint32
	Type        string
	Version     uint32
	Properties  map[string]string
}

// ParseRegistryGlobalRemove parses a Registry::GlobalRemove event
func ParseRegistryGlobalRemove(payload []byte) (uint32, error) {
	pod, _, err := DecodePOD(payload)
	if err != nil {
		return 0, fmt.Errorf("failed to decode POD: %w", err)
	}

	if pod.Type != TypeStruct {
		return 0, fmt.Errorf("expected Struct, got type %d", pod.Type)
	}

	children, err := pod.GetStructChildren()
	if err != nil {
		return 0, fmt.Errorf("failed to get struct children: %w", err)
	}

	if len(children) < 1 {
		return 0, fmt.Errorf("expected at least 1 field, got %d", len(children))
	}

	// Parse id (field 0)
	id, err := children[0].GetInt()
	if err != nil {
		return 0, fmt.Errorf("failed to get id: %w", err)
	}

	return uint32(id), nil
}

// ParseRegistryGlobal parses a Registry::Global event
func ParseRegistryGlobal(payload []byte) (*GlobalObject, error) {
	pod, _, err := DecodePOD(payload)
	if err != nil {
		return nil, fmt.Errorf("failed to decode POD: %w", err)
	}

	if pod.Type != TypeStruct {
		return nil, fmt.Errorf("expected Struct, got type %d", pod.Type)
	}

	children, err := pod.GetStructChildren()
	if err != nil {
		return nil, fmt.Errorf("failed to get struct children: %w", err)
	}

	if len(children) < 5 {
		return nil, fmt.Errorf("expected at least 5 fields, got %d", len(children))
	}

	obj := &GlobalObject{
		Properties: make(map[string]string),
	}

	// Parse id (field 0)
	id, err := children[0].GetInt()
	if err != nil {
		return nil, fmt.Errorf("failed to get id: %w", err)
	}
	obj.ID = uint32(id)

	// Parse permissions (field 1)
	permissions, err := children[1].GetInt()
	if err != nil {
		return nil, fmt.Errorf("failed to get permissions: %w", err)
	}
	obj.Permissions = uint32(permissions)

	// Parse type (field 2)
	objType, err := children[2].GetString()
	if err != nil {
		return nil, fmt.Errorf("failed to get type: %w", err)
	}
	obj.Type = objType

	// Parse version (field 3)
	version, err := children[3].GetInt()
	if err != nil {
		return nil, fmt.Errorf("failed to get version: %w", err)
	}
	obj.Version = uint32(version)

	// Parse properties (field 4) - Struct with n_items followed by key-value pairs
	if len(children) >= 5 && children[4].Type == TypeStruct {
		propsChildren, err := children[4].GetStructChildren()
		if err == nil && len(propsChildren) >= 1 {
			// First field is n_items
			// Following fields are key-value pairs
			for i := 1; i+1 < len(propsChildren); i += 2 {
				key, err1 := propsChildren[i].GetString()
				value, err2 := propsChildren[i+1].GetString()
				if err1 == nil && err2 == nil {
					obj.Properties[key] = value
				}
			}
		}
	}

	return obj, nil
}

// ParseCoreError parses a Core::Error event
func ParseCoreError(payload []byte) (uint32, int32, string, error) {
	pod, _, err := DecodePOD(payload)
	if err != nil {
		return 0, 0, "", fmt.Errorf("failed to decode POD: %w", err)
	}

	if pod.Type != TypeStruct {
		return 0, 0, "", fmt.Errorf("expected Struct, got type %d", pod.Type)
	}

	children, err := pod.GetStructChildren()
	if err != nil {
		return 0, 0, "", fmt.Errorf("failed to get struct children: %w", err)
	}

	if len(children) < 3 {
		return 0, 0, "", fmt.Errorf("expected at least 3 fields, got %d", len(children))
	}

	// Parse id (field 0)
	id, err := children[0].GetInt()
	if err != nil {
		return 0, 0, "", fmt.Errorf("failed to get id: %w", err)
	}

	// Parse seq (field 1) - not used, skip

	// Parse res/error code (field 2)
	res, err := children[2].GetInt()
	if err != nil {
		return 0, 0, "", fmt.Errorf("failed to get res: %w", err)
	}

	// Parse message (field 3)
	var message string
	if len(children) >= 4 {
		message, _ = children[3].GetString()
	}

	return uint32(id), res, message, nil
}

// ParseCoreDone parses a Core::Done event
func ParseCoreDone(payload []byte) (uint32, uint32, error) {
	pod, _, err := DecodePOD(payload)
	if err != nil {
		return 0, 0, fmt.Errorf("failed to decode POD: %w", err)
	}

	if pod.Type != TypeStruct {
		return 0, 0, fmt.Errorf("expected Struct, got type %d", pod.Type)
	}

	children, err := pod.GetStructChildren()
	if err != nil {
		return 0, 0, fmt.Errorf("failed to get struct children: %w", err)
	}

	if len(children) < 2 {
		return 0, 0, fmt.Errorf("expected at least 2 fields, got %d", len(children))
	}

	// Parse id (field 0)
	id, err := children[0].GetInt()
	if err != nil {
		return 0, 0, fmt.Errorf("failed to get id: %w", err)
	}

	// Parse seq (field 1)
	seq, err := children[1].GetInt()
	if err != nil {
		return 0, 0, fmt.Errorf("failed to get seq: %w", err)
	}

	return uint32(id), uint32(seq), nil
}

// DeviceInfo represents Device::Info event data
type DeviceInfo struct {
	ID         uint32
	ChangeMask uint64
	Properties map[string]string
}

// ParseDeviceInfo parses a Device::Info event
func ParseDeviceInfo(payload []byte) (*DeviceInfo, error) {
	pod, _, err := DecodePOD(payload)
	if err != nil {
		return nil, fmt.Errorf("failed to decode POD: %w", err)
	}

	if pod.Type != TypeStruct {
		return nil, fmt.Errorf("expected Struct, got type %d", pod.Type)
	}

	children, err := pod.GetStructChildren()
	if err != nil {
		return nil, fmt.Errorf("failed to get struct children: %w", err)
	}

	if len(children) < 2 {
		return nil, fmt.Errorf("expected at least 2 fields, got %d", len(children))
	}

	info := &DeviceInfo{
		Properties: make(map[string]string),
	}

	// Parse id (field 0)
	id, err := children[0].GetInt()
	if err != nil {
		return nil, fmt.Errorf("failed to get id: %w", err)
	}
	info.ID = uint32(id)

	// Parse change_mask (field 1) - Long type
	changeMask, err := children[1].GetLong()
	if err != nil {
		return nil, fmt.Errorf("failed to get change_mask: %w", err)
	}
	info.ChangeMask = uint64(changeMask)

	// Parse properties (field 2) - Struct with n_items followed by key-value pairs
	if len(children) >= 3 && children[2].Type == TypeStruct {
		propsChildren, err := children[2].GetStructChildren()
		if err == nil && len(propsChildren) >= 1 {
			// First field is n_items
			// Following fields are key-value pairs
			for i := 1; i+1 < len(propsChildren); i += 2 {
				key, err1 := propsChildren[i].GetString()
				value, err2 := propsChildren[i+1].GetString()
				if err1 == nil && err2 == nil {
					info.Properties[key] = value
				}
			}
		}
	}

	return info, nil
}

// Removed async Connection/PendingRequest complexity - using simple synchronous approach

// ConnectToPipeWire connects to the PipeWire socket and returns the file descriptor
func ConnectToPipeWire() (int, error) {
	// Try to find the socket
	runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
	if runtimeDir == "" {
		runtimeDir = os.Getenv("PIPEWIRE_RUNTIME_DIR")
	}
	if runtimeDir == "" {
		return -1, fmt.Errorf("neither XDG_RUNTIME_DIR nor PIPEWIRE_RUNTIME_DIR is set")
	}

	socketPath := filepath.Join(runtimeDir, "pipewire-0")

	fmt.Printf("Connecting to PipeWire socket: %s\n", socketPath)

	// Create socket with SOCK_CLOEXEC (blocking for simpler code)
	fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0)
	if err != nil {
		return -1, fmt.Errorf("failed to create socket: %w", err)
	}

	// Connect to the socket
	addr := &syscall.SockaddrUnix{Name: socketPath}
	err = syscall.Connect(fd, addr)
	if err != nil {
		syscall.Close(fd)
		return -1, fmt.Errorf("failed to connect to socket: %w", err)
	}

	return fd, nil
}

func main() {
	// Check for subcommands
	if len(os.Args) >= 2 && os.Args[1] == "trace" {
		if err := TraceCommand(os.Args[2:]); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	fmt.Println("PipeWire Device Lister")
	fmt.Println("======================")

	// Connect to PipeWire
	fd, err := ConnectToPipeWire()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
	defer syscall.Close(fd)

	fmt.Println("Connected successfully!")

	var headerSeq uint32 = 0 // Track message sequence
	const registryID uint32 = 1
	const clientID uint32 = 1 // Client will be assigned ID 1

	// Track next available client-side proxy ID
	// Start at 2 (0=core, 1=registry, client uses separate ID space)
	nextProxyID := uint32(2)

	// Send Core::Hello
	fmt.Println("\nSending Core::Hello (version=3)...")
	err = SendCoreHello(fd, headerSeq)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error sending hello: %v\n", err)
		os.Exit(1)
	}
	headerSeq++

	// Send Client::UpdateProperties with minimal properties
	fmt.Println("Sending Client::UpdateProperties...")
	props := map[string]string{
		"application.name":           "pw-sesh",
		"application.process.binary": "pw-sesh",
	}
	err = SendClientUpdateProperties(fd, clientID, headerSeq, props)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error sending UpdateProperties: %v\n", err)
		os.Exit(1)
	}
	headerSeq++

	// Send Core::GetRegistry
	fmt.Printf("Sending Core::GetRegistry (new_id=%d)...\n", registryID)
	err = SendCoreGetRegistry(fd, headerSeq, registryID)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error sending GetRegistry: %v\n", err)
		os.Exit(1)
	}
	headerSeq++

	// Send Core::Sync
	syncSeq := uint32(12345) // Arbitrary sync sequence number
	fmt.Printf("Sending Core::Sync (seq=%d)...\n", syncSeq)
	err = SendCoreSync(fd, 0, syncSeq)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error sending sync: %v\n", err)
		os.Exit(1)
	}
	headerSeq++

	// Read messages until we get Core::Done with our syncSeq
	fmt.Println("\nWaiting for registry globals...")
	allMessages := make([]*Message, 0)

	for {
		messages, err := ReceiveMessages(fd)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error receiving messages: %v\n", err)
			os.Exit(1)
		}

		for _, msg := range messages {
			allMessages = append(allMessages, msg)

			// Check if this is Core::Done with our sync seq
			if msg.Header.ID == 0 && msg.Header.Opcode == 1 {
				_, doneSeq, err := ParseCoreDone(msg.Payload)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Error parsing Core::Done: %v\n", err)
					continue
				}
				if doneSeq == syncSeq {
					// Done! We've received all registry globals
					goto done
				}
			}
		}
	}
done:

	fmt.Printf("\nāœ“ Received %d total messages\n", len(allMessages))

	// Parse globals from messages
	globals := make(map[uint32]*GlobalObject)
	for _, msg := range allMessages {
		if msg.Header.ID == registryID {
			if msg.Header.Opcode == 0 {
				// Registry::Global event
				obj, err := ParseRegistryGlobal(msg.Payload)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Error parsing Registry::Global: %v\n", err)
					continue
				}
				globals[obj.ID] = obj
			} else if msg.Header.Opcode == 1 {
				// Registry::GlobalRemove event
				id, err := ParseRegistryGlobalRemove(msg.Payload)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Error parsing Registry::GlobalRemove: %v\n", err)
					continue
				}
				// Remove from our map
				delete(globals, id)
				fmt.Printf("  (Global ID %d was removed)\n", id)
			}
		}
	}

	// Filter and display devices
	fmt.Println("\n======================")
	fmt.Printf("Found %d global objects\n", len(globals))
	fmt.Println("======================")

	devices := make([]*GlobalObject, 0)
	for _, obj := range globals {
		if obj.Type == "PipeWire:Interface:Device" {
			devices = append(devices, obj)
		}
	}

	fmt.Printf("\nDevices (%d):\n", len(devices))
	fmt.Println("-------------")
	for _, dev := range devices {
		fmt.Printf("\nDevice ID %d:\n", dev.ID)
		fmt.Printf("  Type: %s\n", dev.Type)
		fmt.Printf("  Version: %d\n", dev.Version)

		// Show interesting properties
		if name, ok := dev.Properties["device.description"]; ok {
			fmt.Printf("  Description: %s\n", name)
		}
		if name, ok := dev.Properties["device.name"]; ok {
			fmt.Printf("  Name: %s\n", name)
		}
		if api, ok := dev.Properties["device.api"]; ok {
			fmt.Printf("  API: %s\n", api)
		}
		if class, ok := dev.Properties["media.class"]; ok {
			fmt.Printf("  Class: %s\n", class)
		}
	}

	fmt.Println("\nāœ“ Successfully listed all devices!")

	// Skip BlueZ monitor for now - focus on ALSA
	// Now create an ALSA monitor to see real audio devices
	fmt.Println("\n======================")
	fmt.Println("Creating ALSA Monitor")
	fmt.Println("======================")

	alsaMonitorID := nextProxyID
	nextProxyID++

	alsaProps := map[string]string{
		"factory.name": "api.alsa.enum.udev",
	}

	fmt.Printf("\nSending Core::CreateObject for ALSA monitor (ID=%d)...\n", alsaMonitorID)
	err = SendCoreCreateObject(fd, headerSeq, "spa-device-factory", "PipeWire:Interface:Device", 3, alsaProps, alsaMonitorID)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error creating ALSA monitor: %v\n", err)
		os.Exit(1)
	}
	headerSeq++

	// Read ALSA monitor creation response and keep reading for a bit
	fmt.Println("\nWaiting for ALSA monitor creation and device discovery...")

	// Set socket to non-blocking for subsequent reads
	err = syscall.SetNonblock(fd, true)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error setting non-blocking: %v\n", err)
		os.Exit(1)
	}

	// Keep reading messages with a poll timeout - wait longer for nodes to appear
	allDeviceMessages := make([]*Message, 0)
	timeoutCount := 0
	for i := range 30 { // Try up to 30 poll cycles
		// Poll with 1000ms timeout
		pollFds := []unix.PollFd{
			{Fd: int32(fd), Events: unix.POLLIN},
		}
		n, err := unix.Poll(pollFds, 1000) // 1000ms timeout
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error polling: %v\n", err)
			break
		}

		if n == 0 {
			// Timeout - no more messages
			timeoutCount++
			fmt.Printf("  Poll timeout %d/3...\n", timeoutCount)
			if timeoutCount >= 3 {
				// After 3 consecutive timeouts (3s of inactivity), assume we're done
				fmt.Printf("Poll timeout after %d batches (no activity for 3s)\n", i-2)
				break
			}
			continue
		}

		timeoutCount = 0 // Reset on successful read

		// Data available, read it
		messages, err := ReceiveMessages(fd)
		if err != nil {
			// EAGAIN is expected with non-blocking socket
			if err.Error() == "failed to recvmsg: resource temporarily unavailable" {
				break
			}
			fmt.Fprintf(os.Stderr, "Error receiving response: %v\n", err)
			break
		}

		allDeviceMessages = append(allDeviceMessages, messages...)
		fmt.Printf("Batch %d: Received %d messages\n", i+1, len(messages))
	}

	fmt.Printf("\nTotal messages received: %d\n", len(allDeviceMessages))

	// Collect discovered objects
	discoveredDevices := make([]*GlobalObject, 0)
	discoveredNodes := make([]*GlobalObject, 0)

	fmt.Println("\nAll messages received:")
	for i, msg := range allDeviceMessages {
		fmt.Printf("%d. ID=%d, Opcode=%d, Size=%d\n", i+1, msg.Header.ID, msg.Header.Opcode, msg.Header.Size)
		if msg.Header.ID == registryID {
			if msg.Header.Opcode == 0 {
				obj, _ := ParseRegistryGlobal(msg.Payload)
				if obj != nil {
					fmt.Printf("   -> Registry::Global: %s (global_id=%d)\n", obj.Type, obj.ID)
				}
			} else if msg.Header.Opcode == 1 {
				id, _ := ParseRegistryGlobalRemove(msg.Payload)
				fmt.Printf("   -> Registry::GlobalRemove: global_id=%d\n", id)
			}
		} else if msg.Header.ID == alsaMonitorID {
			fmt.Printf("   -> Message for ALSA monitor proxy\n")
		} else if msg.Header.ID == 0 {
			if msg.Header.Opcode == 3 {
				id, code, errMsg, _ := ParseCoreError(msg.Payload)
				fmt.Printf("   -> Core::Error for object %d: code=%d, msg=%q\n", id, code, errMsg)
			} else if msg.Header.Opcode == 5 {
				fmt.Printf("   -> Core::BoundId\n")
			}
		}
	}

	fmt.Println("\nDiscovered objects:")
	for _, msg := range allDeviceMessages {
		if msg.Header.ID == registryID {
			if msg.Header.Opcode == 0 {
				// Registry::Global
				obj, err := ParseRegistryGlobal(msg.Payload)
				if err != nil {
					continue
				}

				// Collect audio devices
				if obj.Type == "PipeWire:Interface:Device" && obj.Properties["device.api"] == "alsa:pcm" {
					discoveredDevices = append(discoveredDevices, obj)
					fmt.Printf("  Device ID=%d: %s (media.class=%s)\n",
						obj.ID, obj.Properties["object.path"], obj.Properties["media.class"])
				}

				// Collect nodes
				if obj.Type == "PipeWire:Interface:Node" {
					discoveredNodes = append(discoveredNodes, obj)
					fmt.Printf("  Node ID=%d: %s (%s)\n",
						obj.ID, obj.Properties["node.name"], obj.Properties["media.class"])
				}
			}
		}
	}

	if len(discoveredDevices) == 0 {
		fmt.Println("No audio devices discovered!")
	}

	if len(discoveredNodes) > 0 {
		fmt.Printf("\nFound %d nodes!\n", len(discoveredNodes))
		fmt.Println("\nāœ“ Devices are creating nodes automatically!")
		fmt.Println("\nāœ“ Done!")
		return
	}

	if len(discoveredDevices) > 0 {
		fmt.Println("\nNo nodes appeared yet - let's try binding to a device")

		// Bind to the first device
		fmt.Println("\n======================")
		fmt.Println("Binding to First Device")
		fmt.Println("======================")

		firstDevice := discoveredDevices[0]
		deviceProxyID := nextProxyID
		nextProxyID++

		fmt.Printf("\nBinding to device global_id=%d (%s) with proxy_id=%d...\n",
			firstDevice.ID, firstDevice.Properties["object.path"], deviceProxyID)
		err = SendRegistryBind(fd, registryID, headerSeq, firstDevice.ID, "PipeWire:Interface:Device", 3, deviceProxyID)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error binding to device: %v\n", err)
			os.Exit(1)
		}
		headerSeq++

		// Read messages after binding
		fmt.Println("\nWaiting for device binding response...")
		timeoutCount = 0
		boundDeviceMessages := make([]*Message, 0)
		for i := range 10 {
			pollFds := []unix.PollFd{
				{Fd: int32(fd), Events: unix.POLLIN},
			}
			n, err := unix.Poll(pollFds, 1000)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error polling: %v\n", err)
				break
			}

			if n == 0 {
				timeoutCount++
				if timeoutCount >= 2 {
					fmt.Printf("Poll timeout after %d batches\n", i-1)
					break
				}
				continue
			}

			timeoutCount = 0
			messages, err := ReceiveMessages(fd)
			if err != nil {
				if err.Error() == "failed to recvmsg: resource temporarily unavailable" {
					break
				}
				fmt.Fprintf(os.Stderr, "Error receiving response: %v\n", err)
				break
			}

			boundDeviceMessages = append(boundDeviceMessages, messages...)
			fmt.Printf("Batch %d: Received %d messages\n", i+1, len(messages))
		}

		fmt.Printf("\nāœ“ Successfully bound to device!\n")

		// Now enumerate available profiles
		fmt.Println("\n======================")
		fmt.Println("Enumerating Device Profiles")
		fmt.Println("======================")

		enumSeq := uint32(54321) // Arbitrary sequence number to match responses
		fmt.Printf("\nSending Device::EnumParams for profiles (seq=%d)...\n", enumSeq)
		err = SendDeviceEnumParams(fd, deviceProxyID, headerSeq, enumSeq, SPA_PARAM_EnumProfile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error enumerating params: %v\n", err)
			os.Exit(1)
		}
		headerSeq++

		// Read Device::Param responses
		fmt.Println("\nWaiting for profile enumeration...")
		timeoutCount = 0
		paramMessages := make([]*Message, 0)
		for i := range 10 {
			pollFds := []unix.PollFd{
				{Fd: int32(fd), Events: unix.POLLIN},
			}
			n, err := unix.Poll(pollFds, 1000)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error polling: %v\n", err)
				break
			}

			if n == 0 {
				timeoutCount++
				if timeoutCount >= 2 {
					fmt.Printf("Poll timeout after %d batches\n", i-1)
					break
				}
				continue
			}

			timeoutCount = 0
			messages, err := ReceiveMessages(fd)
			if err != nil {
				if err.Error() == "failed to recvmsg: resource temporarily unavailable" {
					break
				}
				fmt.Fprintf(os.Stderr, "Error receiving response: %v\n", err)
				break
			}

			paramMessages = append(paramMessages, messages...)
			fmt.Printf("Batch %d: Received %d messages\n", i+1, len(messages))
		}

		fmt.Printf("\nReceived %d profile messages:\n", len(paramMessages))
		for i, msg := range paramMessages {
			if msg.Header.ID == deviceProxyID && msg.Header.Opcode == 1 {
				// Device::Param - contains profile data
				pod, _, err := DecodePOD(msg.Payload)
				if err != nil {
					continue
				}

				children, _ := pod.GetStructChildren()
				if len(children) >= 5 {
					profilePod := children[4]
					fmt.Printf("\nProfile %d:\n", i+1)
					fmt.Println(profilePod.PrettyPrint(2))
				}
			}
		}

		// Now set the "on" profile (index 1)
		fmt.Println("\n======================")
		fmt.Println("Setting Profile to 'on'")
		fmt.Println("======================")

		// Create a Profile parameter object with index=1
		// Object format: Object(type=262151, id=8) with key=1 (SPA_PARAM_PROFILE_index) => Int(1)
		// We need to create: Object with properties
		// For simplicity, let's just create an Object with index property

		// Build the profile parameter POD
		// Object structure: [object_type:4][object_id:4][key:4][flags:4][value_pod]
		profileData := make([]byte, 0)

		// object_type (262151 = ParamProfile type)
		objType := make([]byte, 4)
		binary.LittleEndian.PutUint32(objType, 262151)
		profileData = append(profileData, objType...)

		// object_id (8 = Profile)
		objID := make([]byte, 4)
		binary.LittleEndian.PutUint32(objID, 8)
		profileData = append(profileData, objID...)

		// Property: key=1 (index), flags=0, value=Int(1)
		key := make([]byte, 4)
		binary.LittleEndian.PutUint32(key, 1) // SPA_PARAM_PROFILE_index
		profileData = append(profileData, key...)

		flags := make([]byte, 4)
		binary.LittleEndian.PutUint32(flags, 0)
		profileData = append(profileData, flags...)

		// Value: Int(1) for "on" profile
		indexPod := NewInt(1)
		profileData = append(profileData, indexPod.Encode()...)

		// Pad to 8-byte alignment
		for len(profileData)%8 != 0 {
			profileData = append(profileData, 0)
		}

		// Create the Object POD
		profilePod := &POD{
			Size: uint32(len(profileData)),
			Type: TypeObject,
			Data: profileData,
		}

		fmt.Printf("\nSending Device::SetParam with profile:\n")
		fmt.Println(profilePod.PrettyPrint(2))

		err = SendDeviceSetParam(fd, deviceProxyID, headerSeq, SPA_PARAM_Profile, profilePod)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error setting profile: %v\n", err)
			os.Exit(1)
		}
		headerSeq++

		// Read messages to see if nodes get created
		fmt.Println("\nWaiting for nodes to be created...")
		timeoutCount = 0
		nodeMessages := make([]*Message, 0)
		for i := range 20 {
			pollFds := []unix.PollFd{
				{Fd: int32(fd), Events: unix.POLLIN},
			}
			n, err := unix.Poll(pollFds, 1000)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error polling: %v\n", err)
				break
			}

			if n == 0 {
				timeoutCount++
				if timeoutCount >= 3 {
					fmt.Printf("Poll timeout after %d batches\n", i-2)
					break
				}
				continue
			}

			timeoutCount = 0
			messages, err := ReceiveMessages(fd)
			if err != nil {
				if err.Error() == "failed to recvmsg: resource temporarily unavailable" {
					break
				}
				fmt.Fprintf(os.Stderr, "Error receiving response: %v\n", err)
				break
			}

			nodeMessages = append(nodeMessages, messages...)
			fmt.Printf("Batch %d: Received %d messages\n", i+1, len(messages))
		}

		fmt.Printf("\nReceived %d messages after setting profile:\n", len(nodeMessages))
		createdNodes := make([]*GlobalObject, 0)
		for _, msg := range nodeMessages {
			if msg.Header.ID == registryID && msg.Header.Opcode == 0 {
				// Registry::Global - check for nodes
				obj, err := ParseRegistryGlobal(msg.Payload)
				if err == nil && obj.Type == "PipeWire:Interface:Node" {
					createdNodes = append(createdNodes, obj)
					fmt.Printf("\nāœ“ Node created! Global ID: %d\n", obj.ID)
					if nodeName, ok := obj.Properties["node.name"]; ok {
						fmt.Printf("  node.name: %s\n", nodeName)
					}
					if mediaClass, ok := obj.Properties["media.class"]; ok {
						fmt.Printf("  media.class: %s\n", mediaClass)
					}
				}
			}
		}

		if len(createdNodes) > 0 {
			fmt.Printf("\nšŸŽ‰ SUCCESS! Created %d audio nodes!\n", len(createdNodes))

			// Now bind to the first node to get full details
			fmt.Println("\n======================")
			fmt.Println("Binding to First Node")
			fmt.Println("======================")

			firstNode := createdNodes[0]
			nodeProxyID := nextProxyID
			nextProxyID++

			fmt.Printf("\nBinding to node global_id=%d (%s) with proxy_id=%d...\n",
				firstNode.ID, firstNode.Properties["node.name"], nodeProxyID)
			err = SendRegistryBind(fd, registryID, headerSeq, firstNode.ID, "PipeWire:Interface:Node", 3, nodeProxyID)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error binding to node: %v\n", err)
				os.Exit(1)
			}
			headerSeq++

			// Read node info
			fmt.Println("\nWaiting for node info...")
			timeoutCount = 0
			nodeInfoMessages := make([]*Message, 0)
			for i := range 10 {
				pollFds := []unix.PollFd{
					{Fd: int32(fd), Events: unix.POLLIN},
				}
				n, err := unix.Poll(pollFds, 1000)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Error polling: %v\n", err)
					break
				}

				if n == 0 {
					timeoutCount++
					if timeoutCount >= 2 {
						fmt.Printf("Poll timeout after %d batches\n", i-1)
						break
					}
					continue
				}

				timeoutCount = 0
				messages, err := ReceiveMessages(fd)
				if err != nil {
					if err.Error() == "failed to recvmsg: resource temporarily unavailable" {
						break
					}
					fmt.Fprintf(os.Stderr, "Error receiving response: %v\n", err)
					break
				}

				nodeInfoMessages = append(nodeInfoMessages, messages...)
				fmt.Printf("Batch %d: Received %d messages\n", i+1, len(messages))
			}

			fmt.Printf("\n======================")
			fmt.Printf("\nNode Information")
			fmt.Printf("\n======================\n")

			for _, msg := range nodeInfoMessages {
				if msg.Header.ID == 0 && msg.Header.Opcode == 5 {
					fmt.Println("\nāœ“ Core::BoundId (binding confirmed)")
				} else if msg.Header.ID == nodeProxyID && msg.Header.Opcode == 0 {
					// Node::Info - parse the structure
					pod, _, err := DecodePOD(msg.Payload)
					if err != nil {
						fmt.Printf("Failed to decode: %v\n", err)
						continue
					}

					children, err := pod.GetStructChildren()
					if err != nil || len(children) < 9 {
						fmt.Printf("Failed to parse node info struct\n")
						continue
					}

					// Node::Info structure:
					// [0]: id (Int)
					// [1]: max_input_ports (Int)
					// [2]: max_output_ports (Int)
					// [3]: change_mask (Long)
					// [4]: n_input_ports (Int)
					// [5]: n_output_ports (Int)
					// [6]: state (Id)
					// [7]: error (String or None)
					// [8]: props (Struct with key-value pairs)
					// [9]: param_info (Struct)

					nodeID, _ := children[0].GetInt()
					maxInput, _ := children[1].GetInt()
					maxOutput, _ := children[2].GetInt()
					changeMask, _ := children[3].GetLong()
					nInput, _ := children[4].GetInt()
					nOutput, _ := children[5].GetInt()

					fmt.Println("\nāœ“ Node::Info received!")
					fmt.Printf("\n  Node ID: %d\n", nodeID)
					fmt.Printf("  Ports: %d input (max %d), %d output (max %d)\n",
						nInput, maxInput, nOutput, maxOutput)
					fmt.Printf("  Change Mask: 0x%x\n", changeMask)

					// Parse properties (field 8)
					if len(children) > 8 && children[8].Type == TypeStruct {
						propChildren, err := children[8].GetStructChildren()
						if err == nil && len(propChildren) > 0 {
							// First field is n_items
							nItems, _ := propChildren[0].GetInt()
							fmt.Printf("\n  Properties (%d items):\n", nItems)

							// Following fields are key-value pairs
							for i := 1; i+1 < len(propChildren); i += 2 {
								key, err1 := propChildren[i].GetString()
								value, err2 := propChildren[i+1].GetString()
								if err1 == nil && err2 == nil {
									// Only show interesting properties
									if key == "node.name" || key == "node.description" ||
										key == "media.class" || key == "device.id" ||
										key == "api.alsa.pcm.name" || key == "api.alsa.path" ||
										key == "object.path" || key == "object.id" {
										fmt.Printf("    %-20s = %s\n", key, value)
									}
								}
							}

							fmt.Println("\n  All properties:")
							for i := 1; i+1 < len(propChildren); i += 2 {
								key, err1 := propChildren[i].GetString()
								value, err2 := propChildren[i+1].GetString()
								if err1 == nil && err2 == nil {
									fmt.Printf("    %-30s = %s\n", key, value)
								}
							}
						}
					}

					// Parse param_info (field 9) - shows what parameters this node supports
					if len(children) > 9 && children[9].Type == TypeStruct {
						paramChildren, err := children[9].GetStructChildren()
						if err == nil && len(paramChildren) > 1 {
							nParams, _ := paramChildren[0].GetInt()
							fmt.Printf("\n  Supported Parameters (%d):\n", nParams)

							// param_info is: Int: n_items, (Id: param_id, Int: flags)*
							for i := 1; i+1 < len(paramChildren); i += 2 {
								// param_id is an Id type
								if len(paramChildren[i].Data) >= 4 {
									paramID := binary.LittleEndian.Uint32(paramChildren[i].Data[0:4])
									flags, _ := paramChildren[i+1].GetInt()

									paramName := "Unknown"
									switch paramID {
									case SPA_PARAM_EnumFormat:
										paramName = "EnumFormat"
									case SPA_PARAM_Format:
										paramName = "Format"
									case SPA_PARAM_Props:
										paramName = "Props"
									case SPA_PARAM_EnumProfile:
										paramName = "EnumProfile"
									case SPA_PARAM_Profile:
										paramName = "Profile"
									case SPA_PARAM_Latency:
										paramName = "Latency"
									}

									fmt.Printf("    [%d] %s (flags=0x%x)\n", paramID, paramName, flags)
								}
							}
						}
					}
				}
			}
		} else {
			fmt.Println("\n⚠ No nodes were created")
		}

		// Keep the connection alive so devices/nodes persist
		fmt.Println("\n======================")
		fmt.Println("Session Manager Running")
		fmt.Println("======================")
		fmt.Println("\nPress Ctrl+C to exit and cleanup devices...")
		fmt.Println("Or put this process in the background with Ctrl+Z, then 'bg'")

		// Keep reading messages in case of events
		for {
			pollFds := []unix.PollFd{
				{Fd: int32(fd), Events: unix.POLLIN},
			}
			n, err := unix.Poll(pollFds, 5000) // 5 second timeout
			if err != nil {
				fmt.Fprintf(os.Stderr, "\nError polling: %v\n", err)
				break
			}

			if n > 0 {
				messages, err := ReceiveMessages(fd)
				if err != nil {
					fmt.Fprintf(os.Stderr, "\nError receiving: %v\n", err)
					break
				}

				// Print any interesting events
				for _, msg := range messages {
					if msg.Header.ID == registryID {
						if msg.Header.Opcode == 0 {
							obj, _ := ParseRegistryGlobal(msg.Payload)
							if obj != nil {
								fmt.Printf("[Event] New global: %s (ID=%d)\n", obj.Type, obj.ID)
							}
						} else if msg.Header.Opcode == 1 {
							id, _ := ParseRegistryGlobalRemove(msg.Payload)
							fmt.Printf("[Event] Global removed: ID=%d\n", id)
						}
					}
				}
			}
		}
	} else {
		fmt.Println("\nNo devices discovered to bind to")
	}

	fmt.Println("\nāœ“ Done!")
}