Debian Codegraph @

src/scripts/monitors/bluez.lua

raw
1 -- WirePlumber
2 --
3 -- Copyright © 2021 Collabora Ltd.
4 -- @author George Kiagiadakis <[email protected]>
5 --
6 -- SPDX-License-Identifier: MIT
7
8 COMBINE_OFFSET = 64
9 LOOPBACK_SOURCE_ID = 128
10 DEVICE_SOURCE_ID = 0
11 DEVICE_SINK_ID = 1
12
13 cutils = require ("common-utils")
14 log = Log.open_topic ("s-monitors")
15
16 config = {}
17 config.seat_monitoring = Core.test_feature ("monitor.bluez.seat-monitoring")
18 config.properties = Conf.get_section_as_properties ("monitor.bluez.properties")
19 config.rules = Conf.get_section_as_json ("monitor.bluez.rules", Json.Array {})
20
21 -- This is not a setting, it must always be enabled
22 config.properties["api.bluez5.connection-info"] = true
23
24 devices_om = ObjectManager {
25 Interest {
26 type = "device",
27 Constraint { "device.api", "=", "bluez5" },
28 }
29 }
30
31 nodes_om = ObjectManager {
32 Interest {
33 type = "node",
34 Constraint { "node.name", "#", "*.bluez_*put*"},
35 Constraint { "device.id", "+" },
36 }
37 }
38
39 function setOffloadActive(device, value)
40 local pod = Pod.Object {
41 "Spa:Pod:Object:Param:Props", "Props", bluetoothOffloadActive = value
42 }
43 device:set_params("Props", pod)
44 end
45
46 nodes_om:connect("object-added", function(_, node)
47 node:connect("state-changed", function(node, old_state, cur_state)
48 local interest = Interest {
49 type = "device",
50 Constraint { "object.id", "=", node.properties["device.id"]}
51 }
52 for d in devices_om:iterate (interest) do
53 if cur_state == "running" then
54 setOffloadActive(d, true)
55 else
56 setOffloadActive(d, false)
57 end
58 end
59 end)
60 end)
61
62 function createOffloadScoNode(parent, id, type, factory, properties)
63 local dev_props = parent.properties
64
65 local args = {
66 ["audio.channels"] = 1,
67 ["audio.position"] = "[MONO]",
68 }
69
70 local desc =
71 dev_props["device.description"]
72 or dev_props["device.name"]
73 or dev_props["device.nick"]
74 or dev_props["device.alias"]
75 or "bluetooth-device"
76 -- sanitize description, replace ':' with ' '
77 args["node.description"] = desc:gsub("(:)", " ")
78
79 if factory:find("sink") then
80 local capture_args = {
81 ["device.id"] = parent["bound-id"],
82 ["media.class"] = "Audio/Sink",
83 ["node.pause-on-idle"] = false,
84 }
85 for k, v in pairs(properties) do
86 capture_args[k] = v
87 end
88
89 local name = "bluez_output" .. "." .. (properties["api.bluez5.address"] or dev_props["device.name"]) .. "." .. tostring(id)
90 args["node.name"] = name:gsub("([^%w_%-%.])", "_")
91 args["capture.props"] = Json.Object(capture_args)
92 args["playback.props"] = Json.Object {
93 ["node.passive"] = true,
94 ["node.pause-on-idle"] = false,
95 ["state.restore-props"] = false,
96 }
97 elseif factory:find("source") then
98 local playback_args = {
99 ["device.id"] = parent["bound-id"],
100 ["media.class"] = "Audio/Source",
101 ["node.pause-on-idle"] = false,
102 }
103 for k, v in pairs(properties) do
104 playback_args[k] = v
105 end
106
107 local name = "bluez_input" .. "." .. (properties["api.bluez5.address"] or dev_props["device.name"]) .. "." .. tostring(id)
108 args["node.name"] = name:gsub("([^%w_%-%.])", "_")
109 args["capture.props"] = Json.Object {
110 ["node.passive"] = true,
111 ["node.pause-on-idle"] = false,
112 ["state.restore-props"] = false,
113 }
114 args["playback.props"] = Json.Object(playback_args)
115 else
116 log:warning(parent, "Unsupported factory: " .. factory)
117 return
118 end
119
120 -- Transform 'args' to a json object here
121 local args_json = Json.Object(args)
122
123 -- and get the final JSON as a string from the json object
124 local args_string = args_json:get_data()
125
126 local loopback_properties = {}
127
128 local loopback = LocalModule("libpipewire-module-loopback", args_string, loopback_properties)
129 parent:store_managed_object(id, loopback)
130 end
131
132 device_set_nodes_om = ObjectManager {
133 Interest {
134 type = "node",
135 Constraint { "api.bluez5.set.leader", "+", type = "pw" },
136 }
137 }
138
139 device_set_nodes_om:connect ("object-added", function(_, node)
140 -- Connect ObjectConfig events to the right node
141 if not monitor then
142 return
143 end
144
145 local interest = Interest {
146 type = "device",
147 Constraint { "object.id", "=", node.properties["device.id"] }
148 }
149 log:info("Device set node found: " .. tostring (node["bound-id"]))
150 for device in devices_om:iterate (interest) do
151 local device_id = device.properties["spa.object.id"]
152 if not device_id then
153 goto next_device
154 end
155
156 local spa_device = monitor:get_managed_object (tonumber (device_id))
157 if not spa_device then
158 goto next_device
159 end
160
161 local id = node.properties["card.profile.device"]
162 if id ~= nil then
163 log:info(".. assign to device: " .. tostring (device["bound-id"]) .. " node " .. tostring (id))
164 spa_device:store_managed_object (id, node)
165 end
166
167 ::next_device::
168 end
169 end)
170
171 function createSetNode(parent, id, type, factory, properties)
172 local args = {}
173 local target_class
174 local stream_class
175 local rules = {}
176 local members_json = Json.Raw (properties["api.bluez5.set.members"])
177 local channels_json = Json.Raw (properties["api.bluez5.set.channels"])
178 local members = members_json:parse ()
179 local channels = channels_json:parse ()
180
181 if properties["media.class"] == "Audio/Sink" then
182 args["combine.mode"] = "sink"
183 target_class = "Audio/Sink/Internal"
184 stream_class = "Stream/Output/Audio/Internal"
185 else
186 args["combine.mode"] = "source"
187 target_class = "Audio/Source/Internal"
188 stream_class = "Stream/Input/Audio/Internal"
189 end
190
191 log:info("Device set: " .. properties["node.name"])
192
193 for _, member in pairs(members) do
194 log:info("Device set member:" .. member["object.path"])
195 table.insert(rules,
196 Json.Object {
197 ["matches"] = Json.Array {
198 Json.Object {
199 ["object.path"] = member["object.path"],
200 ["media.class"] = target_class,
201 },
202 },
203 ["actions"] = Json.Object {
204 ["create-stream"] = Json.Object {
205 ["media.class"] = stream_class,
206 ["audio.position"] = Json.Array (member["channels"]),
207 ["state.restore-props"] = false,
208 }
209 },
210 }
211 )
212 end
213
214 local combine_props = properties:parse ()
215 combine_props["node.virtual"] = false
216 combine_props["device.api"] = "bluez5"
217 combine_props["api.bluez5.set.members"] = nil
218 combine_props["api.bluez5.set.channels"] = nil
219 combine_props["api.bluez5.set.leader"] = true
220 combine_props["audio.position"] = Json.Array (channels)
221
222 args["combine.props"] = Json.Object (combine_props)
223 args["stream.props"] = Json.Object {}
224 args["stream.rules"] = Json.Array (rules)
225
226 local args_json = Json.Object(args)
227 local args_string = args_json:get_data()
228 local combine_properties = {}
229 log:info("Device set node: " .. args_string)
230 return LocalModule("libpipewire-module-combine-stream", args_string, combine_properties)
231 end
232
233 function getNodeName (prefix, bt_address, dev_name, node_id)
234 local name = prefix .. "." .. (bt_address or dev_name) .. "." .. tostring(node_id)
235 -- sanitize name
236 return name:gsub("([^%w_%-%.])", "_")
237 end
238
239 function createNode(parent, id, type, factory, properties)
240 local dev_props = parent.properties
241 local parent_id = parent["bound-id"]
242 local parent_spa_id = tonumber(dev_props["spa.object.id"])
243
244 if cutils.parseBool (config.properties ["bluez5.hw-offload-sco"]) and factory:find("sco") then
245 createOffloadScoNode(parent, id, type, factory, properties)
246 return
247 end
248
249 -- set the device id and spa factory name; REQUIRED, do not change
250 properties["device.id"] = parent_id
251 properties["factory.name"] = factory
252 properties["spa.object.id"] = id
253
254 -- set the default pause-on-idle setting
255 properties["node.pause-on-idle"] = false
256
257 -- set the node description
258 local desc =
259 dev_props["device.description"]
260 or dev_props["device.name"]
261 or dev_props["device.nick"]
262 or dev_props["device.alias"]
263 or "bluetooth-device"
264 -- sanitize description, replace ':' with ' '
265 properties["node.description"] = desc:gsub("(:)", " ")
266
267 -- set the node name
268 local name_prefix = ((factory:find("sink") and "bluez_output") or
269 (factory:find("source") and "bluez_input" or factory))
270 properties["node.name"] = getNodeName (name_prefix,
271 properties["api.bluez5.address"], dev_props["device.name"], id)
272
273 -- set priority
274 if not properties["priority.driver"] then
275 local priority = factory:find("source") and 2010 or 1010
276 properties["priority.driver"] = priority
277 properties["priority.session"] = priority
278 end
279
280 -- autoconnect if it's a stream
281 if properties["api.bluez5.profile"] == "headset-audio-gateway" or
282 properties["api.bluez5.profile"] == "bap-sink" or
283 factory:find("a2dp.source") or factory:find("media.source") then
284 properties["node.autoconnect"] = true
285 end
286
287 -- apply properties from the rules in the configuration file
288 properties = JsonUtils.match_rules_update_properties (config.rules, properties)
289
290 -- create the node; bluez requires "local" nodes, i.e. ones that run in
291 -- the same process as the spa device, for several reasons
292
293 if properties["api.bluez5.set.leader"] then
294 local combine = createSetNode(parent, id, type, factory, properties)
295 parent:store_managed_object(id + COMBINE_OFFSET, combine)
296 parent:set_managed_pending(id)
297 else
298 log:info("Create node: " .. properties["node.name"] .. ": " .. factory .. " " .. tostring (id))
299
300 -- Set sink/source specific properties
301 if factory == "api.bluez5.sco.source" or
302 (factory == "api.bluez5.a2dp.source" and cutils.parseBool (properties["api.bluez5.a2dp-duplex"])) then
303 properties["bluez5.loopback"] = false
304 if properties["api.bluez5.profile"] ~= "headset-audio-gateway" then
305 properties["api.bluez5.internal"] = true
306 end
307 end
308
309 local node = LocalNode("adapter", properties)
310 node:activate(Feature.Proxy.BOUND)
311 parent:store_managed_object(id, node)
312 end
313 end
314
315 function removeNode(parent, id)
316 local dev_props = parent.properties
317 local parent_spa_id = tonumber(dev_props["spa.object.id"])
318
319 log:debug("Remove node: " .. tostring (id))
320
321 -- Clear also the device set module, if any
322 parent:store_managed_object(id + COMBINE_OFFSET, nil)
323 end
324
325 function createDevice(parent, id, type, factory, properties)
326 local device = parent:get_managed_object(id)
327 if not device then
328 -- ensure a proper device name
329 local name =
330 (properties["device.name"] or
331 properties["api.bluez5.address"] or
332 properties["device.description"] or
333 tostring(id)):gsub("([^%w_%-%.])", "_")
334
335 if not name:find("^bluez_card%.", 1) then
336 name = "bluez_card." .. name
337 end
338 properties["device.name"] = name
339
340 -- set the icon name
341 if not properties["device.icon-name"] then
342 local icon = nil
343 local icon_map = {
344 -- form factor -> icon
345 ["microphone"] = "audio-input-microphone",
346 ["webcam"] = "camera-web",
347 ["handset"] = "phone",
348 ["portable"] = "multimedia-player",
349 ["tv"] = "video-display",
350 ["headset"] = "audio-headset",
351 ["headphone"] = "audio-headphones",
352 ["speaker"] = "audio-speakers",
353 ["hands-free"] = "audio-handsfree",
354 }
355 local f = properties["device.form-factor"]
356 local b = properties["device.bus"]
357
358 icon = icon_map[f] or "audio-card"
359 properties["device.icon-name"] = icon .. (b and ("-" .. b) or "")
360 end
361
362 -- initial profile is to be set by policy-device-profile.lua, not spa-bluez5
363 properties["bluez5.profile"] = "off"
364 properties["spa.object.id"] = id
365
366 -- apply properties from the rules in the configuration file
367 properties = JsonUtils.match_rules_update_properties (config.rules, properties)
368
369 -- create the device
370 device = SpaDevice(factory, properties)
371 if device then
372 device:connect("create-object", createNode)
373 device:connect("object-removed", removeNode)
374 parent:store_managed_object(id, device)
375 else
376 log:warning ("Failed to create '" .. factory .. "' device")
377 return
378 end
379 end
380
381 log:info(parent, string.format("%d, %s (%s): %s",
382 id, properties["device.description"],
383 properties["api.bluez5.address"], properties["api.bluez5.connection"]))
384
385 -- activate the device after the bluez profiles are connected
386 if properties["api.bluez5.connection"] == "connected" then
387 device:activate(Feature.SpaDevice.ENABLED | Feature.Proxy.BOUND)
388 else
389 device:deactivate(Features.ALL)
390 end
391 end
392
393 function removeDevice(parent, id)
394 log:debug("Remove device: " .. tostring (id))
395 end
396
397 function createMonitor()
398 local monitor = SpaDevice("api.bluez5.enum.dbus", config.properties)
399 if monitor then
400 monitor:connect("create-object", createDevice)
401 monitor:connect("object-removed", removeDevice)
402 else
403 log:notice("PipeWire's BlueZ SPA plugin is missing or broken. " ..
404 "Bluetooth devices will not be supported.")
405 return nil
406 end
407 monitor:activate(Feature.SpaDevice.ENABLED)
408
409 return monitor
410 end
411
412 function CreateDeviceLoopbackSource (dev_props, dev_id)
413 local dev_name = dev_props["api.bluez5.address"] or dev_props["device.name"]
414 local dec_desc = dev_props["device.description"] or dev_props["device.name"]
415 or dev_props["device.nick"] or dev_props["device.alias"] or "bluetooth-device"
416 local target_object = getNodeName ("bluez_input",
417 dev_props["api.bluez5.address"], dev_props["device.name"], DEVICE_SOURCE_ID)
418
419 -- sanitize description, replace ':' with ' '
420 dec_desc = dec_desc:gsub("(:)", " ")
421
422 log:info("create SCO source loopback node: " .. dev_name)
423
424 local args = Json.Object {
425 ["capture.props"] = Json.Object {
426 ["node.name"] = string.format ("bluez_capture_internal.%s", dev_name),
427 ["media.class"] = "Stream/Input/Audio/Internal",
428 ["node.description"] =
429 string.format ("Bluetooth internal capture stream for %s", dec_desc),
430 ["audio.channels"] = 1,
431 ["audio.position"] = "[MONO]",
432 ["bluez5.loopback"] = true,
433 ["stream.dont-remix"] = true,
434 ["node.passive"] = true,
435 ["node.dont-fallback"] = true,
436 ["node.linger"] = true,
437 ["state.restore-props"] = false,
438 ["target.object"] = target_object,
439 },
440 ["playback.props"] = Json.Object {
441 ["node.name"] = string.format ("bluez_input.%s", dev_name),
442 ["node.description"] = string.format ("%s", dec_desc),
443 ["node.virtual"] = false,
444 ["audio.position"] = "[MONO]",
445 ["media.class"] = "Audio/Source",
446 ["device.id"] = dev_id,
447 ["card.profile.device"] = DEVICE_SOURCE_ID,
448 ["device.routes"] = "1",
449 ["priority.session"] = 2010,
450 ["bluez5.loopback"] = true,
451 }
452 }
453 return LocalModule("libpipewire-module-loopback", args:get_data(), {})
454 end
455
456 function checkProfiles (dev)
457 local device_id = dev["bound-id"]
458 local props = dev.properties
459 local device_spa_id = tonumber(props["spa.object.id"])
460
461 -- Get the associated BT SpaDevice
462 local internal_id = tostring (props["spa.object.id"])
463 local spa_device = monitor:get_managed_object (internal_id)
464 if spa_device == nil then
465 return
466 end
467
468 -- Check if the device supports headset profile
469 local has_headset_profile = false
470 for p in dev:iterate_params("EnumProfile") do
471 local profile = cutils.parseParam (p, "EnumProfile")
472 if profile.name:find ("headset") then
473 has_headset_profile = true
474 end
475 end
476
477 -- Setup Route/Port correctly for loopback nodes
478 if has_headset_profile then
479 local param = Pod.Object ({
480 "Spa:Pod:Object:Param:Props",
481 "Props",
482 params = Pod.Struct ({ "bluez5.autoswitch-routes", true })
483 })
484 dev:set_param("Props", param)
485 end
486
487 if has_headset_profile then
488 -- Always create the source loopback device if autoswitch is enabled.
489 -- Otherwise, only create the source loopback device if the current profile
490 -- is headset, and destroy the source loopback deivce if the current profile
491 -- is A2DP.
492 if Settings.get_boolean ("bluetooth.autoswitch-to-headset-profile") then
493 -- Create source loopback
494 local source_loopback = spa_device:get_managed_object (LOOPBACK_SOURCE_ID)
495 if source_loopback == nil and has_headset_profile then
496 source_loopback = CreateDeviceLoopbackSource (props, device_id)
497 spa_device:store_managed_object(LOOPBACK_SOURCE_ID, source_loopback)
498 end
499 else
500 -- Check if current profile is headset
501 local is_current_profile_headset = false
502 for p in dev:iterate_params("Profile") do
503 local profile = cutils.parseParam (p, "Profile")
504 if profile.name:find ("headset") then
505 is_current_profile_headset = true
506 end
507 break
508 end
509
510 if is_current_profile_headset then
511 -- Create source loopback
512 local source_loopback = spa_device:get_managed_object (LOOPBACK_SOURCE_ID)
513 if source_loopback == nil and has_headset_profile then
514 source_loopback = CreateDeviceLoopbackSource (props, device_id)
515 spa_device:store_managed_object(LOOPBACK_SOURCE_ID, source_loopback)
516 end
517 else
518 -- Destroy source loopback
519 spa_device:store_managed_object(LOOPBACK_SOURCE_ID, nil)
520 end
521 end
522 end
523 end
524
525 function onDeviceParamsChanged (dev, param_name)
526 if param_name == "EnumProfile" then
527 checkProfiles (dev)
528 elseif param_name == "Profile" then
529 checkProfiles (dev)
530 end
531 end
532
533 devices_om:connect("object-added", function(_, dev)
534 dev:connect ("params-changed", onDeviceParamsChanged)
535 checkProfiles (dev)
536 end)
537
538 if config.seat_monitoring then
539 logind_plugin = Plugin.find("logind")
540 end
541 if logind_plugin then
542 -- if logind support is enabled, activate
543 -- the monitor only when the seat is active
544 function startStopMonitor(seat_state)
545 log:info(logind_plugin, "Seat state changed: " .. seat_state)
546
547 if seat_state == "active" then
548 monitor = createMonitor()
549 elseif monitor then
550 monitor:deactivate(Feature.SpaDevice.ENABLED)
551 monitor = nil
552 end
553 end
554
555 logind_plugin:connect("state-changed", function(p, s) startStopMonitor(s) end)
556 startStopMonitor(logind_plugin:call("get-state"))
557 else
558 monitor = createMonitor()
559 end
560
561 nodes_om:activate()
562 devices_om:activate()
563 device_set_nodes_om:activate()
564
565 function evaluateAutoswitch ()
566 -- Evaluate loopbacks on all BT devices
567 for dev in devices_om:iterate () do
568 checkProfiles (dev)
569 end
570 end
571
572 Settings.subscribe ("bluetooth.autoswitch-to-headset-profile", function ()
573 evaluateAutoswitch ()
574 end)
575 evaluateAutoswitch ()