Debian Codegraph @

resources/images/codec.go

raw
1 // Copyright 2025 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package images
15
16 import (
17 "bufio"
18 "bytes"
19 "encoding/binary"
20 "errors"
21 "fmt"
22 "image"
23 "image/color"
24 "image/color/palette"
25 "image/draw"
26 "image/gif"
27 "image/jpeg"
28 "image/png"
29 "io"
30 "strings"
31
32 "github.com/bep/imagemeta"
33 "github.com/bep/logg"
34 "github.com/gohugoio/hugo/common/himage"
35 "github.com/gohugoio/hugo/common/hugio"
36 "golang.org/x/image/bmp"
37 "golang.org/x/image/tiff"
38 )
39
40 // Decoder defines the decoding of an image format.
41 // These matches the globalmpackage image functions.
42 type Decoder interface {
43 Decode(r io.Reader) (image.Image, error)
44 DecodeConfig(r io.Reader) (image.Config, error)
45 }
46
47 type ToEncoder interface {
48 EncodeTo(conf ImageConfig, w io.Writer, src image.Image) error
49 }
50
51 // EncoderWithOptions defines the encoding of an image format with the given options.
52 type Encoder interface {
53 Encode(w io.Writer, src image.Image, options map[string]any) error
54 }
55
56 // EncodeDecoder defines both decoding and encoding of an image format as defined by the standard library.
57 type EncodeDecoder interface {
58 Decoder
59 Encoder
60 }
61
62 // Codec is a generic image codec supporting multiple formats.
63 type Codec struct {
64 webp EncodeDecoder
65 avif EncodeDecoder
66 debugl logg.LevelLogger
67 }
68
69 func newCodec(webp, avif EncodeDecoder, debugl logg.LevelLogger) *Codec {
70 return &Codec{webp: webp, avif: avif, debugl: debugl}
71 }
72
73 func (d *Codec) EncodeTo(conf ImageConfig, w io.Writer, img image.Image) error {
74 d.debugl.Log(
75 // This construct looks odd, but the func will only be called if debug is enabled.
76 logg.StringFunc(
77 func() string {
78 return fmt.Sprintf("Encoding image to format %s with config %+v", conf.TargetFormat, conf)
79 },
80 ),
81 )
82 switch conf.TargetFormat {
83 case JPEG:
84 var rgba *image.RGBA
85 quality := conf.Quality
86
87 if nrgba, ok := img.(*image.NRGBA); ok {
88 if nrgba.Opaque() {
89 rgba = &image.RGBA{
90 Pix: nrgba.Pix,
91 Stride: nrgba.Stride,
92 Rect: nrgba.Rect,
93 }
94 }
95 }
96 if rgba != nil {
97 return jpeg.Encode(w, rgba, &jpeg.Options{Quality: quality})
98 }
99 return jpeg.Encode(w, img, &jpeg.Options{Quality: quality})
100 case PNG:
101 encoder := png.Encoder{CompressionLevel: png.DefaultCompression}
102 return encoder.Encode(w, img)
103 case GIF:
104 if anim, ok := img.(himage.AnimatedImage); ok {
105 if g, ok := anim.GetRaw().(*gif.GIF); ok {
106 return gif.EncodeAll(w, g)
107 }
108
109 // Animated image, but not a GIF. Convert it.
110 frames := anim.GetFrames()
111 if len(frames) == 0 {
112 return gif.Encode(w, img, &gif.Options{NumColors: 256})
113 }
114
115 frameDurations := anim.GetFrameDurations()
116 if len(frameDurations) != len(frames) {
117 return errors.New("gif: number of frame durations does not match number of frames")
118 }
119
120 outGif := &gif.GIF{
121 Delay: himage.FrameDurationsToGifDelays(frameDurations),
122 }
123
124 outGif.LoopCount = anim.GetLoopCount()
125
126 for _, frame := range frames {
127 bounds := frame.Bounds()
128 palettedImage := image.NewPaletted(bounds, palette.Plan9)
129 draw.Draw(palettedImage, palettedImage.Rect, frame, bounds.Min, draw.Src)
130 outGif.Image = append(outGif.Image, palettedImage)
131 }
132
133 return gif.EncodeAll(w, outGif)
134 }
135 return gif.Encode(w, img, &gif.Options{
136 NumColors: 256,
137 })
138 case TIFF:
139 return tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
140 case BMP:
141 return bmp.Encode(w, img)
142 case AVIF:
143 opts := map[string]any{
144 "compression": conf.Compression,
145 "quality": conf.Quality,
146 "encoderSpeed": conf.EncoderSpeed,
147 "hint": conf.Hint,
148 }
149 return d.avif.Encode(w, img, opts)
150 case WEBP:
151 // Convert bool to int because the C code reads it as a number.
152 useSharpYuvInt := 0
153 if conf.UseSharpYuv {
154 useSharpYuvInt = 1
155 }
156 opts := map[string]any{
157 "compression": conf.Compression,
158 "quality": conf.Quality,
159 "hint": conf.Hint,
160 "useSharpYuv": useSharpYuvInt,
161 "method": conf.Method,
162 }
163 return d.webp.Encode(w, img, opts)
164 default:
165 return fmt.Errorf("format %q not supported", conf.TargetFormat)
166 }
167 }
168
169 func (d *Codec) DecodeFormat(f Format, r io.Reader) (image.Image, error) {
170 d.debugl.Log(
171 logg.StringFunc(
172 func() string {
173 return fmt.Sprintf("Decoding image from format %s", f)
174 },
175 ),
176 )
177 switch f {
178 case JPEG, PNG:
179 // We reworked this decode/encode setup to get full WebP support in v0.153.0.
180 // In the first take of that we used f to decide whether to call png.Decode or jpeg.Decode here,
181 // but testing it on some sites, it seems that it's not uncommon to store JPEGs with PNG extensions and vice versa.
182 // So, to reduce some noise in that release, we fallback to the standard library here,
183 // which will read the magic bytes and decode accordingly.
184 img, _, err := image.Decode(r)
185 return img, err
186 case GIF:
187 g, err := gif.DecodeAll(r)
188 if err != nil {
189 return nil, fmt.Errorf("failed to decode gif: %w", err)
190 }
191 if len(g.Delay) > 1 {
192 return &giphy{gif: g, Image: g.Image[0]}, nil
193 }
194 return g.Image[0], nil
195 case TIFF:
196 return tiff.Decode(r)
197 case BMP:
198 return bmp.Decode(r)
199 case AVIF:
200 return d.avif.Decode(r)
201 case WEBP:
202 img, err := d.webp.Decode(r)
203 if err == nil {
204 return img, nil
205 }
206 if rs, ok := r.(io.ReadSeeker); ok {
207 // See issue 14288. Turns out it's not uncommon to e.g. name their PNG files with a WEBP extension.
208 // With the old Go's webp decoder, this didn't fail (it looked for the file header),
209 // but now some error has surfaced.
210 // To reduce some noise, we try to reset and decode again using the standard library.
211 _, err2 := rs.Seek(0, io.SeekStart)
212 if err2 != nil {
213 return nil, err
214 }
215 img, _, err2 = image.Decode(rs)
216 if err2 == nil {
217 return img, nil
218 }
219 }
220 return nil, err
221 default:
222 return nil, errors.New("format not supported")
223 }
224 }
225
226 func (d *Codec) Decode(r io.Reader) (image.Image, error) {
227 d.debugl.Log(
228 logg.StringFunc(
229 func() string {
230 return "Decoding image from unknown format"
231 },
232 ),
233 )
234 rr := toPeekReader(r)
235 format, err := formatFromImage(rr)
236 if err != nil {
237 return nil, err
238 }
239 if format != 0 {
240 return d.DecodeFormat(format, rr)
241 }
242
243 // Fallback to the standard image.Decode.
244 img, _, err := image.Decode(rr)
245 return img, err
246 }
247
248 func (d *Codec) DecodeConfig(f Format, r io.Reader) (image.Config, string, error) {
249 rr := toPeekReader(r)
250 format, err := formatFromImage(rr)
251 if err != nil {
252 return image.Config{}, "", err
253 }
254 if format == 0 {
255 format = f
256 }
257 r = rr
258 if format.UseImageMetaConfigDecoder() {
259 rs, err := hugio.NewReadSeekerNoOpCloserFromReader(r)
260 if err != nil {
261 return image.Config{}, "", err
262 }
263 rs.Seek(0, 0)
264 res, err := imagemeta.Decode(
265 imagemeta.Options{
266 R: rs,
267 ImageFormat: format.ToImageMetaImageFormatFormat(),
268 Sources: imagemeta.CONFIG,
269 },
270 )
271 if err == nil {
272 return image.Config{
273 Width: res.ImageConfig.Width,
274 Height: res.ImageConfig.Height,
275 ColorModel: color.RGBAModel,
276 }, strings.ToLower(format.String()), nil
277 }
278
279 // Fallback to the standard image.DecodeConfig.
280 rs.Seek(0, 0)
281 r = rs
282 }
283
284 conf, name, err := image.DecodeConfig(r)
285
286 return conf, name, err
287 }
288
289 // toPeekReader converts an io.Reader to a peekReader.
290 func toPeekReader(r io.Reader) peekReader {
291 if rr, ok := r.(peekReader); ok {
292 return rr
293 }
294 return bufio.NewReader(r)
295 }
296
297 // A peekReader is an io.Reader that can also peek ahead.
298 type peekReader interface {
299 io.Reader
300 Peek(int) ([]byte, error)
301 }
302
303 const (
304 // The WebP file header is 12 bytes long and starts with "RIFF" followed by
305 // 4 bytes indicating the file size, followed by "WEBP" and the VP8 chunk header.
306 // We use '?' as a wildcard for the 4 size bytes.
307 magicWebp = "RIFF????WEBPVP8"
308 // The GIF file header is 6 bytes long and starts with "GIF87a" or "GIF89a".
309 magicGif = "GIF8???"
310 )
311
312 var (
313 avifBrandAvis = []byte("avis")
314 avifBrandAvif = []byte("avif")
315 avifFtyp = []byte("ftyp")
316 )
317
318 type magicFormat struct {
319 magic string
320 format Format
321 }
322
323 var magicFormats = []magicFormat{
324 {magic: magicWebp, format: WEBP},
325 {magic: magicGif, format: GIF},
326 }
327
328 // formatFromImage determines the image format from the magic bytes.
329 // Note that this is only a partial implementation,
330 // as we currently only need WebP, GIF and AVIF detection.
331 // The others can be handled by the standard library.
332 func formatFromImage(r peekReader) (Format, error) {
333 for _, mf := range magicFormats {
334 magicLen := len(mf.magic)
335 b, err := r.Peek(magicLen)
336 if err == nil && match(mf.magic, b) {
337 return mf.format, nil
338 }
339 }
340 if isAvif(r) {
341 return AVIF, nil
342 }
343 return 0, nil
344 }
345
346 // isAvif reports whether r begins with an ISOBMFF ftyp box that identifies
347 // the file as AVIF, either via the major brand ("avif"/"avis") or the
348 // compatible brands list (e.g. major "mif1" with "avif" as a compatible brand).
349 func isAvif(r peekReader) bool {
350 b, _ := r.Peek(12)
351 if len(b) < 12 || !bytes.Equal(b[4:8], avifFtyp) {
352 return false
353 }
354 if brand := b[8:12]; bytes.Equal(brand, avifBrandAvif) || bytes.Equal(brand, avifBrandAvis) {
355 return true
356 }
357 b, _ = r.Peek(64)
358 if len(b) < 16 {
359 return false
360 }
361 end := int(binary.BigEndian.Uint32(b[:4]))
362 if end < 16 || end > len(b) {
363 end = len(b)
364 }
365 for i := 16; i+4 <= end; i += 4 {
366 if brand := b[i : i+4]; bytes.Equal(brand, avifBrandAvif) || bytes.Equal(brand, avifBrandAvis) {
367 return true
368 }
369 }
370 return false
371 }
372
373 func match(magic string, b []byte) bool {
374 if len(magic) != len(b) {
375 return false
376 }
377 for i := 0; i < len(magic); i++ {
378 if magic[i] != '?' && magic[i] != b[i] {
379 return false
380 }
381 }
382 return true
383 }
384
385 var (
386 _ himage.AnimatedImage = (*giphy)(nil)
387 _ himage.ImageConfigProvider = (*giphy)(nil)
388 )
389
390 type giphy struct {
391 image.Image
392 gif *gif.GIF
393 }
394
395 func (g *giphy) GetRaw() any {
396 return g.gif
397 }
398
399 func (g *giphy) GetLoopCount() int {
400 return g.gif.LoopCount
401 }
402
403 func (g *giphy) GetFrames() []image.Image {
404 frames := make([]image.Image, len(g.gif.Image))
405 for i, frame := range g.gif.Image {
406 frames[i] = frame
407 }
408 return frames
409 }
410
411 func (g *giphy) GetImageConfig() image.Config {
412 return g.gif.Config
413 }
414
415 func (g *giphy) SetFrames(frames []image.Image) {
416 if len(frames) == 0 {
417 panic("frames cannot be empty")
418 }
419 g.gif.Image = make([]*image.Paletted, len(frames))
420 for i, frame := range frames {
421 g.gif.Image[i] = frame.(*image.Paletted)
422 }
423 g.Image = g.gif.Image[0]
424 }
425
426 func (g *giphy) SetWidthHeight(width, height int) {
427 g.gif.Config.Width = width
428 g.gif.Config.Height = height
429 }
430
431 func (g *giphy) GetFrameDurations() []int {
432 return himage.GifDelaysToFrameDurations(g.gif.Delay)
433 }