Repository navigation
Expand file tree
/
Copy pathtplg_binary.py
More file actions
1869 lines (1693 loc) · 81.9 KB
/
Copy pathtplg_binary.py
File metadata and controls
1869 lines (1693 loc) · 81.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: BSD-3-Clause
"""Binary ALSA .tplg source identification and editable GraphViewModel reconstruction."""
from __future__ import annotations
from dataclasses import dataclass, field
import io
import os
import re
import shutil
import subprocess
import tarfile
from typing import Any, Dict, List, Optional, Set, Tuple
from .model import (
CMakeTargetVariant,
ConfigNode,
GraphEdge,
GraphNode,
GraphPort,
GraphViewModel,
MachineTopologyEntry,
PipelineContainer,
TplgClassDef,
discover_all_topology2_dirs,
parse_abi_header_text,
read_workspace_sof_abi,
resolve_sof_and_workspace_roots,
)
from . import parser as _parser_mod
from . import tplg_ipc4 as _ipc4
# Fallback UUID -> Widget class mapping when workspace include/components is unavailable or incomplete
_KNOWN_UUID_CLASS_HINTS: Dict[str, str] = {
"a8a9bc61d018184a8e7b2639219804b7": "gain",
"b26e6539713b49408d3ff92cd5c43c09": "mixin",
"5a50563cd7248f41bddcc1f5a3ac2ae0": "mixout",
"e6c05051f927c84e8351c705b642d12f": "eq-iir",
"e70ca943a5f3df41ac06ba98651ae6a3": "eq-fir",
"dae46eb36f00f947a06dfecbe2d8b6ce": "drc",
"491751ddfad95c45b3a713585693f1af": "tdfb",
"1e967a16e48aea1189f1000c29ce1635": "kpb",
"6c8a4f213a491e4b8b1e0d3b6f8a2c15": "ecns",
"7d6c5b4a9f8e1b4a2c3d4e5f60718293": "wov-arbiter",
"329ab5f7a5559f4c9004984c47678791": "mfcc",
"a771e67a1746094abf6d9d2975b68791": "mww",
"f9401882d5f24a4cb46842c24d262e12": "mww",
"4fc35fd90f37c74abc86bfdc83f169a1": "wov",
"6838be396ccb334694472379089c592f": "src",
}
_DAPM_TYPE_CLASS_HINTS: Dict[int, str] = {
_ipc4.SND_SOC_TPLG_DAPM_AIF_IN: "host-copier",
_ipc4.SND_SOC_TPLG_DAPM_AIF_OUT: "host-copier",
_ipc4.SND_SOC_TPLG_DAPM_DAI_IN: "dai-copier",
_ipc4.SND_SOC_TPLG_DAPM_DAI_OUT: "dai-copier",
_ipc4.SND_SOC_TPLG_DAPM_BUFFER: "module-copier",
_ipc4.SND_SOC_TPLG_DAPM_PGA: "gain",
_ipc4.SND_SOC_TPLG_DAPM_MIXER: "mixin",
_ipc4.SND_SOC_TPLG_DAPM_SRC: "src",
_ipc4.SND_SOC_TPLG_DAPM_ASRC: "asrc",
_ipc4.SND_SOC_TPLG_DAPM_SIGGEN: "siggen",
_ipc4.SND_SOC_TPLG_DAPM_EFFECT: "process",
}
_PREFIX_CLASS_HINTS: Tuple[Tuple[str, str], ...] = (
("host-copier", "host-copier"),
("dai-copier", "dai-copier"),
("alh-copier", "alh-dai-copier"),
("alh-dai-copier", "alh-dai-copier"),
("module-copier", "module-copier"),
("copier.host", "host-copier"),
("copier.dai", "dai-copier"),
("copier.alh", "alh-dai-copier"),
("wov-arbiter", "wov-arbiter"),
("smart_amp", "smart_amp"),
("eqiir", "eq-iir"),
("eq-iir", "eq-iir"),
("eqfir", "eq-fir"),
("eq-fir", "eq-fir"),
("dcblock", "dcblock"),
("multiband_drc", "multiband_drc"),
("crossover", "crossover"),
("mixin", "mixin"),
("mixout", "mixout"),
("gain", "gain"),
("siggen", "siggen"),
("kpb", "kpb"),
("mfcc", "mfcc"),
("mww", "mww"),
("ecns", "ecns"),
("tdfb", "tdfb"),
("drc", "drc"),
("src", "src"),
("asrc", "asrc"),
("wov", "wov"),
("aria", "aria"),
)
@dataclass
class TplgDiffReport:
"""Structural & parameter comparison between a parsed .tplg binary and a source GraphViewModel."""
similarity_pct: float = 0.0
is_exact: bool = False
missing_pipelines_in_source: List[int] = field(default_factory=list)
extra_pipelines_in_source: List[int] = field(default_factory=list)
missing_widgets_in_source: List[str] = field(default_factory=list)
extra_widgets_in_source: List[str] = field(default_factory=list)
missing_routes_in_source: List[Tuple[str, str]] = field(default_factory=list)
extra_routes_in_source: List[Tuple[str, str]] = field(default_factory=list)
param_diffs: List[str] = field(default_factory=list)
summary: str = ""
@dataclass
class TplgBinaryVersionInfo:
"""Decoded ABI, protocol, and ALSA manifest version metadata extracted from a .tplg binary."""
ipc_protocol: str = "" # "IPC4", "IPC3", or ""
sof_abi_major: Optional[int] = None
sof_abi_minor: Optional[int] = None
sof_abi_patch: Optional[int] = None
sof_abi_str: str = ""
sof_abi_bytes: bytes = b""
tplg_abi_version: int = 0
tplg_version: int = 0
@property
def sof_abi_tuple(self) -> Optional[Tuple[int, int, int]]:
if (
self.sof_abi_major is None
or self.sof_abi_minor is None
or self.sof_abi_patch is None
):
return None
return (self.sof_abi_major, self.sof_abi_minor, self.sof_abi_patch)
@property
def label(self) -> str:
parts: List[str] = []
if self.ipc_protocol:
parts.append(self.ipc_protocol)
if self.sof_abi_str:
parts.append(f"SOF ABI {self.sof_abi_str}")
if self.tplg_abi_version:
parts.append(f"tplg ABI v{self.tplg_abi_version}")
return " • ".join(parts) if parts else "Unknown binary version"
@dataclass
class WorkspaceVersionMatch:
"""Result of resolving a version-matched topology2 workspace for a compiled .tplg binary."""
workspace: Optional[object] = None
workspace_abi: Optional[Tuple[int, int, int]] = None
binary_abi: Optional[Tuple[int, int, int]] = None
status: str = "no_workspace" # exact, compatible, git_snapshot, ipc3_unsupported, mismatch, unknown_binary_abi, no_workspace
source_desc: str = ""
snapshot_commit: str = ""
def extract_tplg_version_info(tplg: _ipc4.TplgIpc4Topology) -> TplgBinaryVersionInfo:
"""Extract protocol, SOF ABI version, and ALSA manifest version from a parsed .tplg."""
sof_bytes = bytes(getattr(tplg, "sof_abi_bytes", b"") or b"")
raw_maj = getattr(tplg, "sof_abi_major", None)
raw_min = getattr(tplg, "sof_abi_minor", None)
raw_pat = getattr(tplg, "sof_abi_patch", None)
has_decoded_abi = bool(sof_bytes) and raw_maj is not None and int(raw_maj) > 0
return TplgBinaryVersionInfo(
ipc_protocol=str(getattr(tplg, "ipc_protocol", "") or ""),
sof_abi_major=int(raw_maj) if has_decoded_abi else None,
sof_abi_minor=int(raw_min) if (has_decoded_abi and raw_min is not None) else None,
sof_abi_patch=int(raw_pat) if (has_decoded_abi and raw_pat is not None) else None,
sof_abi_str=str(getattr(tplg, "sof_abi_str", "") or "") if has_decoded_abi else "",
sof_abi_bytes=sof_bytes,
tplg_abi_version=int(getattr(tplg, "abi_version", 0) or 0),
tplg_version=int(getattr(tplg, "tplg_version", 0) or 0),
)
VERSIONED_SNAPSHOT_SUBDIR = os.path.join("sof-builder", "versioned-sources")
def is_versioned_snapshot_path(path: str) -> bool:
"""Return True if path resides inside a read-only cached versioned-sources git snapshot."""
if not path:
return False
abs_p = os.path.abspath(path)
default_cache = os.path.abspath(os.path.join(os.path.expanduser("~"), ".cache", VERSIONED_SNAPSHOT_SUBDIR))
try:
if os.path.commonpath([abs_p, default_cache]) == default_cache:
return True
except ValueError:
pass
cur = os.path.dirname(abs_p) if not os.path.isdir(abs_p) else abs_p
for _ in range(8):
if os.path.isfile(os.path.join(cur, ".snapshot_ready")):
return True
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent
return False
@dataclass
class TplgSourceMatchResult:
"""Candidate source .conf + CMake variant matched against a compiled .tplg binary."""
conf_path: str
rel_path: str
entry: Optional[MachineTopologyEntry]
variant: Optional[CMakeTargetVariant]
match_reason: str
diff: TplgDiffReport
source_vm: Optional[GraphViewModel] = None
version_info: Optional[TplgBinaryVersionInfo] = None
version_match: Optional[WorkspaceVersionMatch] = None
_VERSIONED_WORKSPACE_CACHE: Dict[str, object] = {}
def _load_or_reuse_workspace(
topology2_root: str,
current_ws: Optional[object] = None,
) -> Optional[object]:
"""Return a scanned Topology2Workspace for topology2_root, reusing caches when available."""
abs_root = os.path.abspath(topology2_root)
if current_ws is not None and os.path.abspath(getattr(current_ws, "root_dir", "")) == abs_root:
_VERSIONED_WORKSPACE_CACHE[abs_root] = current_ws
return current_ws
cached = _VERSIONED_WORKSPACE_CACHE.get(abs_root)
if cached is not None:
return cached
if not os.path.isdir(abs_root):
return None
ws = _parser_mod.Topology2Workspace(abs_root)
ws.scan_all()
_VERSIONED_WORKSPACE_CACHE[abs_root] = ws
return ws
def _git_top_level(path: str) -> str:
"""Return the enclosing git repository root for path, or '' if not a git repo."""
if not path or not os.path.isdir(path):
return ""
try:
res = subprocess.run(
["git", "-C", path, "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
check=True,
timeout=3,
)
top = res.stdout.strip()
return os.path.abspath(top) if top and os.path.isdir(top) else ""
except Exception:
return ""
def _git_show_abi(git_root: str, ref_spec: str, abi_rel: str) -> Optional[Tuple[int, int, int]]:
"""Read and parse kernel/abi.h from a specific git revision without touching working tree."""
try:
res = subprocess.run(
["git", "-C", git_root, "show", f"{ref_spec}:{abi_rel}"],
capture_output=True,
text=True,
check=True,
timeout=3,
)
return parse_abi_header_text(res.stdout)
except Exception:
return None
def _find_git_commit_for_abi(
topology2_dir: str,
target_abi: Tuple[int, int, int],
) -> Optional[Tuple[str, str, str, str]]:
"""Search read-only git history for a commit whose abi.h matches target_abi.
Returns `(git_root, commit_sha, tplg_rel_subpath, abi_rel_path)` or None.
"""
norm_t2 = os.path.abspath(topology2_dir)
sof_root, _ = resolve_sof_and_workspace_roots(norm_t2)
tplg_repo = _git_top_level(norm_t2)
sof_repo = _git_top_level(sof_root) if sof_root else ""
# Candidate pairs of (git_repo_root, abi_rel_path, tplg_rel_subpath)
repo_specs: List[Tuple[str, str, str]] = []
if sof_repo:
t2_rel = os.path.relpath(norm_t2, sof_repo)
if not t2_rel.startswith(".."):
repo_specs.append((sof_repo, "src/include/kernel/abi.h", t2_rel))
if tplg_repo and tplg_repo != sof_repo:
t2_rel = os.path.relpath(norm_t2, tplg_repo)
if not t2_rel.startswith(".."):
for abi_cand in ("include/kernel/abi.h", "src/include/kernel/abi.h", "topology2/abi.h"):
repo_specs.append((tplg_repo, abi_cand, t2_rel))
for git_root, abi_rel, tplg_rel in repo_specs:
try:
log_res = subprocess.run(
["git", "-C", git_root, "log", "-n", "120", "--format=%H", "--", abi_rel],
capture_output=True,
text=True,
check=True,
timeout=5,
)
except Exception:
continue
commits = [c.strip() for c in log_res.stdout.splitlines() if c.strip()]
seen_revs: Set[str] = set()
revs_to_check: List[str] = []
# Pass 1: direct commits touching abi.h (newest first, e.g. revert/bump target)
for sha in commits:
if sha not in seen_revs:
seen_revs.add(sha)
revs_to_check.append(sha)
# Pass 2: parents right before an ABI bump commit
for sha in commits:
try:
p_res = subprocess.run(
["git", "-C", git_root, "rev-parse", "--verify", f"{sha}^"],
capture_output=True,
text=True,
check=True,
timeout=3,
)
parent_sha = p_res.stdout.strip()
except Exception:
parent_sha = ""
if parent_sha and parent_sha not in seen_revs:
seen_revs.add(parent_sha)
revs_to_check.append(parent_sha)
for rev in revs_to_check:
parsed = _git_show_abi(git_root, rev, abi_rel)
if parsed == target_abi:
chk = subprocess.run(
["git", "-C", git_root, "cat-file", "-e", f"{rev}:{tplg_rel}"],
capture_output=True,
timeout=3,
)
if chk.returncode == 0:
return (git_root, rev, tplg_rel, abi_rel)
return None
def _make_tree_readonly(root_dir: str) -> None:
"""Recursively mark snapshot files 0o444 and subdirectories 0o555 to keep cache immutable."""
dir_paths: List[str] = []
for cur_dir, _dirs, files in os.walk(root_dir):
for fn in files:
fpath = os.path.join(cur_dir, fn)
try:
os.chmod(fpath, 0o444)
except OSError:
pass
if os.path.abspath(cur_dir) != os.path.abspath(root_dir):
dir_paths.append(cur_dir)
for dpath in reversed(dir_paths):
try:
os.chmod(dpath, 0o555)
except OSError:
pass
def _rmtree_writable(root_dir: str) -> None:
if not os.path.exists(root_dir):
return
for cur_dir, dirs, files in os.walk(root_dir):
try:
os.chmod(cur_dir, 0o755)
except OSError:
pass
for dn in dirs:
try:
os.chmod(os.path.join(cur_dir, dn), 0o755)
except OSError:
pass
for fn in files:
try:
os.chmod(os.path.join(cur_dir, fn), 0o644)
except OSError:
pass
shutil.rmtree(root_dir, ignore_errors=True)
def _materialize_git_topology_snapshot(
git_root: str,
commit_sha: str,
tplg_rel: str,
abi_rel: str,
target_abi: Tuple[int, int, int],
cache_root: Optional[str] = None,
) -> Optional[str]:
"""Extract historical topology2 + abi.h via `git archive` into a read-only cache dir."""
base_cache = cache_root or os.path.join(
os.path.expanduser("~"), ".cache", VERSIONED_SNAPSHOT_SUBDIR
)
ver_tag = f"{target_abi[0]}.{target_abi[1]}.{target_abi[2]}"
snap_root = os.path.join(base_cache, f"{commit_sha[:12]}-abi-{ver_tag}")
snap_tplg_dir = os.path.join(snap_root, tplg_rel)
marker = os.path.join(snap_root, ".snapshot_ready")
if os.path.isfile(marker) and os.path.isdir(snap_tplg_dir):
return snap_tplg_dir
tmp_root = f"{snap_root}.tmp.{os.getpid()}"
try:
_rmtree_writable(tmp_root)
os.makedirs(tmp_root, exist_ok=True)
proc = subprocess.run(
["git", "-C", git_root, "archive", "--format=tar", commit_sha, tplg_rel, abi_rel],
capture_output=True,
check=True,
timeout=20,
)
with tarfile.open(fileobj=io.BytesIO(proc.stdout), mode="r:") as tf:
# Safe extraction inside tmp_root (filter out any non-relative entries)
safe_members = [
m for m in tf.getmembers()
if not m.name.startswith("/") and ".." not in m.name.split("/")
]
try:
tf.extractall(tmp_root, members=safe_members, filter="data")
except TypeError:
tf.extractall(tmp_root, members=safe_members)
with open(os.path.join(tmp_root, ".snapshot_ready"), "w", encoding="utf-8") as mf:
mf.write(f"{commit_sha}\n{ver_tag}\n")
_make_tree_readonly(tmp_root)
if os.path.isdir(snap_root):
_rmtree_writable(snap_root)
os.makedirs(os.path.dirname(snap_root), exist_ok=True)
os.replace(tmp_root, snap_root)
return snap_tplg_dir if os.path.isdir(snap_tplg_dir) else None
except Exception:
_rmtree_writable(tmp_root)
return None
def resolve_workspace_for_binary(
bin_ver: TplgBinaryVersionInfo,
current_ws: Optional[object] = None,
cache_root: Optional[str] = None,
) -> Tuple[Optional[object], WorkspaceVersionMatch]:
"""Locate or materialize the Topology2Workspace whose ABI best matches a .tplg binary."""
preferred_dir = str(getattr(current_ws, "root_dir", "") or "")
candidate_dirs = discover_all_topology2_dirs(preferred_dir=preferred_dir)
if current_ws is not None and os.path.isdir(preferred_dir):
abs_pref = os.path.abspath(preferred_dir)
if abs_pref not in candidate_dirs:
candidate_dirs.insert(0, abs_pref)
if not candidate_dirs and current_ws is None:
return (
None,
WorkspaceVersionMatch(
workspace=None,
binary_abi=bin_ver.sof_abi_tuple,
status="no_workspace",
source_desc="No topology2 source workspace found locally",
),
)
fallback_dir = preferred_dir or (candidate_dirs[0] if candidate_dirs else "")
fallback_abi = read_workspace_sof_abi(fallback_dir) if fallback_dir else None
if bin_ver.ipc_protocol == "IPC3":
ws_obj = current_ws if current_ws is not None else _load_or_reuse_workspace(fallback_dir, current_ws)
return (
ws_obj,
WorkspaceVersionMatch(
workspace=ws_obj,
workspace_abi=fallback_abi,
binary_abi=bin_ver.sof_abi_tuple,
status="ipc3_unsupported",
source_desc=(
f"Binary uses {bin_ver.label}; topology2 sources only build IPC4 binaries "
"(opening decoded binary view)"
),
),
)
target_abi = bin_ver.sof_abi_tuple
if target_abi is None:
ws_obj = current_ws if current_ws is not None else _load_or_reuse_workspace(fallback_dir, current_ws)
return (
ws_obj,
WorkspaceVersionMatch(
workspace=ws_obj,
workspace_abi=fallback_abi,
binary_abi=None,
status="unknown_binary_abi",
source_desc="Binary manifest has no SOF ABI version; using local workspace",
),
)
# 1. Inspect local checkouts for exact SOF ABI match (major, minor, patch)
local_entries: List[Tuple[str, Optional[Tuple[int, int, int]]]] = []
for cdir in candidate_dirs:
w_abi = read_workspace_sof_abi(cdir)
local_entries.append((cdir, w_abi))
if w_abi == target_abi:
ws_obj = _load_or_reuse_workspace(cdir, current_ws)
ver_s = f"{w_abi[0]}.{w_abi[1]}.{w_abi[2]}"
return (
ws_obj,
WorkspaceVersionMatch(
workspace=ws_obj,
workspace_abi=w_abi,
binary_abi=target_abi,
status="exact",
source_desc=f"Exact ABI {ver_s} match ({cdir})",
),
)
# 2. Search read-only git history across known checkouts and cache a historical snapshot
for cdir, _ in local_entries:
found = _find_git_commit_for_abi(cdir, target_abi)
if found is not None:
git_root, sha, tplg_rel, abi_rel = found
snap_dir = _materialize_git_topology_snapshot(
git_root, sha, tplg_rel, abi_rel, target_abi, cache_root=cache_root
)
if snap_dir:
ws_obj = _load_or_reuse_workspace(snap_dir, None)
if ws_obj is not None:
ver_s = f"{target_abi[0]}.{target_abi[1]}.{target_abi[2]}"
return (
ws_obj,
WorkspaceVersionMatch(
workspace=ws_obj,
workspace_abi=target_abi,
binary_abi=target_abi,
status="git_snapshot",
snapshot_commit=sha,
source_desc=f"Git snapshot commit {sha[:10]} matching SOF ABI {ver_s}",
),
)
# 3. Choose closest compatible local checkout (same major.minor preferred)
best_dir = fallback_dir
best_abi = fallback_abi
best_score = (99, 9999, 9999)
for idx, (cdir, w_abi) in enumerate(local_entries):
if w_abi is None:
score = (10, 9999, idx)
elif w_abi[0] == target_abi[0] and w_abi[1] == target_abi[1]:
score = (0, abs(w_abi[2] - target_abi[2]), idx)
elif w_abi[0] == target_abi[0]:
score = (1, abs(w_abi[1] - target_abi[1]) * 100 + abs(w_abi[2] - target_abi[2]), idx)
else:
score = (2, abs(w_abi[0] - target_abi[0]) * 1000, idx)
if score < best_score:
best_score = score
best_dir = cdir
best_abi = w_abi
ws_obj = _load_or_reuse_workspace(best_dir, current_ws)
bin_s = f"{target_abi[0]}.{target_abi[1]}.{target_abi[2]}"
ws_s = f"{best_abi[0]}.{best_abi[1]}.{best_abi[2]}" if best_abi else "unknown"
if best_abi and best_abi[0] == target_abi[0] and best_abi[1] == target_abi[1]:
return (
ws_obj,
WorkspaceVersionMatch(
workspace=ws_obj,
workspace_abi=best_abi,
binary_abi=target_abi,
status="compatible",
source_desc=f"Compatible local workspace ABI {ws_s} (binary is {bin_s})",
),
)
return (
ws_obj,
WorkspaceVersionMatch(
workspace=ws_obj,
workspace_abi=best_abi,
binary_abi=target_abi,
status="mismatch",
source_desc=f"ABI mismatch: binary is {bin_s}, local workspace is {ws_s}",
),
)
def _uuid_str_to_hex(uuid_str: str) -> str:
"""Normalize colon-separated or dashed UUID strings to lowercase 32-hex chars."""
cleaned = re.sub(r"[^0-9a-fA-F]", "", str(uuid_str or ""))
return cleaned.lower() if len(cleaned) == 32 else ""
def _uuid_bytes_to_colon(uuid_bytes: bytes) -> str:
return ":".join(f"{b:02X}" for b in uuid_bytes)
def _jaccard(a: set, b: set) -> float:
if not a and not b:
return 1.0
if not a or not b:
return 0.0
return len(a & b) / len(a | b)
def _extract_binary_fingerprint(tplg: _ipc4.TplgIpc4Topology) -> Tuple[Set[int], Set[str], Set[Tuple[str, str]], Set[int]]:
pipe_ids = set(tplg.pipelines.keys())
widgets = {
w.name for w in tplg.widgets
if w.pipeline_id in pipe_ids and any(w.orig_uuid_bytes)
}
routes = {
(r.source_name, r.sink_name) for r in tplg.routes
if r.source_name in widgets and r.sink_name in widgets
}
pcms = {p.pcm_id for p in tplg.pcms}
return pipe_ids, widgets, routes, pcms
def _extract_vm_fingerprint(vm: GraphViewModel) -> Tuple[Set[int], Set[str], Set[Tuple[str, str]], Set[int]]:
pipe_ids = set(vm.containers.keys())
widgets = {
nid for nid, n in vm.nodes.items()
if n.class_category == "Widget" and n.class_name not in ("pipeline", "virtual")
}
routes = {
(e.source_node, e.sink_node) for e in vm.edges
if e.source_node in widgets and e.sink_node in widgets
}
pcms: Set[int] = set()
for n in vm.nodes.values():
if n.class_category == "Widget":
raw_pid = n.config.get_scalar("pcm_id")
if raw_pid is not None and str(raw_pid).lstrip("-").isdigit():
pcms.add(int(str(raw_pid)))
return pipe_ids, widgets, routes, pcms
def diff_binary_vs_source(tplg: _ipc4.TplgIpc4Topology, vm: GraphViewModel) -> TplgDiffReport:
"""Compute similarity score and structural differences between a .tplg binary and source VM."""
b_pipes, b_widgets, b_routes, b_pcms = _extract_binary_fingerprint(tplg)
s_pipes, s_widgets, s_routes, s_pcms = _extract_vm_fingerprint(vm)
pipe_sim = _jaccard(b_pipes, s_pipes)
wid_sim = _jaccard(b_widgets, s_widgets)
route_sim = _jaccard(b_routes, s_routes)
pcm_sim = _jaccard(b_pcms, s_pcms)
score = 100.0 * (0.30 * pipe_sim + 0.40 * wid_sim + 0.15 * route_sim + 0.15 * pcm_sim)
miss_p = sorted(b_pipes - s_pipes)
extra_p = sorted(s_pipes - b_pipes)
miss_w = sorted(b_widgets - s_widgets)
extra_w = sorted(s_widgets - b_widgets)
miss_r = sorted(b_routes - s_routes)
extra_r = sorted(s_routes - b_routes)
miss_pcm = sorted(b_pcms - s_pcms)
extra_pcm = sorted(s_pcms - b_pcms)
def _collect_src_pin_fmt_sets(
cfg: ConfigNode, block_key: str, prefix: str
) -> Tuple[Set[int], Set[int], Set[int], Set[int], Set[str], Set[str]]:
rates: Set[int] = set()
chs: Set[int] = set()
bds: Set[int] = set()
vbds: Set[int] = set()
stypes: Set[str] = set()
ils: Set[str] = set()
def _extract_node_scalars(item: ConfigNode, fname: str) -> List[str]:
sub = item.get_child(fname)
if sub is None:
return []
if sub.node_type == "scalar":
sv = str(sub.value).strip()
return [sv] if sv else []
out: List[str] = []
for x in sub.children:
cand = str(x.value if str(x.value or "") != "" else x.key).strip()
if cand:
out.append(cand)
return out
def _norm_st(raw_st: str) -> str:
u = raw_st.strip().strip('"').strip("'").upper()
if "FLOAT" in u or u == "4":
return "float"
if "UNSIGNED" in u or u == "3":
return "unsigned"
if "SIGNED" in u or u == "2":
return "signed"
if "MSB" in u or u == "0":
return "msb"
if "LSB" in u or u == "1":
return "lsb"
if "A_LAW" in u or u == "5":
return "a_law"
if "MU_LAW" in u or u == "6":
return "mu_law"
return u.lower()
def _norm_il(raw_il: str) -> str:
u = raw_il.strip().strip('"').strip("'").lower()
if "non" in u or u == "1":
return "non-interleaved"
if "interleaved" in u or u == "0":
return "interleaved"
return u
fmt_roots = [
c for c in cfg.children
if c.key in (block_key, f"CombineArrays.{block_key}") and c.children
]
for fmt_root in fmt_roots:
for item in fmt_root.children:
for r_s in _extract_node_scalars(item, f"{prefix}rate"):
if r_s.isdigit() and int(r_s) > 0:
rates.add(int(r_s))
for c_s in _extract_node_scalars(item, f"{prefix}channels"):
if c_s.isdigit() and int(c_s) > 0:
chs.add(int(c_s))
for bd_s in _extract_node_scalars(item, f"{prefix}bit_depth"):
if bd_s.isdigit() and int(bd_s) > 0:
bds.add(int(bd_s))
for vbd_s in _extract_node_scalars(item, f"{prefix}valid_bit_depth"):
if vbd_s.isdigit() and int(vbd_s) > 0:
vbds.add(int(vbd_s))
for st_s in _extract_node_scalars(item, f"{prefix}sample_type"):
nst = _norm_st(st_s)
if nst:
stypes.add(nst)
for il_s in _extract_node_scalars(item, f"{prefix}interleaving_style"):
nil = _norm_il(il_s)
if nil:
ils.add(nil)
if fmt_roots:
if not stypes:
stypes.add("lsb")
if not ils:
ils.add("interleaved")
return rates, chs, bds, vbds, stypes, ils
_stype_idx_map = {
0: "msb", 1: "lsb", 2: "signed", 3: "unsigned",
4: "float", 5: "a_law", 6: "mu_law",
}
_curve_map = {
"windows_no_fade": 0, "windows_fade": 1, "linear": 2,
"log": 3, "linear_zc": 4, "log_zc": 5,
}
def _parse_int_opt(raw_v: Any) -> Optional[int]:
s = str(raw_v or "").strip().strip('"').strip("'")
if not s or s.startswith("$"):
return None
try:
return int(s, 0)
except ValueError:
return None
def _parse_bytes_hex_str(raw_v: str) -> Optional[bytes]:
toks = [t for t in re.split(r"[\s,]+", str(raw_v or "").strip().strip('"').strip("'")) if t]
if not toks:
return None
out = bytearray()
for t in toks:
try:
v = int(t, 16) if t.lower().startswith("0x") or any(c in "abcdefABCDEF" for c in t) else int(t, 10)
except ValueError:
return None
if not (0 <= v <= 255):
return None
out.append(v)
return bytes(out)
def _src_controls_for(sn: GraphNode) -> List[Tuple[str, ConfigNode]]:
ctl_nodes = [
(c.class_name, c.config)
for c in vm.nodes.values()
if c.parent_node_id == sn.id and c.class_category == "Control"
]
if ctl_nodes:
return ctl_nodes
cg = sn.config.get_child("Object.Control")
if cg is None:
return []
return [(ch.key.split(".", 1)[0], ch) for ch in cg.children]
param_diffs: List[str] = []
for bw in tplg.widgets:
if bw.name not in vm.nodes:
continue
sn = vm.nodes[bw.name]
s_in = len(sn.in_ports)
s_out = len(sn.out_ports)
if bw.num_input_pins != s_in:
param_diffs.append(f"{bw.name}: input_pins bin={bw.num_input_pins} vs src={s_in}")
if bw.num_output_pins != s_out:
param_diffs.append(f"{bw.name}: output_pins bin={bw.num_output_pins} vs src={s_out}")
b_cpc = bw.word_tokens.get(_ipc4.SOF_TKN_COMP_CPC, 0)
s_cpc_raw = _parse_int_opt(sn.config.get_scalar("cpc", ""))
if b_cpc and s_cpc_raw is not None and s_cpc_raw != b_cpc:
param_diffs.append(f"{bw.name}: cpc bin={b_cpc} vs src={s_cpc_raw}")
# Component-specific decoded parameters (gain/ramp, SRC, ASRC)
if sn.class_name == "gain" or bw.orig_dapm_type == _ipc4.SND_SOC_TPLG_DAPM_PGA:
if _ipc4.SOF_TKN_GAIN_RAMP_TYPE in bw.word_tokens or bw.pga_curve_type != 0:
s_ct_raw = str(sn.config.get_scalar("curve_type", "") or "").strip().lower()
s_ct = _curve_map.get(s_ct_raw, _parse_int_opt(s_ct_raw))
if s_ct is not None and s_ct != bw.pga_curve_type:
param_diffs.append(f"{bw.name}: curve_type bin={bw.pga_curve_type} vs src={s_ct_raw}")
if _ipc4.SOF_TKN_GAIN_RAMP_DURATION in bw.word_tokens or bw.pga_curve_duration != 0:
s_cd = _parse_int_opt(sn.config.get_scalar("curve_duration", ""))
if s_cd is not None and s_cd != bw.pga_curve_duration:
param_diffs.append(f"{bw.name}: curve_duration bin={bw.pga_curve_duration} vs src={s_cd}")
if _ipc4.SOF_TKN_GAIN_VAL in bw.word_tokens or bw.pga_target_volume != 0x7FFFFFFF:
s_iv = _parse_int_opt(sn.config.get_scalar("init_value", ""))
if s_iv is not None and s_iv != bw.pga_target_volume:
param_diffs.append(f"{bw.name}: init_value bin={bw.pga_target_volume} vs src={s_iv}")
elif sn.class_name == "src" or bw.orig_dapm_type == _ipc4.SND_SOC_TPLG_DAPM_SRC:
if _ipc4.SOF_TKN_SRC_RATE_IN in bw.word_tokens:
s_ri = _parse_int_opt(sn.config.get_scalar("rate_in", ""))
b_ri = bw.word_tokens[_ipc4.SOF_TKN_SRC_RATE_IN]
if s_ri is not None and s_ri != b_ri:
param_diffs.append(f"{bw.name}: src rate_in bin={b_ri} vs src={s_ri}")
if _ipc4.SOF_TKN_SRC_RATE_OUT in bw.word_tokens or bw.src_sink_rate > 0:
s_ro = _parse_int_opt(sn.config.get_scalar("rate_out", ""))
b_ro = bw.src_sink_rate or bw.word_tokens.get(_ipc4.SOF_TKN_SRC_RATE_OUT, 0)
if s_ro is not None and b_ro and s_ro != b_ro:
param_diffs.append(f"{bw.name}: src rate_out bin={b_ro} vs src={s_ro}")
elif sn.class_name == "asrc" or bw.orig_dapm_type == _ipc4.SND_SOC_TPLG_DAPM_ASRC:
if _ipc4.SOF_TKN_ASRC_RATE_OUT in bw.word_tokens or bw.asrc_out_freq > 0:
s_ao = _parse_int_opt(sn.config.get_scalar("rate_out", ""))
b_ao = bw.asrc_out_freq or bw.word_tokens.get(_ipc4.SOF_TKN_ASRC_RATE_OUT, 0)
if s_ao is not None and b_ao and s_ao != b_ao:
param_diffs.append(f"{bw.name}: asrc rate_out bin={b_ao} vs src={s_ao}")
if _ipc4.SOF_TKN_ASRC_OPERATION_MODE in bw.word_tokens or bw.asrc_mode != 0:
s_am = _parse_int_opt(sn.config.get_scalar("operation_mode", ""))
if s_am is not None and s_am != bw.asrc_mode:
param_diffs.append(f"{bw.name}: asrc mode bin={bw.asrc_mode} vs src={s_am}")
# Compare kcontrol metadata and bytes-control payloads
if bw.orig_kcontrols:
src_ctls = _src_controls_for(sn)
used_src_idxs: Set[int] = set()
for kc in bw.orig_kcontrols:
if kc.ops_info == _ipc4.SND_SOC_TPLG_CTL_BYTES or kc.ctl_type == _ipc4.SND_SOC_TPLG_TYPE_BYTES:
ktype = "bytes"
elif kc.enum_texts or kc.ctl_type == _ipc4.SND_SOC_TPLG_TYPE_ENUM:
ktype = "enum"
else:
ktype = "mixer"
match_i = next(
(
i for i, (st, scfg) in enumerate(src_ctls)
if i not in used_src_idxs
and st == ktype
and str(scfg.get_scalar("name", "") or "").strip() == kc.name
),
None,
)
if match_i is None:
match_i = next(
(i for i, (st, _scfg) in enumerate(src_ctls) if i not in used_src_idxs and st == ktype),
None,
)
if match_i is None:
param_diffs.append(f"{bw.name}: missing {ktype} control '{kc.name}'")
continue
used_src_idxs.add(match_i)
_, scfg = src_ctls[match_i]
if ktype == "bytes":
b_payload = kc.raw_priv_data or kc.abi_data
s_hex = str(scfg.get_scalar("bytes_hex", "") or "").strip()
if not s_hex:
data_grp = next((ch for ch in scfg.children if ch.key.startswith("Object.Base.data")), None)
if data_grp is not None:
s_hex = str(data_grp.get_scalar("bytes", "") or "").strip()
s_payload = _parse_bytes_hex_str(s_hex) if s_hex else None
if s_payload is not None:
if s_payload != b_payload:
param_diffs.append(f"{bw.name}: bytes control '{kc.name}' payload differs")
elif b_payload:
inc_p = str(scfg.get_scalar("included_param_file", "") or "").strip()
param_diffs.append(
f"{bw.name}: bytes control '{kc.name}' payload equivalence unverified ({inc_p or 'include'})"
)
elif ktype == "mixer":
s_min = _parse_int_opt(scfg.get_scalar("min", ""))
s_max = _parse_int_opt(scfg.get_scalar("max", ""))
if s_min is not None and s_min != kc.min_val:
param_diffs.append(f"{bw.name}: mixer '{kc.name}' min bin={kc.min_val} vs src={s_min}")
if s_max is not None and s_max != kc.max_val:
param_diffs.append(f"{bw.name}: mixer '{kc.name}' max bin={kc.max_val} vs src={s_max}")
s_inv = str(scfg.get_scalar("invert", "") or "").strip().lower()
if s_inv in ("true", "1", "false", "0"):
if (s_inv in ("true", "1")) != bool(kc.invert):
param_diffs.append(f"{bw.name}: mixer '{kc.name}' invert differs")
if kc.scale_step > 0 or kc.scale_min != 0:
tlv = scfg.get_child("Object.Base.tlv.scale") or scfg.get_child("Object.Base.tlv")
scale_node = (tlv.get_child("Object.Base.scale") if tlv is not None else None) or tlv
if scale_node is not None:
st_min = _parse_int_opt(scale_node.get_scalar("min", ""))
st_step = _parse_int_opt(scale_node.get_scalar("step", ""))
if st_min is not None and st_min != kc.scale_min:
param_diffs.append(f"{bw.name}: mixer '{kc.name}' tlv min bin={kc.scale_min} vs src={st_min}")
if st_step is not None and st_step != kc.scale_step:
param_diffs.append(f"{bw.name}: mixer '{kc.name}' tlv step bin={kc.scale_step} vs src={st_step}")
elif ktype == "enum" and kc.enum_texts:
s_opts_raw = str(scfg.get_scalar("enum_options", "") or "").strip()
if s_opts_raw:
s_opts = [o.strip() for o in s_opts_raw.split(",") if o.strip()]
if s_opts and s_opts != list(kc.enum_texts):
param_diffs.append(f"{bw.name}: enum '{kc.name}' options differ")
# Compare input and output pin audio format parameters
for _io_dir, pin_fmts, block_key, pfx in (
("in", bw.input_pin_fmts, "Object.Base.input_audio_format", "in_"),
("out", bw.output_pin_fmts, "Object.Base.output_audio_format", "out_"),
):
if not pin_fmts:
continue
b_rates = {pf.audio_fmt.sampling_frequency for pf in pin_fmts if pf.audio_fmt.sampling_frequency > 0}
b_chs = {pf.audio_fmt.channels_count for pf in pin_fmts if pf.audio_fmt.channels_count > 0}
b_bds = {pf.audio_fmt.bit_depth for pf in pin_fmts if pf.audio_fmt.bit_depth > 0}
b_vbds = {(pf.audio_fmt.valid_bit_depth or pf.audio_fmt.bit_depth) for pf in pin_fmts if (pf.audio_fmt.valid_bit_depth or pf.audio_fmt.bit_depth) > 0}
b_stypes = {_stype_idx_map.get(pf.audio_fmt.s_type, str(pf.audio_fmt.s_type)) for pf in pin_fmts}
b_ils = {"non-interleaved" if pf.audio_fmt.interleaving_style == 1 else "interleaved" for pf in pin_fmts}
s_rates, s_chs, s_bds, s_vbds, s_stypes, s_ils = _collect_src_pin_fmt_sets(sn.config, block_key, pfx)
if b_rates and s_rates and b_rates != s_rates:
param_diffs.append(f"{bw.name}: {pfx}rate bin={sorted(b_rates)} vs src={sorted(s_rates)}")
if b_chs and s_chs and b_chs != s_chs:
param_diffs.append(f"{bw.name}: {pfx}channels bin={sorted(b_chs)} vs src={sorted(s_chs)}")
if b_bds and s_bds and b_bds != s_bds:
param_diffs.append(f"{bw.name}: {pfx}bit_depth bin={sorted(b_bds)} vs src={sorted(s_bds)}")
if b_vbds and s_vbds and b_vbds != s_vbds:
param_diffs.append(f"{bw.name}: {pfx}valid_bit_depth bin={sorted(b_vbds)} vs src={sorted(s_vbds)}")
if b_stypes and s_stypes and b_stypes != s_stypes:
param_diffs.append(f"{bw.name}: {pfx}sample_type bin={sorted(b_stypes)} vs src={sorted(s_stypes)}")
if b_ils and s_ils and b_ils != s_ils:
param_diffs.append(f"{bw.name}: {pfx}interleaving_style bin={sorted(b_ils)} vs src={sorted(s_ils)}")
# Subtract a small tie-breaker penalty per parameter mismatch so exact 2ch/4ch variants outscore siblings
score = max(0.0, score - min(10.0, 0.5 * len(param_diffs)))
is_exact = (
not miss_p
and not extra_p
and not miss_w
and not extra_w
and not miss_r
and not extra_r
and not miss_pcm
and not extra_pcm
and not param_diffs
)
parts: List[str] = []
if is_exact:
summary = "Exact structural match (0 differences)"
else:
if miss_p:
parts.append(f"+{len(miss_p)} bin-only pipelines {miss_p[:4]}")
if extra_p:
parts.append(f"-{len(extra_p)} src-only pipelines {extra_p[:4]}")
if miss_w:
parts.append(f"+{len(miss_w)} bin-only widgets")
if extra_w:
parts.append(f"-{len(extra_w)} src-only widgets")
if miss_r or extra_r:
parts.append(f"routes diff (+{len(miss_r)}/-{len(extra_r)})")
if miss_pcm or extra_pcm:
parts.append(f"PCMs diff (+{len(miss_pcm)}/-{len(extra_pcm)})")
if param_diffs:
parts.append(f"{len(param_diffs)} param diffs")
summary = "; ".join(parts) if parts else f"{score:.1f}% match"
return TplgDiffReport(
similarity_pct=score,
is_exact=is_exact,
missing_pipelines_in_source=miss_p,
extra_pipelines_in_source=extra_p,
missing_widgets_in_source=miss_w,
extra_widgets_in_source=extra_w,
missing_routes_in_source=miss_r,
extra_routes_in_source=extra_r,
param_diffs=param_diffs,
summary=summary,
)
def _stem_aliases(stem: str) -> List[str]:
"""Generate likely CMake target output_name aliases for vendor-bundled .tplg filenames."""
aliases = [stem]
plat_swaps = (
("sof-ptl-", "sof-wcl-"),
("sof-wcl-", "sof-ptl-"),