package capture import "image" const blockSize = 32 // DirtyRect computes the bounding rectangle of pixel blocks that differ // between prev and cur, so the caller can send only the changed region // instead of a full frame every tick. prev and cur must share bounds. func DirtyRect(prev, cur *image.RGBA) (rect image.Rectangle, changed bool) { bounds := cur.Bounds() minX, minY := bounds.Max.X, bounds.Max.Y maxX, maxY := -1, -1 for by := bounds.Min.Y; by < bounds.Max.Y; by += blockSize { bh := min(blockSize, bounds.Max.Y-by) for bx := bounds.Min.X; bx < bounds.Max.X; bx += blockSize { bw := min(blockSize, bounds.Max.X-bx) if blockDiffers(prev, cur, bx, by, bw, bh) { minX = min(minX, bx) minY = min(minY, by) maxX = max(maxX, bx+bw) maxY = max(maxY, by+bh) } } } if maxX < 0 { return image.Rectangle{}, false } return image.Rect(minX, minY, maxX, maxY), true } func blockDiffers(prev, cur *image.RGBA, x, y, w, h int) bool { rowLen := w * 4 for j := 0; j < h; j++ { prevOff := prev.PixOffset(x, y+j) curOff := cur.PixOffset(x, y+j) pRow := prev.Pix[prevOff : prevOff+rowLen] cRow := cur.Pix[curOff : curOff+rowLen] for k := range pRow { if pRow[k] != cRow[k] { return true } } } return false }