#!/usr/bin/python3
"""Capture a frame from a Himax HM1092 IR sensor behind an Intel IPU6/IPU7.

Configures the media graph, optionally turns the IR illuminator on for the
duration of the capture, grabs frames from the ISYS capture node and writes a
grayscale PNG. Only the Python standard library is used; media-ctl and v4l2-ctl
must be on PATH.

  hm1092-capture -o face.png            # illuminator on, autoscaled
  hm1092-capture -o dark.png --no-torch # ambient NIR only
  hm1092-capture --list                 # show what was detected

Root is normally required: the capture node and the illuminator's i2c bus
are both privileged. Where the kernel exposes the illuminator as a LED class
device (Dell XPS 14/16: INT3472 registers HIMX1092_00::ir_flood_led) that is
driven instead of the LM3643, and a user who can open the capture node can
grab unlit frames without root.
"""

import argparse
import glob
import os
import re
import struct
import subprocess
import sys
import tempfile
import zlib

SENSOR = "hm1092"

# The LM3643 register map, the brightness default and the emitter caps all live
# in lm3643.py so this tool and the relay cannot drift apart. They had drifted
# already: this file used to carry its own copy of the map.
sys.path.insert(0, "/usr/lib/hm1092")
from lm3643 import TORCH_DEFAULT, TORCH_MAX, Illuminator  # noqa: E402

DEFAULT_TORCH = TORCH_DEFAULT


def run(cmd, **kw):
    return subprocess.run(cmd, capture_output=True, text=True, **kw)


def need(tool):
    if not any(os.access(os.path.join(p, tool), os.X_OK)
               for p in os.environ.get("PATH", "").split(":")):
        sys.exit(f"{tool} not found on PATH")


class Graph:
    """The bits of the media topology this capture needs."""

    def __init__(self, mdev):
        self.mdev = mdev
        self.topology = run(["media-ctl", "-d", mdev, "-p"]).stdout

    def sensor_entity(self):
        m = re.search(r"entity \d+: (%s [\d-]+)" % SENSOR, self.topology)
        return m.group(1) if m else None

    def sensor_subdev(self):
        m = re.search(r"entity \d+: %s [\d-]+.*?device node name (\S+)"
                      % SENSOR, self.topology, re.S)
        return m.group(1) if m else None

    def csi_entity(self):
        """The CSI-2 receiver the sensor's source pad is wired to."""
        block = re.search(r'entity \d+: %s [\d-]+.*?-> "([^"]+)":' % SENSOR,
                          self.topology, re.S)
        return block.group(1) if block else None

    def capture_entity_and_node(self, csi):
        """First capture entity reachable from the CSI receiver's source pads."""
        block = re.search(r"entity \d+: %s \(.*?(?=\n- entity|\Z)"
                          % re.escape(csi), self.topology, re.S)
        if not block:
            return None, None
        m = re.search(r'-> "([^"]*Capture \d+)":', block.group(0))
        if not m:
            return None, None
        cap = m.group(1)
        node = re.search(r"entity \d+: %s \(.*?device node name (\S+)"
                         % re.escape(cap), self.topology, re.S)
        return cap, (node.group(1) if node else None)


def configure(mdev, g, sensor_ent, csi, cap, width, height, code):
    run(["media-ctl", "-d", mdev, "-l",
         '"%s":1 -> "%s":0 [1]' % (csi, cap)])
    for target in ('"%s":0' % sensor_ent, '"%s":0' % csi, '"%s":1' % csi):
        run(["media-ctl", "-d", mdev, "-V",
             "%s [fmt:%s/%dx%d]" % (target, code, width, height)])


_lamp = None


def torch(bus, on, brightness=DEFAULT_TORCH):
    """Drive the LM3643 IR emitter. Returns False if the bus is unusable.

    Goes through lm3643.Illuminator rather than shelling out to i2cset, so a
    one-shot capture gets the same burst cap and duty limit the relay does. A
    debug tool that can leave the emitter lit is exactly as much of an eye
    hazard as a daemon that can.
    """
    global _lamp
    try:
        if _lamp is None:
            _lamp = Illuminator(bus, brightness=brightness, log=lambda m: None)
        if on:
            return _lamp.assert_on()
        _lamp.set(False)
        return True
    except OSError:
        return False


def torch_off():
    """Idempotent, and safe to call from a finally that may never have lit."""
    global _lamp
    if _lamp is not None:
        try:
            _lamp.close()
        finally:
            _lamp = None


