#!/usr/bin/env python3
"""Golden Codex 1.2.0: the image's Soulmark. Reference implementation of the rule in SPEC.md, section 4.

The fingerprint covers everything in the file that decides how the picture is drawn, and nothing that is descriptive
metadata, so that embedding or removing a record, a caption or a credential never changes it.

  JPEG  SHA-256 over two parts, in order.
        (a) Before the first scan: each segment after SOI, in order, leaving out only the descriptive ones: COM (FFFE),
            APP1 (FFE1: Exif and XMP), APP11 (FFEB: content credentials) and APP13 (FFED: IPTC and Photoshop data).
            Every other segment is covered, including APP0 (JFIF: pixel aspect ratio), APP2 (colour profile) and APP14
            (colour transform). Fill bytes between these segments are skipped.
        (b) From the first SOS marker to the EOI marker inclusive: every byte exactly as it stands in the file.
  PNG   SHA-256 over, in file order, the type and data of every chunk EXCEPT the descriptive ones (tEXt, zTXt, iTXt,
        eXIf, tIME, caBX) and IEND; the data of all IDAT chunks is joined as one stream preceded once by the four bytes
        "IDAT". Lengths and CRCs are not covered. Animation chunks, colour chunks and unknown chunks are all covered.
  NOT covered in either: the orientation flag and any thumbnail (both live in Exif) and all text metadata.

A file that cannot be read as a strict sequence of segments or chunks is refused (ValueError), never fingerprinted: a
file that is cut off, a length that runs past the end, a file with no image data, a PNG chunk that fails its checksum, PNG image data that is not in consecutive IDAT chunks, or a JPEG in which a marker
other than a restart marker appears inside scan data and is not followed by a well-formed segment. Bytes after EOI or
IEND are not part of the picture and are not covered.

Usage: image_soulmark.py <file>...     prints sha256-<base64url> for each
       image_soulmark.py --self-test <dir>   builds test images, embeds metadata with exiftool, checks the rule holds."""
import base64, hashlib, struct, sys, zlib

def _out(h): return "sha256-" + base64.urlsafe_b64encode(h.digest()).rstrip(b"=").decode()

def jpeg(b):
    if b[:2] != b"\xff\xd8": raise ValueError("not a JPEG")
    h = hashlib.sha256(); i = 2; scan_from = None
    while True:
        if i + 1 >= len(b) or b[i] != 0xFF: raise ValueError("JPEG marker expected at byte %d" % i)
        m = b[i + 1]
        if m == 0xFF: i += 1; continue                      # fill byte
        if m == 0xD9:                                       # EOI
            if scan_from is None: raise ValueError("JPEG has no image data")
            h.update(b[scan_from:i + 2]); return _out(h)
        if 0xD0 <= m <= 0xD7 or m == 0x01:
            if scan_from is None: h.update(b[i:i + 2])
            i += 2; continue
        if i + 4 > len(b): raise ValueError("JPEG cut off inside a segment header")
        n = struct.unpack(">H", b[i + 2:i + 4])[0]; j = i + 2 + n
        if n < 2 or j > len(b): raise ValueError("JPEG segment length runs past the end of the file")
        if m == 0xDA:                                       # scan: header, then entropy-coded data to the next real marker
            if scan_from is None: scan_from = i
            while True:
                j = b.find(b"\xff", j)
                if j < 0 or j + 1 >= len(b): raise ValueError("JPEG cut off inside a scan")
                if b[j + 1] == 0x00 or 0xD0 <= b[j + 1] <= 0xD7: j += 2; continue
                if b[j + 1] == 0xFF: j += 1; continue
                break
        elif scan_from is None:
            if m not in (0xFE, 0xE1, 0xEB, 0xED): h.update(b[i:j])
        i = j

