Skip to content

sof-ucm: Add GTK4 end-to-end pipeline visualizer and ALSA UCM2 editor - #8

Merged
lgirdwood merged 2 commits into
mainfrom
feat/sof-ucm
Nov 24, 2026
Merged

lgirdwood merged 2 commits into
mainfrom
feat/sof-ucm

Conversation

@lgirdwood

Copy link
Copy Markdown
Member

Summary

Adds sof-ucm, a GTK4 Python application for visualizing end-to-end audio pipelines from ALSA PCMs through DSP topologies and codec DAPM/HDA graphs to hardware endpoints, alongside ALSA UCM2 profile inspection, overlay, editing, generation, and alsaucm testing.

Key Capabilities

  • Local & Remote (SSH) Discovery (discovery.py, tplg_loader.py):
    • Reads sound cards, ALSA PCM streams, amixer contents kcontrols, ASoC DAPM widgets/routes (/sys/kernel/debug/asoc), HDA codec widget graphs (/proc/asound/cardN/codec#*), SOF IPC4 topologies (.tplg), and /usr/share/alsa/ucm2 configurations locally or over SSH (--ssh USER@HOST).
  • Columnar End-to-End Pipeline Graph (graph_builder.py, layout.py):
    • Organizes graphs in three zones: all ALSA PCMs in a vertical left column, DSP PipelineContainers + DAPM/HDA codec widgets across center columns, and hardware Endpoints (speakers, headphones, mics, jacks, line in/out, SPDIF, HDMI/DP, BT) in a vertical right column with attached kcontrol clusters.
  • Hardware-Accelerated Canvas (graph_canvas.py):
    • Renders with Gtk.Snapshot / Gsk and a cached Cairo edge/connector texture (sof-builder style), smooth pointer-anchored zoom & pan with drag cursors, grouped/claimed pointer gestures, interactive kcontrol sliders/switches/dropdowns, and headless PNG export (--render-png).
  • UCM2 Authoring & Validation (ucm_parser.py, ucm_serializer.py, ucm_editor.py, left_panes.py, right_inspector.py, window.py):
    • Verb/Device overlay & reachability tracing, live recording (Record -> UCM) of kcontrol changes, New UCM Wizard, raw file tabs, validation diagnostics, and alsaucm verification.
  • Build & Packaging (Makefile, README.md, packaging/rpm/sof-utils.spec):
    • Integrates sof-ucm into build, install, uninstall, check, deb, rpm, and clean targets.

Testing

  • make -C /home/lrg/work/sof-utils check (py_compile clean across sof-builder, sof-ucm, sof-top)
  • python3 -m unittest discover -s /home/lrg/work/sof-utils/sof-ucm/tests -v (6 tests passed)
  • Verified headless PNG renders on local ALSA HDA card and SSH-remote SOF (dragon-fly) device, plus GTK4 gesture grouping/pan verification.

Add the `sof-ucm` GTK4 application and integrate it into the top-level build, documentation, and packaging:

- `sof_ucm/discovery.py`, `tplg_loader.py`, `model.py`: Discover ALSA sound cards, PCM streams, kcontrols (`amixer contents`), DAPM widgets/routes, HDA codec nodes (`/proc/asound/cardN/codec#*`), and SOF IPC4 topology (`.tplg`) on either the local machine or a remote DUT over SSH (`SshTransport`).
- `sof_ucm/graph_builder.py`, `layout.py`: Build end-to-end graphs linking left-column ALSA PCMs -> DSP pipeline containers & codec DAPM/HDA nodes -> right-column hardware endpoints (speakers, headphones, mics, jacks, line in/out, SPDIF, HDMI/DP, BT) with attached kcontrols.
- `sof_ucm/graph_canvas.py`: Hardware-accelerated `Gtk.Snapshot` / `Gsk` + cached Cairo edge renderer matching `sof-builder` styling, smooth pan/zoom with drag cursors and grouped/claimed pointer gestures, interactive kcontrol sliders/switches/dropdowns, and offscreen PNG export (`--render-png`).
- `sof_ucm/ucm_parser.py`, `ucm_serializer.py`, `ucm_editor.py`, `left_panes.py`, `right_inspector.py`, `window.py`: Parse, visualize, overlay, validate, edit, generate, and test ALSA UCM2 profiles (`alsaucm`) locally or over SSH.
- `Makefile`, `README.md`, `packaging/rpm/sof-utils.spec`: Register `sof-ucm` targets, install/packaging rules, and unit tests.

Signed-off-by: Liam Girdwood <liam.r.girdwood@linux.intel.com>
@lgirdwood
lgirdwood marked this pull request as ready for review November 24, 2026 12:47

@lgirdwood lgirdwood left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reviewed all 25 files (8a814c246a) and ran the unit test suite locally (6/6 passing in 0.59s).

Really nice architecture matching sof-builder's Gtk.Snapshot + cached Cairo edge layer, pure-Python .tplg + UCM2 parsers, and local/SSH transport abstraction. Summary of key findings:

  1. Bugs / Runtime Breakage:

    • Test (alsaucm) command tokenization (sof-ucm/sof_ucm/window.py:826-830): cmds passes f"_verb {verb}" / f"_enadev {d}" as single strings instead of separate tokens, so alsaucm's set IDENTIFIER VALUE consumes the next command (list / set) as VALUE and fails with alsaucm: unknown command '_devices'.
    • Edge texture cache collision (sof-ucm/sof_ucm/graph_canvas.py:1310-1319): _edge_tex_key keys on len(vm.highlighted_edge_ids) / len(vm.highlighted_node_ids) rather than the sets themselves (and _on_trace_node doesn't bump _edge_version), serving stale edge highlights when switching between equal-size traces.
    • .tplg link loop & private-data bounds (sof-ucm/sof_ucm/tplg_loader.py:578-587): Unconditional break on the first iteration of DAI_LINK/BACKEND_LINK/CODEC_LINK drops subsequent links when hdr_count > 1, and cpriv_sz / pcm_priv_size should check <= block_end.
    • Flattening of multi-file / conditional UCM2 profiles (sof-ucm/sof_ucm/ucm_serializer.py:286-295): Calling sync_profile_raw_files() on existing profiles (like Intel/sof-hda-dsp) overwrites HiFi.conf from the host-evaluated flattened AST, stripping If/Condition blocks and duplicating SectionDevices that came from Included files.
    • Pango markup escaping & single-quoted UCM strings (sof-ucm/sof_ucm/ucm_editor.py:38-62, 164-166, 191): Escape msg with GLib.markup_escape_text() before set_markup(), and track '...' alongside "..." in check_ucm_syntax_balance().
  2. Security / Filesystem Safety:

    • Path confinement on raw_files export/staging & batched pkexec (sof-ucm/sof_ucm/window.py:840, 855, 878-881): Relative Includes outside ucm_root_dir yield ../ keys in raw_files; validate commonpath against dest_root/tmpd before writing (especially with pkexec), use mktemp -d + cleanup for remote SSH staging instead of fixed /tmp/sof-ucm-stage, and batch pkexec writes so saving doesn't prompt once per file.
    • SSH ControlPath & -- option terminator (sof-ucm/sof_ucm/discovery.py:140-155): Move ControlPath out of world-writable /tmp into a 0700 runtime/cache dir (%C) and add "--" before self.target.
  3. Build, Tests & Minor Notes:

    • Wire $(PYTHON) -B -m unittest discover -s tests into sof-ucm/Makefile's check: target, and guard test_local_machine_card_discovery_and_render() (sof-ucm/tests/test_tplg_and_graph.py:136) with skipTest when running on headless/cardless CI runners.
    • Note: self.undo_mgr = UndoRedoManager() (window.py:93) is instantiated but not yet hooked up to edits/shortcuts, and _on_canvas_kcontrol_changed() (window.py:653) runs amixer synchronously on the GTK main thread (noticeable over higher-latency SSH).

Comment on lines +140 to +155
cmd = [
"ssh",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=6",
"-o", "ControlMaster=auto",
"-o", "ControlPersist=60",
"-o", "ControlPath=/tmp/sof-ucm-ssh-%r@%h:%p",
]
if self.port != 22:
cmd.extend(["-p", str(self.port)])
if self.identity_file:
cmd.extend(["-i", self.identity_file])
cmd.extend(self.extra_opts)
cmd.append(self.target)
return cmd

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Two SSH hardening fixes here:

  1. ControlPath in world-writable /tmp: /tmp/sof-ucm-ssh-%r@%h:%p is predictable in /tmp (vulnerable to pre-created socket/symlink collisions on multi-user systems and 108-byte UNIX_PATH_MAX limits on long hostnames). Prefer placing the socket in os.environ.get("XDG_RUNTIME_DIR") or a 0o700 dir under ~/.cache/sof-ucm using OpenSSH's %C hash token.
  2. Option injection via self.target: self.ssh_entry (window.py:403) passes user input into self.target; append "--", self.target so a target starting with - (e.g. -oProxyCommand=...) cannot be parsed as an ssh flag.

Comment on lines +1310 to +1319
key = (
id(vm),
self._edge_version,
vm.has_active_trace,
len(vm.highlighted_edge_ids),
len(vm.highlighted_node_ids),
sel_node,
sel_edge,
)
if self._edge_tex is not None and self._edge_tex_key == key:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

key only hashes len(vm.highlighted_edge_ids) and len(vm.highlighted_node_ids), and _on_trace_node() (window.py:617-626) does not increment self._edge_version.

When double-clicking from one pipeline to another of the same length (e.g. two HDMI/DP paths with identical node/edge counts, where sel_node was already updated on the first press of the double-click), key == self._edge_tex_key matches the stale texture and keeps rendering the previous trace's highlighted edges. Including frozenset(vm.highlighted_edge_ids) (or bumping _edge_version whenever trace/UCM highlights change) avoids the collision.

Comment on lines +578 to +587
for _ in range(hdr_count):
if off + 200 > block_end:
break
l_size = struct.unpack_from("<I", data, off)[0]
l_name = _cstr(data[off + 8:off + 52]) if l_size >= 52 else ""
l_sname = _cstr(data[off + 52:off + 96]) if l_size >= 96 else ""
l_id = struct.unpack_from("<I", data, off + 4)[0]
tplg.links.append(TplgLinkDesc(link_id=l_id, name=l_name, stream_name=l_sname))
break

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

  • Line 586 has an unconditional break, so only the first link in any multi-element DAI_LINK / BACKEND_LINK / CODEC_LINK block (hdr_count > 1) is ever recorded.
  • Also in _parse_single_control() (lines 327, 360, 377) and SND_SOC_TPLG_TYPE_PCM (line 563), cpriv_sz / pcm_priv_size is added to off without checking next_off <= block_end (and SOF_TPLG_NUM_OUT_FALLBACK := on line 483 is an unused walrus variable).

Comment on lines +161 to +167
text = self.get_text()
ok, _ln, msg = check_ucm_syntax_balance(text)
if ok:
self.status_lbl.set_markup(f"<span foreground='#34d399'>{msg}</span>")
else:
self.status_lbl.set_markup(f"<span foreground='#f87171'>{msg}</span>")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

  • Unescaped Pango markup (here and line 191): msg (especially f"Parse error: {exc}" in _on_apply_clicked) can contain <, >, or &, causing Gtk.Label.set_markup() to emit a Pango parse warning and blank the status label. Escape msg via GLib.markup_escape_text(msg).
  • Single-quoted strings in check_ucm_syntax_balance() (lines 38-62): _tokenize_ucm() (ucm_parser.py:50) treats both "..." and '...' as string tokens, but check_ucm_syntax_balance() only tracks in_dquote, so # or [/] inside single-quoted control arguments (e.g. 'HDMI [0] Switch') trigger false syntax errors.

Comment on lines +286 to +295
def sync_profile_raw_files(profile: UcmProfile) -> None:
"""Regenerate raw_files entries from the structured UcmProfile AST."""
master_key = profile.master_rel_path or f"{profile.card_driver or 'card'}.conf"
profile.raw_files[master_key] = serialize_master_conf(profile)
for vname, verb in profile.verbs.items():
vkey = verb.file_path or f"{vname}.conf"
if profile.ucm_root_dir and vkey.startswith(profile.ucm_root_dir):
vkey = vkey[len(profile.ucm_root_dir):].lstrip("/")
profile.raw_files[vkey] = serialize_verb_conf(verb)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Two serialization issues when editing existing real-world UCM2 profiles (e.g. Intel/sof-hda-dsp):

  1. Flattening included / conditional sections: load_ucm_profile() evaluates If/Condition blocks against the current machine and merges SectionDevices from Included files into verb.devices. Calling sync_profile_raw_files() on an inspector edit then overwrites master_key and HiFi.conf from the flattened AST — stripping If/Condition/DefineRegex/Macro blocks while serialize_master_conf() still emits Include.*.File, duplicating included SectionDevices inside HiFi.conf.
  2. String escaping & SectionModifier.ConflictingDevice: serialize_master_conf() / serialize_verb_conf() (lines 176, 182, 206, 227, 235, 257, 265, 278) interpolate Comment, Define, and Value strings into "..." without escaping \ or ", and mod.conflicting_devices (parsed in ucm_parser.py:418) is omitted in SectionModifier (lines 262-281).

Comment thread sof-ucm/sof_ucm/window.py Outdated
Comment on lines +826 to +830
cmds = ["set", f"_verb {verb}"]
for d in devices:
cmds.extend(["set", f"_enadev {d}"])
cmds.extend(["list", "_devices"])

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

alsaucm's set IDENTIFIER VALUE command expects two separate argv tokens. Passing f"_verb {verb}" / f"_enadev {d}" as single list items causes run_alsaucm_command() (discovery.py:1081) to quote '_verb HiFi' as IDENTIFIER, consuming the next token ('set' or 'list') as VALUE and failing with alsaucm: unknown command '_devices':

Suggested change
cmds = ["set", f"_verb {verb}"]
for d in devices:
cmds.extend(["set", f"_enadev {d}"])
cmds.extend(["list", "_devices"])
cmds = ["set", "_verb", verb]
for d in devices:
cmds.extend(["set", "_enadev", d])
cmds.extend(["list", "_devices"])

Comment thread sof-ucm/sof_ucm/window.py Outdated
Comment on lines +848 to +858
stage = "/tmp/sof-ucm-stage"
self.transport.run(
f"rm -rf {stage} && mkdir -p {stage} && "
f"for f in ucm.conf lib common codecs HDA; do "
f"[ -e /usr/share/alsa/ucm2/$f ] && ln -s /usr/share/alsa/ucm2/$f {stage}/$f; done"
)
for rel, content in self.profile.raw_files.items():
self.transport.write_text(posixpath.join(stage, rel.lstrip("/")), content, use_sudo=False)
rc, out, err = run_alsaucm_command(self.transport, cid, stage, cmds)
self.append_log(f"[SSH ALSAUCM rc={rc}] verb={verb} devices={devices}\n{out}\n{err}".strip())

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Three staging / export safety issues across lines 840-882:

  1. Predictable & leaked remote staging dir (lines 848-858): Hardcoding /tmp/sof-ucm-stage in world-writable /tmp collides across users/sessions and is never cleaned up after run_alsaucm_command(). Create it with mktemp -d /tmp/sof-ucm-stage.XXXXXX and remove it afterwards.
  2. Path traversal via raw_files keys (lines 840, 855, 879): Relative Include paths outside ucm_root_dir produce rel = posixpath.relpath(...) keys starting with ../ (ucm_parser.py:433). Verify os.path.commonpath([os.path.abspath(dest_root), os.path.abspath(full_path)]) == os.path.abspath(dest_root) before writing (especially in _on_save_folder_chosen when need_sudo=True runs pkexec).
  3. Per-file pkexec prompts (lines 878-881): Calling LocalTransport().write_text(..., use_sudo=True) inside the for rel, content in self.profile.raw_files.items(): loop spawns a separate Polkit password dialog for every file in the profile.

Comment thread sof-ucm/Makefile
Comment on lines +17 to +19
check:
$(PYTHON) -B -m py_compile sof-ucm $(PY_SRCS)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Run the tests/ suite here too (takes ~0.6s) so top-level make check / make test validates sof-ucm/tests as well as syntax:

Suggested change
check:
$(PYTHON) -B -m py_compile sof-ucm $(PY_SRCS)
check:
$(PYTHON) -B -m py_compile sof-ucm $(PY_SRCS) $(wildcard tests/*.py)
$(PYTHON) -B -m unittest discover -s tests

Comment on lines +136 to +146
def test_local_machine_card_discovery_and_render(self) -> None:
transport = LocalTransport()
snap = discover_machine_audio(transport, 2)
vm = build_end_to_end_graph(snap)
layout_end_to_end_graph(vm)
self.assertGreater(len(vm.nodes), 0)
pcm_nodes = [n for n in vm.nodes.values() if n.class_category == "PCM"]
ep_nodes = [n for n in vm.nodes.values() if n.class_category == "Endpoint"]
mid_nodes = [n for n in vm.nodes.values() if n.class_category not in ("PCM", "Endpoint", "Control")]
self.assertGreater(len(pcm_nodes), 0)
self.assertGreater(len(ep_nodes), 0)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hardcoding card 2 and asserting len(pcm_nodes) > 0 will fail on CI runners or containers with no ALSA sound cards (/proc/asound/cards empty or missing). Discover cards first and self.skipTest(...) when no local card with PCMs is present.

- `discovery.py`: Move SSH ControlPath to a `0700` `XDG_RUNTIME_DIR` / `~/.cache/sof-ucm` directory using `%C`, and append `--` before target host.
- `graph_canvas.py`, `window.py`: Key `_edge_tex_key` on highlighted edge/node `frozenset`s and bump `_edge_version` on trace clear/update to prevent stale cached trace highlights.
- `tplg_loader.py`: Remove premature `break` in multi-link blocks so all `DAI_LINK`/`BACKEND_LINK`/`CODEC_LINK` elements parse, add `<= block_end` private-data bounds checks in control and PCM parsing, and drop unused walrus assignment.
- `ucm_editor.py`: Escape Pango status markup via `GLib.markup_escape_text()` and track single-quoted strings in `check_ucm_syntax_balance()`.
- `ucm_serializer.py`, `model.py`: Escape backslashes and quotes in serialized strings, emit `SectionModifier.ConflictingDevice`, avoid duplicating foreign-`Include`d devices, and preserve existing conditional/include raw UCM2 files during `sync_profile_raw_files()`.
- `window.py`: Fix `alsaucm` command argument tokenization (`["set", "_verb", verb]`), enforce `commonpath` confinement on local/SSH staging and export, use `mktemp -d` + cleanup for remote staging, batch `pkexec` writes, run `set_kcontrol_value` off the GTK main loop, and wire `UndoRedoManager` (`Ctrl+Z` / `Ctrl+Y`).
- `Makefile`, `tests/`: Run unit tests in `sof-ucm/Makefile` `check`, guard local-card test with `skipTest`, and add regression tests for all review fixes.

Signed-off-by: Liam Girdwood <liam.r.girdwood@linux.intel.com>
@lgirdwood
lgirdwood merged commit 357b579 into main Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants