commits
tags
import QtQuick
import TvLauncher
// Ljud via PipeWire/WirePlumber (wpctl).
Item {
id: page
readonly property bool available: shell.has("wpctl")
readonly property bool hasDump: shell.has("pw-dump")
property real volume: 0
property bool muted: false
property var sinks: []
property string error: ""
function focusFirst() { list.focusFirst() }
function refresh() {
if (!available) return
shell.run("wpctl", ["get-volume", "@DEFAULT_AUDIO_SINK@"], (code, out, err) => {
if (code !== 0) {
error = (err || out).trim() || "Kunde inte läsa volymen."
return
}
error = ""
const m = out.match(/Volume:\s*([\d.]+)/)
if (m) volume = Math.min(1, parseFloat(m[1]))
muted = out.indexOf("MUTED") >= 0
})
if (hasDump) {
shell.run("pw-dump", [], (code, out) => {
if (code !== 0) return
try { if (page) page.sinks = page.parseDump(JSON.parse(out)) } catch (e) { console.warn("pw-dump:", e) }
}, 8000)
} else {
shell.run("wpctl", ["status"], (code, out) => {
if (code === 0) sinks = parseSinks(out)
})
}
}
// Bygger listan över ljudutgångar ur pw-dump. Ett ALSA-ljudkort har bara en
// profil aktiv åt gången (t.ex. analog ELLER HDMI), så utgångarna på de
// andra profilerna finns inte som sinks förrän profilen byts. Därför listas
// kortens tillgängliga utgångsprofiler, plus övriga sinks (Bluetooth m.m.).
function parseDump(objs) {
let defaultName = ""
const devices = {}, nodes = [], sources = []
for (const o of objs) {
const props = (o.info && o.info.props) || {}
if (o.type === "PipeWire:Interface:Metadata" && o.metadata) {
for (const m of o.metadata)
if (m.key === "default.audio.sink" && m.value && m.value.name) defaultName = m.value.name
} else if (o.type === "PipeWire:Interface:Device" && props["media.class"] === "Audio/Device") {
devices[o.id] = o
} else if (o.type === "PipeWire:Interface:Node" && props["media.class"] === "Audio/Sink") {
nodes.push({ id: String(o.id), name: props["node.description"] || props["node.nick"] || props["node.name"],
nodeName: props["node.name"], device: props["device.id"], profile: props["device.profile.name"] || "" })
} else if (o.type === "PipeWire:Interface:Node" && props["media.class"] === "Audio/Source") {
sources.push({ device: props["device.id"], profile: props["device.profile.name"] || "" })
}
}
const out = []
const cardIds = {}
for (const devId in devices) {
const d = devices[devId]
const props = d.info.props
const params = d.info.params || {}
const enumP = params.EnumProfile || []
const cur = (params.Profile && params.Profile[0]) || null
if (props["device.api"] !== "alsa" || enumP.length === 0) continue
cardIds[devId] = true
// Kortets Profile-parameter kan släpa efter (den har setts säga
// "analog" medan HDMI-sinken är aktiv), så det som faktiskt finns
// – kortets sinks/sources – avgör vilken utgång som är aktiv.
const devSinks = nodes.filter(n => n.device == devId && n.profile !== "")
const devSrc = sources.find(n => n.device == devId && n.profile !== "")
const curOut = devSinks.length > 0 ? "output:" + devSinks[0].profile
: cur ? cur.name.split("+")[0] : ""
const curIn = devSinks.length > 0 ? (devSrc ? "input:" + devSrc.profile : "")
: cur ? cur.name.split("+").slice(1).join("+") : ""
const groups = {}, order = []
for (const pr of enumP) {
if (!pr.name || pr.name.indexOf("output:") !== 0 || pr.available === "no") continue
const key = pr.name.split("+")[0]
if (!groups[key]) { groups[key] = []; order.push(key) }
groups[key].push(pr)
}
for (const key of order) {
const g = groups[key]
// Behåll samma ingång som nu (mikrofonen försvinner inte vid byte).
const pick = g.find(p => p.name.split("+").slice(1).join("+") === curIn)
|| g.find(p => p.name.indexOf("+") >= 0) || g[0]
const plain = g.find(p => p.name === key)
const active = key === curOut
const sink = active ? (devSinks.find(n => "output:" + n.profile === key) || devSinks[0]) : null
out.push({
id: sink ? sink.id : "",
device: String(devId),
profile: String(pick.index),
// PipeWire tror redan att profilen är vald – den måste "puttas".
stale: !active && !!cur && cur.index === pick.index,
name: (plain || pick).description || key,
isDefault: !!sink && sink.nodeName === defaultName,
kind: key
})
}
}
for (const n of nodes) {
if (cardIds[n.device]) continue
out.push({ id: n.id, device: "", profile: "", name: n.name, isDefault: n.nodeName === defaultName, kind: n.nodeName })
}
return out
}
// Plockar ut "Sinks:" under "Audio" ur wpctl status.
function parseSinks(text) {
const out = []
let inAudio = false, inSinks = false
for (const raw of text.split("\n")) {
const t = raw.trim()
if (/^Audio\b/.test(t)) { inAudio = true; continue }
if (/^(Video|Settings)\b/.test(t)) { inAudio = false; inSinks = false; continue }
if (!inAudio) continue
if (t.indexOf("Sinks:") >= 0) { inSinks = true; continue }
if (/(Sources|Filters|Streams|Devices|Sink endpoints|Source endpoints):/.test(t)) { inSinks = false; continue }
if (!inSinks) continue
const s = raw.replace(/^[\s│├└─]+/, "")
const m = s.match(/^(\*)?\s*(\d+)\.\s+(.*?)(\s+\[vol:.*\])?\s*$/)
if (m) out.push({ id: m[2], device: "", profile: "", kind: "", name: m[3], isDefault: m[1] === "*" })
}
return out
}
function setVolume(v) {
volume = v
shell.run("wpctl", ["set-volume", "-l", "1.0", "@DEFAULT_AUDIO_SINK@", v.toFixed(2)], () => refresh())
}
function toggleMute() {
muted = !muted
shell.run("wpctl", ["set-mute", "@DEFAULT_AUDIO_SINK@", "toggle"], () => refresh())
}
function setDefault(id) {
shell.run("wpctl", ["set-default", id], () => refresh())
}
// Byter kortets profil och gör den nya utgången till standard när den dykt upp.
property string pendingDevice: ""
function selectOutput(o) {
if (o.id !== "") { setDefault(o.id); return }
pendingDevice = o.device
const go = () => shell.run("wpctl", ["set-profile", o.device, o.profile], () => pendingTimer.restart())
// Samma profilindex som PipeWire redan tror är aktivt ignoreras, så gå via "av".
if (o.stale) shell.run("wpctl", ["set-profile", o.device, "0"], go)
else go()
}
onSinksChanged: {
if (pendingDevice === "") return
const s = sinks.find(x => x.device === pendingDevice && x.id !== "")
if (!s) return
pendingDevice = ""
if (!s.isDefault) setDefault(s.id)
}
Timer { id: pendingTimer; interval: 600; repeat: false; onTriggered: page.refresh() }
Component.onCompleted: refresh()
Timer { interval: 4000; running: page.available && page.visible; repeat: true; onTriggered: page.refresh() }
CardList {
id: list
anchors.fill: parent
SettingsCard {
visible: !page.available
icon: "volume-mute"
title: "Ljudsystemet saknas"
subtitle: "Installera PipeWire och logga sedan ut och in igen:\nsudo apt install pipewire-audio wireplumber"
}
SettingsCard {
visible: page.available && page.error !== ""
icon: "volume-mute"
title: "Kunde inte nå ljudsystemet"
subtitle: page.error + "\nKontrollera: systemctl --user status pipewire wireplumber"
}
SliderCard {
visible: page.available && page.error === ""
icon: page.muted ? "volume-mute" : "volume"
title: "Volym"
value: page.volume
valueText: page.muted ? "Ljud av" : Math.round(page.volume * 100) + " %"
onMoved: (v) => page.setVolume(v)
onActivated: page.toggleMute()
}
SettingsCard {
visible: page.available && page.error === ""
icon: "volume-mute"
title: "Stäng av ljudet"
toggle: page.muted
onActivated: page.toggleMute()
}
SectionTitle {
visible: page.available && page.sinks.length > 0
text: "Ljudutgång"
}
Repeater {
model: page.sinks
delegate: SettingsCard {
required property var modelData
readonly property string tag: modelData.name + " " + (modelData.kind || "")
icon: /hdmi|displayport/i.test(tag) ? "speaker" : (/head|blue|bt|bluez/i.test(tag) ? "headphones" : "volume")
title: modelData.name
subtitle: modelData.isDefault ? "Används nu" : "Tryck för att använda"
checked: modelData.isDefault
onActivated: page.selectOutput(modelData)
}
}
}
}