Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 53 additions & 3 deletions bin/omarchy-audio-output-sink
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/bin/bash

# omarchy:summary=Print the sink whose volume and mute a given output really uses
# omarchy:args=[sink-name]
# omarchy:args=[--active] [sink-name]
# omarchy:group=audio
# omarchy:examples=omarchy audio output sink | omarchy audio output sink omarchy_speaker_tuning
# omarchy:examples=omarchy audio output sink | omarchy audio output sink --active | omarchy audio output sink omarchy_speaker_tuning

set -uo pipefail

Expand All @@ -17,8 +17,58 @@ set -uo pipefail
# HDMI are selected it returns those, not the speakers a tuning happens to front.
# Callers that need to describe some *other* output -- an output switcher naming
# the next one in the rotation -- pass that sink explicitly.
#
# With --active this instead resolves the sink an uncorked stream is actually
# playing into when that is not the default sink, so the volume keys follow a
# call or playback routed to another output (a headset, an HDMI TV) instead of
# always moving the default. A communication stream (media.role
# "phone"/"communication", PipeWire's canonical VOIP role) outranks background
# playback when several streams are playing; with no non-default stream the
# answer is the default, unchanged.

# The sink an uncorked stream is playing into, when that is not the default
# sink. Prints the sink name, or nothing to keep the default.
active_stream_sink() {
local default_sink indices idx name
default_sink="$(pactl get-default-sink 2>/dev/null)"
[[ -n $default_sink ]] || return 0

sink="${1:-$(pactl get-default-sink 2>/dev/null)}"
# Sink indices carrying an uncorked stream, call streams first, so a meeting
# outranks background playback when several streams are playing at once.
indices="$(pactl -f json list sink-inputs 2>/dev/null |
jq -r '
(.[] | select(.corked == false)
| select((.properties["media.role"] // "") | test("phone|communication|voip"; "i"))
| .sink),
(.[] | select(.corked == false) | .sink)' 2>/dev/null)"

for idx in $indices; do
name="$(pactl -f json list sinks 2>/dev/null |
jq -r --argjson i "$idx" '.[] | select(.index == $i) | .name' 2>/dev/null)"
[[ -n $name ]] || continue
[[ $name == "$default_sink" ]] && continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Music wins over calls

A call on the default output loses to background music on another output. The resolver puts the call first, but this unconditional continue discards it because it uses the default output. The loop then returns the music output, so volume and mute keys control music rather than the call. Keep the preferred call output even when it is the default, and add this mixed-output case to the tests.

[[ $name == *.monitor ]] && continue
printf '%s\n' "$name"
return 0
done
return 0
}

follow_active=false
sink=""
while (($#)); do
case $1 in
--active) follow_active=true ;;
-*) echo "Unknown option: $1" >&2; exit 1 ;;
*) sink="$1" ;;
esac
shift
done

if [[ $follow_active == true && -z $sink ]]; then
sink="$(active_stream_sink)"
fi
sink="${sink:-$(pactl get-default-sink 2>/dev/null)}"

if [[ -z $sink || $sink == alsa_output.* ]]; then
printf '%s\n' "$sink"
Expand Down
24 changes: 19 additions & 5 deletions bin/omarchy-audio-output-volume
Original file line number Diff line number Diff line change
@@ -1,20 +1,34 @@
#!/bin/bash

# omarchy:summary=Adjust output volume and show the Omarchy OSD
# omarchy:args=<raise|lower|mute-toggle|+N|-N>
# omarchy:examples=omarchy audio output volume raise | omarchy audio output volume lower | omarchy audio output volume mute-toggle | omarchy audio output volume +1
# omarchy:args=[--follow-active] <raise|lower|mute-toggle|+N|-N>
# omarchy:examples=omarchy audio output volume raise | omarchy audio output volume --follow-active raise | omarchy audio output volume mute-toggle | omarchy audio output volume +1

follow_active=false
while [[ $1 == --* ]]; do
case $1 in
--follow-active) follow_active=true ;;
*) echo "Unknown option: $1" >&2; exit 1 ;;
esac
shift
done

action="${1:-}"

if [[ -z $action ]]; then
echo "Usage: omarchy-audio-output-volume <raise|lower|mute-toggle|+N|-N>"
echo "Usage: omarchy-audio-output-volume [--follow-active] <raise|lower|mute-toggle|+N|-N>"
exit 1
fi

