M1: processor CLI

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
lucioandClaude Opus 5.5 committed 2026-11-04 04:07:45 -08:00
commit 18a397653a
21 files changed
+2775

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
package process
import (
"context"
"crypto/sha256"
"encoding"
"encoding/hex"
"fmt"
"image"
_ "image/jpeg"
"io"
"math"
"math/big"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/rwcarlsen/goexif/exif"
)
type EXIF struct {
Make string `json:"make,omitempty"`
Model string `json:"model,omitempty"`
Lens string `json:"lens,omitempty"`
FocalLength float64 `json:"focal_length,omitempty"`
FNumber float64 `json:"f_number,omitempty"`
Exposure string `json:"exposure,omitempty"`
ISO int `json:"iso,omitempty"`
Date string `json:"date,omitempty"`
}
type Source struct {
Path string
Hash string
Size int64
Width int
Height int
EXIF *EXIF
Record *Record
digest []byte
}
var copyBuffers = sync.Pool{New: func() any {
buf := make([]byte, 1<<20)
return &buf
}}
func (p *Processor) Inspect(ctx context.Context, paths []string) (map[string]*Source, map[string]error) {
sources := make(map[string]*Source, len(paths))
failures := make(map[string]error)
var mu sync.Mutex
jobs := make(chan string)
var wg sync.WaitGroup
for w := 0; w < min(runtime.NumCPU(), len(paths)); w++ {
wg.Add(1)
go func() {
defer wg.Done()
for path := range jobs {
src, err := p.inspect(ctx, path)
mu.Lock()
if err != nil {
failures[path] = err
} else {
sources[path] = src
}
mu.Unlock()
}
}()
}
for _, path := range paths {
jobs <- path
}
close(jobs)
wg.Wait()
return sources, failures
}
func (p *Processor) inspect(ctx context.Context, path string) (*Source, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
h := sha256.New()
buf := copyBuffers.Get().(*[]byte)
size, err := io.CopyBuffer(h, f, *buf)
copyBuffers.Put(buf)
if err != nil {
return nil, fmt.Errorf("read %s: %w", path, err)
}
digest, err := h.(encoding.BinaryMarshaler).MarshalBinary()
if err != nil {
return nil, err
}
src := &Source{Path: path, Size: size, digest: digest}
src.Hash = p.hashWith(digest, "photo")
if rec, ok := p.Lookup(src.Hash); ok {
src.Record = rec
src.Width, src.Height = rec.Width, rec.Height
src.EXIF = rec.EXIF
return src, nil
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
cfg, _, err := image.DecodeConfig(f)
if err != nil {
return nil, fmt.Errorf("%s: not a readable JPEG: %w", path, err)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
meta, orientation := readEXIF(f)
src.EXIF = meta
src.Width, src.Height = cfg.Width, cfg.Height
if orientation >= 5 && orientation <= 8 {
src.Width, src.Height = cfg.Height, cfg.Width
}
return src, nil
}
func (p *Processor) hashWith(digest []byte, extra string) string {
h := sha256.New()
if err := h.(encoding.BinaryUnmarshaler).UnmarshalBinary(digest); err != nil {
panic(err)
}
io.WriteString(h, "\x00"+p.fingerprint+"\x00"+extra)
return hex.EncodeToString(h.Sum(nil))[:16]
}
func (p *Processor) CoverHash(src *Source, crop [4]int) string {
return p.hashWith(src.digest, fmt.Sprintf("cover:%d,%d,%d,%d", crop[0], crop[1], crop[2], crop[3]))
}
func readEXIF(r io.Reader) (meta *EXIF, orientation int) {
defer func() {
if recover() != nil {
meta, orientation = nil, 1
}
}()
x, err := exif.Decode(r)
if err != nil || x == nil {
return nil, 1
}
orientation = 1
if tag, err := x.Get(exif.Orientation); err == nil {
if v, err := tag.Int(0); err == nil {
orientation = v
}
}
e := &EXIF{
Make: exifString(x, exif.Make),
Model: exifString(x, exif.Model),
Lens: exifString(x, exif.LensModel),
}
if r, ok := exifRat(x, exif.FocalLength); ok {
e.FocalLength = round(ratFloat(r), 1)
}
if r, ok := exifRat(x, exif.FNumber); ok {
e.FNumber = round(ratFloat(r), 1)
}
if r, ok := exifRat(x, exif.ExposureTime); ok {
e.Exposure = formatExposure(r)
}
if tag, err := x.Get(exif.ISOSpeedRatings); err == nil {
if v, err := tag.Int(0); err == nil && v > 0 {
e.ISO = v
}
}
for _, field := range []exif.FieldName{exif.DateTimeOriginal, exif.DateTimeDigitized, exif.DateTime} {
if raw := exifString(x, field); raw != "" {
if t, err := time.Parse("2006:01:02 15:04:05", raw); err == nil {
e.Date = t.Format("2006-01-02T15:04:05")
break
}
}
}
if *e == (EXIF{}) {
return nil, orientation
}
return e, orientation
}
func exifString(x *exif.Exif, field exif.FieldName) string {
tag, err := x.Get(field)
if err != nil {
return ""
}
s, err := tag.StringVal()
if err != nil {
return ""
}
return strings.TrimSpace(strings.TrimRight(s, "\x00"))
}
func exifRat(x *exif.Exif, field exif.FieldName) (*big.Rat, bool) {
tag, err := x.Get(field)
if err != nil {
return nil, false
}
r, err := tag.Rat(0)
if err != nil || r == nil || r.Sign() <= 0 {
return nil, false
}
return r, true
}
func ratFloat(r *big.Rat) float64 {
f, _ := r.Float64()
return f
}
func round(v float64, digits int) float64 {
scale := math.Pow(10, float64(digits))
return math.Round(v*scale) / scale
}
func formatExposure(r *big.Rat) string {
seconds := ratFloat(r)
if seconds >= 0.3 {
return strconv.FormatFloat(round(seconds, 1), 'f', -1, 64)
}
return "1/" + strconv.Itoa(int(math.Round(1/seconds)))
}
+277
View File
@@ -0,0 +1,277 @@
package process
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/luciochen233/luphoto/internal/config"
"github.com/luciochen233/luphoto/internal/fsutil"
)
const processorVersion = "luphoto-pyramid-1"
type Level struct {
Width int `json:"width"`
Height int `json:"height"`
Cols int `json:"cols"`
Rows int `json:"rows"`
Quality int `json:"quality"`
Tiles []string `json:"tiles"`
Bytes []int64 `json:"bytes"`
}
type Pyramid struct {
Hash string `json:"hash"`
Width int `json:"width"`
Height int `json:"height"`
Levels []Level `json:"levels"`
Seed string `json:"seed"`
}
type Record struct {
Pyramid
Kind string `json:"kind"`
Format string `json:"format"`
TileSize int `json:"tile_size"`
Overlap int `json:"overlap"`
Crop []int `json:"crop,omitempty"`
EXIF *EXIF `json:"exif,omitempty"`
Processed time.Time `json:"processed"`
}
func (r *Record) TileBytes() int64 {
var total int64
for _, level := range r.Levels {
for _, b := range level.Bytes {
total += b
}
}
return total
}
func (r *Record) TileCount() int {
n := 0
for _, level := range r.Levels {
n += len(level.Tiles)
}
return n
}
type Processor struct {
images config.Images
vips *Vips
key []byte
fingerprint string
TilesDir string
StateDir string
recordsDir string
workDir string
Threads int
}
func New(ctx context.Context, cfg *config.Config) (*Processor, error) {
tiles := filepath.Join(cfg.Paths.Output, "t")
records := filepath.Join(cfg.State, "pyramids")
work := filepath.Join(cfg.Paths.Cache, "work")
for _, dir := range []string{cfg.Paths.Output, tiles, cfg.State, records, cfg.Paths.Cache, work} {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
}
key, err := loadOrCreateKey(filepath.Join(cfg.State, "site.key"))
if err != nil {
return nil, err
}
threads := runtime.NumCPU() / cfg.Build.Workers
if threads < 1 {
threads = 1
}
env := os.Environ()
if os.Getenv("VIPS_CONCURRENCY") == "" {
env = append(env, "VIPS_CONCURRENCY="+strconv.Itoa(threads))
}
env = append(env, "TMPDIR="+work)
v, err := DetectVips(ctx, env)
if err != nil {
return nil, err
}
img := cfg.Images
keySum := sha256.Sum256(key)
fingerprint := strings.Join([]string{
processorVersion,
"tile=" + strconv.Itoa(img.TileSize),
"overlap=" + strconv.Itoa(img.Overlap),
"format=" + img.Format,
fmt.Sprintf("q=%d,%d,%d", img.Quality.Top, img.Quality.Mid, img.Quality.Low),
"min_levels=" + strconv.Itoa(img.MinLevels),
"seed=" + strconv.Itoa(img.SeedPx),
"names=" + img.TileNames,
"scramble=" + strconv.FormatBool(img.ScrambleCells),
"key=" + hex.EncodeToString(keySum[:4]),
}, "|")
return &Processor{
images: img,
vips: v,
key: key,
fingerprint: fingerprint,
TilesDir: tiles,
StateDir: cfg.State,
recordsDir: records,
workDir: work,
Threads: threads,
}, nil
}
func (p *Processor) VipsVersion() string {
return p.vips.Version
}
func loadOrCreateKey(path string) ([]byte, error) {
key, err := os.ReadFile(path)
if err == nil {
if len(key) != 32 {
return nil, fmt.Errorf("site key %s: expected 32 bytes, found %d", path, len(key))
}
return key, nil
}
if !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
key = make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return nil, err
}
if err := fsutil.WriteFileAtomic(path, key, 0o600); err != nil {
return nil, err
}
return key, nil
}
func (p *Processor) recordPath(hash string) string {
return filepath.Join(p.recordsDir, hash+".json")
}
func (p *Processor) Lookup(hash string) (*Record, bool) {
var rec Record
if err := fsutil.ReadJSON(p.recordPath(hash), &rec); err != nil || rec.Hash != hash {
return nil, false
}
info, err := os.Stat(filepath.Join(p.TilesDir, hash))
if err != nil || !info.IsDir() {
return nil, false
}
return &rec, true
}
type Job struct {
Hash string
Kind string
Label string
Source *Source
Crop *[4]int
}
func (j *Job) pixels() int {
if j.Crop != nil {
return j.Crop[2] * j.Crop[3]
}
return j.Source.Width * j.Source.Height
}
type Result struct {
Job *Job
Record *Record
Err error
Duration time.Duration
}
func (p *Processor) Run(ctx context.Context, jobs []*Job, workers int, done func(Result)) {
ordered := append([]*Job(nil), jobs...)
sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].pixels() > ordered[j].pixels() })
queue := make(chan *Job)
var wg sync.WaitGroup
var mu sync.Mutex
for w := 0; w < min(workers, len(ordered)); w++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range queue {
start := time.Now()
rec, err := p.process(ctx, job)
res := Result{Job: job, Record: rec, Err: err, Duration: time.Since(start)}
mu.Lock()
done(res)
mu.Unlock()
}
}()
}
for _, job := range ordered {
queue <- job
}
close(queue)
wg.Wait()
}
func (p *Processor) ForgetUnreferenced(keep map[string]bool) (int, error) {
entries, err := os.ReadDir(p.TilesDir)
if err != nil {
return 0, err
}
removed := 0
var firstErr error
for _, entry := range entries {
name := entry.Name()
if strings.HasPrefix(name, ".") {
if strings.Contains(name, fsutil.TempMarker) {
_ = os.RemoveAll(filepath.Join(p.TilesDir, name))
}
continue
}
if keep[name] {
continue
}
if err := os.Remove(p.recordPath(name)); err != nil && !errors.Is(err, fs.ErrNotExist) && firstErr == nil {
firstErr = err
}
if err := os.RemoveAll(filepath.Join(p.TilesDir, name)); err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
removed++
}
records, err := os.ReadDir(p.recordsDir)
if err == nil {
for _, entry := range records {
hash := strings.TrimSuffix(entry.Name(), ".json")
if !keep[hash] {
_ = os.Remove(filepath.Join(p.recordsDir, entry.Name()))
}
}
}
return removed, firstErr
}
func (p *Processor) CleanWork() {
entries, err := os.ReadDir(p.workDir)
if err != nil {
return
}
for _, entry := range entries {
_ = os.RemoveAll(filepath.Join(p.workDir, entry.Name()))
}
}
+354
View File
@@ -0,0 +1,354 @@
package process
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/luciochen233/luphoto/internal/fsutil"
)
const minLongEdge = 100
func LevelSizes(width, height, minLevels int) [][2]int {
sizes := [][2]int{{width, height}}
for {
w, h := sizes[len(sizes)-1][0], sizes[len(sizes)-1][1]
if (max(w, h) < minLongEdge && len(sizes) >= minLevels) || (w == 1 && h == 1) {
break
}
sizes = append(sizes, [2]int{(w + 1) / 2, (h + 1) / 2})
}
for i, j := 0, len(sizes)-1; i < j; i, j = i+1, j-1 {
sizes[i], sizes[j] = sizes[j], sizes[i]
}
return sizes
}
func (p *Processor) levelQuality(level, count int, size [2]int) int {
switch {
case level >= count-2:
return p.images.Quality.Top
case max(size[0], size[1]) <= 1100:
return p.images.Quality.Low
default:
return p.images.Quality.Mid
}
}
func (p *Processor) TileID(hash string, level, x, y int) string {
mac := hmac.New(sha256.New, p.key)
mac.Write([]byte(hash + "|" + strconv.Itoa(level) + "|" + strconv.Itoa(x) + "|" + strconv.Itoa(y)))
return hex.EncodeToString(mac.Sum(nil))[:16]
}
type refFile struct {
path string
refs atomic.Int32
}
func (r *refFile) release() {
if r.refs.Add(-1) == 0 {
_ = os.Remove(r.path)
}
}
func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
work := filepath.Join(p.workDir, job.Hash)
stage := filepath.Join(p.TilesDir, "."+job.Hash+fsutil.TempMarker+"stage")
for _, dir := range []string{work, stage} {
if err := os.RemoveAll(dir); err != nil {
return nil, err
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
}
defer os.RemoveAll(work)
committed := false
defer func() {
if !committed {
_ = os.RemoveAll(stage)
}
}()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
top := filepath.Join(work, "top.v")
if err := p.prepare(ctx, job, work, top); err != nil {
return nil, err
}
width, height, err := VSize(top)
if err != nil {
return nil, err
}
sizes := LevelSizes(width, height, p.images.MinLevels)
count := len(sizes)
seedLevel := count - 1
for i, size := range sizes {
if max(size[0], size[1]) >= p.images.SeedPx {
seedLevel = i
break
}
}
levels := make([]Level, count)
var seed string
var firstErr error
var errOnce sync.Once
fail := func(err error) {
errOnce.Do(func() {
firstErr = err
cancel()
})
}
var wg sync.WaitGroup
current := &refFile{path: top}
for i := count - 1; i >= 0; i-- {
if ctx.Err() != nil {
break
}
if i == seedLevel {
s, err := p.seed(ctx, current.path, work)
if err != nil {
fail(err)
break
}
seed = s
}
if i > 0 {
current.refs.Store(2)
} else {
current.refs.Store(1)
}
wg.Add(1)
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])
if err != nil {
fail(fmt.Errorf("level %d: %w", i, err))
return
}
levels[i] = level
}(i, current)
if i == 0 {
break
}
next := &refFile{path: filepath.Join(work, "l"+strconv.Itoa(i-1)+".v")}
err := p.resize(ctx, current.path, next.path, sizes[i], sizes[i-1])
current.release()
if err != nil {
fail(fmt.Errorf("resize to level %d: %w", i-1, err))
break
}
current = next
}
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
if err := ctx.Err(); err != nil {
return nil, err
}
leftovers, err := os.ReadDir(stage)
if err != nil {
return nil, err
}
for _, entry := range leftovers {
if entry.IsDir() || strings.HasSuffix(entry.Name(), ".dzi") {
if err := os.RemoveAll(filepath.Join(stage, entry.Name())); err != nil {
return nil, err
}
}
}
final := filepath.Join(p.TilesDir, job.Hash)
if err := os.RemoveAll(final); err != nil {
return nil, err
}
if err := os.Rename(stage, final); err != nil {
return nil, err
}
committed = true
rec := &Record{
Pyramid: Pyramid{Hash: job.Hash, Width: width, Height: height, Levels: levels, Seed: seed},
Kind: job.Kind,
Format: p.images.Format,
TileSize: p.images.TileSize,
Overlap: p.images.Overlap,
Processed: time.Now().UTC().Truncate(time.Second),
}
if job.Kind == "photo" {
rec.EXIF = job.Source.EXIF
}
if job.Crop != nil {
rec.Crop = job.Crop[:]
}
if err := fsutil.WriteJSONAtomic(p.recordPath(job.Hash), rec); err != nil {
return nil, err
}
return rec, nil
}
func (p *Processor) prepare(ctx context.Context, job *Job, work, top string) error {
input := job.Source.Path + "[autorotate]"
if job.Crop != nil {
cropped := filepath.Join(work, "crop.v")
c := job.Crop
if err := p.vips.Run(ctx, "extract_area", input, cropped,
strconv.Itoa(c[0]), strconv.Itoa(c[1]), strconv.Itoa(c[2]), strconv.Itoa(c[3])); err != nil {
return err
}
defer os.Remove(cropped)
input = cropped
}
err := p.vips.Run(ctx, "icc_transform", input, top, "srgb", "--embedded", "--intent", "perceptual")
if err == nil {
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
_ = os.Remove(top)
if fallbackErr := p.vips.Run(ctx, "colourspace", input, top, "srgb"); fallbackErr != nil {
return errors.Join(err, fallbackErr)
}
return nil
}
func formatScale(to, from int) string {
return strconv.FormatFloat(float64(to)/float64(from), 'g', -1, 64)
}
func (p *Processor) resize(ctx context.Context, src, dst string, from, to [2]int) error {
if err := p.vips.Run(ctx, "resize", src, dst, formatScale(to[0], from[0]),
"--vscale", formatScale(to[1], from[1]), "--kernel", "lanczos3"); err != nil {
return err
}
w, h, err := VSize(dst)
if err != nil {
return err
}
if w != to[0] || h != to[1] {
return fmt.Errorf("vips produced %dx%d, expected %dx%d", w, h, to[0], to[1])
}
return nil
}
func (p *Processor) seed(ctx context.Context, src, work string) (string, error) {
out := filepath.Join(work, "seed."+p.images.Format)
if err := p.vips.Run(ctx, "thumbnail", src, out+p.vips.SaveOptions(p.images.Quality.Low),
strconv.Itoa(p.images.SeedPx), "--height", strconv.Itoa(p.images.SeedPx)); err != nil {
return "", fmt.Errorf("seed: %w", err)
}
data, err := os.ReadFile(out)
if err != nil {
return "", err
}
_ = os.Remove(out)
return base64.StdEncoding.EncodeToString(data), nil
}
type tileFile struct {
name string
x, y int
}
func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level, count int, size [2]int) (Level, error) {
quality := p.levelQuality(level, count, size)
base := filepath.Join(stage, strconv.Itoa(level))
ext := "." + p.images.Format
if err := p.vips.Run(ctx, "dzsave", src, base,
"--layout", "dz",
"--depth", "one",
"--tile-size", strconv.Itoa(p.images.TileSize),
"--overlap", strconv.Itoa(p.images.Overlap),
"--suffix", ext+p.vips.SaveOptions(quality)); err != nil {
return Level{}, err
}
dir := filepath.Join(base+"_files", "0")
entries, err := os.ReadDir(dir)
if err != nil {
return Level{}, err
}
ts := p.images.TileSize
cols := (size[0] + ts - 1) / ts
rows := (size[1] + ts - 1) / ts
files := make([]tileFile, 0, len(entries))
for _, entry := range entries {
name := entry.Name()
if !strings.HasSuffix(name, ext) {
continue
}
xs, ys, ok := strings.Cut(strings.TrimSuffix(name, ext), "_")
x, errX := strconv.Atoi(xs)
y, errY := strconv.Atoi(ys)
if !ok || errX != nil || errY != nil || x < 0 || y < 0 || x >= cols || y >= rows {
return Level{}, fmt.Errorf("unexpected tile %s", name)
}
files = append(files, tileFile{name: name, x: x, y: y})
}
if len(files) != cols*rows {
return Level{}, fmt.Errorf("expected %dx%d tiles, found %d", cols, rows, len(files))
}
out := Level{
Width: size[0],
Height: size[1],
Cols: cols,
Rows: rows,
Quality: quality,
Tiles: make([]string, cols*rows),
Bytes: make([]int64, cols*rows),
}
renamers := min(4, (len(files)+31)/32)
var wg sync.WaitGroup
errs := make([]error, renamers)
for r := 0; r < renamers; r++ {
wg.Add(1)
go func(r int) {
defer wg.Done()
for i := r; i < len(files); i += renamers {
if ctx.Err() != nil {
errs[r] = ctx.Err()
return
}
f := files[i]
id := p.TileID(hash, level, f.x, f.y)
target := filepath.Join(stage, id+ext)
if err := os.Rename(filepath.Join(dir, f.name), target); err != nil {
errs[r] = err
return
}
info, err := os.Stat(target)
if err != nil {
errs[r] = err
return
}
slot := f.y*cols + f.x
out.Tiles[slot] = id
out.Bytes[slot] = info.Size()
}
}(r)
}
wg.Wait()
if err := errors.Join(errs...); err != nil {
return Level{}, err
}
_ = os.RemoveAll(base + "_files")
_ = os.Remove(base + ".dzi")
return out, nil
}
+120
View File
@@ -0,0 +1,120 @@
package process
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
)
type Vips struct {
Version string
Major int
Minor int
Strip string
env []string
}
var versionPattern = regexp.MustCompile(`vips-(\d+)\.(\d+)(\.\d+)?`)
func DetectVips(ctx context.Context, env []string) (*Vips, error) {
path, err := exec.LookPath("vips")
if err != nil {
return nil, errors.New("vips not found in PATH; install libvips-tools")
}
cmd := exec.CommandContext(ctx, path, "--version")
cmd.Env = env
out, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("vips --version: %w", err)
}
m := versionPattern.FindStringSubmatch(string(out))
if m == nil {
return nil, fmt.Errorf("vips --version: unrecognised output %q", strings.TrimSpace(string(out)))
}
major, _ := strconv.Atoi(m[1])
minor, _ := strconv.Atoi(m[2])
v := &Vips{Version: strings.TrimPrefix(m[0], "vips-"), Major: major, Minor: minor, env: env}
if major > 8 || (major == 8 && minor >= 15) {
v.Strip = "keep=none"
} else {
v.Strip = "strip"
}
if major < 8 || (major == 8 && minor < 12) {
return nil, fmt.Errorf("libvips %s is too old; 8.12 or newer is required", v.Version)
}
return v, nil
}
type limitedBuffer struct {
buf bytes.Buffer
limit int
}
func (l *limitedBuffer) Write(p []byte) (int, error) {
if room := l.limit - l.buf.Len(); room > 0 {
if len(p) > room {
l.buf.Write(p[:room])
} else {
l.buf.Write(p)
}
}
return len(p), nil
}
func (v *Vips) Run(ctx context.Context, args ...string) error {
cmd := exec.CommandContext(ctx, "vips", args...)
cmd.Env = v.env
stderr := &limitedBuffer{limit: 4096}
cmd.Stderr = stderr
cmd.Stdout = io.Discard
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
msg := strings.TrimSpace(stderr.buf.String())
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("vips %s: %s", args[0], msg)
}
return nil
}
func (v *Vips) SaveOptions(quality int) string {
return "[Q=" + strconv.Itoa(quality) + "," + v.Strip + "]"
}
var (
vipsMagicIntel = []byte{0xb6, 0xa6, 0xf2, 0x08}
vipsMagicSparc = []byte{0x08, 0xf2, 0xa6, 0xb6}
)
func VSize(path string) (int, int, error) {
f, err := os.Open(path)
if err != nil {
return 0, 0, err
}
defer f.Close()
var header [12]byte
if _, err := io.ReadFull(f, header[:]); err != nil {
return 0, 0, fmt.Errorf("%s: %w", path, err)
}
var order binary.ByteOrder
switch {
case bytes.Equal(header[:4], vipsMagicIntel):
order = binary.LittleEndian
case bytes.Equal(header[:4], vipsMagicSparc):
order = binary.BigEndian
default:
return 0, 0, fmt.Errorf("%s: not a vips image", path)
}
return int(int32(order.Uint32(header[4:8]))), int(int32(order.Uint32(header[8:12]))), nil
}