"""cocotb test for video_top_tfp410.sv with a small raster (64 x 24 visible). Captures two frames from the output pins and checks the sync timing and every visible pixel against pattern_model.py.""" from __future__ import annotations import cocotb import numpy as np from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, RisingEdge from pattern_model import frame # Must match the parameters in test_cocotb_video_top.py. H = dict(active=64, fp=4, sync=8, bp=12) V = dict(active=24, fp=2, sync=3, bp=4) H_POL, V_POL, GRID = 1, 0, 8 H_TOTAL = sum(H.values()) V_TOTAL = sum(V.values()) async def capture(dut, mode: int, n_cycles: int) -> dict[str, list[int]]: dut.rst.value = 1 dut.mode.value = mode await ClockCycles(dut.clk_pix, 3) await FallingEdge(dut.clk_pix) dut.rst.value = 0 trace: dict[str, list[int]] = {"de": [], "hs": [], "vs": [], "rgb": []} for _ in range(n_cycles): await RisingEdge(dut.clk_pix) await FallingEdge(dut.clk_pix) trace["de"].append(int(dut.tfp_de.value)) trace["hs"].append(int(dut.tfp_hsync.value) == H_POL) # active-high view trace["vs"].append(int(dut.tfp_vsync.value) == V_POL) trace["rgb"].append(int(dut.tfp_data.value)) return trace def runs(seq: list[int], value: int) -> list[tuple[int, int]]: """(start, length) of every complete run of `value` in seq.""" out, start = [], None for i, v in enumerate(seq): if v == value and start is None: start = i if v != value and start is not None: out.append((start, i - start)) start = None return out @cocotb.test() async def all_modes(dut) -> None: cocotb.start_soon(Clock(dut.clk_pix, 40, unit="ns").start()) for mode in range(4): t = await capture(dut, mode, 2 * H_TOTAL * V_TOTAL + 50) de_runs = runs(t["de"], 1) hs_runs = runs(t["hs"], 1) vs_runs = runs(t["vs"], 1) assert all(n == H["active"] for _, n in de_runs), "DE length per line" assert all(n == H["sync"] for _, n in hs_runs), "hsync width" assert all(n == V["sync"] * H_TOTAL for _, n in vs_runs), "vsync width" for s, n in de_runs: # front porch after each visible line nxt = [h for h, _ in hs_runs if h > s] if nxt: assert nxt[0] - (s + n) == H["fp"], "horizontal front porch" # The capture starts at reset, so the first DE run is line 0 of frame 1. assert de_runs[0][0] < H_TOTAL lines = de_runs[:V["active"]] assert len(lines) == V["active"] img = np.zeros((V["active"], H["active"], 3), dtype=np.uint8) for row, (s, n) in enumerate(lines): for col in range(n): v = t["rgb"][s + col] img[row, col] = ((v >> 16) & 255, (v >> 8) & 255, v & 255) ref = frame(mode, H["active"], V["active"], GRID) assert np.array_equal(img, ref), f"mode {mode}: picture differs from the model" blank = [t["rgb"][i] for i in range(len(t["de"])) if not t["de"][i]] assert not any(blank), "RGB must be black outside DE" dut._log.info(f"mode {mode}: {len(de_runs)} lines checked, picture matches")