Files
Reims-Go/internal/thumb/thumb.go
T

231 lines
5.6 KiB
Go

// Package thumb turns a QEMU screendump into a small JPEG for the VM page.
package thumb
import (
"bufio"
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"os"
"strconv"
)
// Load decodes a screendump written as "png" or "ppm" (binary P6).
func Load(path, format string) (image.Image, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
if format == "png" {
return png.Decode(bufio.NewReader(f))
}
return decodePPM(bufio.NewReader(f))
}
// Size returns the source-frame dimensions without decoding its pixels.
func Size(path, format string) (image.Point, error) {
f, err := os.Open(path)
if err != nil {
return image.Point{}, err
}
defer f.Close()
if format == "png" {
cfg, err := png.DecodeConfig(bufio.NewReader(f))
if err != nil {
return image.Point{}, err
}
return image.Pt(cfg.Width, cfg.Height), nil
}
if format != "ppm" {
return image.Point{}, fmt.Errorf("unsupported screendump format %q", format)
}
return ppmSize(bufio.NewReader(f))
}
// decodePPM reads a binary PPM (P6, maxval ≤ 255), the format QEMU's
// screendump writes when no format is given.
func decodePPM(r *bufio.Reader) (image.Image, error) {
size, err := ppmSize(r)
if err != nil {
return nil, err
}
w, h := size.X, size.Y
img := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
row := img.Pix[y*img.Stride : (y+1)*img.Stride]
// Expand RGB to RGBA backwards in the same row.
if _, err := io.ReadFull(r, row[:w*3]); err != nil {
return nil, fmt.Errorf("ppm: %w", err)
}
for x := w - 1; x >= 0; x-- {
copy(row[x*4:x*4+3], row[x*3:x*3+3])
row[x*4+3] = 255
}
}
return img, nil
}
func ppmSize(r *bufio.Reader) (image.Point, error) {
tok := func() (string, error) {
var b []byte
for {
c, err := r.ReadByte()
if err != nil {
return "", err
}
switch {
case c == '#':
if _, err := r.ReadString('\n'); err != nil {
return "", err
}
case c == ' ' || c == '\t' || c == '\n' || c == '\r':
if len(b) > 0 {
return string(b), nil
}
default:
b = append(b, c)
}
}
}
magic, err := tok()
if err != nil {
return image.Point{}, err
}
if magic != "P6" {
return image.Point{}, fmt.Errorf("ppm: unsupported magic %q", magic)
}
var dims [3]int
for i := range dims {
s, err := tok()
if err != nil {
return image.Point{}, err
}
if dims[i], err = strconv.Atoi(s); err != nil {
return image.Point{}, fmt.Errorf("ppm: bad header: %w", err)
}
}
w, h, maxv := dims[0], dims[1], dims[2]
if w <= 0 || h <= 0 || w > 16384 || h > 16384 || maxv <= 0 || maxv > 255 {
return image.Point{}, errors.New("ppm: unsupported size or depth")
}
return image.Pt(w, h), nil
}
// Scale shrinks img to at most maxW pixels wide by averaging each source
// block (box filter), which keeps text and UI edges readable at small sizes.
func Scale(img image.Image, maxW int) image.Image {
b := img.Bounds()
sw, sh := b.Dx(), b.Dy()
if sw <= maxW || sw == 0 {
return img
}
dw := maxW
dh := sh * dw / sw
if dh < 1 {
dh = 1
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
if src, ok := img.(*image.RGBA); ok {
scaleRGBA(dst, src, sw, sh, dw, dh)
return dst
}
for y := 0; y < dh; y++ {
y0, y1 := y*sh/dh, (y+1)*sh/dh
for x := 0; x < dw; x++ {
x0, x1 := x*sw/dw, (x+1)*sw/dw
var r, g, bl, n uint32
for sy := y0; sy < y1; sy++ {
for sx := x0; sx < x1; sx++ {
cr, cg, cb, _ := img.At(b.Min.X+sx, b.Min.Y+sy).RGBA()
r, g, bl, n = r+cr>>8, g+cg>>8, bl+cb>>8, n+1
}
}
if n == 0 {
n = 1
}
dst.SetRGBA(x, y, color.RGBA{uint8(r / n), uint8(g / n), uint8(bl / n), 255})
}
}
return dst
}
// scaleRGBA is Scale's box filter for *image.RGBA, the type decodePPM
// returns. It reads Pix directly: going through img.At boxes every pixel
// in an interface, which for a 4K frame is about 8 million allocations.
func scaleRGBA(dst, src *image.RGBA, sw, sh, dw, dh int) {
for y := 0; y < dh; y++ {
y0, y1 := y*sh/dh, (y+1)*sh/dh
drow := dst.Pix[y*dst.Stride:]
for x := 0; x < dw; x++ {
x0, x1 := x*sw/dw, (x+1)*sw/dw
var r, g, bl, n uint32
for sy := y0; sy < y1; sy++ {
row := src.Pix[sy*src.Stride+x0*4 : sy*src.Stride+x1*4]
for i := 0; i < len(row); i += 4 {
r, g, bl = r+uint32(row[i]), g+uint32(row[i+1]), bl+uint32(row[i+2])
}
n += uint32(x1 - x0)
}
if n == 0 {
n = 1
}
d := drow[x*4 : x*4+4]
d[0], d[1], d[2], d[3] = uint8(r/n), uint8(g/n), uint8(bl/n), 255
}
}
}
// Blank reports whether a frame is (almost) one flat colour — a powered-off
// or not-yet-drawn console — so the UI can keep its placeholder instead.
func Blank(img image.Image) bool {
b := img.Bounds()
step := max(1, b.Dx()/64)
var samples blankSamples
for y := b.Min.Y; y < b.Max.Y; y += step {
for x := b.Min.X; x < b.Max.X; x += step {
r, g, bl, _ := img.At(x, y).RGBA()
samples.add(uint8(r>>8), uint8(g>>8), uint8(bl>>8))
}
}
return samples.blank()
}
type blankSamples struct {
first color.RGBA
total, diff int
}
func (s *blankSamples) add(r, g, b byte) {
if s.total == 0 {
s.first = color.RGBA{r, g, b, 255}
}
s.total++
if absDiff(r, s.first.R)+absDiff(g, s.first.G)+absDiff(b, s.first.B) > 24 {
s.diff++
}
}
func (s blankSamples) blank() bool { return s.total == 0 || s.diff*100 < s.total }
func absDiff(a, b uint8) int {
if a > b {
return int(a - b)
}
return int(b - a)
}
// JPEG encodes img at the given quality.
func JPEG(img image.Image, quality int) ([]byte, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
return buf.Bytes(), nil
}