Debian Codegraph @

src/scripts/device/autoswitch-bluetooth-profile.lua

raw
1 -- WirePlumber
2 --
3 -- Copyright © 2021 Asymptotic Inc.
4 -- @author Sanchayan Maity <[email protected]>
5 --
6 -- Based on bt-profile-switch.lua in tests/examples
7 -- Copyright © 2021 George Kiagiadakis
8 --
9 -- Based on bluez-autoswitch in media-session
10 -- Copyright © 2021 Pauli Virtanen
11 --
12 -- SPDX-License-Identifier: MIT
13 --
14 -- This script is charged to automatically change BT profiles on a device. If a
15 -- client is linked to the device's loopback source node, the associated BT
16 -- device profile is automatically switched to HSP/HFP. If there is no clients
17 -- linked to the device's loopback source node, the BT device profile is
18 -- switched back to A2DP profile.
19 --
20 -- We switch to the highest priority profile that has an Input route available.
21 -- The reason for this is that we may have microphone enabled with non-HFP
22 -- codecs eg. Faststream.
23 -- When a stream goes away if the list with which we track the streams above
24 -- is empty, then we revert back to the old profile.
25
26 -- settings file: bluetooth.conf
27
28 lutils = require ("linking-utils")
29 cutils = require ("common-utils")
30 log = Log.open_topic ("s-device")
31 persistent_storage_hooks_registered = false
32 autoswitch_hooks_registered = false
33
34 local PROFILE_RESTORE_TIMEOUT_MSEC = 2000
35 local PROFILE_SWITCH_TIMEOUT_MSEC = 500
36
37 local state = nil
38 local headset_profiles = {}
39 local non_headset_profiles = {}
40 local capture_stream_links = {}
41 local restore_timeout_source = {}
42 local switch_timeout_source = {}
43
44 function saveHeadsetProfile (device, profile_name, persistent)
45 local key = "saved-headset-profile:" .. device.properties ["device.name"]
46 headset_profiles [key] = profile_name
47 if state ~= nil and persistent then
48 state:save_after_timeout (headset_profiles)
49 end
50 end
51
52 function getSavedHeadsetProfile (device)
53 local key = "saved-headset-profile:" .. device.properties ["device.name"]
54 return headset_profiles [key]
55 end
56
57 function saveNonHeadsetProfile (device, profile_name)
58 non_headset_profiles [device.properties ["device.name"]] = profile_name
59 end
60
61 function getSavedNonHeadsetProfile (device)
62 return non_headset_profiles [device.properties ["device.name"]]
63 end
64
65 function findProfile (device, index, name)
66 for p in device:iterate_params ("EnumProfile") do
67 local profile = cutils.parseParam (p, "EnumProfile")
68 if profile ~= nil then
69 if (index ~= nil and profile.index == index) or
70 (name ~= nil and profile.name == name) then
71 return profile
72 end
73 end
74 end
75
76 return nil
77 end
78
79 function getCurrentProfile (device)
80 for p in device:iterate_params ("Profile") do
81 local profile = cutils.parseParam (p, "Profile")
82 if profile then
83 return profile
84 end
85 end
86 return nil
87 end
88
89 function hasProfileInputRoute (device, profile_index)
90 for p in device:iterate_params ("EnumRoute") do
91 local route = cutils.parseParam (p, "EnumRoute")
92 if route and route.direction == "Input" and route.profiles then
93 for _, v in pairs (route.profiles) do
94 if v == profile_index then
95 return true
96 end
97 end
98 end
99 end
100 return false
101 end
102
103 function isHeadsetProfile (device, profile)
104 if hasProfileInputRoute (device, profile.index) and
105 (string.find (profile.name, "^headset%-head%-unit") or profile.name == "bap-duplex") then
106 return true
107 else
108 return false
109 end
110 end
111
112 function highestPrioHeadsetProfile (device)
113 local found_profile = nil
114 for p in device:iterate_params ("EnumRoute") do
115 local route = cutils.parseParam (p, "EnumRoute")
116 if route ~= nil and route.profiles ~= nil and route.direction == "Input" then
117 for _, v in pairs (route.profiles) do
118 local p = findProfile (device, v)
119 if p ~= nil and isHeadsetProfile (device, p) then
120 if found_profile == nil or found_profile.priority < p.priority then
121 found_profile = p
122 end
123 end
124 end
125 end
126 end
127 return found_profile
128 end
129
130 function highestPrioNonHeadsetProfile (device)
131 local found_profile = nil
132 for p in device:iterate_params ("EnumRoute") do
133 local route = cutils.parseParam (p, "EnumRoute")
134 if route ~= nil and route.profiles ~= nil and route.direction ~= "Input" then
135 for _, v in pairs (route.profiles) do
136 local p = findProfile (device, v)
137 if p ~= nil and not isHeadsetProfile (device, p) then
138 if found_profile == nil or found_profile.priority < p.priority then
139 found_profile = p
140 end
141 end
142 end
143 end
144 end
145 return found_profile
146 end
147
148 function switchDeviceToHeadsetProfile (dev_id, device_om)
149 -- Find the actual device
150 local device = device_om:lookup {
151 Constraint { "bound-id", "=", dev_id, type = "gobject" }
152 }
153 if device == nil then
154 log:info ("Device with id " .. tostring(dev_id).. " not found")
155 return
156 end
157
158 -- Do not switch if the current profile is already a headset profile
159 local cur_profile = getCurrentProfile (device)
160 if cur_profile ~= nil and isHeadsetProfile (device, cur_profile) then
161 log:info (device,
162 "Current profile is already a headset profile, no need to switch")
163 return
164 elseif cur_profile == nil then
165 log:info (device, "Could not get current profile, not switching")
166 return
167 end
168
169 -- Get saved headset profile if any, otherwise find the highest priority one
170 local profile = nil
171 local profile_name = getSavedHeadsetProfile (device)
172 if profile_name ~= nil then
173 profile = findProfile (device, nil, profile_name)
174 if profile ~= nil and not isHeadsetProfile (device, profile) then
175 saveHeadsetProfile (device, nil, false)
176 profile = nil
177 end
178 end
179 if profile == nil then
180 profile = highestPrioHeadsetProfile (device)
181 end
182
183 -- Switch if headset profile was found
184 if profile ~= nil then
185 local pod = Pod.Object {
186 "Spa:Pod:Object:Param:Profile", "Profile",
187 index = profile.index,
188 save = false
189 }
190 log:info (device, "Switching profile from: " .. cur_profile.name
191 .. " to: " .. profile.name)
192 device:set_params ("Profile", pod)
193 else
194 log:warning ("Could not find valid headset profile, not switching")
195 end
196 end
197
198 function restoreProfile (dev_id, device_om)
199 -- Find the actual device
200 local device = device_om:lookup {
201 Constraint { "bound-id", "=", dev_id, type = "gobject" }
202 }
203 if device == nil then
204 log:info ("Device with id " .. tostring(dev_id).. " not found")
205 return
206 end
207
208 -- Do not restore if the current profile is already a non-headset profile
209 local cur_profile = getCurrentProfile (device)
210 if cur_profile ~= nil and not isHeadsetProfile (device, cur_profile) then
211 log:info (device,
212 "Current profile is already a non-headset profile, no need to restore")
213 return
214 elseif cur_profile == nil then
215 log:info (device, "Could not get current profile, not switching")
216 return
217 end
218
219 -- Get saved non-headset profile if any, otherwise find the highest priority one
220 local profile = nil
221 local profile_name = getSavedNonHeadsetProfile (device)
222 if profile_name ~= nil then
223 profile = findProfile (device, nil, profile_name)
224 if profile ~= nil and isHeadsetProfile (device, profile) then
225 saveNonHeadsetProfile (device, nil)
226 profile = nil
227 end
228 end
229 if profile == nil then
230 profile = highestPrioNonHeadsetProfile (device)
231 end
232
233 -- Restore if non-headset profile was found
234 if profile ~= nil then
235 local pod = Pod.Object {
236 "Spa:Pod:Object:Param:Profile", "Profile",
237 index = profile.index,
238 save = false
239 }
240 log:info (device, "Restoring profile from: " .. cur_profile.name
241 .. " to: " .. profile.name)
242 device:set_params ("Profile", pod)
243 else
244 log:warning ("Could not find valid non-headset profile, not switching")
245 end
246 end
247
248 function triggerSwitchDeviceToHeadsetProfile (source, dev_id)
249 -- Always clear any pending restore/switch callbacks when triggering a new switch
250 if restore_timeout_source[dev_id] ~= nil then
251 restore_timeout_source[dev_id]:destroy ()
252 restore_timeout_source[dev_id] = nil
253 log:info ("Cancelled profile restore on device " .. tostring (dev_id))
254 end
255 if switch_timeout_source[dev_id] ~= nil then
256 switch_timeout_source[dev_id]:destroy ()
257 switch_timeout_source[dev_id] = nil
258 log:info ("Cancelled profile switch on device " .. tostring (dev_id))
259 end
260
261 -- create new switch callback
262 log:info ("Triggering profile switch on device " .. tostring (dev_id))
263 switch_timeout_source[dev_id] = Core.timeout_add (PROFILE_SWITCH_TIMEOUT_MSEC, function ()
264 switch_timeout_source[dev_id] = nil
265
266 local e = source:call ("create-event", "autoswitch-bluez-headset-profile", nil, nil)
267 e:set_data ("device-id", dev_id)
268 EventDispatcher.push_event (e)
269 end)
270 end
271
272 function triggerRestoreProfile (source, dev_id)
273 -- Always clear any pending restore/switch callbacks when triggering a new restore
274 if switch_timeout_source[dev_id] ~= nil then
275 switch_timeout_source[dev_id]:destroy ()
276 switch_timeout_source[dev_id] = nil
277 log:info ("Cancelled profile switch on device " .. tostring (dev_id))
278 end
279 if restore_timeout_source[dev_id] ~= nil then
280 restore_timeout_source[dev_id]:destroy ()
281 restore_timeout_source[dev_id] = nil
282 log:info ("Cancelled profile restore on device " .. tostring (dev_id))
283 end
284
285 -- create new restore callback
286 log:info ("Triggering profile restore on device " .. tostring (dev_id))
287 restore_timeout_source[dev_id] = Core.timeout_add (PROFILE_RESTORE_TIMEOUT_MSEC, function ()
288 restore_timeout_source[dev_id] = nil
289
290 local e = source:call ("create-event", "autoswitch-bluez-a2dp-profile", nil, nil)
291 e:set_data ("device-id", dev_id)
292 EventDispatcher.push_event (e)
293 end)
294 end
295
296 function getLinkedBluetoothLoopbackSourceNodeForStream (stream, node_om, link_om, visited_link_groups)
297 local stream_id = stream["bound-id"]
298
299 -- Make sure the node is linked
300 local link = link_om:lookup {
301 Constraint { "link.input.node", "=", stream_id, type = "pw-global"}
302 }
303 if link == nil then
304 return nil
305 end
306 local peer_id = link.properties["link.output.node"]
307
308 -- If the peer node is the BT loopback source node, return its Id.
309 -- Otherwise recursively advance in the graph if it is linked to a filter.
310 local bt_node = node_om:lookup {
311 Constraint { "media.class", "matches", "Audio/Source", type = "pw-global" },
312 Constraint { "bound-id", "=", peer_id, type = "gobject" },
313 Constraint { "bluez5.loopback", "=", "true", type = "pw" }
314 }
315 if bt_node ~= nil then
316 return bt_node
317 else
318 local filter_main_node = node_om:lookup {
319 Constraint { "bound-id", "=", peer_id, type = "gobject" },
320 Constraint { "node.link-group", "+", type = "pw" }
321 }
322 if filter_main_node ~= nil then
323 local filter_link_group = filter_main_node.properties ["node.link-group"]
324 if visited_link_groups == nil then
325 visited_link_groups = {}
326 end
327 if visited_link_groups [filter_link_group] then
328 return nil
329 else
330 visited_link_groups [filter_link_group] = true
331 end
332 for filter_stream_node in node_om:iterate {
333 Constraint { "media.class", "matches", "Stream/Input/Audio", type = "pw-global" },
334 Constraint { "stream.monitor", "!", "true", type = "pw" },
335 Constraint { "bluez5.loopback", "!", "true", type = "pw" },
336 Constraint { "node.link-group", "=", filter_link_group, type = "pw" }
337 } do
338 local bt_node = getLinkedBluetoothLoopbackSourceNodeForStream (filter_stream_node, node_om, link_om, visited_link_groups)
339 if bt_node ~= nil then
340 return bt_node
341 end
342 end
343 end
344 end
345
346 return nil
347 end
348
349 function isBluetoothLoopbackSourceNodeLinkedToStream (bt_node, node_om, link_om)
350 local bt_node_id = bt_node["bound-id"]
351 for stream in node_om:iterate {
352 Constraint { "media.class", "matches", "Stream/Input/Audio", type = "pw-global" },
353 Constraint { "node.link-group", "-", type = "pw" },
354 Constraint { "stream.monitor", "!", "true", type = "pw" },
355 Constraint { "bluez5.loopback", "!", "true", type = "pw" }
356 } do
357 local linked_bt_node = getLinkedBluetoothLoopbackSourceNodeForStream (stream, node_om, link_om)
358 if linked_bt_node ~= nil then
359 local linked_bt_node_id = linked_bt_node ["bound-id"]
360 if tonumber (linked_bt_node_id) == tonumber (bt_node_id) then
361 return true
362 end
363 end
364 end
365 return false
366 end
367
368 local switch_profile_hook = AsyncEventHook {
369 name = "switch-profile@autoswitch-bluetooth-profile",
370 interests = {
371 EventInterest {
372 Constraint { "event.type", "=", "autoswitch-bluez-headset-profile" },
373 },
374 },
375 steps = {
376 start = {
377 next = "none",
378 execute = function (event, transition)
379 local source = event:get_source ()
380 local device_om = source:call ("get-object-manager", "device")
381 local device_id = event:get_data ("device-id")
382
383 -- Switch profile
384 switchDeviceToHeadsetProfile (device_id, device_om)
385
386 -- Wait until the profile is applied
387 Core.sync (function ()
388 transition:advance ()
389 end)
390 end
391 },
392 }
393 }
394
395 local restore_profile_hook = AsyncEventHook {
396 name = "restore-profile@autoswitch-bluetooth-profile",
397 interests = {
398 EventInterest {
399 Constraint { "event.type", "=", "autoswitch-bluez-a2dp-profile" },
400 },
401 },
402 steps = {
403 start = {
404 next = "none",
405 execute = function (event, transition)
406 local source = event:get_source ()
407 local device_om = source:call ("get-object-manager", "device")
408 local device_id = event:get_data ("device-id")
409
410 -- Restore profile
411 restoreProfile (device_id, device_om)
412
413 -- Wait until the profile is applied
414 Core.sync (function ()
415 transition:advance ()
416 end)
417 end
418 },
419 }
420 }
421
422 local evaluate_bluetooth_profiles_hook = SimpleEventHook {
423 name = "evaluate-bluetooth-profiles@autoswitch-bluetooth-profile",
424 interests = {
425 EventInterest {
426 Constraint { "event.type", "=", "evaluate-bluetooth-profiles" },
427 },
428 },
429 execute = function (event)
430 local source = event:get_source ()
431 local node_om = source:call ("get-object-manager", "node")
432 local link_om = source:call ("get-object-manager", "link")
433
434 -- Evaluate all bluetooth loopback source nodes, and switch to headset
435 -- profile only if the node is running and linked to a stream that is not a
436 -- monitor, otherwise just restore the profile.
437 --
438 -- If the bluetooth node is linked to a stream that is a monitor, its state
439 -- will be 'running', so we cannot just rely on the state to know if we
440 -- have to switch or not, we also need to check if the node is linked to
441 -- a stream that is not a monitor.
442 for bt_node in node_om:iterate {
443 Constraint { "media.class", "matches", "Audio/Source" },
444 Constraint { "device.id", "+" },
445 Constraint { "bluez5.loopback", "=", "true", type = "pw" }
446 } do
447 local bt_node_state = bt_node["state"]
448 local bt_dev_id = bt_node.properties ["device.id"]
449
450 if bt_node_state == "running" and
451 isBluetoothLoopbackSourceNodeLinkedToStream (bt_node, node_om, link_om) then
452 triggerSwitchDeviceToHeadsetProfile (source, bt_dev_id)
453 else
454 triggerRestoreProfile (source, bt_dev_id)
455 end
456 end
457 end
458 }
459
460 local link_added_hook = SimpleEventHook {
461 name = "link-added@autoswitch-bluetooth-profile",
462 interests = {
463 EventInterest {
464 Constraint { "event.type", "=", "link-added" },
465 },
466 },
467 execute = function (event)
468 local source = event:get_source ()
469 local node_om = source:call ("get-object-manager", "node")
470 local link = event:get_subject ()
471 local in_stream_id = link.properties["link.input.node"]
472
473 -- Only evaluate bluetooth profiles if a capture stream was linked
474 local stream = node_om:lookup {
475 Constraint { "media.class", "matches", "Stream/Input/Audio", type = "pw-global" },
476 Constraint { "node.link-group", "-", type = "pw" },
477 Constraint { "stream.monitor", "!", "true", type = "pw" },
478 Constraint { "bluez5.loopback", "!", "true", type = "pw" },
479 Constraint { "bound-id", "=", in_stream_id, type = "gobject" },
480 }
481 if stream ~= nil then
482 capture_stream_links [link.id] = true
483 source:call ("push-event", "evaluate-bluetooth-profiles", nil, nil)
484 end
485 end
486 }
487
488 local link_removed_hook = SimpleEventHook {
489 name = "link-removed@autoswitch-bluetooth-profile",
490 interests = {
491 EventInterest {
492 Constraint { "event.type", "=", "link-removed" },
493 },
494 },
495 execute = function (event)
496 local source = event:get_source ()
497 local link = event:get_subject ()
498
499 -- Only evaluate bluetooth profiles if a capture stream was unlinked
500 if capture_stream_links [link.id] then
501 capture_stream_links [link.id] = nil
502 source:call ("push-event", "evaluate-bluetooth-profiles", nil, nil)
503 end
504 end
505 }
506
507 local state_changed_hook = SimpleEventHook {
508 name = "bluez-loopback-state-changed@autoswitch-bluetooth-profile",
509 interests = {
510 EventInterest {
511 Constraint { "event.type", "=", "node-state-changed" },
512 Constraint { "media.class", "matches", "Audio/Source" },
513 Constraint { "device.id", "+" },
514 Constraint { "bluez5.loopback", "=", "true", type = "pw" }
515 },
516 },
517 execute = function (event)
518 local source = event:get_source ()
519 local node = event:get_subject ()
520 local old_state = event:get_properties ()["event.subject.old-state"]
521 local new_state = event:get_properties ()["event.subject.new-state"]
522
523 log:info (node, "state changed from '" .. old_state .. "' to '" .. new_state .. "'")
524
525 -- Dont evaluate if the state changed from idle to suspended
526 if old_state == "idle" and new_state == "suspended" then
527 return
528 end
529
530 source:call ("push-event", "evaluate-bluetooth-profiles", nil, nil)
531 end
532 }
533
534 local node_added_hook = SimpleEventHook {
535 name = "bluez-loopback-added@autoswitch-bluetooth-profile",
536 interests = {
537 EventInterest {
538 Constraint { "event.type", "=", "node-added" },
539 Constraint { "media.class", "matches", "Audio/Source" },
540 Constraint { "device.id", "+" },
541 Constraint { "bluez5.loopback", "=", "true", type = "pw" }
542 },
543 },
544 execute = function (event)
545 local source = event:get_source ()
546 source:call ("push-event", "evaluate-bluetooth-profiles", nil, nil)
547 end
548 }
549
550 local device_profile_changed_hook = SimpleEventHook {
551 name = "bluez-profile-changed@autoswitch-bluetooth-profile",
552 interests = {
553 EventInterest {
554 Constraint { "event.type", "=", "device-params-changed" },
555 Constraint { "event.subject.param-id", "=", "Profile" },
556 Constraint { "device.api", "=", "bluez5" },
557 },
558 },
559 execute = function (event)
560 local device = event:get_subject ()
561
562 -- Always save the current profile when it changes
563 local cur_profile = getCurrentProfile (device)
564 if cur_profile ~= nil then
565 if isHeadsetProfile (device, cur_profile) then
566 log:info (device, "Saving headset profile " .. cur_profile.name)
567 saveHeadsetProfile (device, cur_profile.name, cur_profile.save)
568 else
569 log:info (device, "Saving non-headset profile " .. cur_profile.name)
570 saveNonHeadsetProfile (device, cur_profile.name)
571 end
572 end
573 end
574 }
575
576 function evaluatePersistentStorage ()
577 if Settings.get_boolean ("bluetooth.use-persistent-storage") and
578 not persistent_storage_hooks_registered then
579 state = State ("bluetooth-autoswitch")
580 headset_profiles = state:load ()
581 persistent_storage_hooks_registered = true
582 elseif persistent_storage_hooks_registered then
583 state = nil
584 headset_profiles = {}
585 persistent_storage_hooks_registered = false
586 end
587 end
588
589 function evaluateAutoswitch ()
590 if Settings.get_boolean ("bluetooth.autoswitch-to-headset-profile") and
591 not autoswitch_hooks_registered then
592 capture_stream_links = {}
593 restore_timeout_source = {}
594 switch_timeout_source = {}
595 switch_profile_hook:register ()
596 restore_profile_hook:register ()
597 evaluate_bluetooth_profiles_hook:register ()
598 link_added_hook:register ()
599 link_removed_hook:register ()
600 state_changed_hook:register ()
601 node_added_hook:register ()
602 device_profile_changed_hook:register ()
603 autoswitch_hooks_registered = true
604 elseif autoswitch_hooks_registered then
605 capture_stream_links = nil
606 restore_timeout_source = nil
607 switch_timeout_source = nil
608 switch_profile_hook:remove ()
609 restore_profile_hook:remove ()
610 evaluate_bluetooth_profiles_hook:remove ()
611 link_added_hook:remove ()
612 link_removed_hook:remove ()
613 state_changed_hook:remove ()
614 node_added_hook:remove ()
615 device_profile_changed_hook:remove ()
616 autoswitch_hooks_registered = false
617 end
618 end
619
620 Settings.subscribe ("bluetooth.use-persistent-storage", function ()
621 evaluatePersistentStorage ()
622 end)
623 evaluatePersistentStorage ()
624
625 Settings.subscribe ("bluetooth.autoswitch-to-headset-profile", function ()
626 evaluateAutoswitch ()
627 end)
628 evaluateAutoswitch ()