edidgen 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
edidgen/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """Generate EDID binaries from a validated TOML config."""
2
+
3
+ from edidgen.config import parse_config
4
+ from edidgen.encode import build_edid
5
+ from edidgen.model import Config, Display, Hdmi, Hdr, RangeLimits, Timing, TimingKind
6
+ from edidgen.reader import Diagnostics
7
+ from edidgen.timing import cvt_rb, cvt_rb2
8
+
9
+
10
+ __all__ = [
11
+ "Config",
12
+ "Diagnostics",
13
+ "Display",
14
+ "Hdmi",
15
+ "Hdr",
16
+ "RangeLimits",
17
+ "Timing",
18
+ "TimingKind",
19
+ "build_edid",
20
+ "cvt_rb",
21
+ "cvt_rb2",
22
+ "parse_config",
23
+ ]
edidgen/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from edidgen.cli import main
4
+
5
+
6
+ sys.exit(main())
edidgen/cli.py ADDED
@@ -0,0 +1,123 @@
1
+ """Command-line interface."""
2
+
3
+ import argparse
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ import tomllib
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from edidgen.config import parse_config
12
+ from edidgen.encode import build_edid
13
+ from edidgen.reader import Diagnostics
14
+ from edidgen.tables import VICS
15
+
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Sequence
19
+
20
+ from edidgen.model import Config
21
+
22
+
23
+ def summarize(cfg: Config) -> list[str]:
24
+ lines = [
25
+ f" {'*' if i == 0 else ' '} DTD {t.label():>18} {t.pclk_mhz:8.2f} MHz "
26
+ f"{t.hfreq_khz:6.1f} kHz"
27
+ for i, t in enumerate(cfg.modes)
28
+ ]
29
+ lines += [
30
+ f" VIC {v:<3}{VICS[v].width}x{VICS[v].height}@{VICS[v].refresh:g}"
31
+ f"{'i' if VICS[v].interlaced else ''}{' (native)' if v == cfg.native_vic else ''}"
32
+ for v in cfg.vics
33
+ ]
34
+ return lines
35
+
36
+
37
+ def main(argv: Sequence[str] | None = None) -> int:
38
+ ap = argparse.ArgumentParser(
39
+ description="Generate an EDID binary from a TOML config."
40
+ )
41
+ ap.add_argument("config", type=Path, help="TOML config file")
42
+ ap.add_argument(
43
+ "-o",
44
+ "--output",
45
+ type=Path,
46
+ help="output .bin (default: `output` in the config, else the config name with .bin)",
47
+ )
48
+ ap.add_argument(
49
+ "--check", action="store_true", help="validate only; don't write anything"
50
+ )
51
+ ap.add_argument(
52
+ "--decode", action="store_true", help="run edid-decode on the result"
53
+ )
54
+ ap.add_argument(
55
+ "--allow-invalid",
56
+ action="store_true",
57
+ help="write the EDID even if it breaks the spec (e.g. modes above the HDMI "
58
+ "TMDS limit); values that can't be encoded at all are still errors",
59
+ )
60
+ args = ap.parse_args(argv)
61
+
62
+ try:
63
+ with args.config.open("rb") as f:
64
+ data = tomllib.load(f)
65
+ except OSError as e:
66
+ print(f"error: cannot read {args.config}: {e.strerror}", file=sys.stderr)
67
+ return 2
68
+ except tomllib.TOMLDecodeError as e:
69
+ print(f"{args.config}: TOML syntax error: {e}", file=sys.stderr)
70
+ return 1
71
+
72
+ diag = Diagnostics(allow_invalid=args.allow_invalid)
73
+ cfg = parse_config(data, diag)
74
+ for w in diag.warnings:
75
+ print(f"{args.config}: warning: {w}", file=sys.stderr)
76
+ for v in diag.allowed_violations:
77
+ print(f"{args.config}: invalid (allowed): {v}", file=sys.stderr)
78
+ if cfg is None:
79
+ for err in diag.errors:
80
+ print(f"{args.config}: error: {err}", file=sys.stderr)
81
+ n = len(diag.errors)
82
+ print(f"{n} error{'s' * (n != 1)}; no file written.", file=sys.stderr)
83
+ k = diag.blocking_violations
84
+ if k == n:
85
+ hint = "--allow-invalid would write the EDID anyway (these are spec violations)."
86
+ elif k:
87
+ are = "is a spec violation" if k == 1 else "are spec violations"
88
+ hint = f"{k} of these {are} that --allow-invalid accepts; the rest must be fixed."
89
+ if k:
90
+ print(hint, file=sys.stderr)
91
+ return 1
92
+
93
+ edid = build_edid(cfg)
94
+ n_bad = len(diag.allowed_violations)
95
+ status = (
96
+ f"INVALID ({n_bad} allowed violation{'s' * (n_bad != 1)})" if n_bad else "valid"
97
+ )
98
+ print(
99
+ f"{args.config}: {status} ({len(cfg.modes)} detailed modes, {len(cfg.vics)} VICs)"
100
+ )
101
+ for line in summarize(cfg):
102
+ print(line)
103
+ if args.check:
104
+ return 0
105
+
106
+ out: Path = args.output or (
107
+ args.config.parent / cfg.output
108
+ if cfg.output
109
+ else args.config.with_suffix(".bin")
110
+ )
111
+ try:
112
+ out.write_bytes(edid)
113
+ except OSError as e:
114
+ print(f"error: cannot write {out}: {e.strerror}", file=sys.stderr)
115
+ return 2
116
+ print(f"wrote {out} ({len(edid)} bytes)")
117
+
118
+ if args.decode:
119
+ if shutil.which("edid-decode") is None:
120
+ print("edid-decode not installed; skipping", file=sys.stderr)
121
+ else:
122
+ subprocess.run(["edid-decode", "-c", str(out)], check=False)
123
+ return 0
edidgen/config.py ADDED
@@ -0,0 +1,361 @@
1
+ """Parse and validate a TOML config into a `Config`."""
2
+
3
+ from typing import Final
4
+
5
+ from edidgen.encode import cta_data_blocks, dtd_limit_errors, dtd_violations
6
+ from edidgen.model import Config, Display, Hdmi, Hdr, RangeLimits, Timing, TimingKind
7
+ from edidgen.reader import Diagnostics, Reader, Table
8
+ from edidgen.tables import (
9
+ BIT_DEPTHS,
10
+ DEEP_COLOR_BITS,
11
+ DTD_MAX_PCLK_MHZ,
12
+ INTERFACES,
13
+ VICS,
14
+ )
15
+ from edidgen.timing import ReducedBlanking, cvt_exact
16
+
17
+
18
+ EXPLICIT_KEYS: Final = (
19
+ "pixel_clock_mhz",
20
+ "h_front",
21
+ "h_sync",
22
+ "h_back",
23
+ "v_front",
24
+ "v_sync",
25
+ "v_back",
26
+ )
27
+ CVT_KINDS: Final = {
28
+ TimingKind.CVT: ReducedBlanking.NONE,
29
+ TimingKind.CVT_RB: ReducedBlanking.V1,
30
+ TimingKind.CVT_RB2: ReducedBlanking.V2,
31
+ TimingKind.CVT_RB3: ReducedBlanking.V3,
32
+ }
33
+ EXPLICIT: Final = frozenset({TimingKind.EXPLICIT})
34
+ # Mode options that only make sense for some timing kinds.
35
+ OPTION_KINDS: Final[dict[str, frozenset[TimingKind]]] = {
36
+ **dict.fromkeys(
37
+ (*EXPLICIT_KEYS, "h_sync_positive", "v_sync_positive", "h_border", "v_border"),
38
+ EXPLICIT,
39
+ ),
40
+ "refresh": frozenset(CVT_KINDS),
41
+ "margins": frozenset(CVT_KINDS),
42
+ "video_optimized": frozenset({TimingKind.CVT_RB2}),
43
+ "h_blank": frozenset({TimingKind.CVT_RB3}),
44
+ "v_blank_us": frozenset({TimingKind.CVT_RB3}),
45
+ "early_vsync": frozenset({TimingKind.CVT_RB3}),
46
+ }
47
+
48
+
49
+ def _check_option_kinds(r: Reader, kind: TimingKind) -> None:
50
+ for key, kinds in OPTION_KINDS.items():
51
+ if r.has(key) and kind not in kinds:
52
+ allowed = " or ".join(f'"{k.value}"' for k in TimingKind if k in kinds)
53
+ if key == "refresh":
54
+ msg = "not allowed with explicit timings (it is derived from pixel_clock_mhz and the totals)"
55
+ else:
56
+ msg = f"only allowed with timing = {allowed} (timing is {kind.value!r})"
57
+ r.diag.error(r.where(key), msg)
58
+ r.seen.add(key)
59
+
60
+
61
+ def _parse_explicit(r: Reader, width: int, height: int, *, interlaced: bool) -> Timing:
62
+ for k in EXPLICIT_KEYS:
63
+ if not r.has(k):
64
+ r.diag.error(r.where(k), 'required for timing = "explicit"')
65
+ return Timing(
66
+ # 0.01 MHz is the smallest a DTD can hold; below 10 MHz is a violation.
67
+ pclk_mhz=r.number("pixel_clock_mhz", 0.0, 0.01, DTD_MAX_PCLK_MHZ),
68
+ h_active=width,
69
+ h_front=r.integer("h_front", 0, 0, 1023),
70
+ h_sync=r.integer("h_sync", 0, 1, 1023),
71
+ h_back=r.integer("h_back", 0, 0, 4095),
72
+ v_active=height,
73
+ v_front=r.integer("v_front", 0, 0, 63),
74
+ v_sync=r.integer("v_sync", 0, 1, 63),
75
+ v_back=r.integer("v_back", 0, 0, 4095),
76
+ h_sync_positive=r.boolean("h_sync_positive", default=True),
77
+ v_sync_positive=r.boolean("v_sync_positive", default=True),
78
+ interlaced=interlaced,
79
+ h_border=r.integer("h_border", 0, 0, 255),
80
+ v_border=r.integer("v_border", 0, 0, 255),
81
+ )
82
+
83
+
84
+ def _parse_cvt(
85
+ r: Reader,
86
+ kind: TimingKind,
87
+ width: int,
88
+ height: int,
89
+ *,
90
+ interlaced: bool,
91
+ n_errors: int,
92
+ ) -> Timing | None:
93
+ """Read every CVT option, then compute the timing if the mode had no errors so far."""
94
+ if not r.has("refresh"):
95
+ r.diag.error(r.where("refresh"), "required")
96
+ refresh = r.number("refresh", 60.0, 1.0, 1000.0)
97
+ margins = r.boolean("margins", default=False)
98
+ video_optimized = r.boolean("video_optimized", default=False)
99
+ early_vsync = r.boolean("early_vsync", default=False)
100
+ h_blank = r.integer("h_blank", 80, 80, 200)
101
+ if h_blank % 8:
102
+ r.diag.error(r.where("h_blank"), f"must be a multiple of 8 (got {h_blank})")
103
+ # edid-decode's --cvt raises anything below 460 µs to 460, so that is the floor here.
104
+ v_blank_us = r.integer("v_blank_us", 460, 460, 920)
105
+ if v_blank_us > 705:
106
+ r.diag.warn(
107
+ r.where("v_blank_us"), "above 705 may not be supported by RB3 sources"
108
+ )
109
+ if len(r.diag.errors) != n_errors:
110
+ return None
111
+ return cvt_exact(
112
+ width,
113
+ height,
114
+ refresh,
115
+ CVT_KINDS[kind],
116
+ interlaced=interlaced,
117
+ margins=margins,
118
+ video_optimized=video_optimized,
119
+ h_blank=h_blank,
120
+ v_blank_us=v_blank_us,
121
+ early_vsync=early_vsync,
122
+ ).timing
123
+
124
+
125
+ def parse_mode(r: Reader) -> Timing | None:
126
+ n_errors = len(r.diag.errors)
127
+ width = r.integer("width", 0, 1, 4095)
128
+ height = r.integer("height", 0, 1, 4095)
129
+ if not r.has("width"):
130
+ r.diag.error(r.where("width"), "required")
131
+ if not r.has("height"):
132
+ r.diag.error(r.where("height"), "required")
133
+ default_kind = "explicit" if any(r.has(k) for k in EXPLICIT_KEYS) else "cvt-rb"
134
+ kind = TimingKind(r.choice("timing", default_kind, [k.value for k in TimingKind]))
135
+ interlaced = r.boolean("interlaced", default=False)
136
+ _check_option_kinds(r, kind)
137
+
138
+ timing: Timing | None
139
+ if kind is TimingKind.EXPLICIT:
140
+ timing = _parse_explicit(r, width, height, interlaced=interlaced)
141
+ else:
142
+ timing = _parse_cvt(
143
+ r, kind, width, height, interlaced=interlaced, n_errors=n_errors
144
+ )
145
+ r.finish()
146
+ if len(r.diag.errors) != n_errors or timing is None:
147
+ return None
148
+
149
+ limits = dtd_limit_errors(timing)
150
+ for msg in limits:
151
+ r.diag.error(r.path, msg)
152
+ for msg in dtd_violations(timing):
153
+ r.diag.violation(r.path, msg)
154
+ return None if len(r.diag.errors) != n_errors else timing
155
+
156
+
157
+ def parse_config(data: Table, diag: Diagnostics) -> Config | None:
158
+ root = Reader(data, "", diag)
159
+ output = root.string("output", "") or None
160
+
161
+ d = root.table_("display")
162
+ manufacturer = d.string("manufacturer", "XXX")
163
+ if not (
164
+ len(manufacturer) == 3
165
+ and manufacturer.isascii()
166
+ and manufacturer.isupper()
167
+ and manufacturer.isalpha()
168
+ ):
169
+ diag.error(
170
+ d.where("manufacturer"),
171
+ f"must be 3 uppercase letters A-Z (got {manufacturer!r})",
172
+ )
173
+ name = d.string("name", "VirtDisplay")
174
+ if not name or len(name) > 13 or not all(0x20 <= ord(c) < 0x7F for c in name):
175
+ diag.error(
176
+ d.where("name"), f"must be 1-13 printable ASCII characters (got {name!r})"
177
+ )
178
+ bit_depth = d.integer("bit_depth", 8, 6, 16)
179
+ if bit_depth not in BIT_DEPTHS:
180
+ diag.error(
181
+ d.where("bit_depth"),
182
+ f"must be one of {sorted(BIT_DEPTHS)} (got {bit_depth})",
183
+ )
184
+ size = d.int_pair("size_cm", 1, 255) or (60, 34)
185
+ display = Display(
186
+ name=name,
187
+ manufacturer=manufacturer,
188
+ product_code=d.integer("product_code", 0, 0, 0xFFFF),
189
+ serial=d.integer("serial", 0, 0, 0xFFFFFFFF),
190
+ week=d.integer("week", 1, 0, 54),
191
+ year=d.integer("year", 2026, 1990, 2245),
192
+ size_cm=size,
193
+ gamma=d.number("gamma", 2.2, 1.0, 3.54),
194
+ bit_depth=bit_depth,
195
+ interface=d.choice("interface", "hdmi-a", list(INTERFACES)),
196
+ )
197
+ d.finish()
198
+
199
+ h = root.table_("hdmi")
200
+ is_hdmi = display.interface.startswith("hdmi")
201
+ hdmi = Hdmi(
202
+ enabled=h.boolean("enabled", default=is_hdmi),
203
+ max_tmds_mhz=h.integer("max_tmds_mhz", 340, 25, 600),
204
+ deep_color=tuple(h.int_list("deep_color", 30, 48) or ()),
205
+ y444_deep_color=h.boolean("y444_deep_color", default=True),
206
+ scdc=h.boolean("scdc", default=True),
207
+ )
208
+ for i, dc in enumerate(hdmi.deep_color):
209
+ if dc not in DEEP_COLOR_BITS:
210
+ diag.error(
211
+ f"{h.where('deep_color')}[{i}]",
212
+ f"must be one of {sorted(DEEP_COLOR_BITS)} (got {dc})",
213
+ )
214
+ if hdmi.enabled and not is_hdmi:
215
+ diag.warn(
216
+ h.path,
217
+ f"HDMI data blocks enabled but display.interface is {display.interface!r}",
218
+ )
219
+ if hdmi.max_tmds_mhz % 5:
220
+ diag.error(h.where("max_tmds_mhz"), "must be a multiple of 5")
221
+ h.finish()
222
+
223
+ x = root.table_("hdr")
224
+ hdr = Hdr(
225
+ enabled=x.boolean("enabled", default=False),
226
+ bt2020=x.boolean("bt2020", default=True),
227
+ max_luminance_nits=x.number("max_luminance_nits", 0.0, 0.0, 12000.0),
228
+ max_frame_avg_nits=x.number("max_frame_avg_nits", 0.0, 0.0, 12000.0),
229
+ )
230
+ for key in ("max_luminance_nits", "max_frame_avg_nits"):
231
+ nits: float = getattr(hdr, key)
232
+ if 0 < nits < 50:
233
+ diag.error(x.where(key), "must be 0 (unspecified) or at least 50")
234
+ if hdr.max_frame_avg_nits > hdr.max_luminance_nits > 0:
235
+ diag.violation(
236
+ x.where("max_frame_avg_nits"), "cannot exceed max_luminance_nits"
237
+ )
238
+ x.finish()
239
+
240
+ g = root.table_("range")
241
+ range_limits = RangeLimits(
242
+ vrefresh_hz=g.int_pair("vrefresh_hz", 1, 255),
243
+ hfreq_khz=g.int_pair("hfreq_khz", 1, 255),
244
+ max_pixel_clock_mhz=g.integer("max_pixel_clock_mhz", 0, 10, 2550) or None,
245
+ )
246
+ for key, pair in (
247
+ ("vrefresh_hz", range_limits.vrefresh_hz),
248
+ ("hfreq_khz", range_limits.hfreq_khz),
249
+ ):
250
+ if pair and pair[0] > pair[1]:
251
+ diag.violation(g.where(key), f"min {pair[0]} is greater than max {pair[1]}")
252
+ g.finish()
253
+
254
+ mode_readers = root.table_list("modes")
255
+ # A non-array `modes` was already reported by table_list.
256
+ if not mode_readers and data.get("modes", []) == []:
257
+ diag.error(
258
+ "modes",
259
+ "at least one [[modes]] entry is required (the first is the preferred mode)",
260
+ )
261
+ parsed = [parse_mode(m) for m in mode_readers]
262
+ modes = tuple(t for t in parsed if t is not None)
263
+
264
+ vics = root.int_list("vics", 1, 219) or []
265
+ for i, v in enumerate(vics):
266
+ if v not in VICS:
267
+ diag.error(
268
+ f"vics[{i}]",
269
+ f"VIC {v} is not in the supported table ({', '.join(map(str, sorted(VICS)))})",
270
+ )
271
+ native_vic = root.integer("native_vic", 0, 1, 64) or None
272
+ if native_vic is not None and native_vic not in vics:
273
+ diag.error("native_vic", f"VIC {native_vic} must also be listed in vics")
274
+ root.finish()
275
+
276
+ if diag.errors:
277
+ return None
278
+ cfg = Config(
279
+ output, display, range_limits, hdmi, hdr, modes, tuple(vics), native_vic
280
+ )
281
+ cross_check(cfg, diag)
282
+ return None if diag.errors else cfg
283
+
284
+
285
+ def cross_check(cfg: Config, diag: Diagnostics) -> None:
286
+ """Checks that involve more than one option.
287
+
288
+ Only called once every field parsed cleanly, so `cfg.modes` is complete and non-empty.
289
+ """
290
+ seen: dict[tuple[int, int, int], str] = {}
291
+ for i, t in enumerate(cfg.modes):
292
+ key = (t.h_active, t.v_active, round(t.refresh))
293
+ where = f"modes[{i}]"
294
+ if key in seen:
295
+ diag.warn(where, f"{t.label()} duplicates {seen[key]}")
296
+ seen.setdefault(key, where)
297
+ if cfg.hdmi.enabled and t.pclk_mhz > cfg.hdmi.max_tmds_mhz:
298
+ diag.violation(
299
+ where,
300
+ f"{t.label()} needs {t.pclk_mhz:.2f} MHz but hdmi.max_tmds_mhz is "
301
+ f"{cfg.hdmi.max_tmds_mhz}; the driver would drop this mode",
302
+ )
303
+ if t.pclk_mhz > 340 and cfg.hdmi.enabled and not cfg.hdmi.scdc:
304
+ diag.warn(
305
+ where,
306
+ f"{t.label()} is above 340 MHz; HDMI 2.0 rates usually need hdmi.scdc = true",
307
+ )
308
+
309
+ for i, v in enumerate(cfg.vics):
310
+ vic = VICS[v]
311
+ if cfg.hdmi.enabled and vic.pclk_mhz > cfg.hdmi.max_tmds_mhz:
312
+ diag.violation(
313
+ f"vics[{i}]",
314
+ f"VIC {v} ({vic.width}x{vic.height}@{vic.refresh:g}) needs "
315
+ f"{vic.pclk_mhz:g} MHz but hdmi.max_tmds_mhz is {cfg.hdmi.max_tmds_mhz}",
316
+ )
317
+ if len(set(cfg.vics)) != len(cfg.vics):
318
+ diag.warn("vics", "contains duplicates")
319
+
320
+ r = cfg.range_limits
321
+ if r.vrefresh_hz:
322
+ for i, t in enumerate(cfg.modes):
323
+ if not r.vrefresh_hz[0] <= round(t.refresh) <= r.vrefresh_hz[1]:
324
+ diag.warn(
325
+ f"modes[{i}]",
326
+ f"{t.label()} is outside range.vrefresh_hz {list(r.vrefresh_hz)}",
327
+ )
328
+ if r.hfreq_khz:
329
+ for i, t in enumerate(cfg.modes):
330
+ if not r.hfreq_khz[0] <= t.hfreq_khz <= r.hfreq_khz[1] + 0.999:
331
+ diag.warn(
332
+ f"modes[{i}]",
333
+ f"{t.label()} line rate {t.hfreq_khz:.1f} kHz is outside "
334
+ f"range.hfreq_khz {list(r.hfreq_khz)}",
335
+ )
336
+ if r.max_pixel_clock_mhz:
337
+ for i, t in enumerate(cfg.modes):
338
+ if t.pclk_mhz > r.max_pixel_clock_mhz:
339
+ diag.warn(
340
+ f"modes[{i}]",
341
+ f"{t.label()} pixel clock {t.pclk_mhz:.2f} MHz is above "
342
+ f"range.max_pixel_clock_mhz {r.max_pixel_clock_mhz}",
343
+ )
344
+
345
+ if cfg.hdmi.deep_color and cfg.display.bit_depth < 10:
346
+ diag.warn(
347
+ "hdmi.deep_color", "deep color advertised but display.bit_depth is below 10"
348
+ )
349
+ if cfg.hdr.enabled and cfg.display.bit_depth < 10:
350
+ diag.warn("hdr.enabled", "HDR usually needs display.bit_depth >= 10")
351
+
352
+ # Space in the CTA block: 4 header bytes + data blocks + 18 bytes per DTD.
353
+ extra_dtds = max(0, len(cfg.modes) - 2)
354
+ room = (127 - 4 - len(cta_data_blocks(cfg))) // 18
355
+ if extra_dtds > room:
356
+ diag.error(
357
+ "modes",
358
+ f"{len(cfg.modes)} modes given but only {2 + room} fit (2 in the base "
359
+ f"block, {room} in the CTA block with the current data blocks). Remove modes, "
360
+ "or move standard modes to `vics`",
361
+ )