Debian Codegraph @

internal/warpc/webp.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 warpc
15
16 import (
17 "bytes"
18 "context"
19 "errors"
20 "fmt"
21 "image"
22 "image/color"
23 "image/draw"
24 "io"
25 "maps"
26
27 "github.com/gohugoio/hugo/common/himage"
28 "github.com/gohugoio/hugo/common/hugio"
29 )
30
31 // Keep in sync with genwebp/Makefile.
32 const libwebpVersion = "v1.6.0"
33
34 var (
35 _ SourceProvider = WebpInput{}
36 _ DestinationProvider = WebpInput{}
37 )
38
39 type CommonImageProcessingParams struct {
40 Width int `json:"width,omitempty"`
41 Height int `json:"height,omitempty"`
42 Stride int `json:"stride,omitempty"`
43 HasAlpha bool `json:"hasAlpha,omitempty"`
44 Depth int `json:"depth,omitempty"` // Bit depth per channel (8, 10, 12, 16).
45
46 // For animated images.
47 FrameDurations []int `json:"frameDurations,omitempty"`
48 LoopCount int `json:"loopCount,omitempty"`
49
50 // CICP color properties (for AVIF).
51 ColorPrimaries int `json:"colorPrimaries,omitempty"`
52 TransferCharacteristics int `json:"transferCharacteristics,omitempty"`
53 MatrixCoefficients int `json:"matrixCoefficients,omitempty"`
54
55 // HDR CLLI box (cd/m^2). Populated by the AVIF decoder when a gain map has
56 // been baked into a PQ HDR image, and re-applied by the encoder.
57 MaxCLL int `json:"maxCLL,omitempty"`
58 MaxPALL int `json:"maxPALL,omitempty"`
59 }
60
61 /*
62 If you're reading this and questioning the protocol on top of WASM using JSON and streams instead of WAS Call's with pointers written to linear memory:
63
64 - The goal of this is to eventually make it into one or more RPC plugin APIs.
65 - Passing pointers around has a number of challenges in that context.
66 - One would be that it's not possible to pass pointers to child processes (e.g. non-WASM plugins).
67
68 Also, you would think that this JSON/streams approach would be significantly slower than using pointers directly, but in practice,
69 at least for WebP, the difference is negligible, see below output from a test run:
70
71 [pointers] DecodeWebp took 18.168375ms
72 [pointers] EncodeWebp took 13.959458ms
73 [pointers] DecodeWebpConfig took 93.083µs
74
75 [streams] DecodeWebp took 17.192917ms
76 [streams] EncodeWebp took 14.084792ms
77 [streams] DecodeWebpConfig took 54.334µs
78
79 Also note that the placement of this code in this internal package is also temporary. We 1. Need to get the WASM RPC plugin infrastructure in place, and 2. Need to decide on the final API shape for image processing plugins.
80 */
81 type WebpInput struct {
82 Source hugio.SizeReader `json:"-"` // Will be sent in a separate stream.
83 Destination io.Writer `json:"-"` // Will be used to write the result to.
84 Options map[string]any `json:"options"` // Config options.
85 Params map[string]any `json:"params"` // Command params (width, height, etc.).
86 }
87
88 func (w WebpInput) GetSource() hugio.SizeReader {
89 return w.Source
90 }
91
92 func (w WebpInput) GetDestination() io.Writer {
93 return w.Destination
94 }
95
96 type WebpOutput struct {
97 Params CommonImageProcessingParams `json:"params"`
98 }
99
100 type WebpCodec struct {
101 d func() (Dispatcher[WebpInput, WebpOutput], error)
102 }
103
104 // Decode reads a WEBP image from r and returns it as an image.Image.
105 // Note that animated WebP images are returnes as an himage.AnimatedImage.
106 func (d *WebpCodec) Decode(r io.Reader) (image.Image, error) {
107 dd, err := d.d()
108 if err != nil {
109 return nil, err
110 }
111
112 source, err := hugio.ToSizeReader(r)
113 if err != nil {
114 return nil, err
115 }
116
117 var destination bytes.Buffer
118
119 message := Message[WebpInput]{
120 Header: Header{
121 Version: 1,
122 Command: "decode",
123 RequestKinds: []string{MessageKindJSON, MessageKindBlob},
124 ResponseKinds: []string{MessageKindJSON, MessageKindBlob},
125 },
126
127 Data: WebpInput{
128 Source: source,
129 Destination: &destination,
130 Options: map[string]any{},
131 },
132 }
133
134 out, err := dd.Execute(context.Background(), message)
135 if err != nil {
136 return nil, err
137 }
138
139 w, h, stride := out.Data.Params.Width, out.Data.Params.Height, out.Data.Params.Stride
140 if w == 0 || h == 0 || stride == 0 {
141 return nil, fmt.Errorf("received invalid image dimensions: %dx%d stride %d", w, h, stride)
142 }
143
144 if len(out.Data.Params.FrameDurations) > 0 {
145 // Animated WebP (always RGBA).
146 img := &AnimatedImage{
147 frameDurations: out.Data.Params.FrameDurations,
148 loopCount: out.Data.Params.LoopCount,
149 }
150
151 frameSize := stride * h
152 frames := make([]image.Image, len(destination.Bytes())/frameSize)
153 for i := range frames {
154 frameBytes := destination.Bytes()[i*frameSize : (i+1)*frameSize]
155 frameImg := &image.NRGBA{
156 Pix: frameBytes,
157 Stride: stride,
158 Rect: image.Rect(0, 0, w, h),
159 }
160 frames[i] = frameImg
161 }
162 img.SetFrames(frames)
163 return img, nil
164 }
165
166 var pix []byte
167 var nrgbaStride int
168
169 if out.Data.Params.HasAlpha {
170 // RGBA data (4 bytes per pixel).
171 pix = destination.Bytes()
172 nrgbaStride = stride
173 } else {
174 // RGB data (3 bytes per pixel) - convert to NRGBA.
175 rgbData := destination.Bytes()
176 nrgbaStride = w * 4
177 pix = make([]byte, nrgbaStride*h)
178 for y := range h {
179 srcIdx := y * stride
180 dstIdx := y * nrgbaStride
181 for range w {
182 pix[dstIdx+0] = rgbData[srcIdx+0] // R
183 pix[dstIdx+1] = rgbData[srcIdx+1] // G
184 pix[dstIdx+2] = rgbData[srcIdx+2] // B
185 pix[dstIdx+3] = 0xFF // A (fully opaque)
186 srcIdx += 3
187 dstIdx += 4
188 }
189 }
190 }
191
192 img := &image.NRGBA{
193 Pix: pix,
194 Stride: nrgbaStride,
195 Rect: image.Rect(0, 0, w, h),
196 }
197
198 return img, nil
199 }
200
201 func (d *WebpCodec) DecodeConfig(r io.Reader) (image.Config, error) {
202 dd, err := d.d()
203 if err != nil {
204 return image.Config{}, err
205 }
206
207 // Avoid reading the entire image for config only.
208 const webpMaxHeaderSize = 32
209 b := make([]byte, webpMaxHeaderSize)
210 _, err = r.Read(b)
211 if err != nil {
212 return image.Config{}, err
213 }
214
215 message := Message[WebpInput]{
216 Header: Header{
217 Version: 1,
218 Command: "config",
219 RequestKinds: []string{MessageKindJSON, MessageKindBlob},
220 ResponseKinds: []string{MessageKindJSON},
221 },
222
223 Data: WebpInput{
224 Source: bytes.NewReader(b),
225 },
226 }
227
228 out, err := dd.Execute(context.Background(), message)
229 if err != nil {
230 return image.Config{}, err
231 }
232 return image.Config{
233 Width: out.Data.Params.Width,
234 Height: out.Data.Params.Height,
235 ColorModel: color.RGBAModel,
236 }, nil
237 }
238
239 func (d *WebpCodec) Encode(w io.Writer, img image.Image, opts map[string]any) error {
240 b := img.Bounds()
241 if b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {
242 return errors.New("webp: image is too large to encode")
243 }
244
245 dd, err := d.d()
246 if err != nil {
247 return err
248 }
249
250 const (
251 commandEncodeNRGBA = "encodeNRGBA"
252 commandEncodeGray = "encodeGray"
253 )
254
255 var (
256 bounds = img.Bounds()
257 imageBytes []byte
258 stride int
259 frameDurations []int
260 loopCount int
261 command string
262 )
263
264 switch v := img.(type) {
265 case *image.RGBA:
266 imageBytes = v.Pix
267 stride = v.Stride
268 command = commandEncodeNRGBA
269 case *AnimatedImage:
270 // Animated WebP.
271 frames := v.GetFrames()
272 if len(frames) == 0 {
273 return errors.New("webp: animated image has no frames")
274 }
275 firstFrame := frames[0]
276 bounds = firstFrame.Bounds()
277 nrgba := convertToNRGBA(firstFrame)
278 frameSize := nrgba.Stride * bounds.Dy()
279 imageBytes = make([]byte, frameSize*len(frames))
280 stride = nrgba.Stride
281 for i, frame := range frames {
282 var nrgbaFrame *image.NRGBA
283 if i == 0 {
284 nrgbaFrame = nrgba
285 } else {
286 nrgbaFrame = convertToNRGBA(frame)
287 }
288 copy(imageBytes[i*frameSize:(i+1)*frameSize], nrgbaFrame.Pix)
289 }
290 frameDurations = v.GetFrameDurations()
291 loopCount = v.loopCount
292 command = commandEncodeNRGBA
293 case *image.Gray:
294 imageBytes = v.Pix
295 stride = v.Stride
296 command = commandEncodeGray
297 case himage.AnimatedImage:
298 frames := v.GetFrames()
299 if len(frames) == 0 {
300 return errors.New("webp: animated image has no frames")
301 }
302 firstFrame := frames[0]
303 bounds = firstFrame.Bounds()
304 nrgba := convertToNRGBA(firstFrame)
305 frameSize := nrgba.Stride * bounds.Dy()
306 imageBytes = make([]byte, frameSize*len(frames))
307 stride = nrgba.Stride
308 for i, frame := range frames {
309 var nrgbaFrame *image.NRGBA
310 if i == 0 {
311 nrgbaFrame = nrgba
312 } else {
313 nrgbaFrame = convertToNRGBA(frame)
314 }
315 copy(imageBytes[i*frameSize:(i+1)*frameSize], nrgbaFrame.Pix)
316 }
317 frameDurations = v.GetFrameDurations()
318 loopCount = v.GetLoopCount()
319 command = commandEncodeNRGBA
320 default:
321 nrgba := convertToNRGBA(img)
322 imageBytes = nrgba.Pix
323 stride = nrgba.Stride
324 command = commandEncodeNRGBA
325
326 }
327
328 if len(imageBytes) == 0 {
329 return fmt.Errorf("no image bytes extracted from %T", img)
330 }
331
332 opts = maps.Clone(opts)
333
334 message := Message[WebpInput]{
335 Header: Header{
336 Version: 1,
337 Command: command,
338 RequestKinds: []string{MessageKindJSON, MessageKindBlob},
339 ResponseKinds: []string{MessageKindJSON, MessageKindBlob},
340 },
341
342 Data: WebpInput{
343 Source: bytes.NewReader(imageBytes),
344 Destination: w,
345 Options: opts,
346 Params: map[string]any{
347 "width": bounds.Max.X,
348 "height": bounds.Max.Y,
349 "stride": stride,
350 "frameDurations": frameDurations,
351 "loopCount": loopCount,
352 },
353 },
354 }
355
356 _, err = dd.Execute(context.Background(), message)
357 if err != nil {
358 return err
359 }
360 return nil
361 }
362
363 func convertToNRGBA(src image.Image) *image.NRGBA {
364 dst := image.NewNRGBA(src.Bounds())
365 draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Src)
366 return dst
367 }
368
369 var _ himage.AnimatedImage = (*AnimatedImage)(nil)
370
371 // AnimatedImage represents an animated WebP image.
372 // The naming deliberately matches the fields in the standard library image/gif package.
373 // This type is also used to preserve HDR color properties for single-frame images.
374 type AnimatedImage struct {
375 image.Image // The first frame.
376 frames []image.Image
377 frameDurations []int
378 loopCount int
379 depth int // Bit depth per channel (8, 10, 12, 16). Used to preserve HDR quality.
380
381 // CICP color properties (for preserving color space in HDR images).
382 colorPrimaries int
383 transferCharacteristics int
384 matrixCoefficients int
385
386 // HDR CLLI (cd/m^2). Set when an AVIF gain map has been baked into PQ HDR.
387 maxCLL int
388 maxPALL int
389 }
390
391 func (w *AnimatedImage) GetLoopCount() int {
392 return w.loopCount
393 }
394
395 func (w *AnimatedImage) GetDepth() int {
396 return w.depth
397 }
398
399 func (w *AnimatedImage) GetFrames() []image.Image {
400 return w.frames
401 }
402
403 func (w *AnimatedImage) GetFrameDurations() []int {
404 return w.frameDurations
405 }
406
407 func (w *AnimatedImage) GetRaw() any {
408 return w
409 }
410
411 func (w *AnimatedImage) GetColorPrimaries() int {
412 return w.colorPrimaries
413 }
414
415 func (w *AnimatedImage) GetTransferCharacteristics() int {
416 return w.transferCharacteristics
417 }
418
419 func (w *AnimatedImage) GetMatrixCoefficients() int {
420 return w.matrixCoefficients
421 }
422
423 func (w *AnimatedImage) GetMaxCLL() int {
424 return w.maxCLL
425 }
426
427 func (w *AnimatedImage) GetMaxPALL() int {
428 return w.maxPALL
429 }
430
431 func (w *AnimatedImage) SetFrames(frames []image.Image) {
432 if len(frames) == 0 {
433 panic("frames cannot be empty")
434 }
435 w.frames = frames
436 w.Image = frames[0]
437 }
438
439 func (w *AnimatedImage) SetWidthHeight(width, height int) {
440 // No-op for AnimatedImage.
441 }