-
-
Notifications
You must be signed in to change notification settings - Fork 786
Expand file tree
/
Copy pathpipewire_service.cpp
More file actions
2303 lines (2035 loc) · 76.1 KB
/
Copy pathpipewire_service.cpp
File metadata and controls
2303 lines (2035 loc) · 76.1 KB
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
#include "pipewire/pipewire_service.h"
#include "config/config_service.h"
#include "core/log.h"
#include "ipc/ipc_arg_parse.h"
#include "ipc/ipc_service.h"
#include "pipewire/audio_route_selection.h"
#include "pipewire/wireplumber_mixer.h"
#include "util/string_utils.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <charconv>
#include <chrono>
#include <cmath>
#include <concepts>
#include <cstring>
#include <memory>
#include <optional>
#include <pipewire/device.h>
#include <pipewire/extensions/metadata.h>
#include <pipewire/keys.h>
#include <pipewire/pipewire.h>
#include <ranges>
#include <spa/param/param.h>
#include <spa/param/props.h>
#include <spa/param/route.h>
#include <spa/pod/builder.h>
#include <spa/pod/iter.h>
#include <spa/pod/parser.h>
#include <spa/utils/defs.h>
#include <spa/utils/result.h>
#include <spa/utils/type.h>
#include <string>
#include <string_view>
#include <tuple>
namespace {
// Volume change thresholds.
constexpr auto kVolumeStepDefault = 0.05F;
constexpr auto kVolumeChangeEpsilon = 0.0001F;
// Held-key relative adjustment: accumulate a gesture-local target so async read-back echoes
// can't rubber-band the ramp; a gap past the window or a direction change restarts the gesture.
constexpr auto kVolumeHoldWindow = std::chrono::milliseconds(800);
constexpr auto kVolumeHoldMinIpcInterval = std::chrono::milliseconds(50);
// Write guard: keep optimistic local volume briefly and ignore echoes within epsilon.
constexpr auto kVolumeWriteGuardDuration = std::chrono::milliseconds(400);
constexpr auto kVolumeWriteGuardEpsilon = 0.02F;
// Registry events.
void onRegistryGlobal(
void* data, std::uint32_t id, std::uint32_t, const char* type, std::uint32_t version, const spa_dict* props
) {
auto* svc = static_cast<PipeWireService*>(data);
svc->onRegistryGlobal(id, type, version, props);
}
void onRegistryGlobalRemove(void* data, std::uint32_t id) {
auto* svc = static_cast<PipeWireService*>(data);
svc->onRegistryGlobalRemove(id);
}
const pw_registry_events kRegistryEvents = {
.version = PW_VERSION_REGISTRY_EVENTS,
.global = onRegistryGlobal,
.global_remove = onRegistryGlobalRemove,
};
void onClientInfo(void* data, const pw_client_info* info) {
auto* client = static_cast<PipeWireService::ClientData*>(data);
client->service->onClientInfo(client->id, info);
}
const pw_client_events kClientEvents = {
.version = PW_VERSION_CLIENT_EVENTS,
.info = onClientInfo,
.permissions = nullptr,
};
// Device events
void onDeviceInfo(void* data, const pw_device_info* info) {
auto* dev = static_cast<PipeWireService::DeviceData*>(data);
dev->service->onDeviceInfo(dev->id, info);
}
void onDeviceParam(void* data, int, std::uint32_t id, std::uint32_t index, std::uint32_t next, const spa_pod* param) {
auto* dev = static_cast<PipeWireService::DeviceData*>(data);
dev->service->onDeviceParam(dev->id, id, index, next, param);
}
const pw_device_events kDeviceEvents = {
.version = PW_VERSION_DEVICE_EVENTS,
.info = onDeviceInfo,
.param = onDeviceParam,
};
// Node events.
void onNodeInfo(void* data, const pw_node_info* info) {
auto* nd = static_cast<PipeWireService::NodeData*>(data);
nd->service->onNodeInfo(nd->id, info);
}
void onNodeParam(void* data, int, std::uint32_t id, std::uint32_t index, std::uint32_t next, const spa_pod* param) {
auto* nd = static_cast<PipeWireService::NodeData*>(data);
nd->service->onNodeParam(nd->id, id, index, next, param);
}
const pw_node_events kNodeEvents = {
.version = PW_VERSION_NODE_EVENTS,
.info = onNodeInfo,
.param = onNodeParam,
};
// default.audio.{sink,source} values are often JSON {"name":"…"} but may be a plain node.name string.
std::string extractDefaultMetadataNodeName(std::string_view val) {
constexpr std::string_view kNameKey = "\"name\"";
const auto namePos = val.find(kNameKey);
if (namePos != std::string_view::npos) {
const auto colonPos = val.find(':', namePos + kNameKey.size());
if (colonPos != std::string_view::npos) {
std::size_t i = colonPos + 1;
while (i < val.size() && (val[i] == ' ' || val[i] == '\t')) {
++i;
}
if (i < val.size() && val[i] == '"') {
const std::size_t v0 = i + 1;
const auto v1 = val.find('"', v0);
if (v1 != std::string_view::npos && v1 > v0) {
return std::string(val.substr(v0, v1 - v0));
}
}
}
}
std::string_view s = val;
while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\n' || s.front() == '\r')) {
s.remove_prefix(1);
}
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\n' || s.back() == '\r')) {
s.remove_suffix(1);
}
if (s.size() >= 2 && s.front() == '"' && s.back() == '"') {
s = s.substr(1, s.size() - 2);
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) {
s.remove_prefix(1);
}
while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) {
s.remove_suffix(1);
}
}
if (!s.empty()) {
const char c = s.front();
if (c != '{' && c != '[') {
return std::string(s);
}
}
return {};
}
// Default sink/source metadata.
struct MetadataData {
PipeWireService* service = nullptr;
struct pw_metadata* proxy = nullptr;
spa_hook* listener = nullptr;
};
constexpr Logger kLog("pipewire");
// Deprecated per-stream routing key in the "default" metadata; PipeWire ships no PW_KEY_* for it.
constexpr auto kMetadataTargetNodeKey = "target.node";
int onMetadataProperty(void* data, std::uint32_t subject, const char* key, const char*, const char* value) {
if (key == nullptr) {
return 0;
}
auto* md = static_cast<MetadataData*>(data);
if (std::strcmp(key, "default.audio.sink") == 0 || std::strcmp(key, "default.audio.source") == 0) {
if (value == nullptr) {
return 0;
}
const std::string name = extractDefaultMetadataNodeName(std::string_view(value));
if (!name.empty()) {
spa_dict_item items[1];
items[0] = SPA_DICT_ITEM_INIT(key, name.c_str());
spa_dict dict = SPA_DICT_INIT(items, 1);
md->service->parseDefaultNodes(&dict);
}
return 0;
}
if (std::strcmp(key, PW_KEY_TARGET_OBJECT) == 0) {
// value == nullptr means the property was cleared (route reset to default).
md->service->onTargetObjectMetadata(subject, value != nullptr ? std::string(value) : std::string{});
return 0;
}
return 0;
}
const pw_metadata_events kMetadataEvents = {
.version = PW_VERSION_METADATA_EVENTS,
.property = onMetadataProperty,
};
std::string dictGet(const spa_dict* dict, const char* key) {
if (dict == nullptr) {
return {};
}
const char* val = spa_dict_lookup(dict, key);
return val != nullptr ? std::string(val) : std::string{};
}
bool dictHas(const spa_dict* dict, const char* key) {
return dict != nullptr && spa_dict_lookup(dict, key) != nullptr;
}
[[nodiscard]] bool isTruthyPipeWireProp(std::string_view value) { return value == "true" || value == "1"; }
bool applyStreamFilterPropsFromDict(PipeWireService::NodeData& nd, const spa_dict* props, bool mergeOnly) {
if (props == nullptr) {
return false;
}
bool changed = false;
auto updateStringField = [&](std::string& field, const char* key) {
if (mergeOnly && !dictHas(props, key)) {
return;
}
std::string value = dictGet(props, key);
if (field != value) {
field = std::move(value);
changed = true;
}
};
updateStringField(nd.linkGroup, PW_KEY_NODE_LINK_GROUP);
const bool hasTargetObject = dictHas(props, PW_KEY_TARGET_OBJECT);
const bool hasNodeTarget = dictHas(props, "node.target");
if (!mergeOnly || hasTargetObject || hasNodeTarget) {
std::string target = dictGet(props, PW_KEY_TARGET_OBJECT);
if (target.empty()) {
target = dictGet(props, "node.target");
}
if (nd.targetObject != target) {
nd.targetObject = std::move(target);
changed = true;
}
}
if (!mergeOnly || dictHas(props, PW_KEY_NODE_PASSIVE)) {
const bool passive = isTruthyPipeWireProp(dictGet(props, PW_KEY_NODE_PASSIVE));
if (nd.nodePassive != passive) {
nd.nodePassive = passive;
changed = true;
}
}
if (!mergeOnly || dictHas(props, "stream.capture.sink")) {
const bool captureSink = isTruthyPipeWireProp(dictGet(props, "stream.capture.sink"));
if (nd.streamCaptureSink != captureSink) {
nd.streamCaptureSink = captureSink;
changed = true;
}
}
return changed;
}
template <std::integral T> T parseIntegerOr(const std::string& value, T fallback) {
if (value.empty()) {
return fallback;
}
T out = fallback;
const auto* begin = value.data();
const auto* end = value.data() + value.size();
const auto [ptr, ec] = std::from_chars(begin, end, out);
if (ec != std::errc{} || ptr != end) {
return fallback;
}
return out;
}
std::uint32_t parseUint32Or(const std::string& value, std::uint32_t fallback = 0) {
return parseIntegerOr(value, fallback);
}
std::uint64_t parseUint64Or(const std::string& value, std::uint64_t fallback = 0) {
return parseIntegerOr(value, fallback);
}
std::int32_t parseInt32Or(const std::string& value, std::int32_t fallback = kAnyProfileDevice) {
return parseIntegerOr(value, fallback);
}
std::optional<float> parseFloat(const std::string& value) {
if (value.empty()) {
return std::nullopt;
}
return StringUtils::parseDotDecimal<float>(value);
}
std::optional<bool> parseBool(const std::string& value) {
if (value.empty()) {
return std::nullopt;
}
if (value == "1" || value == "true" || value == "yes" || value == "on") {
return true;
}
if (value == "0" || value == "false" || value == "no" || value == "off") {
return false;
}
return std::nullopt;
}
bool applyClientPropsFromDict(PipeWireService::ClientData& client, const spa_dict* props) {
if (props == nullptr) {
return false;
}
bool changed = false;
auto assignIfBetter = [&changed](std::string& field, std::string value) {
if (!value.empty() && field != value) {
field = std::move(value);
changed = true;
}
};
std::string name = dictGet(props, "application.name");
if (name.empty()) {
name = dictGet(props, "client.name");
}
assignIfBetter(client.name, std::move(name));
std::string appId = dictGet(props, "application.id");
if (appId.ends_with(".desktop")) {
appId.erase(appId.size() - std::string_view(".desktop").size());
}
assignIfBetter(client.appId, std::move(appId));
assignIfBetter(client.binary, dictGet(props, "application.process.binary"));
std::string iconName = dictGet(props, "application.icon-name");
if (iconName.empty()) {
iconName = dictGet(props, "node.icon-name");
}
assignIfBetter(client.iconName, std::move(iconName));
return changed;
}
void parseVolumeArrayProp(const spa_pod_prop* prop, float& outVolume, std::uint32_t* outChannelCount = nullptr) {
if (prop == nullptr) {
return;
}
std::uint32_t nVals = 0;
std::uint32_t choiceType = SPA_CHOICE_None;
const spa_pod* inner = spa_pod_get_values(&prop->value, &nVals, &choiceType);
(void)nVals;
(void)choiceType;
if (inner == nullptr) {
return;
}
if (spa_pod_is_array(inner)) {
const auto* arr = reinterpret_cast<const spa_pod_array*>(inner);
const auto n = static_cast<std::uint32_t>(SPA_POD_ARRAY_N_VALUES(arr));
const std::uint32_t elemSize = SPA_POD_ARRAY_VALUE_SIZE(arr);
const std::uint32_t elemType = SPA_POD_ARRAY_VALUE_TYPE(arr);
if (n > 0 && elemType == SPA_TYPE_Float && elemSize == sizeof(float)) {
const auto* samples = static_cast<const float*>(SPA_POD_ARRAY_VALUES(arr));
float maxVol = 0.0F;
for (std::uint32_t i = 0; i < n; ++i) {
const float cubic = samples[i];
const float linear = std::cbrt(std::max(0.0F, cubic));
maxVol = std::max(linear, maxVol);
}
outVolume = maxVol;
if (outChannelCount != nullptr) {
*outChannelCount = n;
}
return;
}
}
float cubic = 0.0F;
if (spa_pod_get_float(inner, &cubic) == 0) {
outVolume = std::cbrt(std::max(0.0F, cubic));
if (outChannelCount != nullptr) {
*outChannelCount = 1;
}
}
}
struct ParsedPropsVolumes {
float channelVol = 1.0F;
float scalarVol = 1.0F;
float softVol = 1.0F;
std::uint32_t channelCount = 0;
bool hasChannel = false;
bool hasScalar = false;
bool hasSoft = false;
};
void parsePropsObjectVolumeFields(const spa_pod* propsPod, ParsedPropsVolumes basis, ParsedPropsVolumes* out) {
*out = basis;
out->hasChannel = false;
out->hasScalar = false;
out->hasSoft = false;
if (propsPod == nullptr) {
return;
}
auto* obj = reinterpret_cast<spa_pod_object*>(const_cast<spa_pod*>(propsPod));
spa_pod_prop* prop = nullptr;
SPA_POD_OBJECT_FOREACH(obj, prop) {
if (prop->key == SPA_PROP_channelVolumes) {
parseVolumeArrayProp(prop, out->channelVol, &out->channelCount);
out->hasChannel = true;
} else if (prop->key == SPA_PROP_volume) {
std::uint32_t nVals = 0;
std::uint32_t choiceType = SPA_CHOICE_None;
const spa_pod* inner = spa_pod_get_values(&prop->value, &nVals, &choiceType);
(void)nVals;
(void)choiceType;
float cubic = 0.0F;
if (inner != nullptr && spa_pod_get_float(inner, &cubic) == 0) {
out->scalarVol = std::cbrt(std::max(0.0F, cubic));
out->hasScalar = true;
}
} else if (prop->key == SPA_PROP_softVolumes) {
parseVolumeArrayProp(prop, out->softVol);
out->hasSoft = true;
}
}
}
void mergeParsedVolumesIntoNode(PipeWireService::NodeData& nd, const ParsedPropsVolumes& p) {
if (p.hasChannel) {
nd.volume = p.channelVol;
nd.channelCount = p.channelCount;
} else if (p.hasScalar) {
nd.volume = p.scalarVol;
} else if (p.hasSoft) {
nd.volume = p.softVol;
}
}
[[nodiscard]] float resolvedVolume(const ParsedPropsVolumes& p) {
if (p.hasChannel) {
return p.channelVol;
}
if (p.hasScalar) {
return p.scalarVol;
}
if (p.hasSoft) {
return p.softVol;
}
return -1.0F;
}
[[nodiscard]] bool shouldRejectVolumeWrite(const PipeWireService::NodeData& nd, float candidateVol) {
if (nd.lastWrittenVolume < 0.0F) {
return false;
}
const auto now = std::chrono::steady_clock::now();
if (now >= nd.volumeWriteGuardUntil) {
return false;
}
return std::abs(candidateVol - nd.lastWrittenVolume) > kVolumeWriteGuardEpsilon;
}
void confirmVolumeWrite(PipeWireService::NodeData& nd, float candidateVol) {
if (nd.lastWrittenVolume < 0.0F) {
return;
}
if (std::abs(candidateVol - nd.lastWrittenVolume) <= kVolumeWriteGuardEpsilon) {
nd.volumeWriteGuardUntil = {};
}
}
bool mergeIncomingVolumes(PipeWireService::NodeData& nd, const ParsedPropsVolumes& p) {
const float candidate = resolvedVolume(p);
if (candidate >= 0.0F && shouldRejectVolumeWrite(nd, candidate)) {
return false;
}
mergeParsedVolumesIntoNode(nd, p);
if (candidate >= 0.0F) {
confirmVolumeWrite(nd, candidate);
}
return true;
}
// Device ParamRoute updates are per-direction; applying every route's volume to all nodes on the same
// device.id merges playback and capture on combo hardware (see activeRouteForDirection).
[[nodiscard]] bool routeVolumeDirectionMatchesNode(std::string_view mediaClass, std::uint32_t routeDirection) {
if (mediaClass == "Audio/Sink") {
return routeDirection == SPA_DIRECTION_OUTPUT;
}
if (mediaClass == "Audio/Source") {
return routeDirection == SPA_DIRECTION_INPUT;
}
return true;
}
void upsertRoute(std::vector<PipeWireService::DeviceRouteData>& routes, PipeWireService::DeviceRouteData route) {
const std::int32_t lookupIndex = route.index >= 0 ? route.index : -1;
if (lookupIndex < 0) {
return;
}
const auto existing = std::ranges::find(routes, lookupIndex, &PipeWireService::DeviceRouteData::index);
if (existing == routes.end()) {
routes.push_back(route);
return;
}
*existing = route;
}
[[nodiscard]] std::uint32_t routeDirectionForMediaClass(std::string_view mediaClass) {
if (mediaClass == "Audio/Source") {
return SPA_DIRECTION_INPUT;
}
if (mediaClass == "Audio/Sink") {
return SPA_DIRECTION_OUTPUT;
}
return 0;
}
constexpr auto kTrackedNodeClasses = std::to_array<std::string_view>({
"Audio/Sink",
"Audio/Source",
"Stream/Output/Audio",
"Stream/Input/Audio",
});
constexpr auto kPrivacyAudioNodeClasses = std::to_array<std::string_view>({
"Stream/Input/Audio",
});
constexpr auto kMicrophoneSourceClasses = std::to_array<std::string_view>({
"Audio/Source",
});
constexpr auto kAudioCaptureConsumerClasses = std::to_array<std::string_view>({
"Stream/Input/Audio",
});
constexpr auto kCameraSourceClasses = std::to_array<std::string_view>({
"Video/Source",
});
constexpr auto kVideoCaptureConsumerClasses = std::to_array<std::string_view>({
"Stream/Input/Video",
});
constexpr auto kScreenShareNamePrefixes = std::to_array<std::string_view>({
"xdpw-stream",
"xdph-streaming",
"gsr-default",
"game capture",
"screen",
"desktop",
"display",
"cast",
"webrtc",
});
constexpr auto kScreenShareExactNames = std::to_array<std::string_view>({
"gsr-default_output",
});
constexpr auto kScreenShareWeakNamePrefixes = std::to_array<std::string_view>({
"v4l2",
});
constexpr auto kScreenShareNameFragments = std::to_array<std::string_view>({
"screen-cast",
"screen-capture",
"desktop-capture",
"monitor-capture",
"window-capture",
"game-capture",
});
bool isProgramStreamClass(std::string_view mediaClass) { return mediaClass == "Stream/Output/Audio"; }
[[nodiscard]] bool isTrackedNodeClass(std::string_view mediaClass) {
return std::ranges::contains(kTrackedNodeClasses, mediaClass) || mediaClass.contains("Video");
}
// PipeWire exposes virtual endpoints (e.g. EasyEffects) with a suffix such
// as `Audio/Sink/Virtual`; collapse them to the base class so downstream
// tracking treats them like normal sinks/sources.
void normalizeAudioMediaClass(std::string& mediaClass) {
if (mediaClass.starts_with("Audio/Sink")) {
mediaClass = "Audio/Sink";
} else if (mediaClass.starts_with("Audio/Source")) {
mediaClass = "Audio/Source";
}
}
[[nodiscard]] bool isPrivacyCandidateClass(std::string_view mediaClass) {
return std::ranges::contains(kPrivacyAudioNodeClasses, mediaClass)
|| (mediaClass.contains("Video") && !mediaClass.contains("Audio"));
}
[[nodiscard]] std::string lowercaseAscii(std::string_view value) {
std::string out(value);
std::ranges::transform(out, out.begin(), [](unsigned char ch) { return static_cast<char>(std::tolower(ch)); });
return out;
}
[[nodiscard]] bool matchesScreenShareName(std::string_view mediaName, bool includeWeakPrefixes) {
if (mediaName.empty()) {
return false;
}
const std::string lower = lowercaseAscii(mediaName);
return std::ranges::any_of(
kScreenShareNamePrefixes, [&lower](std::string_view prefix) { return lower.starts_with(prefix); }
)
|| (includeWeakPrefixes
&& std::ranges::any_of(
kScreenShareWeakNamePrefixes, [&lower](std::string_view prefix) { return lower.starts_with(prefix); }
))
|| std::ranges::contains(kScreenShareExactNames, lower)
|| std::ranges::any_of(kScreenShareNameFragments, [&lower](std::string_view fragment) {
return lower.contains(fragment);
});
}
[[nodiscard]] bool isMicrophoneSource(const PipeWireService::NodeData& nd) {
return std::ranges::contains(kMicrophoneSourceClasses, nd.mediaClass);
}
[[nodiscard]] bool isAudioCaptureConsumer(const PipeWireService::NodeData& nd) {
return std::ranges::contains(kAudioCaptureConsumerClasses, nd.mediaClass) && !nd.streamCaptureSink;
}
[[nodiscard]] bool isCameraSource(const PipeWireService::NodeData& nd) {
return std::ranges::contains(kCameraSourceClasses, nd.mediaClass);
}
[[nodiscard]] bool isVideoCaptureConsumer(const PipeWireService::NodeData& nd) {
return std::ranges::contains(kVideoCaptureConsumerClasses, nd.mediaClass);
}
[[nodiscard]] bool isScreenSource(const PipeWireService::NodeData& nd) {
if (!nd.mediaClass.contains("Video") || nd.mediaClass.contains("Audio")) {
return false;
}
if (matchesScreenShareName(nd.mediaName, true) || matchesScreenShareName(nd.streamTitle, false)) {
return true;
}
if (isCameraSource(nd)) {
return matchesScreenShareName(nd.name, false);
}
return matchesScreenShareName(nd.name, true);
}
[[nodiscard]] std::string privacyAppName(const PipeWireService::NodeData& nd) {
if (!nd.applicationName.empty()) {
return nd.applicationName;
}
if (!nd.streamTitle.empty()) {
return nd.streamTitle;
}
if (!nd.description.empty()) {
return nd.description;
}
return nd.name;
}
[[nodiscard]] std::optional<PrivacyCaptureKind>
classifyPrivacyCapture(const PipeWireService::NodeData& source, const PipeWireService::NodeData& consumer) {
if (isMicrophoneSource(source) && isAudioCaptureConsumer(consumer)) {
return PrivacyCaptureKind::Microphone;
}
if (isScreenSource(source) && isVideoCaptureConsumer(consumer)) {
return PrivacyCaptureKind::Screen;
}
if (isCameraSource(source) && isVideoCaptureConsumer(consumer)) {
return PrivacyCaptureKind::Camera;
}
return std::nullopt;
}
// QEMU's libvirt PipeWire backend (node.name "qemu-system-<arch>") is a program stream that needs
// special handling: it sets target.object and never sets application.name.
[[nodiscard]] bool isQemuStreamNode(const PipeWireService::NodeData& nd) {
return isProgramStreamClass(nd.mediaClass) && nd.name.starts_with("qemu-system-");
}
[[nodiscard]] bool hasProgramStreamIdentity(const PipeWireService::NodeData& nd) {
if (isQemuStreamNode(nd)) {
return true;
}
return !nd.applicationName.empty() || !nd.applicationId.empty() || !nd.applicationBinary.empty();
}
[[nodiscard]] bool isProgramOutputNode(const PipeWireService::NodeData& nd) {
// Match the "Streams" pavucontrol shows: Stream/Output/Audio without node.link-group /
// node.passive (loopback and filter endpoints). Streams that pin a sink via target.object
// (Telegram/OpenAL, etc.) stay visible when they have client/app identity; anonymous
// target.object nodes are still treated as filter plumbing.
if (!isProgramStreamClass(nd.mediaClass) || !nd.streamClassificationReady) {
return false;
}
if (!nd.linkGroup.empty() || nd.nodePassive) {
return false;
}
if (!nd.targetObject.empty() && !hasProgramStreamIdentity(nd)) {
return false;
}
return true;
}
} // namespace
PipeWireService::PipeWireService() {
pw_init(nullptr, nullptr);
m_loop = pw_loop_new(nullptr);
if (m_loop == nullptr) {
throw std::runtime_error("pipewire: failed to create loop");
}
m_context = pw_context_new(m_loop, nullptr, 0);
if (m_context == nullptr) {
pw_loop_destroy(m_loop);
throw std::runtime_error("pipewire: failed to create context");
}
m_core = pw_context_connect(m_context, nullptr, 0);
if (m_core == nullptr) {
pw_context_destroy(m_context);
pw_loop_destroy(m_loop);
throw std::runtime_error("pipewire: failed to connect to daemon");
}
m_registry = pw_core_get_registry(m_core, PW_VERSION_REGISTRY, 0);
if (m_registry == nullptr) {
pw_core_disconnect(m_core);
pw_context_destroy(m_context);
pw_loop_destroy(m_loop);
throw std::runtime_error("pipewire: failed to get registry");
}
m_registryListener = new spa_hook{};
spa_zero(*m_registryListener);
pw_registry_add_listener(m_registry, m_registryListener, &kRegistryEvents, this);
pw_loop_enter(m_loop);
// Do initial roundtrip to discover existing objects
auto* loop = m_loop;
pw_core_sync(m_core, PW_ID_CORE, 0);
while (pw_loop_iterate(loop, 0) > 0) {
}
enumDefaultAudioDeviceParams();
while (pw_loop_iterate(loop, 0) > 0) {
}
rebuildState();
kLog.info("connected (version {})", pw_get_library_version());
const auto* sink = defaultSink();
if (sink != nullptr) {
kLog.info("default sink \"{}\" vol={:.0F}%", sink->description, sink->volume * 100.0F);
}
}
PipeWireService::~PipeWireService() {
// Destroy node proxies and their listeners
for (auto& [id, nd] : m_nodes) {
if (nd->listener != nullptr) {
spa_hook_remove(nd->listener);
delete nd->listener;
}
if (nd->proxy != nullptr) {
pw_proxy_destroy(reinterpret_cast<pw_proxy*>(nd->proxy));
}
}
m_nodes.clear();
for (auto& [id, client] : m_clients) {
if (client.listener != nullptr) {
spa_hook_remove(client.listener);
delete client.listener;
}
if (client.proxy != nullptr) {
pw_proxy_destroy(reinterpret_cast<pw_proxy*>(client.proxy));
}
}
m_clients.clear();
for (auto& [id, device] : m_devices) {
if (device.listener != nullptr) {
spa_hook_remove(device.listener);
delete device.listener;
}
if (device.proxy != nullptr) {
pw_proxy_destroy(reinterpret_cast<pw_proxy*>(device.proxy));
}
}
m_devices.clear();
for (auto& cleanup : m_metadataCleanups) {
cleanup();
}
m_metadataCleanups.clear();
if (m_registryListener != nullptr) {
spa_hook_remove(m_registryListener);
delete m_registryListener;
}
if (m_registry != nullptr) {
pw_proxy_destroy(reinterpret_cast<pw_proxy*>(m_registry));
}
if (m_core != nullptr) {
pw_core_disconnect(m_core);
}
if (m_context != nullptr) {
pw_context_destroy(m_context);
}
if (m_loop != nullptr) {
pw_loop_leave(m_loop);
pw_loop_destroy(m_loop);
}
pw_deinit();
}
int PipeWireService::fd() const noexcept {
if (m_loop == nullptr) {
return -1;
}
auto* loop = m_loop;
return pw_loop_get_fd(loop);
}
void PipeWireService::dispatch() {
if (m_loop == nullptr) {
return;
}
auto* loop = m_loop;
// Process all pending events without blocking
while (pw_loop_iterate(loop, 0) > 0) {
}
if (m_pendingDefaultAudioDevicePropsEnum) {
m_pendingDefaultAudioDevicePropsEnum = false;
enumDefaultAudioDeviceParams();
while (pw_loop_iterate(loop, 0) > 0) {
}
}
}
void PipeWireService::enumDefaultAudioDeviceParams() {
for (auto& [id, nd] : m_nodes) {
(void)id;
if (nd == nullptr || nd->proxy == nullptr) {
continue;
}
if (nd->mediaClass != "Audio/Sink" && nd->mediaClass != "Audio/Source") {
continue;
}
pw_node_enum_params(nd->proxy, 0, SPA_PARAM_Props, 0, UINT32_MAX, nullptr);
pw_node_enum_params(nd->proxy, 0, SPA_PARAM_Route, 0, UINT32_MAX, nullptr);
}
}
const AudioNode* PipeWireService::defaultSink() const noexcept {
for (const auto& sink : m_state.sinks) {
if (sink.isDefault) {
return &sink;
}
}
return nullptr;
}
const AudioNode* PipeWireService::defaultSource() const noexcept {
for (const auto& source : m_state.sources) {
if (source.isDefault) {
return &source;
}
}
return nullptr;
}
std::string audioDeviceLabel(const AudioNode& node) { return !node.description.empty() ? node.description : node.name; }
void PipeWireService::onRegistryGlobal(std::uint32_t id, const char* type, std::uint32_t, const spa_dict* props) {
if (std::strcmp(type, PW_TYPE_INTERFACE_Client) == 0) {
ClientData client;
client.service = this;
client.id = id;
applyClientPropsFromDict(client, props);
auto [it, inserted] = m_clients.insert_or_assign(id, std::move(client));
auto& stored = it->second;
if (inserted) {
auto* proxy = static_cast<pw_client*>(pw_registry_bind(m_registry, id, type, PW_VERSION_CLIENT, sizeof(void*)));
if (proxy != nullptr) {
stored.proxy = proxy;
stored.listener = new spa_hook{};
spa_zero(*stored.listener);
pw_client_add_listener(proxy, stored.listener, &kClientEvents, &stored);
}
}
for (auto& [_, node] : m_nodes) {
if (node != nullptr) {
refreshNodeIdentity(*node);
}
}
// New client metadata can improve already-known stream node identity.
rebuildState();
return;
}
if (std::strcmp(type, PW_TYPE_INTERFACE_Device) == 0) {
DeviceData device;
device.service = this;
device.id = id;
auto [it, inserted] = m_devices.insert_or_assign(id, std::move(device));
auto& stored = it->second;
if (inserted) {
auto* proxy = static_cast<pw_device*>(pw_registry_bind(m_registry, id, type, PW_VERSION_DEVICE, sizeof(void*)));
if (proxy != nullptr) {
stored.proxy = proxy;
stored.listener = new spa_hook{};
spa_zero(*stored.listener);
pw_device_add_listener(proxy, stored.listener, &kDeviceEvents, &stored);
std::uint32_t params[] = {SPA_PARAM_Route};
pw_device_subscribe_params(proxy, params, 1);
pw_device_enum_params(proxy, 0, SPA_PARAM_Route, 0, UINT32_MAX, nullptr);
}
}
return;
}
if (std::strcmp(type, PW_TYPE_INTERFACE_Link) == 0) {
LinkData link;
link.id = id;
link.outputNodeId = parseUint32Or(dictGet(props, PW_KEY_LINK_OUTPUT_NODE));
link.inputNodeId = parseUint32Or(dictGet(props, PW_KEY_LINK_INPUT_NODE));
if (link.outputNodeId != 0 && link.inputNodeId != 0) {
m_links.insert_or_assign(id, link);
rebuildState();
}
return;
}
// Track audio nodes and privacy-relevant stream nodes.
if (std::strcmp(type, PW_TYPE_INTERFACE_Node) == 0) {
std::string mediaClass = dictGet(props, PW_KEY_MEDIA_CLASS);
normalizeAudioMediaClass(mediaClass);
if (!isTrackedNodeClass(mediaClass)) {
return;
}
auto nd = std::make_unique<NodeData>();
nd->service = this;
nd->id = id;
nd->serial = parseUint64Or(dictGet(props, PW_KEY_OBJECT_SERIAL));
nd->name = dictGet(props, PW_KEY_NODE_NAME);
nd->description = dictGet(props, PW_KEY_NODE_DESCRIPTION);
if (nd->description.empty()) {
nd->description = dictGet(props, PW_KEY_NODE_NICK);
}
if (nd->description.empty()) {
nd->description = nd->name;
}
nd->clientId = parseUint32Or(dictGet(props, "client.id"));
nd->deviceId = parseUint32Or(dictGet(props, "device.id"));
nd->profileDevice = parseInt32Or(dictGet(props, "card.profile.device"));
nd->applicationName = dictGet(props, "application.name");
if (nd->applicationName.empty()) {
nd->applicationName = dictGet(props, "client.name");
}
nd->applicationId = dictGet(props, "application.id");
if (nd->applicationId.ends_with(".desktop")) {
nd->applicationId.erase(nd->applicationId.size() - std::string_view(".desktop").size());
}
nd->applicationBinary = dictGet(props, "application.process.binary");
if (nd->applicationName.empty()) {
nd->applicationName = nd->applicationBinary;
}
if (nd->applicationName.empty()) {
nd->applicationName = nd->description;
}