def png(b):
    if b[:8] != b"\x89PNG\r\n\x1a\n": raise ValueError("not a PNG")
    h = hashlib.sha256(); i = 8; idat = False; first = True; after_idat = False
    while True:
        if i + 12 > len(b): raise ValueError("PNG cut off before its IEND chunk")
        n, t = struct.unpack(">I4s", b[i:i + 8])
        if i + 12 + n > len(b): raise ValueError("PNG chunk length runs past the end of the file")
        d = b[i + 8:i + 8 + n]
        if struct.unpack(">I", b[i + 8 + n:i + 12 + n])[0] != (zlib.crc32(t + d) & 0xFFFFFFFF): raise ValueError("PNG chunk fails its checksum")
        if first and t != b"IHDR": raise ValueError("PNG does not begin with IHDR")
        first = False
        if t == b"IEND":
            if not idat: raise ValueError("PNG has no image data")
            return _out(h)
        if t == b"IDAT":
            if after_idat: raise ValueError("PNG image data is not in consecutive IDAT chunks")
            if not idat: h.update(t); idat = True
            h.update(d)
        else:
            after_idat = idat
            if t not in (b"tEXt", b"zTXt", b"iTXt", b"eXIf", b"tIME", b"caBX"): h.update(t); h.update(d)
        i += 12 + n

def image_soulmark(path):
    b = open(path, "rb").read()
    if b[:2] == b"\xff\xd8": return jpeg(b)
    if b[:8] == b"\x89PNG\r\n\x1a\n": return png(b)
    raise ValueError("1.2.0 defines the image Soulmark for JPEG and PNG only")

