Debian Codegraph @

internal/warpc/avif.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 "fmt"
20 "image"
21 "image/color"
22 "image/draw"
23 "io"
24
25 "github.com/gohugoio/hugo/common/hugio"
26 )
27
28 // Keep in sync with genavif/Makefile.
29 const (
30 libavifVersion = "v1.4.1"
31 aomVersion = "v3.14.1"
32 dav1dVersion = "1.5.3"
33 )
34
35 var (
36 _ SourceProvider = AvifInput{}
37 _ DestinationProvider = AvifInput{}
38 )
39
40 type AvifInput struct {
41 Source hugio.SizeReader `json:"-"` // Will be sent in a separate stream.
42 Destination io.Writer `json:"-"` // Will be used to write the result to.
43 Options map[string]any `json:"options"` // Config options.
44 Params map[string]any `json:"params"` // Command params (width, height, etc.).
45 }
46
47 func (a AvifInput) GetSource() hugio.SizeReader {
48 return a.Source
49 }
50
51 func (a AvifInput) GetDestination() io.Writer {
52 return a.Destination
53 }
54
55 type AvifOutput struct {
56 Params CommonImageProcessingParams `json:"params"`
57 }
58
59 type AvifCodec struct {
60 d func() (Dispatcher[AvifInput, AvifOutput], error)
61 }
62
63 func (d *AvifCodec) DecodeConfig(r io.Reader) (image.Config, error) {
64 dd, err := d.d()
65 if err != nil {
66 return image.Config{}, err
67 }
68
69 rr, err := hugio.ToSizeReader(r)
70 if err != nil {
71 return image.Config{}, err
72 }
73 message := Message[AvifInput]{
74 Header: Header{
75 Version: 1,
76 Command: "config",
77 RequestKinds: []string{MessageKindJSON, MessageKindBlob},
78 ResponseKinds: []string{MessageKindJSON},
79 },
80
81 Data: AvifInput{
82 Source: rr,
83 },
84 }
85
86 out, err := dd.Execute(context.Background(), message)
87 if err != nil {
88 return image.Config{}, err
89 }
90 return image.Config{
91 Width: out.Data.Params.Width,
92 Height: out.Data.Params.Height,
93 ColorModel: color.RGBAModel,
94 }, nil
95 }
96
97 func (d *AvifCodec) Decode(r io.Reader) (image.Image, error) {
98 dd, err := d.d()
99 if err != nil {
100 return nil, err
101 }
102
103 source, err := hugio.ToSizeReader(r)
104 if err != nil {
105 return nil, err
106 }
107
108 var destination bytes.Buffer
109
110 message := Message[AvifInput]{
111 Header: Header{
112 Version: 1,
113 Command: "decode",
114 RequestKinds: []string{MessageKindJSON, MessageKindBlob},
115 ResponseKinds: []string{MessageKindJSON, MessageKindBlob},
116 },
117
118 Data: AvifInput{
119 Source: source,
120 Destination: &destination,
121 Options: map[string]any{},
122 },
123 }
124
125 out, err := dd.Execute(context.Background(), message)
126 if err != nil {
127 return nil, err
128 }
129
130 w, h, stride, depth := out.Data.Params.Width, out.Data.Params.Height, out.Data.Params.Stride, out.Data.Params.Depth
131 if w == 0 || h == 0 || stride == 0 {
132 return nil, fmt.Errorf("received invalid image dimensions: %dx%d stride %d", w, h, stride)
133 }
134
135 // For 10+ bit HDR images, the C code returns 16-bit RGBA data.
136 isHDR := depth > 8
137
138 // libavif returns 16-bit data in native (little-endian) byte order,
139 // but Go's NRGBA64 expects big-endian. Swap bytes for HDR images.
140 if isHDR {
141 pix := destination.Bytes()
142 for i := 0; i < len(pix); i += 2 {
143 pix[i], pix[i+1] = pix[i+1], pix[i]
144 }
145 }
146
147 if len(out.Data.Params.FrameDurations) > 0 {
148 img := &AnimatedImage{
149 frameDurations: out.Data.Params.FrameDurations,
150 loopCount: avifLoopCountToGo(out.Data.Params.LoopCount),
151 depth: depth,
152 colorPrimaries: out.Data.Params.ColorPrimaries,
153 transferCharacteristics: out.Data.Params.TransferCharacteristics,
154 matrixCoefficients: out.Data.Params.MatrixCoefficients,
155 maxCLL: out.Data.Params.MaxCLL,
156 maxPALL: out.Data.Params.MaxPALL,
157 }
158
159 frameSize := stride * h
160 pixLen := len(destination.Bytes())
161 if frameSize == 0 || pixLen%frameSize != 0 {
162 return nil, fmt.Errorf("decoded AVIF buffer size %d is not a multiple of frame size %d", pixLen, frameSize)
163 }
164 frameCount := pixLen / frameSize
165 if frameCount != len(out.Data.Params.FrameDurations) {
166 return nil, fmt.Errorf("decoded AVIF frame count %d does not match frame durations %d", frameCount, len(out.Data.Params.FrameDurations))
167 }
168 frames := make([]image.Image, frameCount)
169 for i := range frames {
170 frameBytes := destination.Bytes()[i*frameSize : (i+1)*frameSize]
171 if isHDR {
172 // NRGBA64 for HDR - libavif returns non-premultiplied alpha.
173 frameImg := &image.NRGBA64{
174 Pix: frameBytes,
175 Stride: stride,
176 Rect: image.Rect(0, 0, w, h),
177 }
178 frames[i] = frameImg
179 } else {
180 // NRGBA - libavif returns non-premultiplied alpha.
181 frameImg := &image.NRGBA{
182 Pix: frameBytes,
183 Stride: stride,
184 Rect: image.Rect(0, 0, w, h),
185 }
186 frames[i] = frameImg
187 }
188 }
189 img.SetFrames(frames)
190 return img, nil
191 }
192
193 if isHDR {
194 // NRGBA64 for HDR - libavif returns non-premultiplied alpha.
195 // Wrap in AnimatedImage to preserve color properties through the pipeline.
196 baseImg := &image.NRGBA64{
197 Pix: destination.Bytes(),
198 Stride: stride,
199 Rect: image.Rect(0, 0, w, h),
200 }
201 img := &AnimatedImage{
202 Image: baseImg,
203 frames: []image.Image{baseImg},
204 depth: depth,
205 colorPrimaries: out.Data.Params.ColorPrimaries,
206 transferCharacteristics: out.Data.Params.TransferCharacteristics,
207 matrixCoefficients: out.Data.Params.MatrixCoefficients,
208 maxCLL: out.Data.Params.MaxCLL,
209 maxPALL: out.Data.Params.MaxPALL,
210 }
211 return img, nil
212 }
213
214 // NRGBA - libavif returns non-premultiplied alpha.
215 img := &image.NRGBA{
216 Pix: destination.Bytes(),
217 Stride: stride,
218 Rect: image.Rect(0, 0, w, h),
219 }
220
221 return img, nil
222 }
223
224 // avifLoopCountToGo translates libavif's repetitionCount (-1 = infinite,
225 // 0 = play once, N = N repetitions) to the convention used by image/gif and
226 // the WebP codec (0 = infinite, -1 = play once, N = N repetitions).
227 func avifLoopCountToGo(repetitionCount int) int {
228 switch repetitionCount {
229 case -1, -2: // AVIF_REPETITION_COUNT_INFINITE, AVIF_REPETITION_COUNT_UNKNOWN
230 return 0
231 case 0:
232 return -1
233 default:
234 return repetitionCount
235 }
236 }
237
238 func (d *AvifCodec) Encode(w io.Writer, src image.Image, options map[string]any) error {
239 dd, err := d.d()
240 if err != nil {
241 return err
242 }
243
244 var cmd string
245 var source hugio.SizeReader
246 var params map[string]any = make(map[string]any)
247
248 switch img := src.(type) {
249 case *AnimatedImage:
250 // AnimatedImage wraps HDR images to preserve color properties.
251 // For single-frame, extract the underlying image and add color properties.
252 frames := img.GetFrames()
253 if len(frames) == 0 {
254 return fmt.Errorf("AnimatedImage has no frames")
255 }
256 // Get color properties from AnimatedImage.
257 params["colorPrimaries"] = img.GetColorPrimaries()
258 params["transferCharacteristics"] = img.GetTransferCharacteristics()
259 params["matrixCoefficients"] = img.GetMatrixCoefficients()
260 params["maxCLL"] = img.GetMaxCLL()
261 params["maxPALL"] = img.GetMaxPALL()
262
263 // Handle the first frame based on its type.
264 firstFrame := frames[0]
265 switch frame := firstFrame.(type) {
266 case *image.NRGBA64:
267 cmd = "encodeNRGBA"
268 pix := make([]byte, len(frame.Pix))
269 for i := 0; i < len(pix); i += 2 {
270 pix[i], pix[i+1] = frame.Pix[i+1], frame.Pix[i]
271 }
272 var err error
273 source, err = hugio.ToSizeReader(bytes.NewReader(pix))
274 if err != nil {
275 return err
276 }
277 params["width"] = frame.Rect.Dx()
278 params["height"] = frame.Rect.Dy()
279 params["stride"] = frame.Stride
280 params["depth"] = img.GetDepth()
281 if params["depth"] == 0 {
282 params["depth"] = 10 // Default to 10-bit for HDR.
283 }
284 case *image.NRGBA:
285 cmd = "encodeNRGBA"
286 var err error
287 source, err = hugio.ToSizeReader(bytes.NewReader(frame.Pix))
288 if err != nil {
289 return err
290 }
291 params["width"] = frame.Rect.Dx()
292 params["height"] = frame.Rect.Dy()
293 params["stride"] = frame.Stride
294 params["depth"] = 8
295 default:
296 // Convert to NRGBA64 for HDR or NRGBA for SDR.
297 b := firstFrame.Bounds()
298 if img.GetDepth() > 8 {
299 newImg := image.NewNRGBA64(image.Rect(0, 0, b.Dx(), b.Dy()))
300 draw.Draw(newImg, newImg.Bounds(), firstFrame, b.Min, draw.Src)
301 cmd = "encodeNRGBA"
302 pix := make([]byte, len(newImg.Pix))
303 for i := 0; i < len(pix); i += 2 {
304 pix[i], pix[i+1] = newImg.Pix[i+1], newImg.Pix[i]
305 }
306 var err error
307 source, err = hugio.ToSizeReader(bytes.NewReader(pix))
308 if err != nil {
309 return err
310 }
311 params["width"] = newImg.Rect.Dx()
312 params["height"] = newImg.Rect.Dy()
313 params["stride"] = newImg.Stride
314 params["depth"] = img.GetDepth()
315 } else {
316 newImg := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
317 draw.Draw(newImg, newImg.Bounds(), firstFrame, b.Min, draw.Src)
318 cmd = "encodeNRGBA"
319 var err error
320 source, err = hugio.ToSizeReader(bytes.NewReader(newImg.Pix))
321 if err != nil {
322 return err
323 }
324 params["width"] = newImg.Rect.Dx()
325 params["height"] = newImg.Rect.Dy()
326 params["stride"] = newImg.Stride
327 params["depth"] = 8
328 }
329 }
330 case *image.NRGBA64:
331 // 16-bit RGBA for HDR images.
332 // Go's NRGBA64 is big-endian, but libavif expects little-endian.
333 // Copy and swap bytes.
334 cmd = "encodeNRGBA"
335 pix := make([]byte, len(img.Pix))
336 for i := 0; i < len(pix); i += 2 {
337 pix[i], pix[i+1] = img.Pix[i+1], img.Pix[i]
338 }
339 var err error
340 source, err = hugio.ToSizeReader(bytes.NewReader(pix))
341 if err != nil {
342 return err
343 }
344 params["width"] = img.Rect.Dx()
345 params["height"] = img.Rect.Dy()
346 params["stride"] = img.Stride
347 params["depth"] = 10 // Encode HDR as 10-bit AVIF.
348 case *image.RGBA64:
349 // 16-bit RGBA for HDR images.
350 // Go's RGBA64 is big-endian, but libavif expects little-endian.
351 // Copy and swap bytes.
352 cmd = "encodeNRGBA"
353 pix := make([]byte, len(img.Pix))
354 for i := 0; i < len(pix); i += 2 {
355 pix[i], pix[i+1] = img.Pix[i+1], img.Pix[i]
356 }
357 var err error
358 source, err = hugio.ToSizeReader(bytes.NewReader(pix))
359 if err != nil {
360 return err
361 }
362 params["width"] = img.Rect.Dx()
363 params["height"] = img.Rect.Dy()
364 params["stride"] = img.Stride
365 params["depth"] = 10 // Encode HDR as 10-bit AVIF.
366 case *image.NRGBA:
367 cmd = "encodeNRGBA"
368 var err error
369 source, err = hugio.ToSizeReader(bytes.NewReader(img.Pix))
370 if err != nil {
371 return err
372 }
373 params["width"] = img.Rect.Dx()
374 params["height"] = img.Rect.Dy()
375 params["stride"] = img.Stride
376 params["depth"] = 8
377 case *image.Gray:
378 cmd = "encodeGray"
379 var err error
380 source, err = hugio.ToSizeReader(bytes.NewReader(img.Pix))
381 if err != nil {
382 return err
383 }
384 params["width"] = img.Rect.Dx()
385 params["height"] = img.Rect.Dy()
386 params["stride"] = img.Stride
387 params["depth"] = 8
388 case *image.Gray16:
389 // 16-bit grayscale for HDR.
390 cmd = "encodeGray"
391 var err error
392 source, err = hugio.ToSizeReader(bytes.NewReader(img.Pix))
393 if err != nil {
394 return err
395 }
396 params["width"] = img.Rect.Dx()
397 params["height"] = img.Rect.Dy()
398 params["stride"] = img.Stride
399 params["depth"] = 10
400 default:
401 // Check if source is HDR (RGBA64 color model) to preserve quality.
402 if src.ColorModel() == color.RGBA64Model || src.ColorModel() == color.NRGBA64Model {
403 b := src.Bounds()
404 newImg := image.NewNRGBA64(image.Rect(0, 0, b.Dx(), b.Dy()))
405 draw.Draw(newImg, newImg.Bounds(), src, b.Min, draw.Src)
406 return d.Encode(w, newImg, options)
407 }
408 // Convert to NRGBA and try again.
409 b := src.Bounds()
410 newImg := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
411 draw.Draw(newImg, newImg.Bounds(), src, b.Min, draw.Src)
412 return d.Encode(w, newImg, options)
413 }
414
415 message := Message[AvifInput]{
416 Header: Header{
417 Version: 1,
418 Command: cmd,
419 RequestKinds: []string{MessageKindJSON, MessageKindBlob},
420 ResponseKinds: []string{MessageKindJSON, MessageKindBlob},
421 },
422
423 Data: AvifInput{
424 Source: source,
425 Destination: w,
426 Options: options,
427 Params: params,
428 },
429 }
430
431 _, err = dd.Execute(context.Background(), message)
432 return err
433 }