oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package renderpage
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "image"
8 "image/color"
9 "image/draw"
10 "image/png"
11 "io"
12 "math"
13
14 "amadan.net/oficina/equipo/internal/runner/render"
15)
16
17// Capture bounds. A capture is decoded only after its IHDR says it is
18// within MaxWidth by MaxHeight and maxPixels, and only from a file of at
19// most maxInput bytes; what the runner writes is its own encoding, at
20// most MaxCaptureBytes.
21const (
22 // MaxWidth is the widest viewport (desktop) and MaxHeight a full
23 // page's clip (spec: full pages capped at 10,000 px).
24 MaxWidth = 1440
25 MaxHeight = render.MaxCaptureHeight
26 // maxPixels caps the decoded image on its own (about 58 MB as 8-bit
27 // RGBA), whatever the two above become.
28 maxPixels = MaxWidth * MaxHeight
29 // maxInput caps the browser's file, as the CDP frame cap does.
30 maxInput = 100 << 20
31 // MaxCaptureBytes is the most one written capture holds (spec: at
32 // most 2 MB).
33 MaxCaptureBytes = 2 << 20
34 // maxScaleSteps bounds the downscaling: each step at least a tenth
35 // smaller, so far fewer suffice for any capture within the bounds.
36 maxScaleSteps = 24
37)
38
39// errCapture is a capture the runner refused: the call is crashed.
40var errCapture = errors.New("render_page: the capture is not a PNG within the bounds")
41
42// decodeCapture reads one PNG the browser made, bounded: the file at
43// most maxInput bytes; IHDR's dimensions checked before any pixel is
44// decoded; then fully decoded (CRCs and the zlib stream checked by
45// image/png), its bounds the declared ones. The pixels are copied into
46// an NRGBA image the runner owns.
47func decodeCapture(r io.Reader) (*image.NRGBA, error) {
48 raw, err := io.ReadAll(io.LimitReader(r, maxInput+1))
49 if err != nil {
50 return nil, err
51 }
52 if len(raw) == 0 || len(raw) > maxInput {
53 return nil, fmt.Errorf("%w: %d bytes", errCapture, len(raw))
54 }
55 cfg, err := png.DecodeConfig(bytes.NewReader(raw))
56 if err != nil {
57 return nil, fmt.Errorf("%w: %v", errCapture, err)
58 }
59 if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > MaxWidth || cfg.Height > MaxHeight || int64(cfg.Width)*int64(cfg.Height) > maxPixels {
60 return nil, fmt.Errorf("%w: %dx%d", errCapture, cfg.Width, cfg.Height)
61 }
62 img, err := png.Decode(bytes.NewReader(raw))
63 if err != nil {
64 return nil, fmt.Errorf("%w: %v", errCapture, err)
65 }
66 b := img.Bounds()
67 if b.Min != (image.Point{}) || b.Dx() != cfg.Width || b.Dy() != cfg.Height {
68 return nil, fmt.Errorf("%w: decoded %v", errCapture, b)
69 }
70 out := image.NewNRGBA(b)
71 draw.Draw(out, b, img, image.Point{}, draw.Src)
72 return out, nil
73}
74
75// encodeCapture is the runner's encoding of img: scaled down, keeping
76// its shape, until the PNG is at most MaxCaptureBytes. It returns the
77// bytes and their dimensions.
78func encodeCapture(img *image.NRGBA) ([]byte, int, int, error) {
79 for step := 0; ; step++ {
80 var b bytes.Buffer
81 if err := png.Encode(&b, img); err != nil {
82 return nil, 0, 0, err
83 }
84 w, h := img.Bounds().Dx(), img.Bounds().Dy()
85 if b.Len() <= MaxCaptureBytes {
86 return b.Bytes(), w, h, nil
87 }
88 if step == maxScaleSteps || w == 1 && h == 1 {
89 return nil, 0, 0, fmt.Errorf("%w: still %d bytes at %dx%d", errCapture, b.Len(), w, h)
90 }
91 // PNG size follows the pixel count: aim a little under the cap,
92 // never less than a quarter or more than nine tenths a side.
93 f := math.Sqrt(float64(MaxCaptureBytes)/float64(b.Len())) * 0.95
94 f = min(max(f, 0.25), 0.9)
95 img = downscale(img, max(1, int(float64(w)*f)), max(1, int(float64(h)*f)))
96 }
97}
98
99// downscale is img at w by h, each pixel the mean of the source pixels
100// its box covers.
101func downscale(img *image.NRGBA, w, h int) *image.NRGBA {
102 sw, sh := img.Bounds().Dx(), img.Bounds().Dy()
103 out := image.NewNRGBA(image.Rect(0, 0, w, h))
104 for y := range h {
105 y0, y1 := y*sh/h, max((y+1)*sh/h, y*sh/h+1)
106 for x := range w {
107 x0, x1 := x*sw/w, max((x+1)*sw/w, x*sw/w+1)
108 var sum [4]int
109 for sy := y0; sy < y1; sy++ {
110 row := img.Pix[sy*img.Stride+x0*4 : sy*img.Stride+x1*4]
111 for i := 0; i < len(row); i += 4 {
112 sum[0] += int(row[i])
113 sum[1] += int(row[i+1])
114 sum[2] += int(row[i+2])
115 sum[3] += int(row[i+3])
116 }
117 }
118 n := (y1 - y0) * (x1 - x0)
119 o := out.PixOffset(x, y)
120 for c := range 4 {
121 out.Pix[o+c] = uint8(sum[c] / n)
122 }
123 }
124 }
125 return out
126}
127
128// diffMark is a changed pixel in a diff image.
129var diffMark = color.NRGBA{0xff, 0x00, 0x40, 0xff}
130
131// compare pairs one page's base and work captures: the share of pixels
132// that differ, over the larger extent of the two (a pixel only one has
133// is changed), and a diff image of that extent with each changed pixel
134// marked and the rest the work capture faded.
135func compare(base, work *image.NRGBA) (float64, *image.NRGBA) {
136 bb, wb := base.Bounds(), work.Bounds()
137 w, h := max(bb.Dx(), wb.Dx()), max(bb.Dy(), wb.Dy())
138 diff := image.NewNRGBA(image.Rect(0, 0, w, h))
139 changed := 0
140 for y := range h {
141 for x := range w {
142 p := image.Point{x, y}
143 inB, inW := p.In(bb), p.In(wb)
144 o := diff.PixOffset(x, y)
145 if inB && inW {
146 bo, wo := base.PixOffset(x, y), work.PixOffset(x, y)
147 if bytes.Equal(base.Pix[bo:bo+4], work.Pix[wo:wo+4]) {
148 c := work.Pix[wo : wo+4]
149 grey := (299*int(c[0]) + 587*int(c[1]) + 114*int(c[2])) / 1000
150 v := uint8(192 + grey*63/255)
151 copy(diff.Pix[o:o+4], []byte{v, v, v, 0xff})
152 continue
153 }
154 }
155 changed++
156 copy(diff.Pix[o:o+4], []byte{diffMark.R, diffMark.G, diffMark.B, diffMark.A})
157 }
158 }
159 return float64(changed) / float64(w*h), diff
160}
161