-
-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathencoder.go
More file actions
314 lines (278 loc) · 7.92 KB
/
encoder.go
File metadata and controls
314 lines (278 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package encoder
import (
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"webp_server_go/config"
"webp_server_go/helper"
"webp_server_go/vips"
log "github.com/sirupsen/logrus"
)
var (
// Source image encoder ignore list for WebP and AVIF
// We shouldn't convert Unknown and AVIF to WebP
webpIgnore = []vips.ImageType{vips.ImageTypeUnknown, vips.ImageTypeAvif}
// We shouldn't convert Unknown,AVIF and GIF to AVIF
avifIgnore = append(webpIgnore, vips.ImageTypeGif)
)
func init() {
vips.SetLogging(nil, vips.LogLevelError)
vips.Startup(&vips.Config{
ConcurrencyLevel: runtime.NumCPU(),
})
}
func ConvertFilter(rawPath, jxlPath, avifPath, webpPath string, extraParams config.ExtraParams, supportedFormats map[string]bool, c chan int) {
// Wait for the conversion to complete and return the converted image
retryDelay := 100 * time.Millisecond // Initial retry delay
for {
if _, found := config.ConvertLock.Get(rawPath); found {
log.Debugf("file %s is locked under conversion, retrying in %s", rawPath, retryDelay)
time.Sleep(retryDelay)
} else {
// The lock is released, indicating that the conversion is complete
break
}
}
// If there is a lock here, it means that another thread is converting the same image
// Lock rawPath to prevent concurrent conversion
config.ConvertLock.Set(rawPath, true, -1)
defer config.ConvertLock.Delete(rawPath)
var wg sync.WaitGroup
wg.Add(3)
if !helper.ImageExists(avifPath) && config.Config.EnableAVIF && supportedFormats["avif"] {
go func() {
err := convertImage(rawPath, avifPath, "avif", extraParams)
if err != nil {
log.Errorln(err)
}
defer wg.Done()
}()
} else {
wg.Done()
}
if !helper.ImageExists(webpPath) && config.Config.EnableWebP && supportedFormats["webp"] {
go func() {
err := convertImage(rawPath, webpPath, "webp", extraParams)
if err != nil {
log.Errorln(err)
}
defer wg.Done()
}()
} else {
wg.Done()
}
if !helper.ImageExists(jxlPath) && config.Config.EnableJXL && supportedFormats["jxl"] {
go func() {
err := convertImage(rawPath, jxlPath, "jxl", extraParams)
if err != nil {
log.Errorln(err)
}
defer wg.Done()
}()
} else {
wg.Done()
}
wg.Wait()
if c != nil {
c <- 1
}
}
func convertImage(rawPath, optimizedPath, imageType string, extraParams config.ExtraParams) error {
// we need to create dir first
var err = os.MkdirAll(path.Dir(optimizedPath), 0755)
if err != nil {
log.Error(err.Error())
}
// If original image is NEF, convert NEF image to JPG first
if strings.HasSuffix(strings.ToLower(rawPath), ".nef") {
var convertedRaw, converted = ConvertRawToJPG(rawPath, optimizedPath)
// If converted, use converted file as raw
if converted {
// Use converted file(JPG) as raw input for further conversion
rawPath = convertedRaw
// Remove converted file after conversion
defer func() {
log.Infoln("Removing intermediate conversion file:", convertedRaw)
err := os.Remove(convertedRaw)
if err != nil {
log.Warnln("failed to delete converted file", err)
}
}()
}
}
img, err := helper.LoadImage(rawPath)
if err == nil {
defer img.Close()
}
// Pre-process image(auto rotate, resize, etc.)
err = preProcessImage(img, imageType, extraParams)
if err != nil {
log.Warnf("Can't pre-process source image: %v", err)
}
// If image is already in the target format, just copy it
imageFormat := img.Format()
switch imageType {
case "webp":
if imageFormat == vips.ImageTypeWebp {
log.Infof("Image is already in WebP format, copying %s to %s", rawPath, optimizedPath)
return helper.CopyFile(rawPath, optimizedPath)
} else {
err = webpEncoder(img, rawPath, optimizedPath)
}
case "avif":
if imageFormat == vips.ImageTypeAvif {
log.Infof("Image is already in AVIF format, copying %s to %s", rawPath, optimizedPath)
return helper.CopyFile(rawPath, optimizedPath)
} else {
err = avifEncoder(img, rawPath, optimizedPath)
}
case "jxl":
if imageFormat == vips.ImageTypeJxl {
log.Infof("Image is already in JXL format, copying %s to %s", rawPath, optimizedPath)
return helper.CopyFile(rawPath, optimizedPath)
} else {
err = jxlEncoder(img, rawPath, optimizedPath)
}
}
return err
}
func jxlEncoder(img *vips.Image, rawPath string, optimizedPath string) error {
var (
buf []byte
quality = config.Config.Quality
err error
)
// If quality >= 100, we use lossless mode
if quality >= 100 {
buf, err = img.JxlsaveBuffer(&vips.JxlsaveBufferOptions{
Effort: 1,
Tier: 4,
Lossless: true,
Distance: 1.0,
})
} else {
buf, err = img.JxlsaveBuffer(&vips.JxlsaveBufferOptions{
Effort: 1,
Tier: 4,
Q: quality,
Lossless: false,
Distance: 1.0,
})
}
if err != nil {
log.Warnf("Can't encode source image: %v to JXL", err)
return err
}
if err := os.WriteFile(optimizedPath, buf, 0600); err != nil {
log.Error(err)
return err
}
convertLog("JXL", rawPath, optimizedPath, quality)
return nil
}
func avifEncoder(img *vips.Image, rawPath string, optimizedPath string) error {
var (
buf []byte
quality = config.Config.Quality
err error
)
// encoder: HeifEncoderSvt - intel & netflix
// HeifEncoderRav1e: Mozilla Rust
// HeifEncoderAom: Official
//StripMetadata: config.Config.StripMetadata,
// If quality >= 100, we use lossless mode
if config.Config.StripMetadata {
_ = img.RemoveExif()
}
if quality >= 100 {
buf, err = img.HeifsaveBuffer(&vips.HeifsaveBufferOptions{
Lossless: true,
Encoder: vips.HeifEncoderSvt,
Compression: vips.HeifCompressionAv1,
})
} else {
buf, err = img.HeifsaveBuffer(&vips.HeifsaveBufferOptions{
Q: quality,
Lossless: false,
Encoder: vips.HeifEncoderSvt,
Compression: vips.HeifCompressionAv1,
})
}
if err != nil {
log.Warnf("Can't encode source image: %v to AVIF", err)
return err
}
if err := os.WriteFile(optimizedPath, buf, 0600); err != nil {
log.Error(err)
return err
}
convertLog("AVIF", rawPath, optimizedPath, quality)
return nil
}
func webpEncoder(img *vips.Image, rawPath string, optimizedPath string) error {
var (
buf []byte
quality = config.Config.Quality
err error
)
if config.Config.StripMetadata {
_ = img.RemoveExif()
}
// If quality >= 100, we use lossless mode
if quality >= 100 {
// Lossless mode will not encounter problems as below, because in libvips as code below
// config.method = ExUtilGetInt(argv[++c], 0, &parse_error);
// use_lossless_preset = 0; // disable -z option
buf, err = img.WebpsaveBuffer(&vips.WebpsaveBufferOptions{
Lossless: true,
//StripMetadata: config.Config.StripMetadata,
})
} else {
// If some special images cannot encode with default ReductionEffort(0), then retry from 0 to 6
// Example: https://github.com/webp-sh/webp_server_go/issues/234
ep := vips.WebpsaveBufferOptions{
Q: quality,
Lossless: false,
//StripMetadata: config.Config.StripMetadata,
}
for i := range 7 {
ep.Effort = i
buf, err = img.WebpsaveBuffer(&ep)
if err != nil && strings.Contains(err.Error(), "unable to encode") {
log.Warnf("Can't encode image to WebP with ReductionEffort %d, trying higher value...", i)
} else if err != nil {
log.Warnf("Can't encode source image to WebP:%v", err)
} else {
break
}
}
buf, err = img.WebpsaveBuffer(&ep)
}
if err != nil {
log.Warnf("Can't encode source image: %v to WebP", err)
return err
}
if err := os.WriteFile(optimizedPath, buf, 0600); err != nil {
log.Error(err)
return err
}
convertLog("WebP", rawPath, optimizedPath, quality)
return nil
}
func convertLog(itype, rawPath string, optimizedPath string, quality int) {
oldf, err := os.Stat(rawPath)
if err != nil {
log.Error(err)
return
}
newf, err := os.Stat(optimizedPath)
if err != nil {
log.Error(err)
return
}
log.Infof("%s@%d%%: %s->%s %d->%d %.2f%% deflated", itype, quality,
rawPath, optimizedPath, oldf.Size(), newf.Size(), float32(newf.Size())/float32(oldf.Size())*100)
}