Repository navigation
sof-ucm: Add GTK4 end-to-end pipeline visualizer and ALSA UCM2 editor - #8
Conversation
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
left a comment
There was a problem hiding this comment.
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:
-
Bugs / Runtime Breakage:
Test (alsaucm)command tokenization (sof-ucm/sof_ucm/window.py:826-830):cmdspassesf"_verb {verb}"/f"_enadev {d}"as single strings instead of separate tokens, soalsaucm'sset IDENTIFIER VALUEconsumes the next command (list/set) asVALUEand fails withalsaucm: unknown command '_devices'.- Edge texture cache collision (
sof-ucm/sof_ucm/graph_canvas.py:1310-1319):_edge_tex_keykeys onlen(vm.highlighted_edge_ids)/len(vm.highlighted_node_ids)rather than the sets themselves (and_on_trace_nodedoesn't bump_edge_version), serving stale edge highlights when switching between equal-size traces. .tplglink loop & private-data bounds (sof-ucm/sof_ucm/tplg_loader.py:578-587): Unconditionalbreakon the first iteration ofDAI_LINK/BACKEND_LINK/CODEC_LINKdrops subsequent links whenhdr_count > 1, andcpriv_sz/pcm_priv_sizeshould check<= block_end.- Flattening of multi-file / conditional UCM2 profiles (
sof-ucm/sof_ucm/ucm_serializer.py:286-295): Callingsync_profile_raw_files()on existing profiles (likeIntel/sof-hda-dsp) overwritesHiFi.conffrom the host-evaluated flattened AST, strippingIf/Conditionblocks and duplicatingSectionDevices that came fromIncluded files. - Pango markup escaping & single-quoted UCM strings (
sof-ucm/sof_ucm/ucm_editor.py:38-62, 164-166, 191): EscapemsgwithGLib.markup_escape_text()beforeset_markup(), and track'...'alongside"..."incheck_ucm_syntax_balance().
-
Security / Filesystem Safety:
- Path confinement on
raw_filesexport/staging & batchedpkexec(sof-ucm/sof_ucm/window.py:840, 855, 878-881): RelativeIncludes outsideucm_root_diryield../keys inraw_files; validatecommonpathagainstdest_root/tmpdbefore writing (especially withpkexec), usemktemp -d+ cleanup for remote SSH staging instead of fixed/tmp/sof-ucm-stage, and batchpkexecwrites so saving doesn't prompt once per file. - SSH
ControlPath&--option terminator (sof-ucm/sof_ucm/discovery.py:140-155): MoveControlPathout of world-writable/tmpinto a0700runtime/cache dir (%C) and add"--"beforeself.target.
- Path confinement on
-
Build, Tests & Minor Notes:
- Wire
$(PYTHON) -B -m unittest discover -s testsintosof-ucm/Makefile'scheck:target, and guardtest_local_machine_card_discovery_and_render()(sof-ucm/tests/test_tplg_and_graph.py:136) withskipTestwhen 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) runsamixersynchronously on the GTK main thread (noticeable over higher-latency SSH).
- Wire
| 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 | ||
|
|
There was a problem hiding this comment.
Two SSH hardening fixes here:
ControlPathin world-writable/tmp:/tmp/sof-ucm-ssh-%r@%h:%pis predictable in/tmp(vulnerable to pre-created socket/symlink collisions on multi-user systems and108-byteUNIX_PATH_MAXlimits on long hostnames). Prefer placing the socket inos.environ.get("XDG_RUNTIME_DIR")or a0o700dir under~/.cache/sof-ucmusing OpenSSH's%Chash token.- Option injection via
self.target:self.ssh_entry(window.py:403) passes user input intoself.target; append"--", self.targetso a target starting with-(e.g.-oProxyCommand=...) cannot be parsed as ansshflag.
| 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: |
There was a problem hiding this comment.
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.
| 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 | ||
|
|
There was a problem hiding this comment.
- Line
586has an unconditionalbreak, so only the first link in any multi-elementDAI_LINK/BACKEND_LINK/CODEC_LINKblock (hdr_count > 1) is ever recorded. - Also in
_parse_single_control()(lines327,360,377) andSND_SOC_TPLG_TYPE_PCM(line563),cpriv_sz/pcm_priv_sizeis added tooffwithout checkingnext_off <= block_end(andSOF_TPLG_NUM_OUT_FALLBACK :=on line483is an unused walrus variable).
| 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>") | ||
|
|
There was a problem hiding this comment.
- Unescaped Pango markup (here and line
191):msg(especiallyf"Parse error: {exc}"in_on_apply_clicked) can contain<,>, or&, causingGtk.Label.set_markup()to emit a Pango parse warning and blank the status label. EscapemsgviaGLib.markup_escape_text(msg). - Single-quoted strings in
check_ucm_syntax_balance()(lines38-62):_tokenize_ucm()(ucm_parser.py:50) treats both"..."and'...'as string tokens, butcheck_ucm_syntax_balance()only tracksin_dquote, so#or[/]inside single-quoted control arguments (e.g.'HDMI [0] Switch') trigger false syntax errors.
| 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) | ||
|
|
There was a problem hiding this comment.
Two serialization issues when editing existing real-world UCM2 profiles (e.g. Intel/sof-hda-dsp):
- Flattening included / conditional sections:
load_ucm_profile()evaluatesIf/Conditionblocks against the current machine and mergesSectionDevices fromIncluded files intoverb.devices. Callingsync_profile_raw_files()on an inspector edit then overwritesmaster_keyandHiFi.conffrom the flattened AST — strippingIf/Condition/DefineRegex/Macroblocks whileserialize_master_conf()still emitsInclude.*.File, duplicating includedSectionDevices insideHiFi.conf. - String escaping &
SectionModifier.ConflictingDevice:serialize_master_conf()/serialize_verb_conf()(lines176,182,206,227,235,257,265,278) interpolateComment,Define, andValuestrings into"..."without escaping\or", andmod.conflicting_devices(parsed inucm_parser.py:418) is omitted inSectionModifier(lines262-281).
| cmds = ["set", f"_verb {verb}"] | ||
| for d in devices: | ||
| cmds.extend(["set", f"_enadev {d}"]) | ||
| cmds.extend(["list", "_devices"]) | ||
|
|
There was a problem hiding this comment.
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':
| 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"]) |
| 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()) | ||
|
|
There was a problem hiding this comment.
Three staging / export safety issues across lines 840-882:
- Predictable & leaked remote staging dir (
lines 848-858): Hardcoding/tmp/sof-ucm-stagein world-writable/tmpcollides across users/sessions and is never cleaned up afterrun_alsaucm_command(). Create it withmktemp -d /tmp/sof-ucm-stage.XXXXXXand remove it afterwards. - Path traversal via
raw_fileskeys (lines 840, 855, 879): RelativeIncludepaths outsideucm_root_dirproducerel = posixpath.relpath(...)keys starting with../(ucm_parser.py:433). Verifyos.path.commonpath([os.path.abspath(dest_root), os.path.abspath(full_path)]) == os.path.abspath(dest_root)before writing (especially in_on_save_folder_chosenwhenneed_sudo=Truerunspkexec). - Per-file
pkexecprompts (lines 878-881): CallingLocalTransport().write_text(..., use_sudo=True)inside thefor rel, content in self.profile.raw_files.items():loop spawns a separate Polkit password dialog for every file in the profile.
| check: | ||
| $(PYTHON) -B -m py_compile sof-ucm $(PY_SRCS) | ||
|
|
There was a problem hiding this comment.
Run the tests/ suite here too (takes ~0.6s) so top-level make check / make test validates sof-ucm/tests as well as syntax:
| 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 |
| 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) |
There was a problem hiding this comment.
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>
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, andalsaucmtesting.Key Capabilities
discovery.py,tplg_loader.py):amixer contentskcontrols, ASoC DAPM widgets/routes (/sys/kernel/debug/asoc), HDA codec widget graphs (/proc/asound/cardN/codec#*), SOF IPC4 topologies (.tplg), and/usr/share/alsa/ucm2configurations locally or over SSH (--ssh USER@HOST).graph_builder.py,layout.py):PCMs in a vertical left column, DSPPipelineContainers + DAPM/HDA codec widgets across center columns, and hardwareEndpoints (speakers, headphones, mics, jacks, line in/out, SPDIF, HDMI/DP, BT) in a vertical right column with attached kcontrol clusters.graph_canvas.py):Gtk.Snapshot/Gskand a cached Cairo edge/connector texture (sof-builderstyle), smooth pointer-anchored zoom & pan with drag cursors, grouped/claimed pointer gestures, interactive kcontrol sliders/switches/dropdowns, and headless PNG export (--render-png).ucm_parser.py,ucm_serializer.py,ucm_editor.py,left_panes.py,right_inspector.py,window.py):Record -> UCM) of kcontrol changes, New UCM Wizard, raw file tabs, validation diagnostics, andalsaucmverification.Makefile,README.md,packaging/rpm/sof-utils.spec):sof-ucmintobuild,install,uninstall,check,deb,rpm, andcleantargets.Testing
make -C /home/lrg/work/sof-utils check(py_compileclean acrosssof-builder,sof-ucm,sof-top)python3 -m unittest discover -s /home/lrg/work/sof-utils/sof-ucm/tests -v(6tests passed)dragon-fly) device, plus GTK4 gesture grouping/pan verification.