# Resolve through any DSP sink to the physical one, so the keys always move real
# loudness and the processing always sees full-scale input. Shared with the audio
# panel and the output switcher.
sink="$(omarchy-audio-output-sink)"
# panel and the output switcher. With --follow-active the keys follow the stream
# playing on another output (a call on a headset) instead of the default sink.
if [[ $follow_active == true ]]; then
sink="$(omarchy-audio-output-sink --active)"
else
sink="$(omarchy-audio-output-sink)"
fi
if [[ -z $sink ]]; then
echo "Could not resolve an audio sink to control." >&2
exit 1
Expand Down
4 changes: 2 additions & 2 deletions default/hypr/bindings/media.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ o.bind("XF86TouchpadOn", "Enable touchpad", "omarchy-toggle-touchpad on", { lock
o.bind("XF86TouchpadOff", "Disable touchpad", "omarchy-toggle-touchpad off", { locked = true })

-- Precise volume and brightness controls.
o.bind("ALT + XF86AudioRaiseVolume", "Volume up precise", "omarchy-audio-output-volume +1", { locked = true, repeating = true })
o.bind("ALT + XF86AudioLowerVolume", "Volume down precise", "omarchy-audio-output-volume -1", { locked = true, repeating = true })
o.bind("ALT + XF86AudioRaiseVolume", "Volume up precise", "omarchy-audio-output-volume --follow-active +1", { locked = true, repeating = true })
o.bind("ALT + XF86AudioLowerVolume", "Volume down precise", "omarchy-audio-output-volume --follow-active -1", { locked = true, repeating = true })
o.bind("ALT + XF86MonBrightnessUp", "Brightness up precise", "omarchy-brightness-display +1%", { locked = true, repeating = true })
o.bind("ALT + XF86MonBrightnessDown", "Brightness down precise", "omarchy-brightness-display 1%-", { locked = true, repeating = true })

Expand Down
2 changes: 1 addition & 1 deletion default/hypr/helpers.lua
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ local function command_from(value, description)
elseif value.panel then
return shell_dispatcher("panel", value.panel, "omarchy-shell shell toggle " .. shell_quote(value.panel))
elseif value.audio then
return shell_dispatcher("audio", value.audio, "omarchy-audio-output-volume " .. shell_quote(value.audio))
return shell_dispatcher("audio", value.audio, "omarchy-audio-output-volume --follow-active " .. shell_quote(value.audio))
elseif value.brightness then
local step = value.brightness == "raise" and "+5%" or "5%-"
return shell_dispatcher("brightness", value.brightness, "omarchy-brightness-display " .. step)
Expand Down
44 changes: 42 additions & 2 deletions shell/plugins/services/media/Service.qml
Original file line number Diff line number Diff line change
Expand Up @@ -465,16 +465,56 @@ Item {
// sink it feeds on every press, from the live routing. An ALSA sink is its
// own physical sink, so only then do the keys act here; any other default
// sink falls back to the script.
//
// During a call the headset is a separate, non-default sink, so Linux routes
// the volume keys to the default sink and they move the speakers while the
// call plays into the headset. To make the keys follow the stream that is
// actually playing, the active sink is resolved through
// omarchy-audio-output-sink --active (an uncorked stream on a non-default
// output wins, else the default). The shell cannot see which sink each
// stream is linked to, so the resolution runs in a process, refreshed when
// the default sink changes, on a timer, and on each press. When the active
// sink is not the default, handleVolumeKey defers to the script, which
// repeats the same resolution and steps that sink.
readonly property var defaultSink: Pipewire.defaultAudioSink
readonly property var volumeSink: defaultSink && String(defaultSink.name).indexOf("alsa_output.") === 0 ? defaultSink : null
property double lastMuteToggle: 0
property string activeSinkName: ""

function refreshActiveSink() {
if (!activeSinkProc.running) activeSinkProc.running = true
}

onDefaultSinkChanged: refreshActiveSink()

Process {
id: activeSinkProc
command: ["omarchy-audio-output-sink", "--active"]
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: root.activeSinkName = String(text).trim()
}
}

Timer {
interval: 5000
running: true
repeat: true
triggeredOnStart: true
onTriggered: root.refreshActiveSink()
}

// Returns false when the default sink is not one to control here, so the
// caller falls back to the script.
// Returns false when the default sink is not one to control here, or when an
// active stream plays on another output, so the caller falls back to the
// script.
function handleVolumeKey(action) {
var audio = volumeSink && volumeSink.audio
if (!audio) return false

if (activeSinkName && activeSinkName !== String(defaultSink.name)) return false

refreshActiveSink()
Comment on lines +514 to +516

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 First press changes speakers

When a headset call starts between polls, activeSinkName still names the default output. handleVolumeKey checks that old value, starts a refresh, then changes the speakers before the result arrives. It returns true, so the script never handles that press. Resolve the output before applying the action, or defer to the script while the cached answer may be stale.


var step = MediaModel.volumeKeyStep(action, Math.round(audio.volume * 100), audio.muted)
if (!step) return false

Expand Down
2 changes: 1 addition & 1 deletion shell/shell.qml
Original file line number Diff line number Diff line change
Expand Up @@ -1618,7 +1618,7 @@ ShellRoot {
} else if (entry.kind === "audio") {
var media = shell.serviceFor("omarchy.media")
if (!media || !media.handleVolumeKey(entry.target))
Util.execArgv(["omarchy-audio-output-volume", entry.target])
Util.execArgv(["omarchy-audio-output-volume", "--follow-active", entry.target])
} else {
shell.toggle(entry.target, "{}")
}
Expand Down
100 changes: 100 additions & 0 deletions test/shell.d/audio-output-active-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/bin/bash

set -euo pipefail

source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh"

require_command jq

test_home=$(mktemp -d)
test_bin=$(mktemp -d)

cleanup() {
rm -rf "$test_home" "$test_bin"
}
trap cleanup EXIT

# Stub pactl for the JSON the resolver reads. The --active path only needs the
# default sink and the `-f json` listings; the results below are ALSA sinks, so
# the resolver short-circuits before its text-format DSP/EasyEffects walk.
cat >"$test_bin/pactl" <<'STUB'
#!/bin/bash
format=""
if [[ ${1:-} == "-f" ]]; then
format="${2:-}"
shift 2
fi
case "$format|$1|$2" in
"|get-default-sink|") cat "$TEST_DATA/default-sink" ;;
"json|list|sinks") cat "$TEST_DATA/sinks.json" ;;
"json|list|sink-inputs") cat "$TEST_DATA/sink-inputs.json" ;;
*) exit 1 ;;
esac
STUB
chmod +x "$test_bin/pactl"

