# Luma-only model of the JPEG steps behind the number-line figure (my own DCT, libjpeg quality tables).
# Expects the NOAA photo at /data/barrelfish.jpg. Needs pillow, numpy, scipy.
import numpy as np
from PIL import Image
from scipy.fft import dctn, idctn

BASE = np.array([
16,11,10,16,24,40,51,61,
12,12,14,19,26,58,60,55,
14,13,16,24,40,57,69,56,
14,17,22,29,51,87,80,62,
18,22,37,56,68,109,103,77,
24,35,55,64,81,104,113,92,
49,64,78,87,103,121,120,101,
72,92,95,98,112,100,103,99]).reshape(8,8)

def table(q):
    s = 5000 // q if q < 50 else 200 - 2 * q
    t = (BASE * s + 50) // 100
    return np.clip(t, 1, 255)

im = Image.open("/data/barrelfish.jpg").convert("YCbCr").crop((0,0,1920,1280))
Y = np.asarray(im)[..., 0].astype(np.float64)
H, W = Y.shape

def blocks(Y):
    return Y.reshape(H//8, 8, W//8, 8).transpose(0,2,1,3)
def unblocks(B):
    return B.transpose(0,2,1,3).reshape(H, W)

def codec(Yp, Q):
    B = blocks(Yp) - 128
    C = dctn(B, axes=(2,3), norm="ortho")
    q = np.round(C / Q)
    rec = idctn(q * Q, axes=(2,3), norm="ortho") + 128
    pix = np.clip(np.round(rec), 0, 255)
    return unblocks(pix), q, C

# verify table vs Pillow
import io
buf = io.BytesIO(); Image.open("/data/barrelfish.jpg").convert("RGB").save(buf, "JPEG", quality=85)
pq = Image.open(io.BytesIO(buf.getvalue())).quantization[0]
print("table85 matches pillow (sorted):", sorted(pq) == sorted(table(85).flatten().tolist()))
print("Q85 luma table"); print(table(85))

# whole-plane: same table
cur = Y.copy(); prevq = None
Q = table(85)
for k in range(1, 11):
    cur, q, C = codec(cur, Q)
    if prevq is not None:
        print(f"same Q85 pass {k}: blocks with any changed quantised coefficient vs previous pass: {(np.abs(q-prevq).sum(axis=(2,3))>0).sum()} of {q.shape[0]*q.shape[1]}; coeffs changed: {(q!=prevq).sum()}")
    prevq = q
# whole-plane: alternate Q85 / Q84 etc
for name, qs in [("85,84,85,84", [85,84]), ("random 70-95", None)]:
    cur = Y.copy(); prevq=None
    import random; rnd = random.Random(7)
    for k in range(1, 11):
        qq = qs[(k-1)%2] if qs else rnd.randint(70,95)
        cur, q, C = codec(cur, table(qq))
        if prevq is not None:
            print(f"{name} pass {k} (q={qq}): coeffs changed vs previous quantised grid(not comparable when table changes): n/a; pixel mad vs original {np.abs(cur-Y).mean():.3f}")
        prevq=q

# pick one real block: aligned block with large (0,1) coefficient near the label
B = blocks(Y) - 128
C = dctn(B, axes=(2,3), norm="ortho")
# search region around the "3" label (x 1550-1640, y 800-880)
by0, by1, bx0, bx1 = 800//8, 880//8, 1560//8, 1640//8
best=None
for by in range(by0,by1):
    for bx in range(bx0,bx1):
        v = abs(C[by,bx,0,1])
        if best is None or v>best[0]: best=(v,by,bx)
print("block", best[1]*8, best[2]*8, "(y,x)")
by, bx = best[1], best[2]
blk = Y[by*8:by*8+8, bx*8:bx*8+8]
c0 = C[by,bx]
print("coef (0,1) raw", c0[0,1], "(1,0)", c0[1,0], "(1,1)", c0[1,1])
# trajectory of coefficient (u,v) = (0,1) and (1,0) for the one block
def traj(sequence, uv):
    cur = blk.copy(); out=[]
    for qq in sequence:
        Qt = table(qq)
        b = cur - 128
        c = dctn(b, norm="ortho")
        out.append((qq, c[uv], Qt[uv], np.round(c[uv]/Qt[uv])))
        qv = np.round(c/Qt)
        rec = idctn(qv*Qt, norm="ortho")+128
        cur = np.clip(np.round(rec),0,255)
    return out
for uv in [(0,1),(1,0),(1,1),(0,2)]:
    print("uv", uv)
    for name, seq in [("same85",[85]*6),("alt 85/84",[85,84,85,84,85,84]),("85,80,85,80..",[85,80,85,80,85,80]), ("descend 85..80",[85,84,83,82,81,80])]:
        t = traj(seq, uv)
        print(" ", name, [f"{a}: raw {c:.2f} step {int(s)} -> {int(q)}" for a,c,s,q in t])
