#!/usr/bin/env python3
# Tegra X1 (L4T 4.9) truncates I2C-over-AUX reads on EDID extension blocks >= 2
# (4-block EDIDs with Block Map + CTA-861 + DisplayID), setting edid->errors
# and locking tegra_dp_mode_filter to its 640x480 failsafe. When DP is active
# and fb1/modes is stuck at 640x480 on a high-res sink, synthesize a valid
# 2-block (Base + CTA-861) EDID in debugfs and re-trigger DP HPD.
import os
import re
import sys

DP_STATE = "/sys/class/switch/dp/state"
DC1_ENABLE = "/sys/devices/platform/host1x/tegradc.1/enable"
FB_BLANK = "/sys/class/graphics/fb1/blank"
FB_MODES = "/sys/class/graphics/fb1/modes"
DBG_EDID = "/sys/kernel/debug/tegradc.1/edid"
DBG_HPD = "/sys/kernel/debug/tegra_dp1/hotplug"


def read_text(path):
    try:
        with open(path, "r") as f:
            return f.read().strip()
    except OSError:
        return ""


def ensure_unblanked():
    if read_text(DC1_ENABLE) == "0":
        try:
            fd = os.open(FB_BLANK, os.O_WRONLY)
            os.write(fd, b"0\n")
            os.close(fd)
        except OSError:
            pass


def reset_debug_edid():
    try:
        fd = os.open(DBG_EDID, os.O_WRONLY)
        os.write(fd, b"0")
        os.close(fd)
    except OSError:
        pass


def main():
    if "--reset" in sys.argv:
        reset_debug_edid()
        return 0

    if read_text(DP_STATE) != "1":
        return 0

    mode_lines = [m.strip() for m in read_text(FB_MODES).splitlines() if m.strip()]
    if not mode_lines or not all("640x480" in m for m in mode_lines):
        ensure_unblanked()
        return 0

    raw_txt = read_text(DBG_EDID)
    hex_bytes = re.findall(r"\b([0-9a-fA-F]{2})\b", raw_txt)
    if len(hex_bytes) < 128 or hex_bytes[:8] != ["00", "ff", "ff", "ff", "ff", "ff", "ff", "00"]:
        return 0

    b0 = bytearray(int(x, 16) for x in hex_bytes[:128])
    pclk_10khz = b0[54] | (b0[55] << 8)
    has_1080p_std = any(b0[i] == 0xd1 and b0[i + 1] == 0xc0 for i in range(38, 54, 2))
    if b0[126] <= 1 and pclk_10khz < 10000 and not has_1080p_std:
        return 0

    phys = bytes(b0[66:69]) if any(b0[66:69]) else bytes([0x12, 0xb8, 0x41])
    if pclk_10khz == 0 or pclk_10khz > 34000:
        b0[54:72] = (
            bytes.fromhex("023a801871382d40582c4500")
            + phys
            + bytes.fromhex("00001e")
        )

    b0[126] = 1
    b0[127] = (256 - sum(b0[:127]) % 256) % 256

    b1 = bytearray(128)
    db = bytes.fromhex(
        "230f5707"                      # Audio Data Block (LPCM)
        "834f0000"                      # Speaker Allocation
        "46901f12040301"                # VDB: VIC 16 (native), 31, 18, 4, 3, 1
        "6d030c002000b844200060010203"  # HDMI 1.4 VSDB
    )
    dtd_off = 4 + len(db)
    b1[0:4] = bytes([0x02, 0x03, dtd_off, 0x71])
    b1[4:dtd_off] = db
    dtd_1080p60 = bytes.fromhex("023a801871382d40582c4500") + phys + bytes.fromhex("00001e")
    dtd_1440p60 = bytes.fromhex("565e00a0a0a0295030203500") + phys + bytes.fromhex("00001a")
    b1[dtd_off:dtd_off + 18] = dtd_1080p60
    b1[dtd_off + 18:dtd_off + 36] = dtd_1440p60
    b1[127] = (256 - sum(b1[:127]) % 256) % 256

    edid = bytes(b0 + b1)
    fd = os.open(DBG_EDID, os.O_WRONLY)
    os.write(fd, edid)
    os.close(fd)

    fd_hpd = os.open(DBG_HPD, os.O_WRONLY)
    os.write(fd_hpd, b"0\n")
    os.close(fd_hpd)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
