From 7f1c441b6ffa73d73f814282aae4dc35f1a6238b Mon Sep 17 00:00:00 2001 From: BennyThink Date: Mon, 6 Dec 2021 21:44:33 +0800 Subject: [PATCH] avif encoding speed, disable AVIF by default --- config.go | 4 +++- encoder.go | 26 +++++++++++++++----------- prefetch_test.go | 2 +- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/config.go b/config.go index 4205a53..15a5ca6 100644 --- a/config.go +++ b/config.go @@ -11,6 +11,7 @@ type Config struct { Quality float32 `json:"QUALITY,string"` AllowedTypes []string `json:"ALLOWED_TYPES"` ExhaustPath string `json:"EXHAUST_PATH"` + EnableAVIF bool `json:"ENABLE_AVIF"` } var ( @@ -33,7 +34,8 @@ const ( "QUALITY": "80", "IMG_PATH": "./pics", "EXHAUST_PATH": "./exhaust", - "ALLOWED_TYPES": ["jpg","png","jpeg","bmp"] + "ALLOWED_TYPES": ["jpg","png","jpeg","bmp"], + "ENABLE_AVIF": false }` sampleSystemd = ` diff --git a/encoder.go b/encoder.go index 163f8ca..cebc20a 100644 --- a/encoder.go +++ b/encoder.go @@ -4,6 +4,10 @@ import ( "bytes" "errors" "fmt" + "github.com/Kagami/go-avif" + "github.com/chai2010/webp" + log "github.com/sirupsen/logrus" + "golang.org/x/image/bmp" "image" "image/jpeg" "image/png" @@ -11,19 +15,14 @@ import ( "os" "path" "path/filepath" + "runtime" "strings" - - log "github.com/sirupsen/logrus" - - "github.com/Kagami/go-avif" - "github.com/chai2010/webp" - "golang.org/x/image/bmp" ) func convertFilter(raw, avifPath, webpPath string, c chan int) { // all absolute paths - if !imageExists(avifPath) { + if !imageExists(avifPath) && config.EnableAVIF { convertImage(raw, avifPath, "avif") } @@ -109,10 +108,15 @@ func avifEncoder(p1, p2 string, quality float32) { return } - var avifQuality = int((100 - quality) / 100 * avif.MaxQuality) - err = avif.Encode(dst, img, &avif.Options{Quality: avifQuality}) + err = avif.Encode(dst, img, &avif.Options{ + Threads: runtime.NumCPU(), + Speed: avif.MaxSpeed, + Quality: int((100 - quality) / 100 * avif.MaxQuality), + SubsampleRatio: nil, + }) + if err != nil { - log.Fatalf("Can't encode source image: %v to AVIF", err) + log.Warnf("Can't encode source image: %v to AVIF", err) } convertLog("AVIF", p1, p2, quality) @@ -130,7 +134,7 @@ func webpEncoder(p1, p2 string, quality float32) { err = webp.Encode(&buf, img, &webp.Options{Lossless: false, Quality: quality}) if err != nil { - log.Fatalf("Can't encode source image: %v to WebP", err) + log.Warnf("Can't encode source image: %v to WebP", err) } if err := ioutil.WriteFile(p2, buf.Bytes(), 0644); err != nil { diff --git a/prefetch_test.go b/prefetch_test.go index 61cbbbb..7788d4d 100644 --- a/prefetch_test.go +++ b/prefetch_test.go @@ -15,7 +15,7 @@ func TestPrefetchImages(t *testing.T) { _ = os.Mkdir(fp, 0755) prefetchImages("./pics/dir1/", "./prefetch") count := fileCount("./prefetch") - assert.Equal(t, int64(2), count) + assert.Equal(t, int64(1), count) _ = os.RemoveAll(fp) }