Repository navigation
Expand file tree
/
Copy pathedid-gen.py
More file actions
executable file
·467 lines (393 loc) · 16.3 KB
/
Copy pathedid-gen.py
File metadata and controls
executable file
·467 lines (393 loc) · 16.3 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
#!/usr/bin/env python3
# edid-gen.py - Generate custom EDID binaries with CVT 1.1 timing
# Copyright (C) 2026 Pau Aliagas <linuxnow@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Generic EDID generator with proper CVT 1.1 timing calculation.
Matches libxcvt 0.1.2 output exactly.
Usage:
edid-gen.py WIDTH HEIGHT [REFRESH]
edid-gen.py 3840 648 # Standard CVT, 60 Hz
edid-gen.py 3840 648 50 # Standard CVT, 50 Hz
edid-gen.py 3840 648 -r # CVT Reduced Blanking
edid-gen.py 3840 648 -n "NovaStar LED"
edid-gen.py 3840 648 -o /tmp/my-edid.bin
"""
import argparse
import struct
import sys
# CVT 1.1 constants (from VESA CVT spec / libxcvt source)
CELL_GRAN = 8 # Character cell granularity (pixels)
MIN_V_PORCH = 3 # Minimum front porch (lines)
MIN_V_BPORCH = 6 # Minimum back porch (lines)
MIN_VSYNC_BP = 550.0 # Minimum vsync + back porch (us)
HSYNC_PERCENTAGE = 8 # Nominal hsync width (% of line period)
CLOCK_STEP = 250 # Pixel clock step (kHz)
# GTF secondary curve constants
M_FACTOR = 600
C_FACTOR = 40
K_FACTOR = 128
J_FACTOR = 20
# Derived (matching C integer math: M*K/256 and (C-J)*K/256+J)
M_PRIME = M_FACTOR * K_FACTOR // 256 # 300
C_PRIME = (C_FACTOR - J_FACTOR) * K_FACTOR // 256 + J_FACTOR # 30
# CVT Reduced Blanking constants
RB_H_BLANK = 160
RB_H_SYNC = 32
RB_MIN_V_BLANK = 460.0 # Minimum vertical blanking time (us)
RB_V_FRONT_PORCH = 3
def cvt_v_sync(hdisplay, vdisplay):
"""Determine vertical sync lines from aspect ratio.
Uses exact integer arithmetic matching libxcvt (not floating point).
"""
if (vdisplay % 3 == 0) and (vdisplay * 4 // 3 == hdisplay):
return 4 # 4:3
elif (vdisplay % 9 == 0) and (vdisplay * 16 // 9 == hdisplay):
return 5 # 16:9
elif (vdisplay % 10 == 0) and (vdisplay * 16 // 10 == hdisplay):
return 6 # 16:10
elif (vdisplay % 4 == 0) and (vdisplay * 5 // 4 == hdisplay):
return 7 # 5:4
elif (vdisplay % 9 == 0) and (vdisplay * 15 // 9 == hdisplay):
return 7 # 15:9
else:
return 10 # Non-standard
def cvt_standard(width, height, refresh):
"""Calculate CVT 1.1 standard timing. Matches libxcvt exactly."""
h_pixels = width - (width % CELL_GRAN)
v_lines = height
v_sync = cvt_v_sync(h_pixels, v_lines)
# 8. Estimate horizontal period
h_period = (1e6 / refresh - MIN_VSYNC_BP) / (v_lines + MIN_V_PORCH)
# 9. Vsync + back porch (lines)
v_sync_bp = int(MIN_VSYNC_BP / h_period) + 1
if v_sync_bp < v_sync + MIN_V_PORCH:
v_sync_bp = v_sync + MIN_V_PORCH
# 11. Total vertical lines
v_total = v_lines + MIN_V_PORCH + v_sync_bp
# 12. Ideal blanking duty cycle
hblank_percentage = C_PRIME - M_PRIME * h_period / 1000.0
if hblank_percentage < 20:
hblank_percentage = 20
# 13. Horizontal blanking (C-style: truncate then round down to 2*CELL_GRAN)
hblank = int(h_pixels * hblank_percentage / (100.0 - hblank_percentage))
hblank -= hblank % (2 * CELL_GRAN)
# 14. Total horizontal pixels
h_total = h_pixels + hblank
# H sync: libxcvt computes hsync_start, rounds UP to next CELL_GRAN
# (always adds at least 1 pixel even if already aligned)
hsync_end = h_pixels + hblank // 2
hsync_start = hsync_end - (h_total * HSYNC_PERCENTAGE) // 100
hsync_start += CELL_GRAN - (hsync_start % CELL_GRAN)
h_sync_width = hsync_end - hsync_start
h_front_porch = hsync_start - h_pixels
h_back_porch = h_total - hsync_end
# 15. Pixel clock (C-style: truncate then round down to CLOCK_STEP)
dot_clock = int(h_total * 1000.0 / h_period)
pixel_clock_khz = dot_clock - (dot_clock % CLOCK_STEP)
# FWXGA hack (from libxcvt): 1360x768 → 1366x768
if h_pixels == 1360 and v_lines == 768:
h_pixels = 1366
hsync_start -= 1
h_front_porch = hsync_start - h_pixels
h_sync_width = hsync_end - hsync_start
return {
'h_active': h_pixels,
'v_active': v_lines,
'h_total': h_total,
'v_total': v_total,
'h_blank': hblank,
'v_blank': v_total - v_lines,
'h_front_porch': h_front_porch,
'h_sync_width': h_sync_width,
'h_back_porch': h_back_porch,
'v_front_porch': MIN_V_PORCH,
'v_sync_width': v_sync,
'v_back_porch': v_sync_bp - v_sync,
'pixel_clock_khz': pixel_clock_khz,
'h_sync_positive': False, # CVT standard: -hsync
'v_sync_positive': True, # CVT standard: +vsync
'reduced': False,
}
def cvt_reduced(width, height, refresh):
"""Calculate CVT 1.1 Reduced Blanking timing. Matches libxcvt exactly."""
h_pixels = width - (width % CELL_GRAN)
v_lines = height
v_sync = cvt_v_sync(h_pixels, v_lines)
# Horizontal: fixed blanking
h_total = h_pixels + RB_H_BLANK
# 8. Estimate horizontal period
h_period = (1e6 / refresh - RB_MIN_V_BLANK) / v_lines
# 9-10. Vertical blanking lines
vbi_lines = int(RB_MIN_V_BLANK / h_period) + 1
min_vbi = RB_V_FRONT_PORCH + v_sync + MIN_V_BPORCH
if vbi_lines < min_vbi:
vbi_lines = min_vbi
v_total = v_lines + vbi_lines
v_back_porch = vbi_lines - RB_V_FRONT_PORCH - v_sync
# H sync: fixed for reduced blanking
hsync_end = h_pixels + RB_H_BLANK // 2
hsync_start = hsync_end - RB_H_SYNC
h_front_porch = hsync_start - h_pixels
h_back_porch = h_total - hsync_end
# 12. Pixel clock
dot_clock = int(h_total * 1000.0 / h_period)
pixel_clock_khz = dot_clock - (dot_clock % CLOCK_STEP)
return {
'h_active': h_pixels,
'v_active': v_lines,
'h_total': h_total,
'v_total': v_total,
'h_blank': RB_H_BLANK,
'v_blank': vbi_lines,
'h_front_porch': h_front_porch,
'h_sync_width': RB_H_SYNC,
'h_back_porch': h_back_porch,
'v_front_porch': RB_V_FRONT_PORCH,
'v_sync_width': v_sync,
'v_back_porch': v_back_porch,
'pixel_clock_khz': pixel_clock_khz,
'h_sync_positive': True, # CVT-RB: +hsync
'v_sync_positive': False, # CVT-RB: -vsync
'reduced': True,
}
def validate_edid_limits(t):
"""Check EDID Detailed Timing Descriptor encoding limits."""
errors = []
if t['h_active'] > 4095:
errors.append(f"h_active {t['h_active']} > 4095 (EDID 12-bit limit)")
if t['h_blank'] > 4095:
errors.append(f"h_blank {t['h_blank']} > 4095 (EDID 12-bit limit)")
if t['v_active'] > 4095:
errors.append(f"v_active {t['v_active']} > 4095 (EDID 12-bit limit)")
if t['v_blank'] > 4095:
errors.append(f"v_blank {t['v_blank']} > 4095 (EDID 12-bit limit)")
if t['h_front_porch'] > 1023:
errors.append(f"h_front_porch {t['h_front_porch']} > 1023 (EDID 10-bit limit)")
if t['h_sync_width'] > 1023:
errors.append(f"h_sync_width {t['h_sync_width']} > 1023 (EDID 10-bit limit)")
if t['v_front_porch'] > 63:
errors.append(f"v_front_porch {t['v_front_porch']} > 63 (EDID 6-bit limit)")
if t['v_sync_width'] > 63:
errors.append(f"v_sync_width {t['v_sync_width']} > 63 (EDID 6-bit limit)")
if t['pixel_clock_khz'] > 655350:
errors.append(f"pixel_clock {t['pixel_clock_khz']/1000:.2f} MHz > 655.35 MHz (EDID 16-bit limit)")
if t['h_front_porch'] < 0:
errors.append(f"h_front_porch is negative ({t['h_front_porch']})")
return errors
def build_edid(timing, name="Custom LCD"):
"""Build a valid 128-byte EDID block from timing parameters."""
edid = bytearray(128)
# ── Header ──
edid[0:8] = b'\x00\xff\xff\xff\xff\xff\xff\x00'
# Manufacturer "LNX" (Linux)
edid[8:10] = struct.pack(
'>H',
((ord('L') - 64) << 10) | ((ord('N') - 64) << 5) | (ord('X') - 64)
)
edid[10:12] = struct.pack('<H', 0x0001) # Product code
edid[12:16] = struct.pack('<I', 0) # Serial (0 = not specified)
# Manufacture date
edid[16] = 1 # Week 1
edid[17] = 36 # 1990 + 36 = 2026
# EDID version 1.3
edid[18] = 1
edid[19] = 3
# Digital input (HDMI/DVI)
edid[20] = 0x80
# Physical size in cm (estimate from pixel dimensions at ~4px/mm)
h_cm = max(1, min(255, timing['h_active'] // 40))
v_cm = max(1, min(255, timing['v_active'] // 40))
edid[21] = h_cm
edid[22] = v_cm
# Gamma 2.2
edid[23] = 120
# Feature support: RGB, sRGB default, preferred timing in DTD1
edid[24] = 0x0E
# Chromaticity (sRGB)
edid[25:35] = bytes([
0xEE, 0x91, 0xA3, 0x54, 0x4C, 0x99, 0x26, 0x0F, 0x50, 0x54
])
# Established timings: none
edid[35:38] = bytes([0x00, 0x00, 0x00])
# Standard timings: unused
for i in range(38, 54, 2):
edid[i] = 0x01
edid[i + 1] = 0x01
# ── Detailed Timing Descriptor #1 ──
t = timing
pixel_clock_10khz = t['pixel_clock_khz'] // 10
d = 54
edid[d+0:d+2] = struct.pack('<H', pixel_clock_10khz)
# Horizontal active + blanking
edid[d+2] = t['h_active'] & 0xFF
edid[d+3] = t['h_blank'] & 0xFF
edid[d+4] = ((t['h_active'] >> 8) & 0x0F) << 4 | ((t['h_blank'] >> 8) & 0x0F)
# Vertical active + blanking
edid[d+5] = t['v_active'] & 0xFF
edid[d+6] = t['v_blank'] & 0xFF
edid[d+7] = ((t['v_active'] >> 8) & 0x0F) << 4 | ((t['v_blank'] >> 8) & 0x0F)
# Sync offset + width
edid[d+8] = t['h_front_porch'] & 0xFF
edid[d+9] = t['h_sync_width'] & 0xFF
edid[d+10] = ((t['v_front_porch'] & 0x0F) << 4) | (t['v_sync_width'] & 0x0F)
edid[d+11] = (
(((t['h_front_porch'] >> 8) & 0x03) << 6)
| (((t['h_sync_width'] >> 8) & 0x03) << 4)
| (((t['v_front_porch'] >> 4) & 0x03) << 2)
| ((t['v_sync_width'] >> 4) & 0x03)
)
# Physical size in mm
h_mm = h_cm * 10
v_mm = v_cm * 10
edid[d+12] = h_mm & 0xFF
edid[d+13] = v_mm & 0xFF
edid[d+14] = (((h_mm >> 8) & 0x0F) << 4) | ((v_mm >> 8) & 0x0F)
# No border
edid[d+15] = 0
edid[d+16] = 0
# Signal flags: digital separate + sync polarity
flags = 0x18 # bits 4-3 = 11 (digital separate)
if t['v_sync_positive']:
flags |= 0x04
if t['h_sync_positive']:
flags |= 0x02
edid[d+17] = flags
# ── Descriptor #2: Monitor name ──
d2 = 72
edid[d2+0:d2+5] = bytes([0x00, 0x00, 0x00, 0xFC, 0x00])
name_bytes = (name[:12] + '\n').encode('ascii')
edid[d2+5:d2+5+len(name_bytes)] = name_bytes
# Pad with spaces if name < 13 chars
for i in range(len(name_bytes), 13):
edid[d2+5+i] = 0x20
# ── Descriptor #3: Monitor range limits ──
d3 = 90
act_refresh = int(t['pixel_clock_khz'] * 1000 / (t['h_total'] * t['v_total']))
edid[d3+0:d3+5] = bytes([0x00, 0x00, 0x00, 0xFD, 0x00])
edid[d3+5] = max(1, act_refresh - 5) # min v-rate
edid[d3+6] = act_refresh + 5 # max v-rate
h_rate_khz = t['pixel_clock_khz'] / t['h_total']
edid[d3+7] = max(1, int(h_rate_khz) - 10) # min h-rate kHz
edid[d3+8] = int(h_rate_khz) + 10 # max h-rate kHz
edid[d3+9] = t['pixel_clock_khz'] // 10000 + 1 # max pixel clock / 10 MHz
edid[d3+10] = 0x00 # default GTF
edid[d3+11] = 0x0a # linefeed (required)
for i in range(12, 18):
edid[d3+i] = 0x20 # space padding (required)
# ── Descriptor #4: Dummy (required by EDID 1.3) ──
d4 = 108
edid[d4+0:d4+5] = bytes([0x00, 0x00, 0x00, 0x10, 0x00])
# No extensions
edid[126] = 0
# Checksum
edid[127] = (256 - sum(edid[:127]) % 256) % 256
return edid
def print_timing(t):
"""Display timing parameters in a readable format."""
pclk_mhz = t['pixel_clock_khz'] / 1000.0
refresh = t['pixel_clock_khz'] * 1000.0 / (t['h_total'] * t['v_total'])
mode = "CVT-RB" if t['reduced'] else "CVT"
hpol = '+' if t['h_sync_positive'] else '-'
vpol = '+' if t['v_sync_positive'] else '-'
print(f"Mode: {t['h_active']}x{t['v_active']} {refresh:.2f} Hz ({mode})")
print(f"Pixel clock: {pclk_mhz:.2f} MHz")
print()
h = t
# Format pixel clock: no leading space, pad to match cvt output
pclk_str = f"{pclk_mhz:.2f}"
print(f'Modeline "{h["h_active"]}x{h["v_active"]}_{refresh:.0f}.00"'
f' {pclk_str}'
f' {h["h_active"]}'
f' {h["h_active"] + h["h_front_porch"]}'
f' {h["h_active"] + h["h_front_porch"] + h["h_sync_width"]}'
f' {h["h_total"]}'
f' {h["v_active"]}'
f' {h["v_active"] + h["v_front_porch"]}'
f' {h["v_active"] + h["v_front_porch"] + h["v_sync_width"]}'
f' {h["v_total"]}'
f' {hpol}hsync {vpol}vsync')
print()
print(f"Horizontal: {h['h_active']} + fp={h['h_front_porch']}"
f" + sync={h['h_sync_width']} + bp={h['h_back_porch']}"
f" = {h['h_total']} total (blank={h['h_blank']})")
print(f"Vertical: {h['v_active']} + fp={h['v_front_porch']}"
f" + sync={h['v_sync_width']} + bp={h['v_back_porch']}"
f" = {h['v_total']} total (blank={h['v_blank']})")
def main():
parser = argparse.ArgumentParser(
description='Generate EDID binary with proper CVT 1.1 timing.',
epilog='Examples:\n'
' %(prog)s 3840 648\n'
' %(prog)s 3840 648 50\n'
' %(prog)s 3840 648 -r\n'
' %(prog)s 1920 1080 -n "My Display" -o /tmp/custom.bin\n',
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument('width', type=int, help='Horizontal resolution (pixels)')
parser.add_argument('height', type=int, help='Vertical resolution (pixels)')
parser.add_argument('refresh', type=int, nargs='?', default=60,
help='Refresh rate in Hz (default: 60)')
parser.add_argument('-r', '--reduced', action='store_true',
help='Use CVT Reduced Blanking (lower bandwidth)')
parser.add_argument('-n', '--name', default='Custom LCD',
help='Monitor name in EDID (max 12 chars)')
parser.add_argument('-o', '--output',
help='Output file (default: /tmp/WIDTHxHEIGHT.bin)')
args = parser.parse_args()
# Calculate timing
if args.reduced:
timing = cvt_reduced(args.width, args.height, args.refresh)
else:
timing = cvt_standard(args.width, args.height, args.refresh)
# Always show modeline
print_timing(timing)
print()
# Check EDID encoding limits
errors = validate_edid_limits(timing)
if errors:
print("WARNING: Cannot encode in EDID:", file=sys.stderr)
for e in errors:
print(f" - {e}", file=sys.stderr)
print("\nModeline is valid but EDID binary was NOT generated.",
file=sys.stderr)
sys.exit(1)
# Build EDID
edid = build_edid(timing, name=args.name[:12])
# Verify
assert len(edid) == 128
assert sum(edid) % 256 == 0, "Checksum failed"
# Write
output = args.output or f"/tmp/{args.width}x{args.height}.bin"
with open(output, 'wb') as f:
f.write(edid)
print(f"EDID written to {output} ({len(edid)} bytes, checksum OK)")
print()
print("Verify:")
print(f" edid-decode {output}")
print()
print("Install:")
print(f" sudo mkdir -p /lib/firmware/edid")
print(f" sudo cp {output} /lib/firmware/edid/")
filename = output.rsplit('/', 1)[-1]
print()
print(" # Replace HDMI-A-1 with your connector"
" (check: ls /sys/class/drm/)")
print(f" sudo grubby --update-kernel=ALL \\")
print(f' --args="drm.edid_firmware=HDMI-A-1:edid/{filename}"')
print()
print(" sudo reboot")
if __name__ == '__main__':
main()