Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
4076 lines (3804 loc) · 177 KB
/
Copy pathparser.py
File metadata and controls
4076 lines (3804 loc) · 177 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
"""Recursive parser and graph builder for ALSA Topology2 (.conf) and CMake targets."""
from __future__ import annotations
import ast
import operator
import os
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
from .model import (
AttrConstraint,
AttrDef,
CMakeTargetVariant,
ConfigNode,
GraphEdge,
GraphNode,
GraphPort,
GraphViewModel,
MachineTopologyEntry,
PipelineContainer,
TplgClassDef,
)
TOKEN_RE = re.compile(
r"""
(?P<doxy>\#\#[^\n]*)|
(?P<comment>\#[^\n]*)|
(?P<ccomment>/\*[\s\S]*?\*/)|
(?P<include><[^>\n]+>)|
(?P<squote>'[^']*')|
(?P<dquote>"[^"]*")|
(?P<lbrace>\{)|
(?P<rbrace>\})|
(?P<lbrack>\[)|
(?P<rbrack>\])|
(?P<word>[^\s\{\}\[\]<>"'#]+)|
(?P<ws>\s+)
""",
re.VERBOSE,
)
def tokenize_alsaconf(text: str) -> List[Tuple[str, str]]:
"""Tokenize alsaconf / topology2 text into (kind, value) pairs."""
tokens: List[Tuple[str, str]] = []
for m in TOKEN_RE.finditer(text):
kind = m.lastgroup
val = m.group()
if kind in ("ws", "comment", "ccomment"):
continue
tokens.append((kind, val))
return tokens
def strip_quotes(val: str) -> str:
if len(val) >= 2 and ((val[0] == '"' and val[-1] == '"') or (val[0] == "'" and val[-1] == "'")):
return val[1:-1]
return val
def split_dotted_key(raw: str) -> List[str]:
"""Split a dotted key like Object.Widget."gain"."1" into ['Object', 'Widget', 'gain', '1']."""
parts: List[str] = []
cur: List[str] = []
in_q: Optional[str] = None
for ch in raw:
if in_q:
if ch == in_q:
in_q = None
else:
cur.append(ch)
else:
if ch in ('"', "'"):
in_q = ch
elif ch == ".":
parts.append("".join(cur))
cur = []
else:
cur.append(ch)
if cur or raw.endswith("."):
parts.append("".join(cur))
return [p for p in parts if p != "" or len(parts) > 2]
class AstStmt:
"""AST node representing a statement in a Topology2 .conf file."""
def __init__(
self,
stmt_type: str,
key: str = "",
value: Any = None,
children: Optional[List["AstStmt"]] = None,
doxy: str = "",
source_file: str = "",
):
self.stmt_type = stmt_type # "include", "searchdir", "block", "array", "kv"
self.key = key
self.value = value
self.children: List["AstStmt"] = children if children is not None else []
self.doxy = doxy
self.source_file = source_file
self.provenance: str = ""
class TokenStream:
def __init__(self, tokens: List[Tuple[str, str]], source_file: str = ""):
self.tokens = tokens
self.pos = 0
self.source_file = source_file
def peek(self, offset: int = 0) -> Optional[Tuple[str, str]]:
idx = self.pos + offset
if 0 <= idx < len(self.tokens):
return self.tokens[idx]
return None
def next(self) -> Optional[Tuple[str, str]]:
tok = self.peek()
if tok is not None:
self.pos += 1
return tok
def eof(self) -> bool:
return self.pos >= len(self.tokens)
def _read_compound_key(stream: TokenStream) -> str:
"""Read a key that may have adjacent quoted segments like Class.Widget.\"gain\"."""
tok = stream.next()
if tok is None:
return ""
key = tok[1]
if key == "!" and not stream.eof():
nxt0 = stream.peek()
if nxt0 is not None and nxt0[0] in ("word", "dquote", "squote"):
key = "!" + stream.next()[1]
# In alsaconf, Class.Widget."gain" or mixer."1" can be tokenized as word('Class.Widget.') + dquote('"gain"')
while not stream.eof():
nxt = stream.peek()
if nxt is None:
break
if key.endswith(".") and nxt[0] in ("dquote", "squote", "word"):
key += stream.next()[1]
elif nxt[0] == "word" and nxt[1].startswith("."):
key += stream.next()[1]
else:
break
return key
def parse_stmt_list(
stream: TokenStream,
stop_tokens: Set[str] = frozenset(),
in_array: bool = False,
) -> List[AstStmt]:
stmts: List[AstStmt] = []
pending_doxy: List[str] = []
while not stream.eof():
pk = stream.peek()
if pk is None:
break
kind, val = pk
if kind in stop_tokens:
break
if kind == "doxy":
stream.next()
clean = val.lstrip("#").strip()
if clean:
pending_doxy.append(clean)
continue
if kind == "include":
stream.next()
inner = val[1:-1].strip()
if inner.startswith("searchdir:"):
stmts.append(
AstStmt(
"searchdir",
key=inner.split(":", 1)[1].strip(),
source_file=stream.source_file,
)
)
else:
stmts.append(
AstStmt(
"include",
key=inner,
source_file=stream.source_file,
)
)
pending_doxy.clear()
continue
if kind == "lbrace":
# Anonymous block `{ ... }` inside an array
stream.next()
children = parse_stmt_list(stream, {"rbrace"}, in_array=False)
if stream.peek() and stream.peek()[0] == "rbrace":
stream.next()
stmts.append(
AstStmt(
"block",
key="{}",
children=children,
doxy="\n".join(pending_doxy),
source_file=stream.source_file,
)
)
pending_doxy.clear()
continue
if kind in ("rbrace", "rbrack"):
# Unmatched closing delimiter; consume to prevent infinite loop
stream.next()
break
key = _read_compound_key(stream)
doxy_str = "\n".join(pending_doxy)
pending_doxy.clear()
nxt = stream.peek()
if nxt is not None and nxt[0] == "lbrace":
stream.next()
children = parse_stmt_list(stream, {"rbrace"}, in_array=False)
if stream.peek() and stream.peek()[0] == "rbrace":
stream.next()
stmts.append(
AstStmt(
"block",
key=key,
children=children,
doxy=doxy_str,
source_file=stream.source_file,
)
)
elif nxt is not None and nxt[0] == "lbrack":
stream.next()
children = parse_stmt_list(stream, {"rbrack"}, in_array=True)
if stream.peek() and stream.peek()[0] == "rbrack":
stream.next()
stmts.append(
AstStmt(
"array",
key=key,
children=children,
doxy=doxy_str,
source_file=stream.source_file,
)
)
elif in_array:
# Standalone scalar element inside `[ ... ]`
stmts.append(
AstStmt(
"kv",
key=strip_quotes(key),
value=strip_quotes(key),
doxy=doxy_str,
source_file=stream.source_file,
)
)
else:
# Scalar key-value outside array
if nxt is not None and nxt[0] in ("word", "squote", "dquote"):
val_tok = stream.next()
stmts.append(
AstStmt(
"kv",
key=strip_quotes(key),
value=strip_quotes(val_tok[1]),
doxy=doxy_str,
source_file=stream.source_file,
)
)
else:
stmts.append(
AstStmt(
"kv",
key=strip_quotes(key),
value="",
doxy=doxy_str,
source_file=stream.source_file,
)
)
return stmts
def parse_conf_text(text: str, source_file: str = "") -> List[AstStmt]:
tokens = tokenize_alsaconf(text)
stream = TokenStream(tokens, source_file=source_file)
return parse_stmt_list(stream)
def parse_conf_file(path: str) -> List[AstStmt]:
with open(path, "r", encoding="utf-8", errors="replace") as f:
text = f.read()
return parse_conf_text(text, source_file=path)
class Topology2Workspace:
"""Loads and indexes an entire tools/topology/topology2 directory."""
def __init__(self, root_dir: str):
self.root_dir = os.path.abspath(root_dir)
self._ast_cache: Dict[str, List[AstStmt]] = {}
# Categorized collections for the 4 left-hand sub-panes
self.base_classes: Dict[str, TplgClassDef] = {} # Pane 1: Base, Control, PCM, Dai
self.processing_modules: Dict[str, TplgClassDef] = {} # Pane 2: Class.Widget.*
self.pipeline_classes: Dict[str, TplgClassDef] = {} # Pane 3: Class.Pipeline.*
self.machine_topologies: List[MachineTopologyEntry] = [] # Pane 4: top-level .conf + CMake variants
# Global lookup of all classes by "Category.Name"
self.all_classes: Dict[str, TplgClassDef] = {}
self.global_defines: Dict[str, str] = {}
self.platform_defaults: Dict[str, str] = {}
self.platform_definitions: List[Dict[str, object]] = []
def get_ast(self, abs_path: str) -> List[AstStmt]:
abs_path = os.path.abspath(abs_path)
if abs_path not in self._ast_cache:
if os.path.isfile(abs_path):
self._ast_cache[abs_path] = parse_conf_file(abs_path)
else:
self._ast_cache[abs_path] = []
return self._ast_cache[abs_path]
def resolve_include(self, include_str: str, search_dirs: List[str], current_file: str = "") -> Optional[str]:
candidates = []
if current_file:
candidates.append(os.path.join(os.path.dirname(current_file), include_str))
candidates.append(os.path.join(self.root_dir, include_str))
for sdir in search_dirs:
candidates.append(os.path.join(self.root_dir, sdir, include_str))
for cand in candidates:
if os.path.isfile(cand):
return os.path.abspath(cand)
return None
def scan_all(self) -> None:
"""Scan the entire topology2 directory and populate all 4 left-pane collections."""
self.base_classes.clear()
self.processing_modules.clear()
self.pipeline_classes.clear()
self.machine_topologies.clear()
self.all_classes.clear()
self.global_defines.clear()
self.platform_defaults.clear()
self.platform_definitions.clear()
# 1. Load common definitions first (so $HDA_HOST_OUTPUT_CLASS etc. are known)
self.global_defines["DEEP_BUF_JACK_RATE"] = "48000"
common_defs = os.path.join(self.root_dir, "include", "common", "common_definitions.conf")
if os.path.isfile(common_defs):
for stmt in self.get_ast(common_defs):
if stmt.stmt_type == "block" and stmt.key == "Define":
for ch in stmt.children:
if ch.stmt_type == "kv":
self.global_defines[ch.key] = str(ch.value)
# 2. Scan include/ directory for all Class.<Category>.<Name> definitions
include_dir = os.path.join(self.root_dir, "include")
if os.path.isdir(include_dir):
for dirpath, _dirnames, filenames in os.walk(include_dir):
for fname in sorted(filenames):
if not fname.endswith(".conf"):
continue
fpath = os.path.join(dirpath, fname)
self._extract_classes_from_file(fpath)
# Resolve SubTreeCopy.baseclass inheritance for pipeline classes
self._resolve_pipeline_inheritance()
# 3. Parse CMake target variants in production/ and development/
variants_by_conf = self._parse_cmake_targets()
# 4. Scan top-level .conf files and development/*.conf for Machine Topologies
top_confs: List[Tuple[str, str]] = []
for fname in sorted(os.listdir(self.root_dir)):
if fname.endswith(".conf") and fname != "dmic-wov-feature.conf":
top_confs.append((fname[:-5], os.path.join(self.root_dir, fname)))
dev_dir = os.path.join(self.root_dir, "development")
if os.path.isdir(dev_dir):
for fname in sorted(os.listdir(dev_dir)):
if fname.endswith(".conf"):
rel_name = f"development/{fname[:-5]}"
top_confs.append((rel_name, os.path.join(dev_dir, fname)))
for base_name, fpath in top_confs:
rel_path = os.path.relpath(fpath, self.root_dir)
variants = variants_by_conf.get(base_name, []) + variants_by_conf.get(os.path.basename(base_name), [])
# Deduplicate variants by output_name
seen_out: Set[str] = set()
unique_vars: List[CMakeTargetVariant] = []
for v in variants:
if v.output_name not in seen_out:
seen_out.add(v.output_name)
unique_vars.append(v)
self.machine_topologies.append(
MachineTopologyEntry(
name=os.path.basename(base_name),
conf_path=fpath,
rel_path=rel_path,
variants=unique_vars,
)
)
# 5. Scan platform/ directory for Platform Topology Definitions & Defaults
plat_dir = os.path.join(self.root_dir, "platform")
if os.path.isdir(plat_dir):
for dirpath, _dirnames, filenames in os.walk(plat_dir):
for fname in sorted(filenames):
if not fname.endswith(".conf"):
continue
fpath = os.path.join(dirpath, fname)
rel_p = os.path.relpath(fpath, self.root_dir)
self._extract_classes_from_file(fpath)
stmts = self.get_ast(fpath)
defs_map: Dict[str, str] = {}
has_objs = False
for st in stmts:
if st.stmt_type == "block" and st.key == "Define":
for ch in st.children:
if ch.stmt_type == "kv":
defs_map[ch.key] = str(ch.value)
elif st.key.startswith("Object."):
has_objs = True
if fname.endswith("-default.conf"):
self.platform_defaults.update(defs_map)
stem = fname[:-5]
if stem in ("tgl", "mtl", "lnl", "ptl"):
pcat = "soc"
elif stem.startswith("dmic"):
pcat = "dmic"
elif stem.startswith("hdmi"):
pcat = "hdmi"
elif stem.startswith("sdw"):
pcat = "sdw"
elif stem.startswith(("bt", "ssp", "nocodec", "uaol")):
pcat = "bt_ssp"
else:
pcat = "feature"
self.platform_definitions.append(
{
"name": fname,
"stem": stem,
"rel_path": rel_p,
"abs_path": fpath,
"category": pcat,
"defines": defs_map,
"has_objects": has_objs,
}
)
self.platform_definitions.sort(key=lambda d: str(d["rel_path"]))
# 6. Aggregate per-module and per-pin input/output audio formats across pipelines, bench configs, and topologies
self._aggregate_module_pin_audio_formats()
def _aggregate_module_pin_audio_formats(self) -> None:
"""Populate default pin counts and aggregate input_audio_format / output_audio_format specs per module."""
if not self.processing_modules:
return
# 1. Normalize default num_input_pins and num_output_pins where class definitions omit them
default_pin_overrides: Dict[str, Tuple[int, int]] = {
"siggen": (0, 1),
"wov": (1, 0),
"crossover": (1, 2),
"muxdemux": (1, 2),
"pipeline": (0, 0),
}
for mname, cdef in self.processing_modules.items():
ov_in, ov_out = default_pin_overrides.get(mname, (1, 1))
if cdef.defaults.get("num_input_pins") is None:
cdef.defaults["num_input_pins"] = ov_in
if cdef.defaults.get("num_output_pins") is None:
cdef.defaults["num_output_pins"] = ov_out
in_by_mod: Dict[str, List[ConfigNode]] = {m: [] for m in self.processing_modules}
out_by_mod: Dict[str, List[ConfigNode]] = {m: [] for m in self.processing_modules}
search_dirs = [
"include",
"include/common",
"include/components",
"include/controls",
"include/pipelines",
"include/pipelines/cavs",
"include/bench",
"platform",
"platform/intel",
]
def add_fmt_cfg(target_list: List[ConfigNode], cfg_n: ConfigNode) -> None:
if any(
ch.node_type == "scalar"
or ch.key.startswith(("in_", "out_", "input_pin", "output_pin", "ibs", "obs"))
for ch in cfg_n.children
):
target_list.append(cfg_n.clone())
else:
for ch in cfg_n.children:
target_list.append(ch.clone())
# Seed from any format objects already embedded inside Class.Widget.<mname>
for mname, cdef in self.processing_modules.items():
for sub in cdef.sub_objects:
if "input_audio_format" in sub.key:
add_fmt_cfg(in_by_mod[mname], sub)
elif "output_audio_format" in sub.key:
add_fmt_cfg(out_by_mod[mname], sub)
def extract_from_widget_stmts(mname: str, stmts: List[AstStmt], cur_file: str) -> None:
if mname not in self.processing_modules:
return
for st in stmts:
if st.stmt_type == "block" and st.key == "{}":
extract_from_widget_stmts(mname, st.children, cur_file)
elif st.stmt_type == "include":
inc_p = self.resolve_include(st.key, search_dirs, cur_file)
if inc_p:
extract_from_widget_stmts(mname, self.get_ast(inc_p), inc_p)
elif st.stmt_type == "block" and st.key.startswith("IncludeByKey."):
for ch in st.children:
if ch.stmt_type == "kv" and ch.value:
for bfmt in ("s16", "s24", "s32"):
val = str(ch.value).replace("$BENCH_MODULE_FORMAT", bfmt)
inc_p = self.resolve_include(val, search_dirs, cur_file)
if inc_p:
extract_from_widget_stmts(mname, self.get_ast(inc_p), inc_p)
if "$BENCH_MODULE_FORMAT" not in str(ch.value):
break
elif ch.stmt_type == "block":
extract_from_widget_stmts(mname, ch.children, cur_file)
elif st.stmt_type in ("block", "array"):
if "input_audio_format" in st.key:
add_fmt_cfg(in_by_mod[mname], self._ast_to_config_node(st, origin="default"))
elif "output_audio_format" in st.key:
add_fmt_cfg(out_by_mod[mname], self._ast_to_config_node(st, origin="default"))
def walk_file_stmts(stmts: List[AstStmt], cur_file: str) -> None:
for st in stmts:
if st.stmt_type in ("block", "array"):
parts = split_dotted_key(st.key)
if len(parts) >= 2 and parts[0] == "Object" and parts[1] == "Widget":
if len(parts) == 2:
for wch in st.children:
wp = split_dotted_key(wch.key)
if wp:
extract_from_widget_stmts(wp[0], wch.children, cur_file)
else:
extract_from_widget_stmts(parts[2], st.children, cur_file)
else:
walk_file_stmts(st.children, cur_file)
# Scan all pipeline widget definitions
for pdef in self.pipeline_classes.values():
for w in pdef.widgets:
extract_from_widget_stmts(str(w["class_name"]), w["stmts"], pdef.source_file)
# Scan bench, development, and production .conf files
for sub_dir_name in ("include/bench", "development", "production"):
sdir = os.path.join(self.root_dir, sub_dir_name)
if not os.path.isdir(sdir):
continue
for dirpath, _dirnames, filenames in os.walk(sdir):
for fname in sorted(filenames):
if fname.endswith(".conf"):
fpath = os.path.join(dirpath, fname)
walk_file_stmts(self.get_ast(fpath), fpath)
def dedup_entries(entries: List[ConfigNode], prefix: str) -> List[ConfigNode]:
pin_key = "input_pin_index" if prefix == "in" else "output_pin_index"
seen: Set[Tuple[str, ...]] = set()
unique: List[ConfigNode] = []
for e in entries:
p_idx = str(e.get_scalar(pin_key, "0")).strip()
r_ch = e.get_child(f"{prefix}_rate")
if r_ch and r_ch.children:
r_sig = ",".join(str(x.key or x.value) for x in r_ch.children)
else:
r_sig = str(e.get_scalar(f"{prefix}_rate", "48000"))
c_ch = e.get_child(f"{prefix}_channels")
if c_ch and c_ch.children:
c_sig = ",".join(str(x.key or x.value) for x in c_ch.children)
else:
c_sig = str(e.get_scalar(f"{prefix}_channels", "2"))
b_sig = str(e.get_scalar(f"{prefix}_bit_depth", "16"))
vb_sig = str(e.get_scalar(f"{prefix}_valid_bit_depth", b_sig))
st_sig = str(e.get_scalar(f"{prefix}_sample_type", "LSB_INTEGER"))
il_sig = str(e.get_scalar(f"{prefix}_interleaving_style", "interleaved"))
sig = (p_idx, r_sig, c_sig, b_sig, vb_sig, st_sig, il_sig)
if sig not in seen:
seen.add(sig)
clone_e = e.clone()
clone_e.key = f"[{len(unique)}]"
if clone_e.get_scalar(pin_key) is None:
clone_e.set_scalar(pin_key, "0", origin="default")
if clone_e.get_scalar(f"{prefix}_rate") is None and clone_e.get_child(f"{prefix}_rate") is None:
clone_e.set_scalar(f"{prefix}_rate", "48000", origin="default")
if clone_e.get_scalar(f"{prefix}_channels") is None and clone_e.get_child(f"{prefix}_channels") is None:
clone_e.set_scalar(f"{prefix}_channels", "2", origin="default")
if clone_e.get_scalar(f"{prefix}_bit_depth") is None:
clone_e.set_scalar(f"{prefix}_bit_depth", "16", origin="default")
if clone_e.get_scalar(f"{prefix}_valid_bit_depth") is None:
clone_e.set_scalar(
f"{prefix}_valid_bit_depth",
str(clone_e.get_scalar(f"{prefix}_bit_depth", "16")),
origin="default",
)
if clone_e.get_scalar(f"{prefix}_interleaving_style") is None:
clone_e.set_scalar(f"{prefix}_interleaving_style", "interleaved", origin="default")
unique.append(clone_e)
return unique
def make_default_entries(mname: str, prefix: str, num_pins: int) -> List[ConfigNode]:
pin_key = "input_pin_index" if prefix == "in" else "output_pin_index"
depths = [(24, 32)] if mname == "muxdemux" else [(16, 16), (24, 32), (32, 32)]
res: List[ConfigNode] = []
for p_idx in range(max(1, min(num_pins, 2))):
for vb, b in depths:
entry = ConfigNode(key=f"[{len(res)}]", node_type="object", category_info="default", origin="default")
entry.set_scalar(pin_key, str(p_idx), origin="default")
entry.set_scalar(f"{prefix}_rate", "48000", origin="default")
entry.set_scalar(f"{prefix}_channels", "2", origin="default")
entry.set_scalar(f"{prefix}_bit_depth", str(b), origin="default")
entry.set_scalar(f"{prefix}_valid_bit_depth", str(vb), origin="default")
entry.set_scalar(f"{prefix}_interleaving_style", "interleaved", origin="default")
entry.set_scalar(f"{prefix}_sample_type", "LSB_INTEGER", origin="default")
res.append(entry)
return res
for mname, cdef in self.processing_modules.items():
num_in = int(str(cdef.defaults.get("num_input_pins", 1) or 0))
num_out = int(str(cdef.defaults.get("num_output_pins", 1) or 0))
in_unique = dedup_entries(in_by_mod[mname], "in") if num_in > 0 else []
out_unique = dedup_entries(out_by_mod[mname], "out") if num_out > 0 else []
if num_in > 0 and not in_unique:
in_unique = make_default_entries(mname, "in", num_in)
if num_out > 0 and not out_unique:
out_unique = make_default_entries(mname, "out", num_out)
# Remove any existing input/output_audio_format sub-objects and replace with aggregated format arrays
cdef.sub_objects = [
s for s in cdef.sub_objects
if "input_audio_format" not in s.key and "output_audio_format" not in s.key
]
if in_unique:
in_arr = ConfigNode(
key="Object.Base.input_audio_format",
node_type="array",
category_info=f"{len(in_unique)} formats",
origin="default",
children=in_unique,
)
cdef.sub_objects.append(in_arr)
if cdef.defaults.get("num_input_audio_formats") is None:
cdef.defaults["num_input_audio_formats"] = len(in_unique)
if out_unique:
out_arr = ConfigNode(
key="Object.Base.output_audio_format",
node_type="array",
category_info=f"{len(out_unique)} formats",
origin="default",
children=out_unique,
)
cdef.sub_objects.append(out_arr)
if cdef.defaults.get("num_output_audio_formats") is None:
cdef.defaults["num_output_audio_formats"] = len(out_unique)
self._rebuild_class_config_tree(cdef)
def _extract_classes_from_file(self, fpath: str) -> None:
stmts = self.get_ast(fpath)
rel_path = os.path.relpath(fpath, self.root_dir)
for stmt in stmts:
if stmt.stmt_type == "block" and stmt.key.startswith("Class."):
parts = split_dotted_key(stmt.key)
if len(parts) >= 3:
cat = parts[1]
cname = parts[2]
cdef = self._build_class_def(cat, cname, stmt, fpath, rel_path)
self.all_classes[f"{cat}.{cname}"] = cdef
if cat == "Widget":
self.processing_modules[cname] = cdef
elif cat == "Pipeline":
self.pipeline_classes[cname] = cdef
else:
self.base_classes[f"{cat}.{cname}"] = cdef
@staticmethod
def _extract_file_description(fpath: str, doxy: str) -> str:
lines: List[str] = []
try:
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
for raw in f:
s = raw.strip()
if not s:
continue
if not s.startswith("#"):
break
c = s.lstrip("#").strip()
c = re.sub(r"^\\struct\s+\S+\s*", "", c).strip()
c = re.sub(r"^\\brief\s*", "", c).strip()
if not c or c.startswith("SPDX"):
continue
if any(
c.startswith(p)
for p in ("All attributes", "by alsatplg", "Usage:", "Object.", "Where N", '"Object.')
):
break
if "All attributes defined herein" in c:
c = c.split("All attributes defined herein")[0].strip()
if c:
lines.append(c)
break
lines.append(c)
except Exception:
pass
if not lines and doxy:
for raw in doxy.splitlines():
c = re.sub(r"^\\(struct|brief)\s*\S*\s*", "", raw.strip()).strip()
if c:
lines.append(c)
if len(lines) >= 2 and lines[0].lower().rstrip(".") in lines[1].lower():
lines = lines[1:]
return " — ".join(lines[:2])
def _build_class_def(
self,
category: str,
name: str,
class_stmt: AstStmt,
fpath: str,
rel_path: str,
) -> TplgClassDef:
desc = self._extract_file_description(fpath, class_stmt.doxy)
cdef = TplgClassDef(
category=category,
name=name,
source_file=fpath,
rel_path=rel_path,
description=desc,
)
# Flatten inline includes inside the class block (e.g. <include/components/widget-common.conf>)
expanded_stmts = self._expand_class_body(class_stmt.children, fpath)
self._populate_class_from_stmts(cdef, expanded_stmts)
if not cdef.description:
if category == "Widget":
wtype = str(cdef.defaults.get("type", "effect"))
cdef.description = f"SOF {name} processing module ({wtype})."
elif category == "Pipeline":
direction = str(cdef.defaults.get("direction", "capture" if "capture" in name else "playback"))
cdef.description = f"{direction.capitalize()} pipeline: {name}."
return cdef
def _expand_class_body(self, stmts: List[AstStmt], current_file: str) -> List[AstStmt]:
result: List[AstStmt] = []
search_dirs = [
"include",
"include/common",
"include/components",
"include/dais",
"include/pipelines",
"include/pipelines/cavs",
]
for st in stmts:
if st.stmt_type == "include":
inc_path = self.resolve_include(st.key, search_dirs, current_file)
if inc_path:
result.extend(self._expand_class_body(self.get_ast(inc_path), inc_path))
else:
if st.children:
st = AstStmt(
stmt_type=st.stmt_type,
key=st.key,
value=st.value,
children=self._expand_class_body(st.children, current_file),
doxy=st.doxy,
source_file=st.source_file,
)
result.append(st)
return result
def _populate_class_from_stmts(self, cdef: TplgClassDef, stmts: List[AstStmt]) -> None:
for st in stmts:
if st.stmt_type == "block" and st.key.startswith("DefineAttribute"):
parts = split_dotted_key(st.key)
attr_name = parts[1] if len(parts) > 1 else st.key
adef = cdef.attributes.get(attr_name, AttrDef(name=attr_name))
if st.doxy:
adef.description = st.doxy
for ch in st.children:
if ch.stmt_type == "kv":
if ch.key == "type":
adef.attr_type = str(ch.value)
elif ch.key == "token_ref":
adef.token_ref = str(ch.value)
if "." in adef.token_ref and adef.attr_type == "string":
ref_t = adef.token_ref.split(".")[-1]
if ref_t in ("word", "short", "byte"):
adef.attr_type = "int"
elif ref_t == "bool":
adef.attr_type = "bool"
elif ch.key == "value":
cdef.defaults[attr_name] = ch.value
elif ch.stmt_type == "block" and ch.key == "constraints":
constraint = AttrConstraint()
for cch in ch.children:
if cch.stmt_type == "array" and cch.key.lstrip("!") == "valid_values":
constraint.valid_values = [str(x.key) for x in cch.children if x.key]
elif cch.stmt_type == "array" and cch.key.lstrip("!") == "tuple_values":
constraint.tuple_values = [str(x.key) for x in cch.children if x.key]
adef.constraints = constraint
cdef.attributes[attr_name] = adef
elif st.stmt_type == "block" and st.key == "attributes":
for ch in st.children:
flag_name = ch.key.lstrip("!")
if ch.stmt_type == "array":
items = [str(x.key) for x in ch.children if x.key]
if flag_name == "constructor":
cdef.constructor_attrs = items
for item in items:
adef = cdef.attributes.get(item, AttrDef(name=item))
if flag_name == "constructor":
adef.is_constructor = True
elif flag_name == "mandatory":
adef.is_mandatory = True
elif flag_name == "immutable":
adef.is_immutable = True
elif flag_name == "deprecated":
adef.is_deprecated = True
cdef.attributes[item] = adef
elif ch.stmt_type == "kv" and flag_name == "unique":
u_attr = str(ch.value)
cdef.unique_attr = u_attr
adef = cdef.attributes.get(u_attr, AttrDef(name=u_attr))
adef.is_unique = True
cdef.attributes[u_attr] = adef
elif st.stmt_type == "block" and st.key.startswith("SubTreeCopy"):
for ch in st.children:
if ch.stmt_type == "kv" and ch.key == "source":
cdef.extends_class = str(ch.value)
elif ch.stmt_type == "block" and ch.key == "tree":
self._populate_class_from_stmts(cdef, ch.children)
elif st.stmt_type in ("block", "array") and (
st.key.startswith("Object.")
or st.key.startswith("CombineArrays.Object.")
or st.key in ("!route", "route")
):
self._extract_class_embedded_objects(cdef, st)
elif st.stmt_type == "kv":
cdef.defaults[st.key] = st.value
# Sync defaults & attributes into cdef.config_tree
self._rebuild_class_config_tree(cdef)
def _extract_class_embedded_objects(self, cdef: TplgClassDef, st: AstStmt) -> None:
parts = split_dotted_key(st.key)
if parts[0].lstrip("!") == "route":
if st.stmt_type == "array":
for item in st.children:
if item.stmt_type == "block":
rdict = {ch.key: str(ch.value) for ch in item.children if ch.stmt_type == "kv"}
if "source" in rdict and "sink" in rdict:
cdef.routes.append(rdict)
elif st.stmt_type == "block":
rdict = {ch.key: str(ch.value) for ch in st.children if ch.stmt_type == "kv"}
if "source" in rdict and "sink" in rdict:
cdef.routes.append(rdict)
return
if len(parts) >= 2 and parts[0] == "CombineArrays" and parts[1] == "Object":
cdef.sub_objects.append(self._ast_to_config_node(st, origin="default"))
return
if len(parts) >= 2 and parts[0] == "Object":
obj_cat = parts[1]
if obj_cat == "Widget":
if len(parts) == 2:
# Object.Widget { host-copier."1" { ... } gain."1" { ... } }
for wch in st.children:
wparts = split_dotted_key(wch.key)
wclass = wparts[0]
winst = wparts[1] if len(wparts) > 1 else "1"
cdef.widgets.append(
{
"class_name": wclass,
"instance": winst,
"stmts": wch.children,
}
)
elif len(parts) >= 3:
wclass = parts[2]
winst = parts[3] if len(parts) > 3 else "1"
cdef.widgets.append(
{
"class_name": wclass,
"instance": winst,
"stmts": st.children,
}
)
elif obj_cat == "Base":
if len(parts) == 2:
for bch in st.children:
bparts = split_dotted_key(bch.key)
if bparts and bparts[0].lstrip("!") == "route":
self._extract_class_embedded_objects(cdef, bch)
else:
cdef.sub_objects.append(self._ast_to_config_node(bch, origin="default"))
elif len(parts) >= 3 and parts[2].lstrip("!") == "route":
if st.stmt_type == "array":
for item in st.children:
if item.stmt_type == "block":
rdict = {ch.key: str(ch.value) for ch in item.children if ch.stmt_type == "kv"}
if "source" in rdict and "sink" in rdict:
cdef.routes.append(rdict)
elif st.stmt_type == "block":
rdict = {ch.key: str(ch.value) for ch in st.children if ch.stmt_type == "kv"}
if "source" in rdict and "sink" in rdict:
cdef.routes.append(rdict)
else:
cdef.sub_objects.append(self._ast_to_config_node(st, origin="default"))
elif obj_cat == "Control":
if len(parts) == 2:
for cch in st.children:
cparts = split_dotted_key(cch.key)
ctype = cparts[0]
cinst = strip_quotes(cparts[1]) if len(cparts) > 1 else "1"
ccfg = self._ast_to_config_node(cch, origin="default")
ccfg.key = f"{ctype}.{cinst}"
cdef.controls.append(
{
"control_type": ctype,
"instance": cinst,
"config": ccfg,
}
)
elif len(parts) >= 3:
ctype = parts[2]
cinst = strip_quotes(parts[3]) if len(parts) > 3 else "1"
ccfg = self._ast_to_config_node(st, origin="default")
ccfg.key = f"{ctype}.{cinst}"
cdef.controls.append(
{
"control_type": ctype,
"instance": cinst,
"config": ccfg,
}
)
else:
cdef.sub_objects.append(self._ast_to_config_node(st, origin="default"))
def _rebuild_class_config_tree(self, cdef: TplgClassDef) -> None:
root = ConfigNode(key=cdef.full_name, node_type="object", category_info=cdef.rel_path)
for aname, adef in cdef.attributes.items():
default_val = cdef.defaults.get(aname, "")
valid_vals = adef.constraints.valid_values if adef.constraints else []
root.set_scalar(
key=aname,
value=default_val,
category_info=f"{adef.attr_type} {adef.flags_summary}".strip(),
origin="default",
is_immutable=adef.is_immutable,
is_mandatory=adef.is_mandatory,
is_constructor=adef.is_constructor,
valid_values=valid_vals,
)
for k, v in cdef.defaults.items():
if k not in cdef.attributes:
root.set_scalar(key=k, value=v, category_info="default", origin="default")
if cdef.controls:
ctrl_group = ConfigNode(key="Object.Control", node_type="object", category_info=f"{len(cdef.controls)} controls")
for ctrl in cdef.controls:
ctrl_group.children.append(ctrl["config"].clone())
root.children.append(ctrl_group)
for sub in cdef.sub_objects:
root.children.append(sub.clone())
cdef.config_tree = root
def _resolve_pipeline_inheritance(self) -> None:
"""Resolve SubTreeCopy.baseclass inheritance for Pipeline classes."""
resolved: Set[str] = set()
def resolve_one(pname: str) -> None:
if pname in resolved or pname not in self.pipeline_classes:
return
resolved.add(pname)
pdef = self.pipeline_classes[pname]