def sysfs_led():
    """The IR flood LED as a LED class device, where the firmware describes it.

    Dell's INT3472 tables carry the flood LED as a GPIO, so the kernel
    registers HIMX1092_00::ir_flood_led and nothing answers at the LM3643's
    i2c address. Returns the brightness attribute, or None.
    """
    hits = sorted(glob.glob("/sys/class/leds/*ir_flood*/brightness"))
    return hits[0] if hits else None


def led_set(path, on):
    """Switch a LED class device fully on or off. False if it is not writable."""
    try:
        level = "0"
        if on:
            with open(os.path.join(os.path.dirname(path), "max_brightness")) as f:
                level = f.read().strip() or "1"
        with open(path, "w") as f:
            f.write(level)
        return True
    except OSError:
        return False


def sensor_i2c_bus(sensor_ent):
    # Entity names look like "hm1092 2-0024": adapter 2, address 0x24.
    m = re.search(r"\s(\d+)-[0-9a-f]{4}$", sensor_ent)
    return int(m.group(1)) if m else None


def fmt_geometry(node):
    out = run(["v4l2-ctl", "-d", node, "--get-fmt-video"]).stdout
    bpl = int(re.search(r"Bytes per Line\s*:\s*(\d+)", out).group(1))
    size = int(re.search(r"Size Image\s*:\s*(\d+)", out).group(1))
    return bpl, size


def write_png(path, w, h, gray):
    raw = bytearray()
    for y in range(h):
        raw.append(0)
        raw += gray[y * w:(y + 1) * w]

    def chunk(tag, data):
        return (struct.pack(">I", len(data)) + tag + data +
                struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))

    png = b"\x89PNG\r\n\x1a\n"
    png += chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 0, 0, 0, 0))
    png += chunk(b"IDAT", zlib.compress(bytes(raw), 9))
    png += chunk(b"IEND", b"")
    with open(path, "wb") as f:
        f.write(png)


