Repository navigation
Expand file tree
/
Copy pathtestbench.py
More file actions
7348 lines (6850 loc) · 310 KB
/
Copy pathtestbench.py
File metadata and controls
7348 lines (6850 loc) · 310 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
"""SOF Testbench (sof-testbench4) runner, SOFR network protocol client, telemetry parser,
audio signal generator, and Gtk.Snapshot waveform viewer.
Uses the SOF Remote Server TCP protocol (SOF_NET_MAGIC = 0x534F4652 'SOFR', v1) exposed
by `sof-testbench4 -S <port> -W` to configure, control, and collect real-time DSP telemetry
from testbench runs.
"""
from __future__ import annotations
import math
import os
import random
import re
import shutil
import socket
import struct
import subprocess
import tempfile
import threading
import time
import wave
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import gi
gi.require_version("Gdk", "4.0")
gi.require_version("Gtk", "4.0")
gi.require_version("Gsk", "4.0")
gi.require_version("Graphene", "1.0")
gi.require_version("Pango", "1.0")
from gi.repository import Gdk, GLib, Graphene, Gsk, Gtk, Pango
from .model import (
debug_log_command,
debug_log_line,
resolve_sof_and_workspace_roots,
)
from .tplg_ipc4 import (
SND_SOC_TPLG_TYPE_BYTES,
SND_SOC_TPLG_TYPE_ENUM,
SND_SOC_TPLG_TYPE_MIXER,
SOF_IPC4_PIPELINE_STATE_PAUSED,
SOF_IPC4_PIPELINE_STATE_RESET,
SOF_IPC4_PIPELINE_STATE_RUNNING,
TplgIpc4Parser,
TplgIpc4Plan,
TplgKcontrolDesc,
build_ipc4_plan,
encode_delete_pipeline,
encode_kcontrol_set_ipc,
encode_large_config_set_chunks,
encode_set_pipeline_state,
)
# -----------------------------------------------------------------------------
# SOF Remote Server Network Protocol Constants (matching sof_remote_proto.h)
# -----------------------------------------------------------------------------
SOF_NET_MAGIC = 0x534F4652 # 'SOFR'
SOF_NET_VERSION = 1
SOF_NET_DEFAULT_PORT = 9998
SOF_NET_OP_FLAG_COMPRESSED = 0x8000
SOF_NET_OP_MASK = 0x7FFF
SOF_NET_COMP_MAGIC = 0x5A464F53 # 'SOFZ'
SOF_NET_OP_PING = 0x0000
SOF_NET_OP_GET_INFO = 0x0001
SOF_NET_OP_PM_CTL = 0x0002
SOF_NET_OP_IPC_TX = 0x0010
SOF_NET_OP_IPC_LARGE_CFG = 0x0011
SOF_NET_OP_WIN_INFO = 0x0020
SOF_NET_OP_WIN_READ = 0x0021
SOF_NET_OP_WIN_WRITE = 0x0022
SOF_NET_OP_WINSTREAM_IO = 0x0023
SOF_NET_OP_TELEM_SNAPSHOT = 0x0028
SOF_NET_OP_WORKLOAD_SIM_CFG = 0x0029
SOF_NET_OP_LLEXT_LOAD = 0x0030
SOF_NET_OP_SHELL_EXEC = 0x0040
SOF_NET_OP_PROBE_CTL = 0x0050
SOF_NET_OP_PCM_CTL = 0x0060
SOF_NET_OP_CARD_LIST = 0x0070
SOF_NET_OP_PCM_CAPS = 0x0071
SOF_NET_OP_DAPM_GRAPH = 0x0072
SOF_NET_OP_COMPR_CTL = 0x0073
SOF_NET_OP_KCTL_LIST = 0x0074
SOF_NET_OP_KCTL_GET = 0x0075
SOF_NET_OP_KCTL_SET = 0x0076
# Workload Simulation Operations & Modes (SOF_NET_OP_WORKLOAD_SIM_CFG)
SOF_WORKLOAD_SIM_OP_GET = 0
SOF_WORKLOAD_SIM_OP_SET = 1
SOF_WORKLOAD_SIM_OP_MOD_SET = 2
SOF_WORKLOAD_SIM_OP_RESET_OVERRIDES = 3
SOF_WORKLOAD_SIM_OFF = 0
SOF_WORKLOAD_SIM_VIRTUAL = 1
SOF_WORKLOAD_SIM_REALTIME = 2
SOF_WORKLOAD_MEM_SRAM = 0
SOF_WORKLOAD_MEM_DRAM = 1
SOF_WORKLOAD_MEM_AUTO = 0xFF
# SRAM Window IDs (SOF_NET_OP_WIN_READ)
SOF_CDEV_WIN_FW_REGS = 0
SOF_CDEV_WIN_OUTBOX = 1
SOF_CDEV_WIN_DEBUG = 2
SOF_CDEV_WIN_PERF = 3
# Power Management Operations (SOF_NET_OP_PM_CTL)
SOF_PM_OP_QUERY = 0
SOF_PM_OP_WAKE_HOLD = 1
SOF_PM_OP_RELEASE_HOLD = 2
SOF_PM_OP_BOOT_DSP = 3
SOF_PM_OP_CORE_GET = 4
SOF_PM_OP_CORE_PUT = 5
# Telemetry Query Flags (SOF_NET_OP_TELEM_SNAPSHOT)
SOF_TELEM_FL_FW_REGS = 1 << 0
SOF_TELEM_FL_TELEM_SLOT = 1 << 1
SOF_TELEM_FL_PERF_WIN3 = 1 << 2
SOF_TELEM_FL_MEM_STATE_TLV = 1 << 3
SOF_TELEM_FL_PWR_STATE_TLV = 1 << 4
SOF_TELEM_FL_EXT_PERF_TLV = 1 << 5
SOF_TELEM_FL_MODULES_INFO_TLV = 1 << 6
SOF_TELEM_FL_SYS_HOST_STATS = 1 << 7
SOF_TELEM_FL_TEL2_SLOT = 1 << 8
SOF_TELEM_FL_PMW2_WIN3 = 1 << 9
SOF_TELEM_FL_HOT_ONLY = 1 << 10
SOF_TELEM_FL_COMPRESS = 1 << 14
SOF_TELEM_FL_WAKE_DSP = 1 << 15
SOF_TELEM_FL_ALL = (
SOF_TELEM_FL_FW_REGS
| SOF_TELEM_FL_TELEM_SLOT
| SOF_TELEM_FL_PERF_WIN3
| SOF_TELEM_FL_MEM_STATE_TLV
| SOF_TELEM_FL_PWR_STATE_TLV
| SOF_TELEM_FL_EXT_PERF_TLV
| SOF_TELEM_FL_MODULES_INFO_TLV
| SOF_TELEM_FL_TEL2_SLOT
| SOF_TELEM_FL_PMW2_WIN3
)
SOF_TEL_EXT_MAGIC = 0x324C4554 # "TEL2"
SOF_TEL_MW3_MAGIC = 0x32574D50 # "PMW2"
# PCM Control Operations (SOF_NET_OP_PCM_CTL)
SOF_PCM_OP_STATUS = 0
SOF_PCM_OP_START_TONE = 1
SOF_PCM_OP_STOP_TONE = 2
SOF_PCM_OP_PLAY_BUFFER = 3
SOF_PCM_OP_CAPTURE_BUFFER = 4
SOF_AUDIO_API_ALSA = 1
SOF_PCM_FMT_S16_LE = 0
SOF_PCM_FMT_S24_LE = 1
SOF_PCM_FMT_S24_3LE = 2
SOF_PCM_FMT_S32_LE = 3
# Probe Control Operations (SOF_NET_OP_PROBE_CTL)
SOF_PROBE_OP_INIT = 1
SOF_PROBE_OP_DEINIT = 2
SOF_PROBE_OP_INFO_ACTIVE = 3
SOF_PROBE_OP_INFO_AVAILABLE = 4
SOF_PROBE_OP_POINTS_ADD = 5
SOF_PROBE_OP_POINTS_REMOVE = 6
SOF_PROBE_OP_READ_BUFFER = 7
# IPC4 BaseFW Large Config Parameter IDs
TB_IPC4_MODULES_INFO_GET = 9
TB_IPC4_MEMORY_STATE_INFO_GET = 14
TB_IPC4_POWER_STATE_INFO_GET = 15
TB_IPC4_PERF_MEASUREMENTS_STATE = 17
TB_IPC4_GLOBAL_PERF_DATA = 18
TB_IPC4_EXTENDED_GLOBAL_PERF_DATA = 30
SOF_CDEV_LARGE_CFG_GET = 0
SOF_CDEV_LARGE_CFG_SET = 1
WELL_KNOWN_IPC4_MODULES: Dict[int, str] = {
0x0000: "basefw",
0x0001: "mixin",
0x0002: "mixout",
0x0003: "copier",
0x0004: "peakvol",
0x0005: "src",
0x0006: "asrc",
0x0007: "probe",
0x0008: "updown_mix",
0x000C: "eq_iir",
0x000D: "eq_fir",
0x000E: "drc",
0x000F: "tdfb",
0x0010: "crossover",
0x0011: "multiband_drc",
0x0012: "aria",
0x0094: "copier",
0x0095: "mixin",
0x0096: "mixout",
0x0097: "gain",
0x0098: "src",
0x1003: "peakvol",
0x1004: "src",
0x1005: "asrc",
0x100B: "mixin",
0x100C: "mixout",
0x1010: "eq_fir",
0x1011: "eq_iir",
0x1013: "drc",
0x1014: "tdfb",
0x1015: "multiband_drc",
}
# -----------------------------------------------------------------------------
# Structured Telemetry & Run Result Dataclasses
# -----------------------------------------------------------------------------
@dataclass
class CoreTelemetry:
core_id: int
enabled: bool = False
tick_count: int = 0
last_time_elapsed_cyc: int = 0
max_time_elapsed_cyc: int = 0
last_time_elapsed_us: float = 0.0
max_time_elapsed_us: float = 0.0
last_ccount: int = 0
avg_kcps: int = 0
peak_kcps: int = 0
budget_kcps: int = 0
cpu_load_pct: float = 0.0
peak_load_pct: float = 0.0
freq_hz: int = 400_000_000
ll_deadline_violations: int = 0
ll_active_tasks: int = 0
ll_avg_cycles: int = 0
ll_peak_cycles: int = 0
ll_total_cycles: int = 0
ll_avg_exec_us: float = 0.0
ll_peak_exec_us: float = 0.0
dp_run_count: int = 0
dp_active_threads: int = 0
dp_deadline_misses: int = 0
dp_avg_cycles: int = 0
dp_peak_cycles: int = 0
dp_total_cycles: int = 0
dp_avg_kcps: int = 0
dp_peak_kcps: int = 0
dp_avg_exec_us: float = 0.0
dp_peak_exec_us: float = 0.0
@property
def ll_ticks(self) -> int:
return self.tick_count
@property
def dp_runs(self) -> int:
return self.dp_run_count
@property
def util_pct(self) -> float:
return self.cpu_load_pct
@property
def ll_exec_avg_us(self) -> float:
return self.ll_avg_exec_us if self.ll_avg_exec_us > 0 else self.last_time_elapsed_us
@property
def ll_exec_peak_us(self) -> float:
return self.ll_peak_exec_us if self.ll_peak_exec_us > 0 else self.max_time_elapsed_us
@property
def overruns(self) -> int:
return self.ll_deadline_violations
@property
def avg_cycles(self) -> int:
return self.ll_avg_cycles or self.last_time_elapsed_cyc
@property
def peak_cycles(self) -> int:
return self.ll_peak_cycles or self.max_time_elapsed_cyc
@dataclass
class PipelineSchedTelemetry:
pipeline_id: int
core_id: int = 0
priority: int = 0
period_us: int = 1000
mem_domain: str = "SRAM"
num_ll_modules: int = 0
num_dp_modules: int = 0
copy_iterations: int = 0
avg_cycles: int = 0
peak_cycles: int = 0
total_cycles: int = 0
avg_kcps: int = 0
peak_kcps: int = 0
avg_exec_us: float = 0.0
peak_exec_us: float = 0.0
xrun_count: int = 0
@property
def exec_avg_us(self) -> float:
return self.avg_exec_us
@property
def exec_peak_us(self) -> float:
return self.peak_exec_us
@property
def copies(self) -> int:
return self.copy_iterations
@property
def mem_type(self) -> str:
return self.mem_domain
@property
def ll_module_count(self) -> int:
return self.num_ll_modules
@property
def dp_module_count(self) -> int:
return self.num_dp_modules
@property
def xruns(self) -> int:
return self.xrun_count
@dataclass
class ModulePinBufferStats:
direction: str # "IN" or "OUT"
pin_index: int = 0
buf_id: int = 0
peer_comp_id: int = 0xFFFFFFFF
peer_widget_name: str = ""
rate: int = 48000
channels: int = 2
frame_fmt: int = 2
buf_size: int = 0
ll_entry_avail: int = 0
ll_entry_free: int = 0
ll_exit_avail: int = 0
ll_exit_free: int = 0
dp_ring_size: int = 0
dp_entry_avail: int = 0
dp_entry_free: int = 0
dp_exit_avail: int = 0
dp_exit_free: int = 0
last_bytes_transferred: int = 0
total_bytes_transferred: int = 0
xrun_count: int = 0
underrun_count: int = 0
overrun_count: int = 0
tick0_xrun_count: int = 0
entry_rms_db: float = -120.0
entry_peak_db: float = -120.0
exit_rms_db: float = -120.0
exit_peak_db: float = -120.0
samples: List[int] = field(default_factory=list)
@dataclass
class ComponentPerfItem:
resource_id: int
module_id: int
instance_id: int
module_name: str
widget_name: str = ""
pipeline_id: int = 0
core_id: int = 0
domain: str = "LL"
mem_domain: str = "SRAM"
is_removed: bool = False
avg_kcps: int = 0
peak_kcps: int = 0
iterations: int = 0
last_cycles: int = 0
avg_cycles: int = 0
peak_cycles: int = 0
total_cycles: int = 0
avg_exec_us: float = 0.0
peak_exec_us: float = 0.0
heap_bytes: int = 0
effective_cpc: int = 0
cpc_violations: int = 0
error_count: int = 0
tick0_error_count: int = 0
last_error_msg: str = ""
fw_errors: List[Dict[str, Any]] = field(default_factory=list)
ibs: int = 0
obs: int = 0
ll_ring_sync_iters: int = 0
ll_ring_sync_cycles: int = 0
in_rms_db: float = -120.0
out_rms_db: float = -120.0
in_pins: List[ModulePinBufferStats] = field(default_factory=list)
out_pins: List[ModulePinBufferStats] = field(default_factory=list)
@property
def comp_id(self) -> int:
return self.resource_id
@property
def exec_avg_us(self) -> float:
return self.avg_exec_us
@property
def exec_peak_us(self) -> float:
return self.peak_exec_us
@property
def mem_type(self) -> str:
return self.mem_domain
@dataclass
class SramSegmentState:
name: str
total_banks: int = 0
powered_banks: int = 0
gated_banks: int = 0
free_phys_pages: int = 0
@dataclass
class KcontrolTelemetryItem:
numid: int
name: str
iface_str: str = "MIXER"
type_id: int = 2
type_str: str = "INT"
access_str: str = "rw"
count: int = 2
min_val: int = 0
max_val: int = 0
values: List[int] = field(default_factory=list)
enum_names: List[str] = field(default_factory=list)
target_widget: str = ""
pipeline_id: int = -1
@dataclass
class TestbenchTelemetry:
connected: bool = False
server_port: int = 0
platform: str = "sof-testbench4"
fw_version: str = "0.0.0.0"
fw_filename: str = ""
ipc_type: int = 1
fw_state: int = 7
dsp_power_state: int = 1
pm_runtime_active: bool = True
num_cores: int = 4
enabled_cores_mask: int = 1
dsp_clock_hz: int = 400_000_000
total_ll_ticks: int = 0
active_pcm_streams: int = 0
# Workload Simulation state (SOF_NET_OP_WORKLOAD_SIM_CFG)
workload_sim_mode: int = 0 # 0=OFF, 1=VIRTUAL, 2=REALTIME
default_mem_domain: int = 0 # 0=SRAM, 1=DRAM
sram_factor_x100: int = 100
dram_factor_x100: int = 160
dram_cycles_per_word: int = 2
num_workload_overrides: int = 0
# PCM status over SOF_NET_OP_PCM_CTL
pcm_tone_running: bool = False
pcm_device: str = "hw:0,0"
pcm_rate: int = 48000
pcm_channels: int = 2
pcm_freq_hz: int = 1000
pcm_frames_played: int = 0
pcm_rms_level: int = 0
pcm_peak_level: int = 0
pcm_xruns: int = 0
# DAPM Graph over SOF_NET_OP_DAPM_GRAPH
dapm_total_nodes: int = 0
dapm_powered_nodes: int = 0
dapm_total_edges: int = 0
dapm_active_edges: int = 0
dapm_nodes: List[Dict[str, Any]] = field(default_factory=list)
dapm_edges: List[Dict[str, Any]] = field(default_factory=list)
# Memory & Heap
hpsram: SramSegmentState = field(default_factory=lambda: SramSegmentState("HPSRAM"))
lpsram: SramSegmentState = field(default_factory=lambda: SramSegmentState("LPSRAM"))
total_heap_bytes: int = 0
module_heap: Dict[str, int] = field(default_factory=dict)
# Cores, Pipelines, Components, Kcontrols & Probes
cores: List[CoreTelemetry] = field(default_factory=list)
pipelines: List[PipelineSchedTelemetry] = field(default_factory=list)
components: List[ComponentPerfItem] = field(default_factory=list)
kcontrols: List[KcontrolTelemetryItem] = field(default_factory=list)
probes: List[Dict[str, Any]] = field(default_factory=list)
loaded_modules: Dict[int, str] = field(default_factory=dict)
fw_error_logs: List[Dict[str, Any]] = field(default_factory=list)
# Extended TEL2 (MW2 Slot 1) & PMW2 (MW3) telemetry
tel2_present: bool = False
tel2_seq: int = 0
tel2_timestamp_us: int = 0
tel2_total_xruns: int = 0
tel2_heaps: List[Dict[str, Any]] = field(default_factory=list)
tel2_vregions: List[Dict[str, Any]] = field(default_factory=list)
tel2_gateways: List[Dict[str, Any]] = field(default_factory=list)
tel2_threads: List[Dict[str, Any]] = field(default_factory=list)
pmw2_present: bool = False
pmw2_io_perf: List[Dict[str, Any]] = field(default_factory=list)
wire_bytes: int = 0
raw_bytes: int = 0
# Shell outputs
shell_info: str = ""
shell_pipelines: str = ""
shell_stats: str = ""
shell_cycles: str = ""
shell_threads: str = ""
shell_platform_cfg: str = ""
shell_sched_telem: str = ""
shell_mod_buffers: str = ""
protocol_log: List[str] = field(default_factory=list)
def format_report(self) -> str:
pwr = "D0 (ACTIVE)" if self.dsp_power_state == 1 else f"D3 (PAUSED/{self.dsp_power_state})"
sim_modes = {0: "OFF (HOST-MEASURED)", 1: "VIRTUAL-CPC", 2: "REALTIME-PACED"}
mem_dom = "DRAM" if self.default_mem_domain == 1 else "SRAM"
lines = [
f"=== SOFR Network Protocol Telemetry (127.0.0.1:{self.server_port}) ===",
f"Platform: {self.platform} | FW: v{self.fw_version} ({self.fw_filename}) | State: {pwr}",
f"Wire Payload: {self.wire_bytes} B / {self.raw_bytes} B raw ({(100.0 * (1.0 - self.wire_bytes / max(1, self.raw_bytes))):.1f}% saved)",
f"DSP Cores: mask=0x{self.enabled_cores_mask:02x}/{self.num_cores} | Total LL Ticks: {self.total_ll_ticks} | Active PCMs: {self.active_pcm_streams}",
f"Workload Sim: {sim_modes.get(self.workload_sim_mode, 'OFF')} | Mem Domain: {mem_dom} (DRAM {self.dram_factor_x100 / 100.0:.2f}x +{self.dram_cycles_per_word} cyc/w) | Overrides: {self.num_workload_overrides}",
f"DAPM Graph: {self.dapm_powered_nodes}/{self.dapm_total_nodes} widgets powered, {self.dapm_active_edges}/{self.dapm_total_edges} routes active",
f"Memory: HPSRAM {self.hpsram.powered_banks}/{self.hpsram.total_banks} banks ON ({self.hpsram.free_phys_pages} free pages) | "
f"LPSRAM {self.lpsram.powered_banks}/{self.lpsram.total_banks} banks ON | Module Heap: {self.total_heap_bytes} B",
f"PCM Stream: {self.pcm_frames_played} frames @ {self.pcm_rate} Hz ({self.pcm_channels} ch) | "
f"RMS={self.pcm_rms_level} Peak={self.pcm_peak_level} Tone={'ON' if self.pcm_tone_running else 'OFF'}",
]
if self.cores:
lines.append("--- Active DSP Core Telemetry ---")
for c in self.cores:
if c.enabled or c.tick_count > 0:
freq_mhz = c.freq_hz / 1e6
lines.append(
f" Core {c.core_id} ({freq_mhz:.0f}MHz): ticks={c.tick_count} last={c.last_time_elapsed_cyc} cyc ({c.last_time_elapsed_us:.1f} us) "
f"max={c.max_time_elapsed_cyc} cyc LL={c.avg_kcps}/{c.peak_kcps} kcps DP={c.dp_avg_kcps}/{c.dp_peak_kcps} kcps "
f"load={c.cpu_load_pct:.2f}% overruns={c.ll_deadline_violations}"
)
if self.components:
lines.append("--- Per-Component Performance, Buffer Level & Heap Telemetry ---")
for comp in self.components:
if comp.module_id == 0:
continue
label = comp.widget_name or f"{comp.module_name} (0x{comp.module_id:02x}:{comp.instance_id})"
heap_str = f" heap={comp.heap_bytes}B" if comp.heap_bytes > 0 else ""
cpc_str = f" cpc={comp.effective_cpc}(v={comp.cpc_violations})" if comp.effective_cpc > 0 else ""
lvl_str = ""
if comp.in_rms_db > -119.0 or comp.out_rms_db > -119.0:
lvl_str = f" in={comp.in_rms_db:+.1f}dB→out={comp.out_rms_db:+.1f}dB"
lines.append(
f" [{comp.domain} C{comp.core_id} {comp.mem_domain}] {label:<30} avg={comp.avg_kcps:5d} kcps "
f"peak={comp.peak_kcps:5d} kcps iters={comp.iterations:4d} cyc={comp.total_cycles}{cpc_str}{lvl_str}{heap_str}"
)
if self.tel2_present:
lines.append(
f"--- Extended Memory Window 2 ('TEL2' seq={self.tel2_seq}, ts={self.tel2_timestamp_us} us, xruns={self.tel2_total_xruns}) ---"
)
for hp in self.tel2_heaps:
lines.append(
f" Heap[{hp['index']}] {hp['type']:<8} alloc={hp['allocated_bytes']}B free={hp['free_bytes']}B "
f"peak={hp['max_allocated_bytes']}B total={hp['total_bytes']}B fails={hp['alloc_fail_count']}"
)
for gw in self.tel2_gateways:
lines.append(
f" Gateway {gw['type']}[{gw['index']}] {gw['direction']:<8} comp=0x{gw['comp_id']:04x} "
f"period={gw['period_bytes']}B buf={gw['dma_buf_size']}B xfer={gw['total_kb']}KB "
f"avail={gw['dma_buf_avail_bytes']}B xruns={gw['xrun_count']}"
)
if self.tel2_threads:
lines.append(f" Zephyr Threads ({len(self.tel2_threads)}):")
for th in self.tel2_threads[:8]:
lines.append(
f" {th['name']:<8} (0x{th['thread_id']:08x}) C{th['core']} prio={th['prio']:3d} "
f"cpu={th['cpu_load_pct']:5.1f}% stack_hwm={th['stack_usage_pct']:5.1f}% ({th['stack_size_bytes']}B)"
)
if self.kcontrols:
lines.append(f"--- Topology Kcontrols ({len(self.kcontrols)}) ---")
for kc in self.kcontrols[:12]:
val_str = ",".join(str(v) for v in kc.values)
lines.append(
f" [numid={kc.numid:2d}] {kc.type_str:<5} {kc.name:<42} = [{val_str}] (widget: {kc.target_widget})"
)
if self.shell_platform_cfg:
lines.append("--- Platform Hardware Configuration ---")
lines.append(self.shell_platform_cfg)
if self.shell_sched_telem:
lines.append("--- Scheduler & Buffer Telemetry (sched-telem) ---")
lines.append(self.shell_sched_telem)
return "\n".join(lines)
@dataclass
class TestbenchRunResult:
success: bool
command: str
in_wav_path: str
out_wav_path: str
in_samples: List[float] = field(default_factory=list)
out_samples: List[float] = field(default_factory=list)
multi_in_samples: List[List[float]] = field(default_factory=list)
multi_out_samples: List[List[float]] = field(default_factory=list)
multi_out_wav_paths: List[str] = field(default_factory=list)
in_peak_db: float = -120.0
out_peak_db: float = -120.0
in_rms_db: float = -120.0
out_rms_db: float = -120.0
stdout: str = ""
stderr: str = ""
summary_text: str = ""
telemetry: Optional[TestbenchTelemetry] = None
# -----------------------------------------------------------------------------
# SOFR Network Protocol Client for sof-testbench4
# -----------------------------------------------------------------------------
class TestbenchRemoteClient:
"""TCP client implementing the SOFR binary framing protocol (sof_remote_proto.h)."""
def __init__(self, host: str = "127.0.0.1", port: int = SOF_NET_DEFAULT_PORT, timeout: float = 2.5):
self.host = host
self.port = port
self.timeout = timeout
self.sock: Optional[socket.socket] = None
self._rpc_lock = threading.RLock()
self.req_id: int = 1
self.protocol_log: List[str] = []
self.last_wire_bytes: int = 0
self.last_raw_bytes: int = 0
self._no_compress: bool = False
self.cached_modules: Dict[int, str] = dict(WELL_KNOWN_IPC4_MODULES)
self.cached_hpsram: Optional[SramSegmentState] = None
self.cached_lpsram: Optional[SramSegmentState] = None
self.cached_enabled_cores_mask: int = 0
# Metadata populated when pipelines/modules are created purely via IPC4 (no -t topology loaded on server)
self.ipc_widget_map: Dict[int, Tuple[str, int]] = {} # comp_id -> (widget_name, pipeline_id)
self.ipc_kcontrols: List[KcontrolTelemetryItem] = []
self.ipc_route_edges: List[Dict[str, Any]] = []
def _log(self, msg: str) -> None:
self.protocol_log.append(msg)
debug_log_line("SOFR", msg)
@staticmethod
def _resolve_ssh_host(host: str) -> str:
try:
socket.getaddrinfo(host, None)
return host
except Exception:
pass
ssh_cfg = os.path.expanduser("~/.ssh/config")
if not os.path.isfile(ssh_cfg):
return host
try:
in_match = False
with open(ssh_cfg, "r", encoding="utf-8", errors="ignore") as f:
for raw in f:
line = raw.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) >= 2 and parts[0].lower() == "host":
in_match = host in parts[1:]
elif in_match and len(parts) >= 2 and parts[0].lower() == "hostname":
return parts[1]
except Exception:
pass
return host
def connect(self) -> bool:
with self._rpc_lock:
self.close()
try:
target_host = self._resolve_ssh_host(self.host)
s = socket.create_connection((target_host, self.port), timeout=self.timeout)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.settimeout(self.timeout)
self.sock = s
return True
except Exception:
self.sock = None
return False
def close(self) -> None:
with self._rpc_lock:
if self.sock is not None:
try:
self.sock.close()
except Exception:
pass
self.sock = None
def _recv_exact(self, n: int) -> bytes:
if self.sock is None:
raise ConnectionError("Socket not connected")
buf = bytearray()
while len(buf) < n:
chunk = self.sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("Remote testbench socket closed")
buf.extend(chunk)
return bytes(buf)
@staticmethod
def _sofz_decompress(src: bytes) -> bytes:
if len(src) < 8:
raise ValueError("Truncated SOFZ header")
magic, raw_size = struct.unpack_from("<II", src, 0)
if magic != SOF_NET_COMP_MAGIC or raw_size > 16 * 1024 * 1024:
raise ValueError(f"Invalid SOFZ header magic=0x{magic:08x} size={raw_size}")
dst = bytearray(raw_size)
in_pos = 8
out_pos = 0
src_len = len(src)
while in_pos < src_len and out_pos < raw_size:
tok = src[in_pos]
in_pos += 1
tag = tok >> 6
if tag == 0:
zlen = tok
if zlen == 0:
if in_pos + 2 > src_len:
raise ValueError("Truncated SOFZ zero run")
zlen = src[in_pos] | (src[in_pos + 1] << 8)
in_pos += 2
if zlen == 0 or out_pos + zlen > raw_size:
raise ValueError("Invalid SOFZ zero run length")
out_pos += zlen
elif tag == 1:
llen = (tok & 0x3F) + 1
if in_pos + llen > src_len or out_pos + llen > raw_size:
raise ValueError("Invalid SOFZ literal run")
dst[out_pos : out_pos + llen] = src[in_pos : in_pos + llen]
in_pos += llen
out_pos += llen
elif tag == 2:
rlen = (tok & 0x3F) + 3
if in_pos + 1 > src_len or out_pos + rlen > raw_size:
raise ValueError("Invalid SOFZ repeat run")
val = src[in_pos]
in_pos += 1
dst[out_pos : out_pos + rlen] = bytes([val]) * rlen
out_pos += rlen
else:
mlen = (tok & 0x3F) + 4
if in_pos + 2 > src_len:
raise ValueError("Truncated SOFZ backref")
dist = src[in_pos] | (src[in_pos + 1] << 8)
in_pos += 2
if dist == 0 or dist > out_pos or out_pos + mlen > raw_size:
raise ValueError("Invalid SOFZ backref offset")
mpos = out_pos - dist
for k in range(mlen):
dst[out_pos + k] = dst[mpos + k]
out_pos += mlen
if out_pos != raw_size:
raise ValueError(f"SOFZ size mismatch {out_pos} != {raw_size}")
return bytes(dst)
def rpc(self, opcode: int, payload: bytes = b"") -> Tuple[int, bytes]:
with self._rpc_lock:
if self.sock is None and not self.connect():
return (-107, b"")
rid = self.req_id
self.req_id += 1
wire_op = opcode if self._no_compress else (opcode | SOF_NET_OP_FLAG_COMPRESSED)
hdr = struct.pack(
"<IHHIIi",
SOF_NET_MAGIC,
SOF_NET_VERSION,
wire_op,
rid,
len(payload),
0,
)
try:
assert self.sock is not None
self.sock.sendall(hdr + payload)
rhdr = self._recv_exact(20)
magic, ver, rop, rrid, plen, status = struct.unpack("<IHHIIi", rhdr)
if magic != SOF_NET_MAGIC or ver != SOF_NET_VERSION:
raise ConnectionError(f"Invalid SOFR header magic=0x{magic:08x} ver={ver}")
if status == -38 and not self._no_compress and plen == 0:
self._no_compress = True
return self.rpc(opcode, payload)
rdata = self._recv_exact(plen) if plen > 0 else b""
self.last_wire_bytes = plen
if (rop & SOF_NET_OP_FLAG_COMPRESSED) and plen >= 8:
rdata = self._sofz_decompress(rdata)
self.last_raw_bytes = len(rdata)
return (status, rdata)
except Exception:
self.close()
return (-104, b"")
def ping(self) -> bool:
st, data = self.rpc(SOF_NET_OP_PING)
ok = st == 0 and data.startswith(b"PONG")
if ok:
self._log(f"[SOFR] OP_PING (0x{SOF_NET_OP_PING:04x}) -> PONG")
return ok
def get_info(self) -> Optional[Dict[str, Any]]:
st, data = self.rpc(SOF_NET_OP_GET_INFO)
if st != 0 or len(data) < 140:
return None
(
abi_ver,
ipc_type,
fw_state,
dsp_power_state,
pm_active,
num_cores,
enabled_cores_mask,
max_payload,
ver_maj,
ver_min,
ver_mic,
ver_bld,
hw_ip,
plat_bytes,
fw_bytes,
) = struct.unpack_from("<IIIIIIIIHHHHI32s64s", data, 0)
info = {
"abi_version": abi_ver,
"ipc_type": ipc_type,
"fw_state": fw_state,
"dsp_power_state": dsp_power_state,
"pm_runtime_active": bool(pm_active),
"num_cores": max(1, min(8, num_cores)),
"enabled_cores_mask": enabled_cores_mask,
"max_payload_size": max_payload,
"fw_version": f"{ver_maj}.{ver_min}.{ver_mic}.{ver_bld}",
"hw_ip_version": hw_ip,
"platform": plat_bytes.split(b"\x00", 1)[0].decode("ascii", errors="replace"),
"fw_filename": fw_bytes.split(b"\x00", 1)[0].decode("ascii", errors="replace"),
}
self._log(
f"[SOFR] OP_GET_INFO -> platform={info['platform']} fw=v{info['fw_version']} "
f"cores_mask=0x{enabled_cores_mask:02x} pwr={'D0' if dsp_power_state == 1 else 'D3'}"
)
return info
def pm_control(self, op: int, core_id: int = 0) -> Tuple[int, Dict[str, Any]]:
req = struct.pack("<IIIIIIII", op, core_id, 0, 0, 0, 0, 0, 0)
st, data = self.rpc(SOF_NET_OP_PM_CTL, req)
op_names = {
SOF_PM_OP_QUERY: "QUERY",
SOF_PM_OP_WAKE_HOLD: "WAKE_HOLD(D0)",
SOF_PM_OP_RELEASE_HOLD: "RELEASE_HOLD(D3)",
SOF_PM_OP_BOOT_DSP: "BOOT_DSP",
SOF_PM_OP_CORE_GET: f"CORE_GET({core_id})",
SOF_PM_OP_CORE_PUT: f"CORE_PUT({core_id})",
}
if st == 0 and len(data) >= 32:
_, _, fw_st, pwr_st, pm_act, cmask, hold, _ = struct.unpack_from("<IIIIIIII", data, 0)
res = {
"fw_state": fw_st,
"dsp_power_state": pwr_st,
"pm_runtime_active": bool(pm_act),
"enabled_cores_mask": cmask,
"fd_holding_d0": bool(hold),
}
self._log(
f"[SOFR] OP_PM_CTL ({op_names.get(op, str(op))}) -> status={st} "
f"pwr={'D0' if pwr_st == 1 else 'D3'} cores=0x{cmask:02x}"
)
return (st, res)
return (st, {})
def set_perf_measurement_state(self, state_val: int = 2) -> int:
"""Configure BaseFW TB_IPC4_PERF_MEASUREMENTS_STATE (17): 0=disabled, 1=stopped, 2=started, 3=paused."""
payload = struct.pack(
"<IIIIII",
0,
0,
TB_IPC4_PERF_MEASUREMENTS_STATE,
SOF_CDEV_LARGE_CFG_SET,
4,
0,
) + struct.pack("<I", state_val)
st, _ = self.rpc(SOF_NET_OP_IPC_LARGE_CFG, payload)
state_names = {0: "DISABLED", 1: "STOPPED", 2: "STARTED", 3: "PAUSED"}
self._log(
f"[SOFR] OP_IPC_LARGE_CFG (PERF_MEASUREMENTS_STATE={state_names.get(state_val, str(state_val))}) -> status={st}"
)
return st
def exec_shell(self, cmd: str, timeout_ms: int = 1500) -> Tuple[int, str]:
cmd_b = cmd.encode("utf-8") + b"\x00"
req = struct.pack("<II", timeout_ms, len(cmd_b)) + cmd_b
st, rdata = self.rpc(SOF_NET_OP_SHELL_EXEC, req)
out = rdata.decode("utf-8", errors="replace") if rdata else ""
self._log(f"[SOFR] OP_SHELL_EXEC '{cmd}' -> status={st} ({len(out)} bytes)")
debug_log_command("SOFR-SHELL", cmd, returncode=st, stdout=out)
return (st, out)
def pcm_control(
self,
op: int,
device: str = "hw:0,0",
rate: int = 48000,
channels: int = 2,
freq_hz: int = 1000,
duration_ms: int = 150,
api_backend: int = SOF_AUDIO_API_ALSA,
fmt_id: int = SOF_PCM_FMT_S16_LE,
) -> Tuple[int, Dict[str, Any], bytes]:
dev_b = device.encode("ascii", errors="ignore")[:31].ljust(32, b"\x00")
req = struct.pack(
"<I32sIIIIIIIII",
op,
dev_b,
rate,
channels,
freq_hz,
duration_ms,
0,
api_backend,
fmt_id,
1024,
4,
)
st, rdata = self.rpc(SOF_NET_OP_PCM_CTL, req)
op_names = {
SOF_PCM_OP_STATUS: "STATUS",
SOF_PCM_OP_START_TONE: f"START_TONE({freq_hz}Hz)",
SOF_PCM_OP_STOP_TONE: "STOP_TONE",
SOF_PCM_OP_PLAY_BUFFER: "PLAY_BUFFER",
SOF_PCM_OP_CAPTURE_BUFFER: f"CAPTURE_BUFFER({duration_ms}ms)",
}
if len(rdata) >= 80:
tone_run, adev, r_rate, r_ch, r_freq, frames, rms, peak, dsz, api_u, fmt_u, xruns = (
struct.unpack_from("<I32sIIIQIIIIII", rdata, 0)
)
pcm_bytes = rdata[80 : 80 + dsz] if dsz > 0 else b""
info = {
"tone_running": bool(tone_run),
"device": adev.split(b"\x00", 1)[0].decode("ascii", errors="replace"),
"rate": r_rate,
"channels": r_ch,
"freq_hz": r_freq,
"frames_played": frames,
"rms_level": rms,
"peak_level": peak,
"data_size": dsz,
"api_used": api_u,
"format": fmt_u,
"xruns": xruns,
}
if op != SOF_PCM_OP_STATUS:
self._log(
f"[SOFR] OP_PCM_CTL ({op_names.get(op, str(op))}) -> frames={frames} "
f"rms={rms} peak={peak} captured={len(pcm_bytes)}B"
)
return (st, info, pcm_bytes)
return (st, {}, b"")
def list_kcontrols(self, card_id: int = 0) -> List[KcontrolTelemetryItem]:
req = struct.pack("<II", card_id, SOF_AUDIO_API_ALSA)
st, kdata = self.rpc(SOF_NET_OP_KCTL_LIST, req)
items: List[KcontrolTelemetryItem] = []
if st != 0 or len(kdata) < 12:
return items
_, _, nk = struct.unpack_from("<III", kdata, 0)
off = 12
khead_fmt = "<III12sIII64sI12sI12sIqqqIiiII"
khead_sz = struct.calcsize(khead_fmt) # 180 bytes
kanc_fmt = "<Iii64s48siHH"
kanc_sz = struct.calcsize(kanc_fmt) # 132 bytes
kinfo_sz = khead_sz + 192 + 64 + kanc_sz # 568 bytes
for _ in range(nk):
if off + kinfo_sz > len(kdata):
break
(
_cid,
numid,
_iface,
if_b,
_dev,
_subdev,
_idx,
nm_b,
ktype,
tstr_b,
_amask,
astr_b,
cnt,
min_v,
max_v,