-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbenchmark.py
More file actions
4156 lines (3704 loc) · 193 KB
/
Copy pathbenchmark.py
File metadata and controls
4156 lines (3704 loc) · 193 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
#!/usr/bin/env python3
"""
Multi-vendor GPU simultaneous-stream transcoding benchmark + live scoreboard.
Tests how many concurrent 4K HEVC -> 1080p H.264 (8 Mbit) real-time transcodes a GPU
can sustain. Works on Intel (VAAPI), AMD (VAAPI), and NVIDIA (NVENC/NVDEC). The GPU is
chosen live in the web UI.
Model (B): each ffmpeg runs flat-out (no -re) with -stream_loop -1, racing the hardware.
Per-stream speed is computed instantaneously from -progress out_time_us deltas (NOT
ffmpeg's cumulative speed= field). The ramp adds one stream per level; the answer is the
highest N where the WORST stream still sustains >= PASS_THRESHOLD x realtime over the
hold window. Methodology is identical across vendors so the numbers are comparable.
The only external-binary dependency is jellyfin-ffmpeg (+ optional lspci/dmidecode/
nvidia-smi/intel_gpu_top for info & proof). Everything else lives here.
"""
import os
import re
import sys
import glob
import json
import time
import shutil
import signal
import shlex
import threading
import subprocess
import hashlib
import struct
import fcntl
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# ---------------------------------------------------------------- config
def _env(k, d):
return os.environ.get(k, d)
FFMPEG = _env("FFMPEG_BIN", "/usr/lib/jellyfin-ffmpeg/ffmpeg")
FFPROBE = _env("FFPROBE_BIN", FFMPEG.rsplit("ffmpeg", 1)[0] + "ffprobe")
RAMDISK = _env("RAMDISK", "/ramdisk")
SOURCE = os.path.join(RAMDISK, "source.mkv")
CLIPS_DIR = _env("CLIPS_DIR", "/app/clips") # transition-era images ship clips here
PROBES_DIR = _env("PROBES_DIR", "/app/probes") # tiny 1s clips for capability probing only
# Canonical clips are PINNED GitHub Release assets (immutable tag clips-v1) — downloaded once,
# hash-verified against this baked-in manifest, cached in appdata. URL is HARDCODED by design:
# changing clips means shipping a new image with a new manifest, never a config edit.
CLIPS_BASE_URL = "https://github.com/SpaceinvaderOne/transcoding-gpu-benchmark/releases/download/clips-v1/"
CLIP_MANIFEST = { # name -> (sha256, exact bytes) — extracted from the validated image
"source_4k_hevc.mkv": ("13ff9e46afac887744c508fac0bf343281ebf1168e8ff9017ab7532be9f5a27a", 455504333),
"source_4k_av1.mkv": ("8e2da2352791d4f3c066c29ebfe92b0bd657ec898233be635d43e099aee728f6", 409161502),
"source_4k_h264.mkv": ("9c44eef58045ceaf1e768a9f6736eb3119e67aae7f3fadde25de19ae58d920e1", 442156462),
"source_4k_hdr.mkv": ("41a36e640fa40609bcbab0ce0f42a1fba58c1ef3808606f816da6ec57cbd4bce", 455506587),
"source_1080p_h264.mkv": ("6394d675568c48fc502adacb98bf59abebe8bfd4ebdb064d6751e9ead636f237", 84393066),
}
INPUT_CODECS = ("h264", "hevc", "av1") # selectable source codecs (must hw-decode)
BURNIN_ASS = _env("BURNIN_ASS", "/app/burnin.ass") # shipped deterministic burn-in subtitles
INPUT_DIR = _env("INPUT_DIR", "/input") # optional BYO-clip drop folder (read-only)
MAX_CUSTOM_FILES = int(_env("MAX_CUSTOM_FILES", "25")) # >this in /input ⇒ "looks like a library"
HOLD_SECONDS = float(_env("HOLD_SECONDS", "25"))
SETTLE_SECONDS = float(_env("SETTLE_SECONDS", "5"))
PASS_THRESHOLD = float(_env("PASS_THRESHOLD", "1.0"))
OUTPUT_BITRATE = _env("OUTPUT_BITRATE", "8M")
SOURCE_BITRATE = _env("SOURCE_BITRATE", "50M")
SOURCE_DURATION = _env("SOURCE_DURATION", "60")
SOURCE_SIZE = _env("SOURCE_SIZE", "3840x2160")
SOURCE_FPS = _env("SOURCE_FPS", "24")
MAX_STREAMS = int(_env("MAX_STREAMS", "128"))
CONV_MAX_STREAMS = int(_env("CONV_MAX_STREAMS", "8")) # conversion ramp stops at throughput plateau
WEB_PORT = int(_env("WEB_PORT", "8088"))
STATE_FILE = _env("STATE_FILE", "/tmp/state.json")
CONFIG_DIR = _env("CONFIG_DIR", "/config") # Unraid appdata mount (CPU baseline persistence)
POWERCAP_DIR = _env("POWERCAP_DIR", "/powercap") # optional RO mount of host
# /sys/devices/virtual/powercap (RAPL CPU power)
BASELINE_FILE = os.path.join(CONFIG_DIR, "cpu_baseline.json")
CLIPS_CACHE_DIR = os.path.join(CONFIG_DIR, "clips") # one-time clip cache (survives updates)
HISTORY_FILE = os.path.join(CONFIG_DIR, "history.json") # per-run history (newest last)
HISTORY_CAP = int(_env("HISTORY_CAP", "200"))
INSTALL_ID_FILE = os.path.join(CONFIG_DIR, "install_id") # random per-install uuid (submission dedup)
SUBMIT_SCHEMA = 1 # leaderboard submission-contract version
CPU_PRESETS = {"streaming": _env("CPU_PRESET_STREAM", "veryfast"), # Plex/Jellyfin live reality
"convert": _env("CPU_PRESET_CONVERT", "medium")} # Tdarr/Unmanic library reality
CPU_ENCODERS = {"h264": "libx264", "hevc": "libx265", "av1": "libsvtav1"}
SAMPLE_INTERVAL = float(_env("SAMPLE_INTERVAL", "1.0"))
DMI_TABLE = _env("DMI_TABLE", "/dmi/DMI") # raw SMBIOS table (optional RO mount)
UNRAID_VER_FILE = _env("UNRAID_VER_FILE", "/unraid-version") # optional RO mount
OS_VER_FILE = _env("OS_VER_FILE", "/os-release") # optional RO mount of the HOST's /etc/os-release
# (non-Unraid fallback; NOT the container's own)
DYNAMIX_CFG = _env("DYNAMIX_CFG", "/dynamix.cfg") # optional RO mount of Unraid's
# dynamix.cfg (temperature unit)
# leaderboard endpoint — hardcoded by policy (changed only by shipping a new image version);
# will move to gpu.spaceinvader.one once the domain's DNS is on Cloudflare. Setting the env var
# to empty/whitespace disables submission entirely (the Submit button never shows).
SUBMIT_URL = _env("SUBMIT_URL", "https://gpu.spaceinvader.one/api/submit").strip()
TOOL_VERSION = "1.8"
# SMBIOS Memory Device "Memory Type" enum (subset)
MEM_TYPE = {0x13: "DDR", 0x14: "DDR2", 0x18: "DDR3", 0x1A: "DDR4", 0x1E: "LPDDR",
0x1F: "LPDDR2", 0x20: "LPDDR3", 0x21: "LPDDR4", 0x22: "DDR5", 0x23: "LPDDR5"}
APP_DIR = os.path.dirname(os.path.abspath(__file__))
SCOREBOARD = os.path.join(APP_DIR, "scoreboard.html")
# stderr signatures for a stream that died at startup — split by WHICH ceiling it hit.
# SESSION = the driver's concurrent-NVENC-session limit; MEMORY = a VRAM allocation failure
# (measured on the patched 5090: each 4K session holds ~1.4 GB, the card fills at ~96% and the
# next session dies in the CUDA scale filter with "Cannot allocate memory").
SESSION_CAP_PATTERNS = (
"openencodesessionex",
"encode session",
"maximum number",
"no encode",
)
MEMORY_CAP_PATTERNS = (
"cannot allocate memory",
"out of memory",
)
NVENC_CAP_PATTERNS = SESSION_CAP_PATTERNS + MEMORY_CAP_PATTERNS # legacy: "any known ceiling"
# NVENC session-limit patch detection (keylase/nvidia-patch). The patch NOPs the session-count
# check inside libnvidia-encode.so; we detect it by scanning that library (bind-mounted into the
# container by the NVIDIA runtime) for the per-driver-version stock vs patched byte signatures.
# The signature table ships as data (nvenc_sigs.json, extracted from patch.sh) because you can
# only PATCH a version the table covers — so any patched card is, by construction, detectable as
# long as we ship the current table. Unknown version ⇒ None (fail safe, never a wrong answer).
NVENC_SIGS_FILE = _env("NVENC_SIGS_FILE", os.path.join(APP_DIR, "nvenc_sigs.json"))
NVENC_ENCODE_LIBS = (
"/usr/lib64/libnvidia-encode.so.",
"/usr/lib/x86_64-linux-gnu/libnvidia-encode.so.",
"/usr/lib/libnvidia-encode.so.",
)
def load_nvenc_sigs(path=NVENC_SIGS_FILE):
"""{driver_version: [stock_hex, patched_hex]} or {} if the data file is missing."""
try:
with open(path) as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except Exception:
return {}
def nvenc_lock_state(lib_bytes, driver_version, sigs):
"""Driver NVENC session-cap state from the encode library's bytes:
'unlocked' (patched — cap removed), 'locked' (stock signature intact), or None (the driver
version isn't in the signature table, or neither signature is present — can't tell)."""
sig = sigs.get(driver_version or "")
if not sig or not lib_bytes:
return None
try:
stock, patched = bytes.fromhex(sig[0]), bytes.fromhex(sig[1])
except (ValueError, IndexError):
return None
if patched and patched in lib_bytes:
return "unlocked"
if stock and stock in lib_bytes:
return "locked"
return None
def detect_nvenc_unlocked(driver_version, sigs=None):
"""True/False/None — is this NVIDIA driver's NVENC session cap patched out? Locates the
encode library for the running driver version and scans it. None when undeterminable."""
if not driver_version:
return None
sigs = load_nvenc_sigs() if sigs is None else sigs
if driver_version not in sigs:
return None
for base in NVENC_ENCODE_LIBS:
lib = base + driver_version
try:
with open(lib, "rb") as f:
data = f.read()
except Exception:
continue
state = nvenc_lock_state(data, driver_version, sigs)
if state is not None:
return state == "unlocked"
return None
# ------------------------------------------------- pure helpers (unit tested)
def parse_progress_kv(line):
"""Parse one ffmpeg -progress 'key=value' line. Returns (key, value) or None."""
line = line.strip()
if not line or "=" not in line:
return None
k, v = line.split("=", 1)
return k.strip(), v.strip()
def compute_inst_speed(prev_out_us, prev_wall, cur_out_us, cur_wall):
"""Instantaneous speed = (delta output seconds) / (delta wall seconds).
out values are ffmpeg out_time_us (microseconds); wall is monotonic seconds.
Returns 0.0 if no wall time elapsed (avoids div-by-zero on the first sample).
"""
dw = cur_wall - prev_wall
if dw <= 0:
return 0.0
return ((cur_out_us - prev_out_us) / 1_000_000.0) / dw
def is_session_cap_error(errtext):
"""True if ffmpeg stderr looks like a hardware/driver encode-session cap."""
t = (errtext or "").lower()
return any(p in t for p in NVENC_CAP_PATTERNS)
def death_reason(errtext):
"""Classify a zero-output startup death by its stderr: 'session' (driver session cap),
'memory' (VRAM allocation failure), or None (unrecognised)."""
t = (errtext or "").lower()
if any(p in t for p in SESSION_CAP_PATTERNS):
return "session"
if any(p in t for p in MEMORY_CAP_PATTERNS):
return "memory"
return None
def vram_slope(samples):
"""Per-session VRAM cost (MB) = MEDIAN of consecutive per-level increments, normalised per
session. Increments only — the level-1 absolute carries one-time context/pool costs. Median
(not mean/fit) so a single co-tenant allocation blip can't skew it. Needs >= 2 increments."""
s = sorted(samples)
incs = []
for (na, va), (nb, vb) in zip(s, s[1:]):
if nb > na and va is not None and vb is not None:
incs.append((vb - va) / (nb - na))
if len(incs) < 2:
return None
incs.sort()
m = len(incs) // 2
return incs[m] if len(incs) % 2 else (incs[m - 1] + incs[m]) / 2
def predict_wall(current_n, free_mb, slope_mb):
"""Predicted total concurrent sessions before VRAM runs out: N + floor(free/slope)."""
if free_mb is None or not slope_mb or slope_mb <= 0:
return None
return current_n + int(free_mb // slope_mb)
def classify_stop(died_zero_output, reason, fail_level, predicted_wall):
"""The four-state limit taxonomy (see the VRAM-instrumentation spec):
throughput (worst stream slid below threshold), session (driver cap signature),
memory (alloc signature, or unrecognised death that lands where the VRAM prediction said
the wall was, +/-1), unknown (hard death nowhere the prediction expected — flag-worthy)."""
if not died_zero_output:
return "throughput"
if reason in ("session", "memory"):
return reason
if predicted_wall is not None and abs(fail_level - predicted_wall) <= 1:
return "memory"
return "unknown"
def millideg_to_c(raw):
"""Convert a sysfs millidegree value to °C (rounded to 0.1), or None."""
try:
return round(int(raw) / 1000.0, 1)
except (TypeError, ValueError):
return None
def estimate_igpu_power(loaded_pkg, idle_pkg):
"""iGPU power estimate = rise in CPU-package power under load (>=0). None if missing."""
if loaded_pkg is None or idle_pkg is None:
return None
return round(max(0.0, loaded_pkg - idle_pkg), 1)
def _num(s):
"""First number in a string like '149.7 W' / '55 %', else None."""
if s is None:
return None
m = re.search(r"-?\d+(?:\.\d+)?", s)
return float(m.group()) if m else None
def parse_nvidia_xml(xml_text):
"""Parse `nvidia-smi -q -x` output for the first GPU. {} on failure.
Returns util/enc/dec/temp/power/power_max/clock/throttle(bool)/procs(list)."""
try:
root = ET.fromstring(xml_text)
except Exception:
return {}
g = root.find("gpu")
if g is None:
return {}
def t(path):
el = g.find(path)
return el.text if el is not None else None
throttle = False
er = g.find("clocks_event_reasons")
if er is not None:
for child in er:
if "Not Active" not in (child.text or "Not Active"):
throttle = True
procs = [pi.findtext("process_name") or "?" for pi in g.findall("processes/process_info")]
return {
"util": _num(t("utilization/gpu_util")),
"enc": _num(t("utilization/encoder_util")),
"dec": _num(t("utilization/decoder_util")),
"temp": _num(t("temperature/gpu_temp")),
"power": _num(t("gpu_power_readings/instant_power_draw")
or t("gpu_power_readings/average_power_draw")
or t("gpu_power_readings/power_draw")
or t("power_readings/power_draw")
or t("power_readings/instant_power_draw")),
"power_max": _num(t("gpu_power_readings/current_power_limit")
or t("power_readings/power_limit")),
"clock": _num(t("clocks/sm_clock")),
"throttle": throttle,
"procs": [p for p in procs if p and p != "?"],
}
def parse_fdinfo(text):
"""Parse a /proc/<pid>/fdinfo/<fd> DRM client. {} if not a DRM fd.
Returns {driver, pdev, video_ns}."""
kv = {}
for line in text.splitlines():
if ":" in line:
k, _, v = line.partition(":")
kv[k.strip()] = v.strip()
if "drm-driver" not in kv:
return {}
m = re.search(r"\d+", kv.get("drm-engine-video", "0"))
return {"driver": kv["drm-driver"], "pdev": kv.get("drm-pdev"),
"video_ns": int(m.group()) if m else 0}
def parse_amd_engines(text):
"""Parse VCN media-engine counters from an amdgpu /proc/<pid>/fdinfo/<fd>.
The encode/decode load lives in drm-engine-enc/-dec (nanosecond accumulators) — the
GPU-wide gpu_busy_percent is the GFX pipe and stays near-idle during transcode.
On this RDNA4/radeonsi stack all VCN work (HEVC decode AND H.264 encode) is accounted
on the single `enc` ring (there is no separate `dec` ring), and the scale_vaapi VPP runs
on `compute` — so we read enc (=VCN media) and compute (=scaler).
Returns {enc_ns, dec_ns, comp_ns, enc_cap, dec_cap, pdev, client} or {} if not amdgpu."""
kv = {}
for line in text.splitlines():
if ":" in line:
k, _, v = line.partition(":")
kv[k.strip()] = v.strip()
if kv.get("drm-driver") != "amdgpu":
return {}
def _ns(key):
m = re.search(r"\d+", kv.get(key, "0"))
return int(m.group()) if m else 0
def _cap(key):
m = re.search(r"\d+", kv.get(key, ""))
return int(m.group()) if m else 1 # absent capacity line == single instance
return {"enc_ns": _ns("drm-engine-enc"), "dec_ns": _ns("drm-engine-dec"),
"comp_ns": _ns("drm-engine-compute"),
"enc_cap": _cap("drm-engine-capacity-enc"),
"dec_cap": _cap("drm-engine-capacity-dec"),
"pdev": kv.get("drm-pdev"), "client": kv.get("drm-client-id")}
def engine_pct(delta_ns, dt_s, cap):
"""Engine occupancy % over a window: busy-ns / (wall-ns * instances), clamped [0,100].
None when the window is non-positive (can't divide)."""
if dt_s is None or dt_s <= 0:
return None
cap = cap or 1
pct = 100.0 * delta_ns / (dt_s * 1e9 * cap)
return round(max(0.0, min(100.0, pct)), 1)
def _mem_kib(v):
"""A DRM fdinfo memory value ("40972 KiB", "12 MiB", "0") -> KiB."""
m = re.match(r"(\d+)\s*(\w*)", v or "")
if not m:
return 0
n, unit = int(m.group(1)), m.group(2)
return {"": n // 1024 if n else 0, "B": n // 1024, "KiB": n,
"MiB": n * 1024, "GiB": n * 1024 * 1024}.get(unit, n)
def parse_xe_fdinfo(text):
"""Parse an Intel xe/i915 DRM fdinfo (Arc dGPUs — captured from a real Arc Pro B50).
VRAM held by the client is drm-resident-vramN (xe) / drm-resident-localN (i915 dGPUs),
in KiB/MiB. Media engines are CYCLE counters (not the ns accumulators amdgpu uses):
drm-cycles-vcs (video decode+encode, capacity 2 on Battlemage) and drm-cycles-vecs
(video enhance — scale_vaapi lands here), each against the free-running
drm-total-cycles-* wall counter. Returns {vram_kib, cycles, pdev, client} or {}."""
kv = {}
for line in (text or "").splitlines():
if ":" in line:
k, _, v = line.partition(":")
kv[k.strip()] = v.strip()
if kv.get("drm-driver") not in ("xe", "i915"):
return {}
vram_kib = 0
for k, v in kv.items():
if re.fullmatch(r"drm-resident-(vram|local)\d+", k):
vram_kib += _mem_kib(v)
def _num(key):
m = re.search(r"\d+", kv.get(key, ""))
return int(m.group()) if m else 0
cycles = {"vcs": _num("drm-cycles-vcs"), "vcs_total": _num("drm-total-cycles-vcs"),
"vcs_cap": _num("drm-engine-capacity-vcs") or 1,
"vecs": _num("drm-cycles-vecs"), "vecs_total": _num("drm-total-cycles-vecs"),
"vecs_cap": _num("drm-engine-capacity-vecs") or 1}
return {"vram_kib": vram_kib, "cycles": cycles,
"pdev": kv.get("drm-pdev"), "client": kv.get("drm-client-id")}
def cycle_pct(d_cycles, d_total, cap):
"""xe engine busy% from cycle-counter deltas: busy ÷ (wall × instances), clamped [0,100].
None when the wall window is non-positive (can't divide)."""
if not d_total or d_total <= 0:
return None
cap = cap or 1
return round(max(0.0, min(100.0, 100.0 * d_cycles / (d_total * cap))), 1)
def parse_bar_vram_mb(resource_text):
"""VRAM total (MB) from a PCI `resource` file: the largest MEM BAR (flag 0x200). Every
xe-driven card requires resizable BAR, so the BAR spans the whole VRAM — the real B50
exposes exactly 16 GiB. A best BAR under 1 GiB is a legacy 256 MB aperture window, NOT
the VRAM size → None (unknown, never guessed)."""
best = 0
for line in (resource_text or "").splitlines():
parts = line.split()
if len(parts) >= 3:
try:
start, end, flags = (int(p, 16) for p in parts[:3])
except ValueError:
continue
if flags & 0x200 and end > start: # IORESOURCE_MEM
best = max(best, end - start + 1)
return round(best / 1048576.0, 1) if best >= 1024 ** 3 else None
def vram_capable(gpu):
"""Which devices get VRAM accounting: NVIDIA/AMD dGPUs (nvidia-smi / amdgpu fdinfo) plus
Intel Arc dGPUs (xe/i915 fdinfo). iGPUs and the CPU share system RAM — nothing to track
(an AMD APU flipped to is_igpu by the link heuristic is excluded the same way)."""
v = gpu.get("vendor")
if v == "intel":
return not gpu.get("is_igpu")
return v in ("nvidia", "amd") and not gpu.get("is_igpu")
def smbios_mem_speeds(data):
"""Parse a raw SMBIOS structure table (bytes); return (configured_max, rated_max)
memory speeds in MT/s, or (None, None). Walks Type 17 (Memory Device) records:
Speed at offset 0x15, Configured Memory Speed at 0x20 (both u16 LE; 0/0xFFFF = unknown)."""
cfg, rated = [], []
i, n = 0, len(data)
while i + 4 <= n:
stype, length = data[i], data[i + 1]
if length < 4 or stype == 127: # bad/end-of-table
break
if stype == 17:
if length > 0x16 and i + 0x17 <= n:
sp = data[i + 0x15] | (data[i + 0x16] << 8)
if sp not in (0, 0xFFFF):
rated.append(sp)
if length > 0x21 and i + 0x22 <= n:
cs = data[i + 0x20] | (data[i + 0x21] << 8)
if cs not in (0, 0xFFFF):
cfg.append(cs)
# advance: skip formatted area, then the string-set (ends at a double NUL)
j = i + length
while j + 1 < n and not (data[j] == 0 and data[j + 1] == 0):
j += 1
j += 2
if j <= i:
break
i = j
return (max(cfg) if cfg else None, max(rated) if rated else None)
def smbios_mem_type(data):
"""Return the memory type string (e.g. 'DDR4', 'DDR5') from SMBIOS Type 17, or None.
Memory Type is a 1-byte field at offset 0x12 of each Memory Device record."""
i, n = 0, len(data)
while i + 4 <= n:
stype, length = data[i], data[i + 1]
if length < 4 or stype == 127:
break
if stype == 17 and length > 0x12 and i + 0x13 <= n:
t = MEM_TYPE.get(data[i + 0x12])
if t:
return t
j = i + length
while j + 1 < n and not (data[j] == 0 and data[j + 1] == 0):
j += 1
j += 2
if j <= i:
break
i = j
return None
# ------------------------------------------------------------- shared state
STATE = {
"ui": "idle", # idle|preparing|running|done|error — which SCREEN to show
"source_ready": False, # is a source clip already present (Start is near-instant)?
"phase": "idle", # idle|preparing|ramping|settling|holding|done|error (live detail)
"message": "Ready.",
"gpus": [], # detected GPUs (picker) [{idx,name,vendor,api,available,note,is_igpu}]
"selected_idx": None, # which GPU is chosen
"selected_name": None,
"selected_input": "hevc", # SOURCE codec to decode (h264|hevc|av1) — must be hw-decodable
"selected_codec": "h264", # output codec for the run (h264|hevc|av1)
"selected_source_res": "4k", # source resolution (4k|1080p) — advanced; default 4K
"selected_target_res": "1080p", # output resolution (4k|1080p|720p, <= source) — default 1080p
"selected_mode": "streaming", # streaming (how many at once) | convert (how fast)
"selected_subs": False, # burn the shipped subtitles in (streaming realism toggle)
"selected_hdr_out": False, # keep HDR (HDR10 passthrough) instead of tone-mapping to SDR
"clips": [], # canonical-clip cache states [{name,status,size_mb}]
"clips_shipped": True, # image bakes the clips in (transition) ⇒ hide the clips panel
"clip_dl": None, # live download progress {name,pct,mb,total_mb}
"custom_files": [], # BYO-clip drop folder contents [{name,path,codec,res}]
"custom_library": False, # /input looks like a media library (too many files)
"selected_custom": None, # chosen custom file NAME (None ⇒ use the shipped clip)
"vendor": None, # intel | amd | nvidia (of the chosen GPU)
"driver": None, # VAAPI driver (iHD/radeonsi) or NVIDIA driver version
"kernel_driver": None, # kernel DRM driver (i915/xe/amdgpu/nvidia)
"is_igpu": False, # show CPU + RAM speed only for the Intel iGPU
"cpu": None, # CPU model (iGPU only)
"ram_speed": None, # configured RAM speed e.g. "2133 MT/s" (iGPU only)
"ram_type": None, # DDR4 | DDR5 (iGPU only)
"ram_hint": None, # "below rated 2667 MT/s (XMP/EXPO off?)" (iGPU only)
"kernel": None, # host kernel
"os_version": None, # Unraid OS version (if mounted)
"telemetry": {}, # live GPU stats {util,temp,power,clock,...}
"streams_per_watt": None, # streams of throughput per watt
"power_estimated": False, # True when power is the iGPU package-delta estimate
"result": None, # structured result payload (for share/submit)
"submit_url_set": False, # is a leaderboard endpoint configured?
"submitted": False, # has THIS result been submitted (button becomes a checkmark)?
"busy_load": None, # pre-test: GPU engine load if already in use
"busy_apps": [], # pre-test: names of apps using the GPU (if knowable)
"busy_named": False, # can we name the apps (host-pid visibility / nvidia)?
"encoder": None, # VAAPI | NVENC
"bitrate": OUTPUT_BITRATE,
"threshold": PASS_THRESHOLD,
"hold_seconds": HOLD_SECONDS,
"settle_seconds": SETTLE_SECONDS, # so the UI can show a per-level ETA
"history": [], # past runs of the SAME device+mode+profile (newest first)
"history_delta": None, # headline change vs history[0] ({metric,prev,cur,pct})
"batch": False, # test-all-devices run in progress / just finished
"batch_queue": [], # device names queued for the batch
"batch_done": 0, # completed batch runs so far
"batch_results": [], # per-device summary rows for the comparison table
"batch_skipped": [], # devices left out of the batch: [{gpu, reason}]
"stream_count": 0,
"streams": [], # [{id, speed, fps, pass}]
"min_speed": None, # worst per-stream inst speed (headline gauge)
"avg_speed": None,
"combined_speed": None, # sum, informational only
"last_passing": 0,
"confirmed_max": None,
"single_stream_speed": None, # 1-stream speed (informational)
"conv_levels": [], # convert mode: [{n, combined}] per COMPLETED level (live curve)
"conv_testing_n": None, # convert mode: worker count currently being measured, or None
"vram_note": None, # live dGPU VRAM slope + predicted wall ("each stream ~1.4 GB…")
"projected": None, # live running estimate = peak combined throughput so far
"cap_reason": None, # "session" when an encode-session cap stopped the ramp
"projected_uncapped": None, # estimated streams if the session cap were lifted
"gpu": None, # {engine_name: busy%} best-effort (Intel)
"ts": 0.0,
}
STATE_LOCK = threading.Lock()
def publish(**kw):
"""Update shared state and atomically write state.json."""
with STATE_LOCK:
STATE.update(kw)
STATE["ts"] = time.time()
data = json.dumps(STATE)
try:
tmp = STATE_FILE + ".tmp"
with open(tmp, "w") as f:
f.write(data)
os.replace(tmp, STATE_FILE)
except Exception:
pass
# --------------------------------------------------------- system/GPU detection
def cpu_model():
try:
with open("/proc/cpuinfo") as f:
for line in f:
if line.startswith("model name"):
return line.split(":", 1)[1].strip()
except Exception:
pass
return None
def _dmidecode_speeds(text):
cfg, rated, mtype = [], [], None
for line in text.splitlines():
line = line.strip()
m = re.match(r"Configured Memory Speed:\s*(\d+)\s*MT/s", line)
if m:
cfg.append(int(m.group(1)))
continue
m = re.match(r"Speed:\s*(\d+)\s*MT/s", line)
if m:
rated.append(int(m.group(1)))
continue
m = re.match(r"Type:\s*(DDR\d|LPDDR\d?)", line)
if m and not mtype:
mtype = m.group(1)
return (max(cfg) if cfg else None, max(rated) if rated else None, mtype)
def ram_info():
"""(configured_mts, rated_mts, type) best-effort. Tries dmidecode (works where the
host exposes /sys/firmware/dmi/tables), then a raw SMBIOS table mounted at DMI_TABLE."""
try:
r = subprocess.run(["dmidecode", "-t", "memory"],
capture_output=True, text=True, timeout=6)
if r.returncode == 0:
cfg, rated, mtype = _dmidecode_speeds(r.stdout)
if cfg:
return (cfg, rated, mtype)
except Exception:
pass
try:
with open(DMI_TABLE, "rb") as f:
data = f.read()
cfg, rated = smbios_mem_speeds(data)
return (cfg, rated, smbios_mem_type(data))
except Exception:
return (None, None, None)
def kernel_version():
try:
return os.uname().release
except Exception:
return None
def parse_os_version(txt):
"""Pull the OS version out of an /etc/unraid-version-style file. Handles Unraid's numeric
version="7.3.2" AND non-numeric ones from other OSes the container runs on — e.g. MOS
reports version="MOS 0.5.0". The old regex anchored the value to a leading digit, so a
non-numeric version fell through and dumped the whole raw line (version="MOS 0.5.0" instead
of MOS 0.5.0). Returns the value inside version="...", or a bare version=..., capped to a
sane length; None when there's nothing usable."""
t = txt or ""
m = re.search(r'version="([^"]+)"', t) or re.search(r'version=([^\s"]+)', t)
return ((m.group(1) if m else t).strip())[:60] or None
def parse_os_release(txt):
"""Pull a human OS name out of an /etc/os-release file: PRETTY_NAME without a trailing
CPU-arch suffix (e.g. "Ubuntu 22.04.3 LTS", "Debian GNU/Linux 12 (bookworm)"). Unraid's
own PRETTY_NAME is "Unraid OS 7.3 x86_64" -> "Unraid OS 7.3", but Unraid is read from the
version file first so we only reach here on non-Unraid hosts. Capped to a sane length;
None when there's no PRETTY_NAME."""
m = re.search(r'^PRETTY_NAME="?([^"\n]+)"?', txt or "", re.M)
if not m:
return None
v = re.sub(r'\s+(x86_64|amd64|aarch64|arm64|i[0-9]86)$', '', m.group(1).strip())
return v[:60] or None
def os_version():
"""Resolve the HOST OS version, most specific source first:
1. /unraid-version (Unraid and Unraid-family builds like MOS ship this) -> precise version;
2. /os-release PRETTY_NAME (any other Linux, via the docker-compose mount) -> distro name;
both are OPTIONAL RO mounts of the HOST's files (never the container's own /etc/os-release,
which is the jellyfin-ffmpeg Debian base). None when neither is mounted. The value is stored
RAW; the board decides whether to prefix "Unraid" (see osLabel in worker.js)."""
try:
with open(UNRAID_VER_FILE) as f:
v = parse_os_version(f.read())
if v:
return v
except Exception:
pass
try:
with open(OS_VER_FILE) as f:
return parse_os_release(f.read())
except Exception:
return None
def parse_display_unit(text):
"""Temperature unit ("C"/"F") from Unraid's dynamix.cfg ([display] unit="F").
Anything missing or unrecognised falls back to Celsius — this only sets the UI
default; all stored/submitted temperatures stay Celsius regardless."""
m = re.search(r'^unit="([CF])"', text or "", re.M)
return m.group(1) if m else "C"
def _read(path):
try:
with open(path) as f:
return f.read().strip()
except Exception:
return None
def _f(s):
"""Parse a float, tolerating None / 'N/A' / '[N/A]'."""
try:
return float(s)
except (TypeError, ValueError):
return None
def read_cpu_package_temp():
"""CPU-package temperature in °C (the iGPU shares this die). Intel: x86_pkg_temp thermal
zone / coretemp Package sensor; AMD: k10temp (Tctl). None if unreadable."""
for zone in glob.glob("/sys/class/thermal/thermal_zone*"):
if (_read(zone + "/type") or "") == "x86_pkg_temp":
t = millideg_to_c(_read(zone + "/temp"))
if t is not None:
return t
for hw in glob.glob("/sys/class/hwmon/hwmon*"):
if (_read(hw + "/name") or "") != "coretemp":
continue
for lbl in glob.glob(hw + "/temp*_label"):
if "Package" in (_read(lbl) or ""):
t = millideg_to_c(_read(lbl.replace("_label", "_input")))
if t is not None:
return t
for hw in glob.glob("/sys/class/hwmon/hwmon*"): # AMD CPUs: k10temp, Tctl preferred
if (_read(hw + "/name") or "") != "k10temp":
continue
for lbl in glob.glob(hw + "/temp*_label"):
if (_read(lbl) or "") in ("Tctl", "Tdie"):
t = millideg_to_c(_read(lbl.replace("_label", "_input")))
if t is not None:
return t
t = millideg_to_c(_read(hw + "/temp1_input"))
if t is not None:
return t
return None
def _pci_link_unknown(pci):
"""True when the device reports no PCIe link speed — the tell for an INTEGRATED GPU
(root-complex endpoints have no link, so the PCI core says "Unknown"; every physical
card reports a real speed). Unreadable counts as unknown → treated as integrated."""
v = (_read(f"/sys/bus/pci/devices/{pci}/current_link_speed") or "").strip()
return (not v) or v.lower().startswith("unknown")
def format_pci_id(vendor_txt, device_txt):
""""0x8086" + "0xe212" -> "8086:e212" — the exact silicon id, immune to a stale pci.ids
name database. None when either half is missing or malformed."""
m1 = re.fullmatch(r"0x([0-9a-fA-F]{4})", (vendor_txt or "").strip())
m2 = re.fullmatch(r"0x([0-9a-fA-F]{4})", (device_txt or "").strip())
return f"{m1.group(1).lower()}:{m2.group(1).lower()}" if (m1 and m2) else None
def pci_device_id(pci):
"""The PCI vendor:device id from sysfs. Carried in the result payload as dormant curation
evidence — the board never uses it automatically (no maintained GPU table), but a human
can resolve exactly which silicon a generically named row was ("Battlemage G21 [Intel
Graphics]": B50 or B60?), whatever the image's pci.ids knew at the time."""
if not pci:
return None
return format_pci_id(_read(f"/sys/bus/pci/devices/{pci}/vendor"),
_read(f"/sys/bus/pci/devices/{pci}/device"))
def _pci_name(pci_addr):
"""Friendly device name via lspci -mm; None if lspci/addr unavailable."""
if not pci_addr:
return None
try:
out = subprocess.run(["lspci", "-mm", "-s", pci_addr],
capture_output=True, text=True, timeout=5).stdout
parts = shlex.split(out)
if len(parts) >= 4:
return parts[3] # the device string
except Exception:
pass
return None
def _nvidia_smi_gpus():
"""List NVIDIA GPUs visible to the container (runtime present). [] otherwise."""
try:
out = subprocess.run(
["nvidia-smi", "--query-gpu=index,name,driver_version,uuid", "--format=csv,noheader"],
capture_output=True, text=True, timeout=8)
if out.returncode != 0:
return []
gpus = []
for line in out.stdout.splitlines():
line = line.strip()
if not line:
continue
parts = [p.strip() for p in line.split(",")]
idx, name = int(parts[0]), parts[1]
drv = parts[2] if len(parts) > 2 else None
uuid_ = parts[3] if len(parts) > 3 and parts[3].startswith("GPU-") else None
gpus.append({"index": idx, "name": name, "driver": drv, "uuid": uuid_})
return gpus
except Exception:
return []
ENCODERS = {
"vaapi": {"h264": "h264_vaapi", "hevc": "hevc_vaapi", "av1": "av1_vaapi"},
"nvenc": {"h264": "h264_nvenc", "hevc": "hevc_nvenc", "av1": "av1_nvenc"},
}
def enc_name(api, codec):
return ENCODERS[api][codec]
def codec_supported(gpu, codec, ten_bit=False):
"""Quick 1-frame probe: can this GPU's encoder actually do this codec? With ten_bit, probes
10-bit (p010/main10) encode — hardware H.264 is 8-bit only so H.264 10-bit always fails."""
if ten_bit and codec == "h264":
return False # no hardware 10-bit H.264 encode exists
enc = enc_name(gpu["api"], codec)
fmt = "p010le" if ten_bit else "nv12"
prof = ["-profile:v", "main10"] if (ten_bit and codec == "hevc") else []
# 1280x720 (not tiny) — AV1 encoders reject sub-minimum resolutions ("no capable devices")
common = [FFMPEG, "-hide_banner", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc=size=1280x720:rate=1", "-frames:v", "1"]
if gpu["api"] == "vaapi":
cmd = (common[:1] + ["-vaapi_device", gpu["device"]] + common[1:]
+ ["-vf", f"format={fmt},hwupload", "-c:v", enc] + prof + ["-f", "null", "-"])
else:
dev = _nv_dev(gpu, "-gpu")
cmd = common + ["-vf", f"format={fmt}", "-c:v", enc] + prof + dev + ["-f", "null", "-"]
try:
r = subprocess.run(cmd, env=stream_env(gpu),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20)
return r.returncode == 0
except Exception:
return False
# ---- resolution / bit-depth matrix -----------------------------------------
RES_DIMS = {"4k": (3840, 2160), "1080p": (1920, 1080), "720p": (1280, 720)}
RES_LABEL = {"4k": "4K", "1080p": "1080p", "720p": "720p"}
SOURCE_RES = ("4k", "1080p") # shippable source resolutions
TARGET_RES = ("4k", "1080p", "720p") # selectable output resolutions
# which source codecs ship at each source resolution (4K = full set + the HDR10 master; 1080p =
# the "modernise my old H.264 library" case only, keeping the image small). "hdr" is a pseudo
# codec: the HDR10 HEVC clip, offered only to devices whose tone-map probe passes.
SOURCE_CODECS_BY_RES = {"4k": ("h264", "hevc", "av1", "hdr"), "1080p": ("h264",)}
def target_res_options(source_res):
"""Output resolutions no larger than the source (never upscale)."""
sh = RES_DIMS[source_res][1]
return [r for r in TARGET_RES if RES_DIMS[r][1] <= sh]
def source_is_10bit(source_codec):
"""The shipped 10-bit masters are HEVC/AV1; H.264 clips are 8-bit."""
return source_codec in ("hevc", "av1")
def ten_bit_output(source_res, target_res, source_codec, out_codec):
"""Preserve 10-bit only when KEEPING resolution (archival intent) from a 10-bit source to an
HEVC/AV1 encoder — hardware H.264 encode is 8-bit only, and a downscale accepts a lighter
version so it goes 8-bit."""
return (source_is_10bit(source_codec) and target_res == source_res
and out_codec in ("hevc", "av1"))
def is_comparable(source_res, target_res):
"""Only the canonical 4K -> 1080p resolution profile is leaderboard-comparable; every other
resolution pair is a local-only run (like a custom file)."""
return source_res == "4k" and target_res == "1080p"
SATURATION_GAIN = 0.05 # <5% more combined throughput ⇒ the media engine has plateaued
def throughput_saturated(combined, best, thresh=SATURATION_GAIN):
"""True once adding a stream no longer meaningfully raises COMBINED throughput (< thresh gain
over the best seen) — the conversion ramp's stop rule (there is NO ≥realtime rule for batch)."""
return best > 0 and combined <= best * (1 + thresh)
def recommended_workers(levels, peak, cap=None):
"""Best concurrent-worker count for batch tools (Tdarr/Unmanic): the worker count with the
HIGHEST measured combined throughput — the absolute fastest way to drain the library. On a GPU
whose one media engine is already saturated (e.g. the UHD 770) adding a stream LOWERS combined
throughput, so this correctly lands on 1. Clamped to a driver session cap if one was hit.
`levels` = [{n, combined}, ...]."""
if not levels or not peak:
return 1
# fastest = max combined; ties break to the FEWER workers (sort by n ascending, keep first max)
n = max(sorted(levels, key=lambda x: x["n"]), key=lambda L: L["combined"])["n"]
return min(n, cap) if cap else n
# ---------------------------------------------- CPU baseline & efficiency comparison (pure logic)
def cpu_baseline_key(mode, profile):
"""The per-(mode, profile) key a CPU baseline is stored/looked-up under."""
return f"{mode}|{profile}"
def baseline_valid(entry, cpu_model, tool_version):
"""A stored CPU baseline is comparable only if it was measured on the SAME CPU and a
tool version with the same MAJOR (a major bump may change the clip/methodology → stale)."""
if not entry:
return False
if entry.get("cpu_model") != cpu_model:
return False
def major(v):
return str(v or "").split(".")[0]
return major(entry.get("tool_version")) == major(tool_version)
def efficiency_ratio(cpu_wps, gpu_wps):
"""How many times more power-efficient the GPU is: CPU watts/stream ÷ GPU watts/stream."""
if not cpu_wps or not gpu_wps:
return None
return round(cpu_wps / gpu_wps, 1)
def speed_ratio(gpu_speed, cpu_speed):
"""How many times faster the GPU is (streams sustained, or ×realtime per file)."""
if not gpu_speed or not cpu_speed:
return None
return round(gpu_speed / cpu_speed, 1)
def compute_vs_cpu(mode, gpu, cpu, is_dgpu):
"""Assemble the 'vs CPU' comparison payload from a GPU result and a CPU baseline entry.
`gpu`/`cpu` carry single_stream, max_sustained, watts_per_stream, peak_power_w (+ cpu preset/
encoder). Speed metric is streams (streaming) or per-file × (conversion). All ratios guard
against zero (CPU may sustain 0 streams / have no power reading)."""
streaming = mode == "streaming"
gpu_speed = gpu.get("max_sustained") if streaming else gpu.get("single_stream")
cpu_speed = cpu.get("max_sustained") if streaming else cpu.get("single_stream")
return {
"efficiency": efficiency_ratio(cpu.get("watts_per_stream"), gpu.get("watts_per_stream")),
"speed": speed_ratio(gpu_speed, cpu_speed),
"speed_kind": "streams" if streaming else "perfile",
"gpu_speed": gpu_speed, "cpu_speed": cpu_speed,
"cpu_could_sustain": (cpu.get("max_sustained") or 0) >= 1 if streaming else True,
# watts_per_stream = watts ÷ combined ×realtime = Wh per HOUR OF VIDEO already —
# dividing by speed again double-counts (the ratio would wrongly become eff × speed)
"energy_gpu": gpu.get("watts_per_stream"),
"energy_cpu": cpu.get("watts_per_stream"),
"watts_gpu": gpu.get("peak_power_w"), "watts_cpu": cpu.get("peak_power_w"),
"cpu_preset": cpu.get("preset"), "cpu_encoder": cpu.get("encoder"),
"dgpu_caveat": bool(is_dgpu),
}
def rapl_delta_uj(prev_uj, cur_uj, max_range_uj):
"""Energy consumed (µJ) between two reads of a RAPL counter that wraps at
max_energy_range_uj. None when inputs are missing or it wrapped with an unknown range."""
if prev_uj is None or cur_uj is None:
return None
if cur_uj >= prev_uj:
return cur_uj - prev_uj
if not max_range_uj:
return None
return cur_uj - prev_uj + max_range_uj
def rapl_watts(delta_uj, dt_s):
"""µJ over a window → watts (1 W = 1e6 µJ/s)."""
if delta_uj is None or not dt_s or dt_s <= 0:
return None
return round(delta_uj / dt_s / 1e6, 1)
def rapl_package_paths(root=POWERCAP_DIR):
"""Top-level RAPL PACKAGE domains under a mounted powercap tree. Matches
<root>/intel-rapl/intel-rapl:<n> whose `name` starts with 'package' — the single-colon glob
naturally skips nested core/uncore subdomains (intel-rapl:0:0) and the intel-rapl-mmio
duplicates (which would double-count the same silicon). [] when unmounted/absent."""
paths = []
for d in sorted(glob.glob(os.path.join(root, "intel-rapl", "intel-rapl:[0-9]*"))
+ glob.glob(os.path.join(root, "intel-rapl:[0-9]*"))):
base = os.path.basename(d)
if ":" in base.replace("intel-rapl:", "", 1): # intel-rapl:0:0 → nested subdomain