def self_test(d):
    import os, shutil, subprocess
    from PIL import Image
    os.makedirs(d, exist_ok=True); p = lambda n: os.path.join(d, n)
    a = Image.radial_gradient("L").convert("RGB").resize((96, 80)); other = a.transpose(Image.FLIP_LEFT_RIGHT).rotate(90, expand=True)
    a.save(p("baseline.jpg"), quality=85); a.save(p("progressive.jpg"), quality=85, progressive=True); a.save(p("lowq.jpg"), quality=40)
    a.save(p("rgb.png")); a.convert("P", palette=Image.ADAPTIVE, colors=16).save(p("palette.png")); other.save(p("other.jpg"), quality=85); other.save(p("other.png"))
    names = ["baseline.jpg", "progressive.jpg", "rgb.png", "palette.png"]; ok = True; rows = []
    for n in names:
        before = image_soulmark(p(n)); e = p("embedded-" + n); shutil.copy(p(n), e)
        r = subprocess.run(["exiftool", "-q", "-overwrite_original", "-XMP-dc:Title=Vespers of the Golden Hour", "-XMP-dc:Description=" + "x" * 900, "-IPTC:Credit=Example", e], capture_output=True, text=True)
        after = image_soulmark(e); changed = open(p(n), "rb").read() != open(e, "rb").read()
        good = r.returncode == 0 and before == after and changed; ok &= good
        rows.append({"file": n, "image_soulmark": before, "same_after_embedding_metadata": before == after, "file_bytes_changed_by_embedding": changed})
        os.remove(e)
    q = Image.open(p("palette.png")); pal = q.getpalette(); pal[0:3] = [255, 0, 0]; q.putpalette(pal); q.save(p("palette-recoloured.png"))
    checks = {"a different picture gives a different value (JPEG)": image_soulmark(p("baseline.jpg")) != image_soulmark(p("other.jpg")),
              "a different picture gives a different value (PNG)": image_soulmark(p("rgb.png")) != image_soulmark(p("other.png")),
              "the same picture saved at another quality gives a different value": image_soulmark(p("baseline.jpg")) != image_soulmark(p("lowq.jpg")),
              "recolouring a palette changes the value though the pixel data is untouched": image_soulmark(p("palette.png")) != image_soulmark(p("palette-recoloured.png"))}
    def chunk(t, d): return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
    png0 = open(p("rgb.png"), "rb").read(); g = lambda v: png0[:33] + chunk(b"gAMA", struct.pack(">I", v)) + png0[33:]
    jpg0 = open(p("baseline.jpg"), "rb").read(); ad = lambda t: jpg0[:2] + b"\xff\xee\x00\x0eAdobe\x00\x64\x00\x00\x00\x00" + bytes([t]) + jpg0[2:]
    icc = lambda body: jpg0[:2] + b"\xff\xe2" + struct.pack(">H", 2 + 14 + len(body)) + b"ICC_PROFILE\x00\x01\x01" + body + jpg0[2:]
    checks["changing a PNG's gamma changes the value"] = png(g(45455)) != png(g(100000)) and png(g(45455)) != png(png0)
    checks["changing a JPEG's Adobe colour transform changes the value"] = jpeg(ad(1)) != jpeg(ad(0))
    checks["changing a JPEG's colour profile changes the value"] = jpeg(icc(b"A" * 64)) != jpeg(icc(b"B" * 64))
    checks["a JPEG comment or an Exif block does not change the value"] = jpeg(jpg0[:2] + b"\xff\xfe\x00\x07hello" + b"\xff\xe1\x00\x08Exif\x00\x00" + jpg0[2:]) == jpeg(jpg0)
    sos = jpg0.index(b"\xff\xda"); eoi = len(jpg0) - 2
    checks["bytes slipped in after the first scan change the value"] = jpeg(jpg0[:eoi] + b"\xff\xe1\x00\x08Exif\x00\x00" + jpg0[eoi:]) != jpeg(jpg0)
    checks["a PNG background colour change changes the value"] = png(png0[:33] + chunk(b"bKGD", b"\x00\x00\x00\x00\x00\x00") + png0[33:]) != png(png0[:33] + chunk(b"bKGD", b"\x00\xff\x00\xff\x00\xff") + png0[33:])
    iend = len(png0) - 12
    checks["turning a PNG into an animation changes the value"] = png(png0[:33] + chunk(b"acTL", struct.pack(">II", 2, 0)) + png0[33:]) != png(png0)
    checks["a PNG text chunk does not change the value"] = png(png0[:iend] + chunk(b"tEXt", b"Title\x00Vespers") + png0[iend:]) == png(png0)
    checks["fill bytes slipped in between scans change the value"] = jpeg(jpg0[:eoi] + b"\xff\xff" + jpg0[eoi:]) != jpeg(jpg0)
    jf = jpg0.index(b"JFIF\x00"); stretched = bytearray(jpg0); stretched[jf + 8:jf + 12] = b"\x00\x02\x00\x01"
    checks["changing a JPEG's pixel aspect ratio changes the value"] = jpeg(bytes(stretched)) != jpeg(jpg0)
    checks["a content-credentials segment or an IPTC block does not change the value"] = jpeg(jpg0[:2] + b"\xff\xeb\x00\x06JUMB" + b"\xff\xed\x00\x06IPTC" + jpg0[2:]) == jpeg(jpg0)
    ok &= all(checks.values())
    for n in ("lowq.jpg", "other.jpg", "other.png", "palette-recoloured.png"): os.remove(p(n))
    import json
    with open(p("vectors.json"), "w") as f: json.dump({"rule": "SPEC.md section 4", "files": rows, "checks": checks}, f, indent=2); f.write("\n")
    for r in rows: print(f"  {r['file']:16s} {r['image_soulmark']}  same after embedding: {r['same_after_embedding_metadata']}")
    for k, v in checks.items(): print(f"  {k}: {v}")
    print("IMAGE SOULMARK: ALL AS EXPECTED" if ok else "IMAGE SOULMARK: SOMETHING IS NOT AS EXPECTED"); return ok

if __name__ == "__main__":
    if sys.argv[1] == "--self-test": sys.exit(0 if self_test(sys.argv[2]) else 1)
    for f in sys.argv[2 if sys.argv[1] == "--" else 1:]:
        try: print(image_soulmark(f), f)
        except ValueError as e: print("refused:", e, f)
