"""Python model of the TMDS encoder in the DVI 1.0 specification (figure 3-5). The code follows the flow chart line by line, with bit lists indexed like the specification: q_m[0] .. q_m[8] and q_out[0] .. q_out[9]. The returned 10-bit integer has q_out[i] in bit i, so q_out[0] is the least significant bit, which is also the first bit on the wire. """ from __future__ import annotations # Control characters, written q_out[0:9] as in the specification, keyed by (C1, C0). CONTROL = { (0, 0): "0010101011", (0, 1): "1101010100", (1, 0): "0010101010", (1, 1): "1101010101", } def bits_to_int(bits: list[int]) -> int: return sum(b << i for i, b in enumerate(bits)) def int_to_bits(value: int, n: int) -> list[int]: return [(value >> i) & 1 for i in range(n)] def control_code(c1: int, c0: int) -> int: return bits_to_int([int(ch) for ch in CONTROL[(c1, c0)]]) def stage1(d: int) -> list[int]: """Transition-minimised 9-bit word q_m[0..8].""" D = int_to_bits(d, 8) n1 = sum(D) q_m = [D[0]] + [0] * 8 if n1 > 4 or (n1 == 4 and D[0] == 0): for i in range(1, 8): q_m[i] = 1 - (q_m[i - 1] ^ D[i]) # XNOR q_m[8] = 0 else: for i in range(1, 8): q_m[i] = q_m[i - 1] ^ D[i] # XOR q_m[8] = 1 return q_m class TmdsEncoder: """Stateful encoder: cnt is the running disparity cnt(t-1).""" def __init__(self) -> None: self.cnt = 0 def encode(self, d: int, c0: int, c1: int, de: int) -> int: if not de: self.cnt = 0 return control_code(c1, c0) q_m = stage1(d) n1 = sum(q_m[:8]) n0 = 8 - n1 q_out = [0] * 10 if self.cnt == 0 or n1 == n0: q_out[9] = 1 - q_m[8] q_out[8] = q_m[8] q_out[:8] = q_m[:8] if q_m[8] else [1 - b for b in q_m[:8]] self.cnt += (n1 - n0) if q_m[8] else (n0 - n1) elif (self.cnt > 0 and n1 > n0) or (self.cnt < 0 and n0 > n1): q_out[9] = 1 q_out[8] = q_m[8] q_out[:8] = [1 - b for b in q_m[:8]] self.cnt += 2 * q_m[8] + (n0 - n1) else: q_out[9] = 0 q_out[8] = q_m[8] q_out[:8] = q_m[:8] self.cnt += -2 * (1 - q_m[8]) + (n1 - n0) return bits_to_int(q_out) def decode(q: int) -> int: """Data decode: undo the conditional inversion (q_out[9]), then the XOR/XNOR chain selected by q_out[8].""" bits = int_to_bits(q, 10) q_m = [1 - b for b in bits[:8]] if bits[9] else bits[:8] D = [q_m[0]] for i in range(1, 8): x = q_m[i] ^ q_m[i - 1] D.append(x if bits[8] else 1 - x) return bits_to_int(D) def transitions(bits: list[int]) -> int: return sum(a != b for a, b in zip(bits, bits[1:]))