default=alsa_output.pci-0000_00_1f.3.analog-stereo
jabra=alsa_output.usb-Jabra_Link_380-00.analog-stereo
monitor=alsa_output.usb-Jabra_Link_380-00.analog-stereo.monitor
hdmi=alsa_output.pci-0000_00_1f.3.hdmi-stereo

resolve() {
HOME="$test_home" XDG_CONFIG_HOME="$test_home/.config" TEST_DATA="$test_home/data" \
PATH="$test_bin:$PATH" bash "$ROOT/bin/omarchy-audio-output-sink" "$@"
}

reset_scenario() {
rm -rf "$test_home/data"
mkdir -p "$test_home/data"
printf '%s\n' "$default" >"$test_home/data/default-sink"
printf '[{"index":70,"name":"%s"},{"index":105,"name":"%s"},{"index":106,"name":"%s"},{"index":107,"name":"%s"}]\n' \
"$default" "$jabra" "$monitor" "$hdmi" >"$test_home/data/sinks.json"
}

# With nothing playing, --active answers the default sink.
reset_scenario
printf '[]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$default" ]] || fail "an idle graph answers the default sink"
pass "--active answers the default sink when nothing is playing"

# An uncorked stream on another output wins over the default.
reset_scenario
printf '[{"index":12,"sink":105,"corked":false,"properties":{}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$jabra" ]] || fail "an active stream on another output answers that output"
pass "--active follows an uncorked stream onto its sink"

# A stream on the default sink keeps the default.
reset_scenario
printf '[{"index":12,"sink":70,"corked":false,"properties":{}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$default" ]] || fail "a stream on the default sink answers the default"
pass "--active keeps the default sink when only it is playing"

# A monitor sink is not an output.
reset_scenario
printf '[{"index":12,"sink":106,"corked":false,"properties":{}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$default" ]] || fail "a monitor sink is not followed"
pass "--active skips a monitor sink"

# A corked stream is not playing.
reset_scenario
printf '[{"index":12,"sink":105,"corked":true,"properties":{}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$default" ]] || fail "a corked stream is not followed"
pass "--active ignores a corked stream"

