Files
2026-11-04 04:40:33 -08:00

249 lines
5.7 KiB
Go

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 {
return formatSeconds(ratFloat(r))
}
func NormalizeExposure(value string) string {
if value == "" || strings.Contains(value, "/") || strings.HasSuffix(value, "s") {
return value
}
seconds, err := strconv.ParseFloat(value, 64)
if err != nil || seconds <= 0 {
return value
}
return formatSeconds(seconds)
}
func formatSeconds(seconds float64) string {
if seconds >= 1 {
return strconv.FormatFloat(round(seconds, 1), 'f', -1, 64) + "s"
}
denominator := 1 / seconds
if denominator < 10 && math.Abs(denominator-math.Round(denominator)) > 0.05 {
return "1/" + strconv.FormatFloat(round(denominator, 1), 'f', -1, 64)
}
return "1/" + strconv.Itoa(int(math.Round(denominator)))
}