#!/usr/bin/env python3
"""make.py - baseline 4:2:0 JPEG test patterns whose entropy-coded data is large at high quality.

Usage: python3 make.py PATTERN WIDTH HEIGHT QUALITY OUT_PREFIX
  PATTERN   q100 or q99 (the quality the pattern was searched for)
  WIDTH     multiple of 16; HEIGHT multiple of 16
Writes OUT_PREFIX.jpg (Pillow, standard Annex K tables scaled by QUALITY, 4:2:0, no optimisation) and
OUT_PREFIX.nv12 (the same samples as raw NV12), and prints the scan size in bytes per pixel.

Each pattern is a 32x16 pixel tile (two 16x16 MCUs) given below as hex rows: 16 Y rows of 32 samples, then 8 Cb
and 8 Cr rows of 16 samples. The tile is repeated over the frame. The JPEG is encoded from these YCbCr samples
directly: the chroma is replicated 2x2 so that libjpeg's 4:2:0 downsampling returns it unchanged. Going through RGB
(a PNG, say) clips the samples and loses most of the effect.

Requires Pillow (built with libjpeg or libjpeg-turbo).
"""
import sys

from PIL import Image

PATTERNS = {
    'q100': '''
000002ff00ff0000fffefe00ff00fbff00fffdffff00ff00fffd00ff00ffffff
ff00fdfffe00020000fa020003ffffffff0200f902ffffffffffff000000ff00
00fdff00ff000000ff0000ff00ffffffff00ff000000ff00fffcff00ff0000ff
faff000000fffd000000ffffff0000ff00f50006f6010000ff0000fffffe0000
00ff0000ff000000ff00ffff00ffffffffff000400ffff00fbffff00ffff00ff
ff00ff000000ff0000ff02ffffff00fd03ffff00ff000700ff04ffffff00ff00
ff0000ff00feffff00ffff02ff030000ff00fffaff000000000000fb00ffff00
00ffffffff00ff00f200000000ff00ff000400ff07ff0000ff00ff00010004ff
00ffffffff00ff00fdfffe00ff00ffff000000f100fc0002ff00000100fa01ff
ff0100ff00ffffff00ff000003fffffdff00fff8ff00000000fffd00ff000003
ff00ff000000ff00ff0300ff00ffffff00ffff00ff00000004ff00fffffc00fd
00ff0000ff0000000003ffffff0000ffffff000400ffff04f600ffff00fffffb
ffff070000fdff01ff00ffff00ffffff05ff0000ff0000000000ffffff0000ff
00ffff00ff00000000ff00ffffff00ffff00ff000000fb00ff0000ff04ffffff
ff00fefdff00000000ffff00ff020000ff0000ff00ffffff00ff000000fffffd
000000ff00fd0000ff00000000ff02ff00e2fffaff00ff00ecffff00ff00f9ff
00ffff00ffff000000ff0000ff0000ff
ff00ff00ffff00ff00ff0000ff00ff00
000000ff0000ffff0000ffff00ffffff
ffff000000ff0000ffff00ffffff0000
ff0000ff000000ff00ffffff00ffff00
0000ffffff000000ffffff000000ffff
ffff00ffffff0000ffff000000ff0000
ff00000000ff0000ffff00ffffffffff
00ffff00fffd00ffffffffffff00ffff
ff00ff00fffe00fe0000ff000000ffff
000000ff0000ffffffff000100ffffff
ffff000000ff000000ffff00ffffff00
ff0000ff000000ff0000ffffff00ffff
0000fffdff000000ffffff00ffff0000
ffff00ffffff000300ff00ff0000ff00
0000000000ff0100ff0000ff0000ff00
''',
    'q99': '''
ff00ff00000002ffff00000001000000ff00ff00020000ffff00000000000000
000000f5ed00ff00ff0200fc00e6ffff000000fdff00ff00ff0000ff00ffffff
ffff0000ffff0000ff00ff0110fdff00faff0005ffff0000ff00ff0000fffb00
ffffffffff00ff00fff6ff00fffbffeaffffffffff00ff00ffffff03fef8ffff
00000000ff000f00ff01ff00020c000000030000fb000000ff00ff0000000000
ff0805ffff08df00ffff0000fffa0000ff0000ffff00ff00ffff0700fff90000
000a00ff10f8ff00ff00ff0000ffffff000003ff00ffff00ff06ff0000ffffff
fffffffffffff00000fffffbff00ff00fffffffffcffff0004ffffffff00ff01
f500ff00000000f9ff00000000160300ff00ff00000000ffff00000000000000
110003ffff00ff00ff0000ff00f8ffff000000ffff00ff02ff0000ff00fffdff
fdff0000ffff0000ff00ff0003ffff00fbff0001ffff0000ff00ff0000fbff00
ffffffffff00ff00ffffff04ffffffffffffffffff02fb00fffdff06fffffdff
00000d00ff020000fa00ff020000000000000000ff000400ff00ff0000000006
ff0000ffff00f600ffff0000ffff0600ff0400ffff00ff01ffff0500ffff0000
000000ff00f8ff03ff00ff0002ffffff000000ff00fffe00ff00ff0000ffffff
ffffffffffffff0000faffffff04fc08fffcfffffaffff0000fff7fffe00ff00
00ffffff00ff00ff00ff0012ff00ffff
fcf8fffdff000cff002300ffffffff00
00ff000200ff000007ff0200fcf700ff
0006ff0000fffffa0000ddffffff00ff
ffff00000000ff04fffd09ffff000000
ff00ffff0000fa05f200ffffff00ffff
ffffff00000000ffe901000006f9e400
f800fbf80aff0000ff000000ff00ff00
00ffffff00ff02ff00fd00ff020000ff
ffffffffff0000ff00fcff0000020000
00ff000000ff0000ffff00ffffff00fe
0002ff0000ffffff000000ffff00ffff
ffff00000000fd00ff00fffffcff0000
ff00ffff0000ff00ff00ffff0000ff00
ffffff00000000ff00ffffffff000500
ff00ffff00ff0000ffff00ff0000ff00
''',
}