# A call (media.role phone) outranks background playback on another output.
reset_scenario
printf '[{"index":12,"sink":105,"corked":false,"properties":{}},{"index":13,"sink":107,"corked":false,"properties":{"media.role":"phone"}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$hdmi" ]] || fail "a communication stream outranks background playback"
pass "--active prefers a call over background playback"

# With no call, an ordinary playback stream is still followed.
reset_scenario
printf '[{"index":12,"sink":105,"corked":false,"properties":{"media.role":"music"}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active) == "$jabra" ]] || fail "an uncorked non-call stream is followed when alone"
pass "--active follows ordinary playback when no call is playing"

# An explicit sink name still wins over --active.
reset_scenario
printf '[{"index":12,"sink":105,"corked":false,"properties":{}}]\n' >"$test_home/data/sink-inputs.json"
[[ $(resolve --active "$hdmi") == "$hdmi" ]] || fail "an explicit sink name wins over --active"
pass "--active with an explicit sink resolves that sink"
12 changes: 8 additions & 4 deletions test/shell.d/media-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,22 @@ assertEqual(media.volumeOsdIcon(0, false), 'volume-muted', 'volume OSD shows mut

// Only an ALSA sink is its own physical sink. Any other default sink, a DSP
// chain or EasyEffects above all, needs omarchy-audio-output-sink's live
// resolution on every press, so its keys fall back to the script.
// resolution on every press, so its keys fall back to the script. The same
// deferral covers the active-stream resolution: when a stream plays on another
// output, the keys follow that output through the script, not the default.
const fs = require('fs')
const serviceQml = fs.readFileSync(path.join(root, 'shell/plugins/services/media/Service.qml'), 'utf8')
assert(
serviceQml.includes('readonly property var volumeSink: defaultSink && String(defaultSink.name).indexOf("alsa_output.") === 0 ? defaultSink : null') &&
/function handleVolumeKey\(action\) \{\s*var audio = volumeSink && volumeSink\.audio\s*if \(!audio\) return false/.test(serviceQml) &&
serviceQml.includes('activeSinkName !== String(defaultSink.name)) return false') &&
serviceQml.includes('command: ["omarchy-audio-output-sink", "--active"]') &&
!serviceQml.includes('volumeSinkName'),
'volume keys act in the shell only on an ALSA sink and otherwise defer to the script'
'volume keys act in the shell only on an ALSA sink, defer to the script for an active stream on another output, and otherwise defer'
)
const shellQml = fs.readFileSync(path.join(root, 'shell/shell.qml'), 'utf8')
assert(
/if \(!media \|\| !media\.handleVolumeKey\(entry\.target\)\)\s*Util\.execArgv\(\["omarchy-audio-output-volume", entry\.target\]\)/.test(shellQml),
'a volume key the shell declines runs omarchy-audio-output-volume'
/if \(!media \|\| !media\.handleVolumeKey\(entry\.target\)\)\s*Util\.execArgv\(\["omarchy-audio-output-volume", "--follow-active", entry\.target\]\)/.test(shellQml),
'a volume key the shell declines runs omarchy-audio-output-volume --follow-active'
)
JS
2 changes: 1 addition & 1 deletion test/shell.d/shell-shortcuts-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ expect_binding $'exec\tomarchy-menu toggle \'setup.power\'\tunlisted menu' "an u
expect_binding $'global\tomarchy:panel.omarchy.emojis\tlisted panel' "a listed panel binds its global shortcut"
expect_binding $'exec\tomarchy-shell shell toggle \'omarchy.wifiqr\'\tunlisted panel' "an unlisted panel falls back to the command"
expect_binding $'global\tomarchy:audio.raise\tlisted audio' "a listed volume key binds its global shortcut"
expect_binding $'exec\tomarchy-audio-output-volume \'+1\'\tunlisted audio' "an unlisted volume step falls back to the script"
expect_binding $'exec\tomarchy-audio-output-volume --follow-active \'+1\'\tunlisted audio' "an unlisted volume step falls back to the script"
expect_binding $'global\tomarchy:brightness.raise\tlisted brightness' "a listed brightness key binds its global shortcut"
expect_binding $'global\tomarchy:ipc.media.next\tlisted ipc' "a listed IPC call binds its global shortcut"
expect_binding $'exec\tomarchy-shell \'media\' \'sourceNext\'\tunlisted ipc' "an unlisted IPC call falls back to omarchy-shell"
Expand Down