def decode(raw_path, w, h, stride, frame_size, rotate, autoscale):
    buf = open(raw_path, "rb").read()
    if len(buf) < frame_size:
        sys.exit("capture produced no complete frame")
    n = len(buf) // frame_size
    # The last frame: exposure and gain have settled by then.
    f = buf[(n - 1) * frame_size: n * frame_size]

    vals = []
    for y in range(h):
        row = f[y * stride: y * stride + w * 2]
        vals.extend(row[2 * x] | (row[2 * x + 1] << 8) for x in range(w))

    if rotate:
        vals.reverse()

    lo, hi = min(vals), max(vals)
    if autoscale:
        # Clip the top 0.1%: a few specular highlights (eyes, jewellery)
        # otherwise flatten everything else.
        hi = sorted(vals)[int(len(vals) * 0.999)]
        span = max(1, hi - lo)
        gray = bytes(max(0, min(255, (v - lo) * 255 // span)) for v in vals)
    else:
        gray = bytes(min(255, v >> 2) for v in vals)
    return gray, n, lo, hi


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("-o", "--output", default="hm1092.png")
    ap.add_argument("-d", "--device", default=None,
                    help="media device (default: autodetect)")
    ap.add_argument("-W", "--width", type=int, default=1296)
    ap.add_argument("-H", "--height", type=int, default=736)
    ap.add_argument("-n", "--frames", type=int, default=15,
                    help="frames to capture; the last one is saved")
    ap.add_argument("--exposure", type=int, default=None)
    ap.add_argument("--gain", type=int, default=None, help="analogue gain")
    ap.add_argument("--torch-brightness", type=int, default=DEFAULT_TORCH,
                    choices=range(0, TORCH_MAX + 1), metavar="0-%d" % TORCH_MAX,
                    help="LM3643 torch level (default: %d, the OEM value; see "
                         "lm3643.py before raising it)" % DEFAULT_TORCH)
    ap.add_argument("--no-torch", action="store_true",
                    help="leave the IR illuminator off")
    ap.add_argument("--no-rotate", action="store_true",
                    help="do not apply the 180 degree flip")
    ap.add_argument("--raw", action="store_true",
                    help="no autoscaling; straight 10->8 bit truncation")
    ap.add_argument("--keep-raw", metavar="PATH",
                    help="also write the undecoded capture here")
    ap.add_argument("--list", action="store_true",
                    help="report the detected topology and exit")
    ap.add_argument("--configure-only", action="store_true",
                    help="set up the media graph, print the capture node path "
                         "and exit; for services that stream the node "
                         "themselves, such as hm1092-relay")
    args = ap.parse_args()

    for t in ("media-ctl", "v4l2-ctl"):
        need(t)

    devices = [args.device] if args.device else sorted(glob.glob("/dev/media*"))
    for mdev in devices:
        g = Graph(mdev)
        sensor_ent = g.sensor_entity()
        if sensor_ent:
            break
    else:
        sys.exit("no %s entity in any media graph - is the driver loaded and "
                 "does ipu-bridge know the sensor?" % SENSOR)

    csi = g.csi_entity()
    cap, node = g.capture_entity_and_node(csi)
    subdev = g.sensor_subdev()
    bus = sensor_i2c_bus(sensor_ent)

    if args.list:
        print(f"media device : {mdev}")
        print(f"sensor       : {sensor_ent}  ({subdev})")
        print(f"receiver     : {csi}")
        print(f"capture      : {cap}  ({node})")
        print(f"i2c bus      : {bus}")
        led = sysfs_led()
        print(f"illuminator  : {led or 'LM3643 on i2c bus %s (assumed)' % bus}")
        return

    if not node:
        sys.exit("could not find a capture node downstream of %s" % csi)
    if os.geteuid() != 0 and not all(os.access(d, os.R_OK | os.W_OK)
                                     for d in (mdev, node)):
        sys.exit("root required to configure the pipeline and capture")

    configure(mdev, g, sensor_ent, csi, cap, args.width, args.height,
              "SGRBG10_1X10")

    if args.configure_only:
        # Shell-sourceable, because the relay unit consumes this to build its
        # argument list. Emitting the i2c bus here rather than hardcoding it in
        # the unit matters: the bus number moves with probe order, and a stale
        # number means the relay drives whatever else answers at 0x63.
        print("HM1092_NODE=%s" % node)
        print("HM1092_WIDTH=%d" % args.width)
        print("HM1092_HEIGHT=%d" % args.height)
        print("HM1092_I2C_BUS=%s" % ("" if bus is None else bus))
        if subdev:
            print("HM1092_SUBDEV=%s" % subdev)
        return

    ctrls = []
    if args.exposure is not None:
        ctrls.append("exposure=%d" % args.exposure)
    if args.gain is not None:
        ctrls.append("analogue_gain=%d" % args.gain)
    if ctrls and subdev:
        run(["v4l2-ctl", "-d", subdev, "--set-ctrl", ",".join(ctrls)])

    run(["v4l2-ctl", "-d", node,
         "--set-fmt-video=width=%d,height=%d,pixelformat=BA10"
         % (args.width, args.height)])
    stride, frame_size = fmt_geometry(node)

    lit = False
    led = None if args.no_torch else sysfs_led()
    if args.no_torch:
        pass
    elif led:
        lit = led_set(led, True)
        if not lit:
            print("warning: cannot write %s (not root?); illuminator left off"
                  % led, file=sys.stderr)
    elif bus is None:
        print("warning: could not derive the i2c bus; illuminator left off",
              file=sys.stderr)
    elif not os.path.exists("/dev/i2c-%d" % bus):
        print("warning: /dev/i2c-%d missing (modprobe i2c-dev); "
              "illuminator left off" % bus, file=sys.stderr)
    else:
        lit = torch(bus, True, args.torch_brightness)
        if not lit:
            print("warning: could not enable the illuminator",
                  file=sys.stderr)

    tmp = args.keep_raw or tempfile.mktemp(suffix=".raw")
    try:
        run(["v4l2-ctl", "-d", node, "--stream-mmap=4",
             "--stream-count=%d" % args.frames,
             "--stream-to=%s" % tmp, "--stream-poll"], timeout=60)
    finally:
        if lit and led:
            led_set(led, False)
        elif lit:
            torch_off()

    gray, n, lo, hi = decode(tmp, args.width, args.height, stride, frame_size,
                             not args.no_rotate, not args.raw)
    write_png(args.output, args.width, args.height, gray)
    if not args.keep_raw and os.path.exists(tmp):
        os.unlink(tmp)

    print("captured %d frames, 10-bit levels %d..%d%s -> %s"
          % (n, lo, hi, "" if lit else " (illuminator off)", args.output))


if __name__ == "__main__":
    main()
