M7: hardening and final pass
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
00ee2a6d12
commit
ae898a2787
30 files changed
+878
-107
No files matched your search
@@ -34,11 +34,12 @@ type Level struct {
|
||||
}
|
||||
|
||||
type Pyramid struct {
|
||||
Hash string `json:"hash"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Levels []Level `json:"levels"`
|
||||
Seed string `json:"seed"`
|
||||
Hash string `json:"hash"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Levels []Level `json:"levels"`
|
||||
Seed string `json:"seed"`
|
||||
Scramble string `json:"scramble,omitempty"`
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
|
||||
@@ -22,6 +22,13 @@ import (
|
||||
|
||||
const minLongEdge = 100
|
||||
|
||||
func (p *Processor) Overlap() int {
|
||||
if p.images.ScrambleCells {
|
||||
return 0
|
||||
}
|
||||
return p.images.Overlap
|
||||
}
|
||||
|
||||
func LevelSizes(width, height, minLevels int) [][2]int {
|
||||
sizes := [][2]int{{width, height}}
|
||||
for {
|
||||
@@ -155,6 +162,10 @@ func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
|
||||
}
|
||||
}
|
||||
|
||||
scrambleSeed := ""
|
||||
if p.images.ScrambleCells {
|
||||
scrambleSeed = p.ScrambleSeed(job.Hash)
|
||||
}
|
||||
levels := make([]Level, count)
|
||||
var seed string
|
||||
var firstErr error
|
||||
@@ -188,7 +199,17 @@ func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
|
||||
go func(i int, src *refFile) {
|
||||
defer wg.Done()
|
||||
defer src.release()
|
||||
level, err := p.cutLevel(ctx, job.Hash, src.path, stage, i, count, sizes[i])
|
||||
input := src.path
|
||||
if p.images.ScrambleCells {
|
||||
scrambled := filepath.Join(work, "s"+strconv.Itoa(i)+".v")
|
||||
if err := ScrambleV(src.path, scrambled, scrambleSeed, i, p.images.TileSize, ScrambleCell); err != nil {
|
||||
fail(fmt.Errorf("scramble level %d: %w", i, err))
|
||||
return
|
||||
}
|
||||
defer os.Remove(scrambled)
|
||||
input = scrambled
|
||||
}
|
||||
level, err := p.cutLevel(ctx, job.Hash, input, stage, i, count, sizes[i])
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("level %d: %w", i, err))
|
||||
return
|
||||
@@ -236,11 +257,11 @@ func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
|
||||
committed = true
|
||||
|
||||
rec := &Record{
|
||||
Pyramid: Pyramid{Hash: job.Hash, Width: width, Height: height, Levels: levels, Seed: seed},
|
||||
Pyramid: Pyramid{Hash: job.Hash, Width: width, Height: height, Levels: levels, Seed: seed, Scramble: scrambleSeed},
|
||||
Kind: job.Kind,
|
||||
Format: p.images.Format,
|
||||
TileSize: p.images.TileSize,
|
||||
Overlap: p.images.Overlap,
|
||||
Overlap: p.Overlap(),
|
||||
Processed: time.Now().UTC().Truncate(time.Second),
|
||||
}
|
||||
if job.Kind == "photo" {
|
||||
@@ -351,7 +372,7 @@ func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level
|
||||
"--layout", "dz",
|
||||
"--depth", "one",
|
||||
"--tile-size", strconv.Itoa(p.images.TileSize),
|
||||
"--overlap", strconv.Itoa(p.images.Overlap),
|
||||
"--overlap", strconv.Itoa(p.Overlap()),
|
||||
"--suffix", ext+p.vips.SaveOptions(quality)); err != nil {
|
||||
return Level{}, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
ScrambleCell = 64
|
||||
scrambleWorkers = 2
|
||||
vipsHeaderSize = 64
|
||||
)
|
||||
|
||||
var bandFormatSize = map[int32]int{0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 8, 8: 8, 9: 16}
|
||||
|
||||
func (p *Processor) ScrambleSeed(hash string) string {
|
||||
mac := hmac.New(sha256.New, p.key)
|
||||
mac.Write([]byte("scramble|" + hash))
|
||||
return hex.EncodeToString(mac.Sum(nil))[:16]
|
||||
}
|
||||
|
||||
func tileSeed(seed string, level, x, y int) uint32 {
|
||||
h := uint32(2166136261)
|
||||
for _, c := range []byte(seed + "|" + strconv.Itoa(level) + "|" + strconv.Itoa(x) + "|" + strconv.Itoa(y)) {
|
||||
h ^= uint32(c)
|
||||
h *= 16777619
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
type mulberry32 struct {
|
||||
state uint32
|
||||
}
|
||||
|
||||
func (m *mulberry32) next() float64 {
|
||||
m.state += 0x6D2B79F5
|
||||
a := m.state
|
||||
t := (a ^ (a >> 15)) * (a | 1)
|
||||
t = (t + (t^(t>>7))*(t|61)) ^ t
|
||||
return float64(t^(t>>14)) / 4294967296
|
||||
}
|
||||
|
||||
func CellPermutation(n int, seed uint32) []int {
|
||||
perm := make([]int, n)
|
||||
for i := range perm {
|
||||
perm[i] = i
|
||||
}
|
||||
rng := mulberry32{state: seed}
|
||||
for i := n - 1; i > 0; i-- {
|
||||
j := int(rng.next() * float64(i+1))
|
||||
perm[i], perm[j] = perm[j], perm[i]
|
||||
}
|
||||
return perm
|
||||
}
|
||||
|
||||
type vHeader struct {
|
||||
width, height int
|
||||
pixelBytes int
|
||||
}
|
||||
|
||||
func readVHeader(f *os.File) (vHeader, error) {
|
||||
var raw [vipsHeaderSize]byte
|
||||
if _, err := io.ReadFull(io.NewSectionReader(f, 0, vipsHeaderSize), raw[:]); err != nil {
|
||||
return vHeader{}, err
|
||||
}
|
||||
var order binary.ByteOrder
|
||||
switch {
|
||||
case raw[0] == vipsMagicIntel[0] && raw[1] == vipsMagicIntel[1] && raw[2] == vipsMagicIntel[2] && raw[3] == vipsMagicIntel[3]:
|
||||
order = binary.LittleEndian
|
||||
case raw[0] == vipsMagicSparc[0] && raw[1] == vipsMagicSparc[1] && raw[2] == vipsMagicSparc[2] && raw[3] == vipsMagicSparc[3]:
|
||||
order = binary.BigEndian
|
||||
default:
|
||||
return vHeader{}, errors.New("not a vips image")
|
||||
}
|
||||
width := int(int32(order.Uint32(raw[4:8])))
|
||||
height := int(int32(order.Uint32(raw[8:12])))
|
||||
bands := int(int32(order.Uint32(raw[12:16])))
|
||||
format := int32(order.Uint32(raw[20:24]))
|
||||
coding := int32(order.Uint32(raw[24:28]))
|
||||
size, ok := bandFormatSize[format]
|
||||
if !ok || coding != 0 || width <= 0 || height <= 0 || bands <= 0 {
|
||||
return vHeader{}, fmt.Errorf("unsupported vips image (format %d, coding %d)", format, coding)
|
||||
}
|
||||
return vHeader{width: width, height: height, pixelBytes: bands * size}, nil
|
||||
}
|
||||
|
||||
func ScrambleV(src, dst, seed string, level, tileSize, cell int) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
header, err := readVHeader(in)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", src, err)
|
||||
}
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ok := false
|
||||
defer func() {
|
||||
out.Close()
|
||||
if !ok {
|
||||
os.Remove(dst)
|
||||
}
|
||||
}()
|
||||
if _, err := io.Copy(out, io.NewSectionReader(in, 0, vipsHeaderSize)); err != nil {
|
||||
return err
|
||||
}
|
||||
rowBytes := int64(header.width) * int64(header.pixelBytes)
|
||||
dataEnd := vipsHeaderSize + rowBytes*int64(header.height)
|
||||
bands := (header.height + tileSize - 1) / tileSize
|
||||
jobs := make(chan int)
|
||||
errs := make([]error, scrambleWorkers)
|
||||
var wg sync.WaitGroup
|
||||
for w := 0; w < min(scrambleWorkers, bands); w++ {
|
||||
wg.Add(1)
|
||||
go func(w int) {
|
||||
defer wg.Done()
|
||||
buf := make([]byte, int64(min(tileSize, header.height))*rowBytes)
|
||||
tmp := make([]byte, cell*cell*header.pixelBytes)
|
||||
for band := range jobs {
|
||||
if errs[w] != nil {
|
||||
continue
|
||||
}
|
||||
errs[w] = scrambleBand(in, out, buf, tmp, header, band, rowBytes, seed, level, tileSize, cell)
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
for band := 0; band < bands; band++ {
|
||||
jobs <- band
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
if err := errors.Join(errs...); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := in.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Size() > dataEnd {
|
||||
if _, err := io.Copy(io.NewOffsetWriter(out, dataEnd), io.NewSectionReader(in, dataEnd, info.Size()-dataEnd)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ok = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func scrambleBand(in, out *os.File, buf, tmp []byte, header vHeader, band int, rowBytes int64, seed string, level, tileSize, cell int) error {
|
||||
top := band * tileSize
|
||||
rows := min(tileSize, header.height-top)
|
||||
data := buf[:int64(rows)*rowBytes]
|
||||
offset := vipsHeaderSize + int64(top)*rowBytes
|
||||
if _, err := in.ReadAt(data, offset); err != nil {
|
||||
return err
|
||||
}
|
||||
cellRows := rows / cell
|
||||
cellBytes := cell * header.pixelBytes
|
||||
tiles := (header.width + tileSize - 1) / tileSize
|
||||
for tx := 0; tx < tiles; tx++ {
|
||||
width := min(tileSize, header.width-tx*tileSize)
|
||||
cols := width / cell
|
||||
n := cols * cellRows
|
||||
if n < 2 {
|
||||
continue
|
||||
}
|
||||
perm := CellPermutation(n, tileSeed(seed, level, tx, band))
|
||||
origin := tx * tileSize * header.pixelBytes
|
||||
at := func(index, row int) []byte {
|
||||
cy, cx := index/cols, index%cols
|
||||
start := int64(cy*cell+row)*rowBytes + int64(origin+cx*cellBytes)
|
||||
return data[start : start+int64(cellBytes)]
|
||||
}
|
||||
done := make([]bool, n)
|
||||
for start := 0; start < n; start++ {
|
||||
if done[start] || perm[start] == start {
|
||||
done[start] = true
|
||||
continue
|
||||
}
|
||||
for r := 0; r < cell; r++ {
|
||||
copy(tmp[r*cellBytes:(r+1)*cellBytes], at(start, r))
|
||||
}
|
||||
i := start
|
||||
for {
|
||||
done[i] = true
|
||||
j := perm[i]
|
||||
if j == start {
|
||||
for r := 0; r < cell; r++ {
|
||||
copy(at(i, r), tmp[r*cellBytes:(r+1)*cellBytes])
|
||||
}
|
||||
break
|
||||
}
|
||||
for r := 0; r < cell; r++ {
|
||||
copy(at(i, r), at(j, r))
|
||||
}
|
||||
i = j
|
||||
}
|
||||
}
|
||||
}
|
||||
_, err := out.WriteAt(data, offset)
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user