def tile(name):
    rows = [bytes.fromhex(r) for r in PATTERNS[name].split()]
    return rows[:16], rows[16:24], rows[24:32]


def plane(rows, w, h):
    tw = len(rows[0])
    out = bytearray()
    for y in range(h):
        r = rows[y % len(rows)]
        out += (r * (w // tw + 1))[:w]
    return bytes(out)


def scan_bytes(jpg):
    """bytes between the end of the SOS segment and EOI (byte stuffing included)"""
    i = 2
    while True:
        assert jpg[i] == 0xFF
        marker, seglen = jpg[i + 1], int.from_bytes(jpg[i + 2:i + 4], 'big')
        if marker == 0xDA:
            start = i + 2 + seglen
            end = jpg.rindex(b'\xff\xd9')
            return end - start
        i += 2 + seglen


def main():
    if len(sys.argv) != 6:
        sys.exit(__doc__)
    name, w, h, q, prefix = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), sys.argv[5]
    if w % 16 or h % 16:
        sys.exit('WIDTH and HEIGHT must be multiples of 16')
    ty, tcb, tcr = tile(name)
    y, cb, cr = plane(ty, w, h), plane(tcb, w // 2, h // 2), plane(tcr, w // 2, h // 2)
    with open(prefix + '.nv12', 'wb') as f:
        f.write(y)
        f.write(bytes(b for pair in zip(cb, cr) for b in pair))
    up = [Image.frombytes('L', (w // 2, h // 2), p).resize((w, h), Image.NEAREST) for p in (cb, cr)]
    img = Image.merge('YCbCr', [Image.frombytes('L', (w, h), y)] + up)
    img.save(prefix + '.jpg', 'JPEG', quality=q, subsampling=2, optimize=False)
    jpg = open(prefix + '.jpg', 'rb').read()
    s = scan_bytes(jpg)
    print(f'{prefix}.jpg: {w}x{h} q{q} file {len(jpg)} B ({len(jpg) / (w * h):.4f} B/px), '
          f'scan {s} B ({s / (w * h):.4f} B/px)')


if __name__ == '__main__':
    main()
