Debian Codegraph @

src/scripts/monitors/alsa.lua

raw
1 -- WirePlumber
2 --
3 -- Copyright © 2021 Collabora Ltd.
4 -- @author George Kiagiadakis <[email protected]>
5 --
6 -- SPDX-License-Identifier: MIT
7
8 SPLIT_PCM_PARENT_OFFSET = 256
9 SPLIT_PCM_OFFSET = 512
10
11 cutils = require ("common-utils")
12 log = Log.open_topic ("s-monitors")
13
14 config = {}
15 config.reserve_device = Core.test_feature ("monitor.alsa.reserve-device")
16 config.properties = Conf.get_section_as_properties ("monitor.alsa.properties")
17 config.rules = Conf.get_section_as_json ("monitor.alsa.rules", Json.Array {})
18
19 -- unique device/node name tables
20 device_names_table = nil
21 node_names_table = nil
22
23 -- SPA ids to node names: name = id_name_table[device_id][node_id]
24 id_name_table = nil
25
26
27 function nonempty(str)
28 return str ~= "" and str or nil
29 end
30
31 function applyDefaultDeviceProperties (properties)
32 properties["api.alsa.use-acp"] = true
33 properties["api.acp.auto-profile"] = false
34 properties["api.acp.auto-port"] = false
35 properties["api.dbus.ReserveDevice1.Priority"] = -20
36 properties["api.alsa.split-enable"] = true
37 end
38
39 function createSplitPCMHWNode(dev_props, properties)
40 local skip_keys = {
41 "api.alsa.split.position", "card.profile.device", "device.profile.description",
42 "device.profile.name"
43 }
44 local props = {}
45
46 for k, v in pairs(properties) do
47 props[k] = v
48 end
49 for _, k in pairs(skip_keys) do
50 props[k] = nil
51 end
52
53 -- create the underlying hidden ALSA node
54 props["node.name"] = props["api.alsa.split.name"]
55 props["node.description"] = string.format("%s %s", dev_props["device.description"],
56 props["api.alsa.path"]:gsub("^[^,]*[,:]", ""))
57 if props["api.alsa.pcm.stream"] == "capture" then
58 props["media.class"] = "Audio/Source/Internal"
59 else
60 props["media.class"] = "Audio/Sink/Internal"
61 end
62 props["api.alsa.use-chmap"] = false
63 props["api.alsa.split.parent"] = true
64 props["audio.position"] = props["api.alsa.split.hw-position"]
65 local channels = Json.Raw (props["api.alsa.split.hw-position"]):parse ()
66 props["audio.channels"] = tostring(#channels)
67
68 props = JsonUtils.match_rules_update_properties (config.rules, props)
69
70 if cutils.parseBool (props ["node.disabled"]) then
71 log:notice ("ALSA node " .. props ["node.name"] .. " disabled")
72 return nil
73 end
74
75 return Node("adapter", props)
76 end
77
78 function createSplitPCMLoopback(parent, id, obj_type, factory, properties)
79 local skip_keys = {
80 -- not suitable for loopback
81 "audio.rate",
82 "clock.quantum-limit",
83 "factory.name",
84 "node.driver",
85 "node.pause-on-idle",
86 "node.want-driver",
87 "port.group",
88 "priority.driver",
89 "resample.disable",
90 "resample.prefill",
91 }
92 local args
93 local props = {}
94
95 props["node.virtual"] = false
96
97 for k, v in pairs(properties) do
98 props[k] = v
99 end
100 for _, k in pairs(skip_keys) do
101 props[k] = nil
102 end
103
104 local split_props = {
105 ["node.name"] = properties["node.name"] .. ".split",
106 ["node.description"] = string.format(I18n.gettext("Split %s"), properties["node.description"]),
107 ["audio.position"] = properties["api.alsa.split.position"],
108 ["stream.dont-remix"] = true,
109 ["node.passive"] = true,
110 ["node.dont-fallback"] = true,
111 ["node.linger"] = true,
112 ["state.restore-props"] = false,
113 ["target.object"] = properties["api.alsa.split.name"],
114 }
115
116 if properties["api.alsa.pcm.stream"] == "playback" then
117 props["media.class"] = "Audio/Sink"
118 split_props["media.class"] = "Stream/Output/Audio/Internal"
119 args = Json.Object {
120 ["capture.props"] = Json.Object (props),
121 ["playback.props"] = Json.Object (split_props),
122 }
123 else
124 props["media.class"] = "Audio/Source"
125 split_props["media.class"] = "Stream/Input/Audio/Internal"
126 args = Json.Object {
127 ["playback.props"] = Json.Object (props),
128 ["capture.props"] = Json.Object (split_props),
129 }
130 end
131
132 return LocalModule("libpipewire-module-loopback", args:get_data(), {})
133 end
134
135 devices_om = ObjectManager {
136 Interest {
137 type = "device",
138 }
139 }
140
141 split_nodes_om = ObjectManager {
142 Interest {
143 type = "node",
144 Constraint { "api.alsa.split.position", "+", type = "pw" },
145 }
146 }
147
148 split_nodes_om:connect ("object-added", function(_, node)
149 -- Connect ObjectConfig events to the right node
150 if not monitor then
151 return
152 end
153
154 local interest = Interest {
155 type = "device",
156 Constraint { "object.id", "=", node.properties["device.id"] }
157 }
158 log:info("Split PCM node found: " .. tostring (node["bound-id"]))
159
160 for device in devices_om:iterate (interest) do
161 local device_id = device.properties["spa.object.id"]
162 if not device_id then
163 goto next_device
164 end
165
166 local spa_device = monitor:get_managed_object (tonumber (device_id))
167 if not spa_device then
168 goto next_device
169 end
170
171 local id = node.properties["card.profile.device"]
172 if id ~= nil then
173 log:info(".. assign to device: " .. tostring (device["bound-id"]) .. " node " .. tostring (id))
174 spa_device:store_managed_object (id, node)
175 end
176
177 ::next_device::
178 end
179 end)
180
181 function createNode(parent, id, obj_type, factory, properties)
182 local dev_props = parent.properties
183 local parent_id = tonumber(dev_props["spa.object.id"])
184
185 -- set the device id and spa factory name; REQUIRED, do not change
186 properties["device.id"] = parent["bound-id"]
187 properties["factory.name"] = factory
188
189 -- set the default pause-on-idle setting
190 properties["node.pause-on-idle"] = false
191
192 -- try to negotiate the max amount of channels
193 if dev_props["api.alsa.use-acp"] ~= "true" then
194 properties["audio.channels"] = properties["audio.channels"] or "64"
195 end
196
197 local dev = properties["api.alsa.pcm.device"]
198 or properties["alsa.device"] or "0"
199 local subdev = properties["api.alsa.pcm.subdevice"]
200 or properties["alsa.subdevice"] or "0"
201 local stream = properties["api.alsa.pcm.stream"] or "unknown"
202 local profile = properties["device.profile.name"]
203 or (stream .. "." .. dev .. "." .. subdev)
204 local profile_desc = properties["device.profile.description"]
205
206 -- set priority
207 if not properties["priority.driver"] then
208 local priority = (dev == "0") and 1000 or 744
209 if stream == "capture" then
210 priority = priority + 1000
211 end
212
213 priority = priority - (tonumber(dev) * 16) - tonumber(subdev)
214
215 if profile:find("^pro%-") then
216 priority = priority + 500
217 elseif profile:find("^analog%-") then
218 priority = priority + 9
219 elseif profile:find("^iec958%-") then
220 priority = priority + 8
221 end
222
223 if dev_props["device.bus"] == "usb" then
224 priority = priority + 100
225 end
226
227 properties["priority.driver"] = priority
228 properties["priority.session"] = priority
229 end
230
231 -- ensure the node has a media class
232 if not properties["media.class"] then
233 if stream == "capture" then
234 properties["media.class"] = "Audio/Source"
235 else
236 properties["media.class"] = "Audio/Sink"
237 end
238 end
239
240 -- ensure the node has a name
241 if not properties["node.name"] then
242 local name =
243 (stream == "capture" and "alsa_input" or "alsa_output")
244 .. "." ..
245 (dev_props["device.name"]:gsub("^alsa_card%.(.+)", "%1") or
246 dev_props["device.name"] or
247 "unnamed-device")
248 .. "." ..
249 profile
250
251 -- sanitize name
252 name = name:gsub("([^%w_%-%.])", "_")
253
254 properties["node.name"] = name
255
256 log:info ("Creating node " .. name)
257
258 -- deduplicate nodes with the same name
259 for counter = 2, 99, 1 do
260 if node_names_table[properties["node.name"]] ~= true then
261 break
262 end
263 properties["node.name"] = name .. "." .. counter
264 log:info ("deduplicating node name -> " .. properties["node.name"])
265 end
266 else
267 log:info ("Creating node " .. properties["node.name"])
268 end
269
270 -- and a nick
271 local nick = nonempty(properties["node.nick"])
272 or nonempty(properties["api.alsa.pcm.name"])
273 or nonempty(properties["alsa.name"])
274 or nonempty(profile_desc)
275 or dev_props["device.nick"]
276 if nick == "USB Audio" then
277 nick = dev_props["device.nick"]
278 end
279 -- also sanitize nick, replace ':' with ' '
280 properties["node.nick"] = nick:gsub("(:)", " ")
281
282 -- ensure the node has a description
283 if not properties["node.description"] then
284 local desc = nonempty(dev_props["device.description"]) or "unknown"
285 local name = nonempty(properties["api.alsa.pcm.name"]) or
286 nonempty(properties["api.alsa.pcm.id"]) or dev
287
288 if profile_desc then
289 desc = desc .. " " .. profile_desc
290 elseif subdev ~= "0" then
291 desc = desc .. " (" .. name .. " " .. subdev .. ")"
292 elseif dev ~= "0" then
293 desc = desc .. " (" .. name .. ")"
294 end
295
296 -- also sanitize description, replace ':' with ' '
297 properties["node.description"] = desc:gsub("(:)", " ")
298 end
299
300 -- add api.alsa.card.* and alsa.* properties for rule matching purposes
301 for k, v in pairs(dev_props) do
302 if k:find("^api%.alsa%.card%..*") or k:find("^alsa%..*") then
303 properties[k] = v
304 end
305 end
306
307 -- add cpu.vm.name for rule matching purposes
308 local vm_type = Core.get_vm_type()
309 if nonempty(vm_type) then
310 properties["cpu.vm.name"] = vm_type
311 end
312
313 -- apply properties from rules defined in JSON .conf file
314 local orig_properties = {}
315 for k, v in pairs(properties) do
316 orig_properties[k] = v
317 end
318 properties = JsonUtils.match_rules_update_properties (config.rules, properties)
319
320 if cutils.parseBool (properties ["node.disabled"]) then
321 log:notice ("ALSA node " .. properties["node.name"] .. " disabled")
322 return
323 end
324
325 node_names_table[properties["node.name"]] = true
326 id_name_table[parent_id][id] = properties["node.name"]
327
328 -- handle split HW node
329 if properties["api.alsa.split.position"] ~= nil then
330 local split_hw_node_name = string.format("%s.%s",
331 (stream == "capture" and "alsa_input" or "alsa_output"),
332 properties["api.alsa.path"]:gsub("([:,])", "_"))
333 properties["api.alsa.split.name"] = split_hw_node_name
334 orig_properties["api.alsa.split.name"] = split_hw_node_name
335
336 if not node_names_table [split_hw_node_name] then
337 log:info ("Create ALSA SplitPCM HW node " .. split_hw_node_name)
338
339 local node = createSplitPCMHWNode(dev_props, orig_properties)
340 if node ~= nil then
341 node:activate(Feature.Proxy.BOUND)
342 parent:store_managed_object(SPLIT_PCM_PARENT_OFFSET + id, node)
343
344 node_names_table[split_hw_node_name] = true
345 id_name_table[parent_id][SPLIT_PCM_PARENT_OFFSET + id] = split_hw_node_name
346 end
347 end
348
349 -- create split PCM node
350 log:info ("Create ALSA SplitPCM split node " .. properties["node.name"])
351
352 local loopback = createSplitPCMLoopback (parent, id, obj_type, factory, properties)
353 parent:store_managed_object(SPLIT_PCM_OFFSET + id, loopback)
354 parent:set_managed_pending(id)
355 return
356 end
357
358 -- create the node
359 local node = Node("adapter", properties)
360 parent:set_managed_pending(id)
361 node:activate(Feature.Proxy.BOUND, function (_, err)
362 if err then
363 log:warning ("Failed to create " .. properties ["node.name"]
364 .. ": " .. tostring(err))
365 end
366 parent:store_managed_object(id, node)
367 end)
368 end
369
370 function removeNode(parent, id)
371 local parent_id = tonumber(parent.properties["spa.object.id"])
372 local ids = {id, SPLIT_PCM_PARENT_OFFSET + id, SPLIT_PCM_OFFSET + id}
373
374 for _, j in pairs(ids) do
375 local node_name = id_name_table[parent_id][j]
376
377 parent:store_managed_object(j, nil)
378
379 if node_name ~= nil then
380 log:info ("Removing node " .. node_name)
381 node_names_table[node_name] = nil
382 id_name_table[parent_id][j] = nil
383 end
384 end
385 end
386
387 function createDevice(parent, id, factory, properties)
388 id_name_table[id] = {}
389 properties["spa.object.id"] = id
390 local device = SpaDevice(factory, properties)
391 if device then
392 device:connect("create-object", createNode)
393 device:connect("object-removed", removeNode)
394 device:activate(Feature.SpaDevice.ENABLED | Feature.Proxy.BOUND)
395 parent:store_managed_object(id, device)
396 else
397 log:warning ("Failed to create '" .. factory .. "' device")
398 end
399 end
400
401 function removeDevice(parent, id)
402 if id_name_table[id] ~= nil then
403 for _, node_name in pairs(id_name_table[id]) do
404 log:info ("Release " .. node_name)
405 node_names_table[node_name] = nil
406 end
407 id_name_table[id] = nil
408 end
409 end
410
411 function prepareDevice(parent, id, obj_type, factory, properties)
412 -- ensure the device has an appropriate name
413 local name = "alsa_card." ..
414 (properties["device.name"] or
415 properties["device.bus-id"] or
416 properties["device.bus-path"] or
417 tostring(id)):gsub("([^%w_%-%.])", "_")
418
419 properties["device.name"] = name
420
421 -- deduplicate devices with the same name
422 for counter = 2, 99, 1 do
423 if device_names_table[properties["device.name"]] ~= true then
424 device_names_table[properties["device.name"]] = true
425 break
426 end
427 properties["device.name"] = name .. "." .. counter
428 end
429
430 -- ensure the device has a description
431 if not properties["device.description"] then
432 local d = nil
433 local f = properties["device.form-factor"]
434 local c = properties["device.class"]
435 local n = properties["api.alsa.card.name"]
436
437 if n == "Loopback" then
438 d = I18n.gettext("Loopback")
439 elseif f == "internal" then
440 d = I18n.gettext("Built-in Audio")
441 elseif c == "modem" then
442 d = I18n.gettext("Modem")
443 end
444
445 d = d or properties["device.product.name"]
446 or properties["api.alsa.card.name"]
447 or properties["alsa.card_name"]
448 or "Unknown device"
449 properties["device.description"] = d
450 end
451
452 -- ensure the device has a nick
453 properties["device.nick"] =
454 properties["device.nick"] or
455 properties["api.alsa.card.name"] or
456 properties["alsa.card_name"]
457
458 -- set the icon name
459 if not properties["device.icon-name"] then
460 local icon = nil
461 local icon_map = {
462 -- form factor -> icon
463 ["microphone"] = "audio-input-microphone",
464 ["webcam"] = "camera-web",
465 ["handset"] = "phone",
466 ["portable"] = "multimedia-player",
467 ["tv"] = "video-display",
468 ["headset"] = "audio-headset",
469 ["headphone"] = "audio-headphones",
470 ["speaker"] = "audio-speakers",
471 ["hands-free"] = "audio-handsfree",
472 }
473 local f = properties["device.form-factor"]
474 local c = properties["device.class"]
475 local b = properties["device.bus"]
476
477 icon = icon_map[f] or ((c == "modem") and "modem") or "audio-card"
478 properties["device.icon-name"] = icon .. "-analog" .. (b and ("-" .. b) or "")
479 end
480
481 -- apply properties from rules defined in JSON .conf file
482 applyDefaultDeviceProperties (properties)
483 properties = JsonUtils.match_rules_update_properties (config.rules, properties)
484
485 if cutils.parseBool (properties ["device.disabled"]) then
486 log:notice ("ALSA card/device " .. properties ["device.name"] .. " disabled")
487 device_names_table [properties ["device.name"]] = nil
488 return
489 end
490
491 -- override the device factory to use ACP
492 if cutils.parseBool (properties ["api.alsa.use-acp"]) then
493 log:info("Enabling the use of ACP on " .. properties["device.name"])
494 factory = "api.alsa.acp.device"
495 end
496
497 -- use HDMI channel detection if enabled in settings
498 if Settings.get_boolean ("monitor.alsa.autodetect-hdmi-channels") then
499 properties["api.acp.use-eld-channels"] = true
500 end
501
502 -- use device reservation, if available
503 if rd_plugin and properties["api.alsa.card"] then
504 local rd_name = "Audio" .. properties["api.alsa.card"]
505 local rd = rd_plugin:call("create-reservation",
506 rd_name,
507 cutils.get_application_name (),
508 properties["device.name"],
509 properties["api.dbus.ReserveDevice1.Priority"]);
510
511 properties["api.dbus.ReserveDevice1"] = rd_name
512
513 -- unlike pipewire-media-session, this logic here keeps the device
514 -- acquired at all times and destroys it if someone else acquires
515 rd:connect("notify::state", function (rd, pspec)
516 local state = rd["state"]
517
518 if state == "acquired" then
519 -- create the device
520 createDevice(parent, id, factory, properties)
521
522 elseif state == "available" then
523 -- attempt to acquire again
524 rd:call("acquire")
525
526 elseif state == "busy" then
527 -- destroy the device
528 removeDevice(parent, id)
529 parent:store_managed_object(id, nil)
530 end
531 end)
532
533 rd:connect("release-requested", function (rd)
534 log:info("release requested")
535 parent:store_managed_object(id, nil)
536 rd:call("release")
537 end)
538
539 rd:call("acquire")
540 else
541 -- create the device
542 createDevice(parent, id, factory, properties)
543 end
544 end
545
546 function createMonitor ()
547 local m = SpaDevice("api.alsa.enum.udev", config.properties)
548 if m == nil then
549 log:notice("PipeWire's ALSA SPA plugin is missing or broken. " ..
550 "Sound cards will not be supported")
551 return nil
552 end
553
554 -- handle create-object to prepare device
555 m:connect("create-object", prepareDevice)
556
557 -- handle object-removed to destroy device reservations and recycle device name
558 m:connect("object-removed", function (parent, id)
559 removeDevice(parent, id)
560
561 local device = parent:get_managed_object(id)
562 if not device then
563 return
564 end
565
566 if rd_plugin then
567 local rd_name = device.properties["api.dbus.ReserveDevice1"]
568 if rd_name then
569 rd_plugin:call("destroy-reservation", rd_name)
570 end
571 end
572 device_names_table[device.properties["device.name"]] = nil
573 end)
574
575 -- reset the name tables to make sure names are recycled
576 device_names_table = {}
577 node_names_table = {}
578 id_name_table = {}
579
580 -- activate monitor
581 log:info("Activating ALSA monitor")
582 m:activate(Feature.SpaDevice.ENABLED)
583 return m
584 end
585
586 -- if the reserve-device plugin is enabled, at the point of script execution
587 -- it is expected to be connected. if it is not, assume the d-bus connection
588 -- has failed and continue without it
589 if config.reserve_device then
590 rd_plugin = Plugin.find("reserve-device")
591 end
592 if rd_plugin and rd_plugin:call("get-dbus")["state"] ~= "connected" then
593 log:notice("reserve-device plugin is not connected to D-Bus, "
594 .. "disabling device reservation")
595 rd_plugin = nil
596 end
597
598 -- handle rd_plugin state changes to destroy and re-create the ALSA monitor in
599 -- case D-Bus service is restarted
600 if rd_plugin then
601 local dbus = rd_plugin:call("get-dbus")
602 dbus:connect("notify::state", function (b, pspec)
603 local state = b["state"]
604 log:info ("rd-plugin state changed to " .. state)
605 if state == "connected" then
606 log:info ("Creating ALSA monitor")
607 monitor = createMonitor()
608 elseif state == "closed" then
609 log:info ("Destroying ALSA monitor")
610 monitor = nil
611 end
612 end)
613 end
614
615 -- create the monitor
616 monitor = createMonitor()
617
618 devices_om:activate()
619 split_nodes_om:activate()