Awesome Go

go-webp

CategoryImages
SubcategoryImages
Stars318

Library for encode and decode webp pictures, using libwebp

About go-webp

This large README is shown as a plain-text preview. Read the full README at the source

![logo](test_data/images/logo.jpg)
# go-webp

[![Release](https://img.shields.io/github/v/release/kolesa-team/go-webp)](https://github.com/kolesa-team/go-webp/releases/latest)
[![Go Reference](https://pkg.go.dev/badge/github.com/kolesa-team/go-webp/v2.svg)](https://pkg.go.dev/github.com/kolesa-team/go-webp/v2)
[![CI](https://github.com/kolesa-team/go-webp/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/kolesa-team/go-webp/actions/workflows/ci.yml?query=branch%3Amaster)
[![Coverage](https://raw.githubusercontent.com/kolesa-team/go-webp/badges/.badges/master/coverage.svg)](https://kolesa-team.github.io/go-webp/)
[![Go version](https://img.shields.io/github/go-mod/go-version/kolesa-team/go-webp)](go.mod)
[![License: MIT](https://img.shields.io/github/license/kolesa-team/go-webp)](LICENSE)
[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)

WebP encoder and decoder written in Go — **no cgo**, no libwebp; the only
dependency outside the standard library is `golang.org/x/sys` (CPU feature
detection). On arm64 and amd64 the hot loops run as assembly (NEON on
arm64; SSE4.1, AVX2 or AVX-512 on amd64, picked at run time), with results
identical to the pure Go code that other architectures and `-tags purego`
builds use (see [Assembly and the `purego` tag](#assembly-and-the-purego-tag)).

- Lossy (VP8) and lossless (VP8L) encoding and decoding.
- Alpha channel for lossy images (`ALPH` chunk, raw or compressed, with
  filtering and level quantization) and the extended `VP8X` container.
- Decoder output is **bit-exact with libwebp 1.6** (`dwebp`), including fancy
  upsampling, `NoFancyUpsampling`, `BypassFiltering`, dithering, alpha
  dithering, cropping and flipping. Scaling uses libwebp's rescaler
  (bit-exact with its portable C version).
- Encoder follows libwebp's algorithms (segmentation, RD-optimised mode
  decision, trellis quantization, LZ77/color cache/meta-Huffman for lossless),
  but the bytes are not identical to `cwebp`'s. Measured against cwebp 1.6.0
  at the same settings (`go test -tags interop -run VsCwebp -v
  ./internal/vp8enc`, two test photos, quality 10–100): lossy methods 4 and 6
  are within −0.8%…+0.3% of cwebp's size at the same PSNR (±0.01 dB);
  method 0 files are 0.1–9% smaller (up to 41% at quality 100) at a PSNR
  within 0.05 dB. Lossless output is the same size as cwebp's at level 6
  and 1.2% larger at level 0 on the benchmark photo (see below).
- Streaming decoder working one macroblock row at a time, pooled scratch
  buffers, zero copies for the common "decode the whole picture" case;
  `DecodeInto` reuses the caller's output buffer.
- Optional helper goroutines (`UseThreads`, `ThreadLevel`) from one
  process-wide budget, with output identical to the single-goroutine one.
- Works everywhere Go does, including `CGO_ENABLED=0`, cross compilation and
  scratch/distroless containers.

Animated WebP is not supported (as in v1, decoding reports
`VP8_STATUS_UNSUPPORTED_FEATURE`).

## Install
```bash
go get github.com/kolesa-team/go-webp/v2
```

Requires Go 1.27 or newer. The only other module it pulls in is
`golang.org/x/sys`, which amd64 builds use to read the CPU's features; no C
toolchain or system library is needed.

The cgo/libwebp based v1 remains available at tag `v1.0.6` (module path
`github.com/kolesa-team/go-webp`).

## Examples

#### Decode:
```go
package main

import (
	"image/jpeg"
	"log"
	"os"

	"github.com/kolesa-team/go-webp/v2/decoder"
	"github.com/kolesa-team/go-webp/v2/webp"
)

func main() {
	file, err := os.Open("test_data/images/m4_q75.webp")
	if err != nil {
		log.Fatalln(err)
	}
	defer file.Close()

	img, err := webp.Decode(file, &decoder.Options{})
	if err != nil {
		log.Fatalln(err)
	}

	if err := os.MkdirAll("example", 0o755); err != nil {
		log.Fatalln(err)
	}
	output, err := os.Create("example/output_decode.jpg")
	if err != nil {
		log.Fatalln(err)
	}

	if err := jpeg.Encode(output, img, &jpeg.Options{Quality: 75}); err != nil {
		output.Close()
		log.Fatalln(err)
	}
	if err := output.Close(); err != nil {
		log.Fatalln(err)
	}
}
```

From the repository root:
```bash
go run ./_examples/decode
```

Importing `github.com/kolesa-team/go-webp/v2/webp` also registers the format
with the standard library, so `image.Decode` and `image.DecodeConfig` work on
WebP files.

#### Encode
```go
package main

import (
	"image/jpeg"
	"log"
	"os"

	"github.com/kolesa-team/go-webp/v2/encoder"
	"github.com/kolesa-team/go-webp/v2/webp"
)

func main() {
	file, err := os.Open("test_data/images/source.jpg")
	if err != nil {
		log.Fatalln(err)
	}
	defer file.Close()

	img, err := jpeg.Decode(file)
	if err != nil {
		log.Fatalln(err)
	}

	options, err := encoder.NewLossyEncoderOptions(encoder.PresetDefault, 75)
	if err != nil {
		log.Fatalln(err)
	}

	if err := os.MkdirAll("example", 0o755); err != nil {
		log.Fatalln(err)
	}
	output, err := os.Create("example/output_encode.webp")
	if err != nil {
		log.Fatalln(err)
	}

	if err := webp.Encode(output, img, options); err != nil {
		output.Close()
		log.Fatalln(err)
	}
	if err := output.Close(); err != nil {
		log.Fatalln(err)
	}
}
```

From the repository root:
```bash
go run ./_examples/encode
```

Lossless: `encoder.NewLosslessEncoderOptions(encoder.PresetDefault, level)`
with `level` from 0 (fastest) to 9 (smallest), like `cwebp -z`.

#### Decode into a reused buffer
```go
var img *image.NRGBA // nil: the first decode allocates it
for _, data := range files {
	dec, err := decoder.NewDecoder(bytes.NewReader(data), nil)
	if err != nil {
		return err
	}
	if img, err = dec.DecodeInto(img); err != nil {
		return err
	}
	process(img) // before the next decode overwrites it
}
```

`(*decoder.Decoder).DecodeInto(dst)` and `webp.DecodeInto(r, dst, options)`
decode like `Decode`, but into `dst`:

- `dst` is raw memory: its previous `Rect` and `Stride` are ignored. When
  `cap(dst.Pix) >= 4*w*h` for the output size `w`x`h` (after crop and
  scale), the pixels are written in place, with no allocation and no
  clearing; otherwise a new buffer is allocated.
- On success `dst.Rect` is `(0,0)-(w,h)`, `dst.Stride` is `4*w`, the
  capacity of a reused buffer is kept, and the returned image is `dst`
  itself. A nil `dst` behaves like `Decode`.
- On error the fields of `dst` are unchanged, but its bytes may have been
  partly overwritten.
- Do not pass a `SubImage`, and do not use `dst` from other goroutines
  during the call.

#### Decode to Y'CbCr
`(*decoder.Decoder).DecodeYCbCr()` returns the 4:2:0 planes of a lossy
picture as an `*image.YCbCr` (1.5 bytes per pixel, no conversion to RGB);
`DecodeNYCbCrA()` adds the alpha plane (`*image.NYCbCrA`, 2.5 bytes per
pixel; all 0xff for an opaque picture).

- The samples are those of the VP8 stream (BT.601 limited range), the same
  as libwebp's `WebPDecodeYUV` / `dwebp -yuv` and as
  `golang.org/x/image/webp`. Colors computed through `image.YCbCr`'s color
  model therefore differ slightly from the RGB of `Decode`, which also
  upsamples the chroma smoothly.
- `Crop` (top-left corner rounded down to even coordinates), `Flip` (each
  plane mirrored), `BypassFiltering`, `DitheringStrength`,
  `AlphaDitheringStrength` (for `DecodeNYCbCrA`) and `UseThreads` apply;
  `Scale` is refused with `VP8_STATUS_INVALID_PARAM`.
- Lossless pictures and animations, and pictures with alpha for
  `DecodeYCbCr`, are refused with `VP8_STATUS_UNSUPPORTED_FEATURE`: check
  `GetFeatures()` first.

#### Cancellation
```go
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
img, err := webp.DecodeContext(ctx, r, nil)
// errors.Is(err, context.DeadlineExceeded) once the deadline has passed
err = webp.EncodeContext(ctx, w, img, options)
```

- Decoding: `(*decoder.Decoder).DecodeContext(ctx)`,
  `DecodeIntoContext(ctx, dst)` and `webp.DecodeContext(ctx, r, options)`
  check `ctx` between batches of output rows (at most 16 rows; a lossless
  picture reads its headers first). The error satisfies
  `errors.Is(err, context.Canceled)` (or `context.DeadlineExceeded`) and
  carries the status `VP8_STATUS_USER_ABORT`;
  `webp.DecodeContext` returns `ctx.Err()` itself when `ctx` is already
  done before `r` is read.
- Encoding: `(*encoder.Encoder).EncodeContext(ctx, w)` and
  `webp.EncodeContext(ctx, w, src, options)` check `ctx` about once per
  macroblock row (lossy) and between passes, search rows and work chunks
  (lossless), on helper goroutines too. They return `ctx.Err()` itself (not
  wrapped) and write nothing to `w`. The source conversion done by
  `NewEncoder` and the RGB to Y'CbCr conversion are not interruptible.
- Helper goroutines have exited when these functions return. With a
  `context.Background()` there is no overhead.

#### Releasing an encoder
`encoder.NewEncoder` copies every source that is not an `*image.NRGBA`
(as v1 did). `(*encoder.Encoder).Release()` hands that copy back to internal
pools for later encoders; afterwards `Encode` and `EncodeContext` return
`encoder.ErrReleased`. `Release` waits for encodes running on other
goroutines, may be called more than once and is safe on a nil `*Encoder`.
Calling it is optional: otherwise the copy goes back to the pools once the
`Encoder` is unreachable. `webp.Encode` and `webp.EncodeContext` release
automatically. (`Encoder` now holds a `sync.RWMutex`: use it through a
pointer, as `NewEncoder` returns it; `go vet` reports copies.)

## Threads

By default every `Decode`/`Encode` call runs on the calling goroutine only.
Helper goroutines are opt-in, per call:

- `decoder.Options.UseThreads`:
  - lossy pictures of at least 1024 macroblocks (about 512x512): the
    caller parses the coefficient tokens of batches of macroblock rows
    while a helper reconstructs and filters them; when that helper is the
    slower stage (the pure Go build, large pictures), the conversion to
    RGBA moves to a second helper, and idle helpers parse the prediction
    modes ahead of the caller;
  - lossy pictures with alpha whose rows down to the bottom of the output
    hold 256K pixels or more: another helper decodes the alpha plane ahead
    of the rows that need it;
  - lossless pictures of at least about 256K output pixels: the caller
    entropy-decodes while a helper applies the inverse transforms and
    writes the output rows (libwebp ignores `use_threads` for lossless
    pictures; this is a go-webp extension). The caller first writes 32K
    pixels itself and times them; the helper starts only if the rest of
    the picture projects to at least 200 µs of that work (pictures made of
    long copies of one colour do not gain from it). On Linux it also
    starts only when all the CPUs the process may run on share one
    last-level cache: with the rows in another core complex's L3 cache the
    helper made the 3000x2000 logo 10% slower on an 8-core EPYC (two L3
    caches) instead of 12-24% faster, so pin such a process to one L3
    domain (`taskset`, a cpuset) to get the gain.
- `encoder.Options.ThreadLevel`:
  - lossy: the analysis pass runs in row bands (384 macroblocks or more,
    1024 at methods 0-1); the macroblock rows are coded as a wavefront on
    up to 8 goroutines when the picture is large enough to pay for the
    hand-offs (with the assembly kernels of arm64 and amd64 about 0.3 MP
    at methods 3-6, 1700 pixels wide at method 2, several MP at methods
    0-1; about 0.1 MP at methods 3-6 in the pure Go build), taking at
    most `GOMAXPROCS` / (lossy encodes in progress) goroutines; and the
    compressed alpha plane of a transparent picture (64K pixels or more)
    is coded while the VP8 frame is;
  - lossless and compressed alpha (256K pixels or more): the hash-chain
    match search, the predictor search (methods 0-4) and the histogram
    remap are split among helpers, which are released at the end of each
    of these phases; level 9 codes at most two candidate configurations at
    a time (one at a time above 8 MP).

All helpers of the process come from one budget of `GOMAXPROCS-1`
goroutines (re-read on every call), shared by all concurrent `Decode` and
`Encode` calls. A call that finds no free slot does the work on its own
goroutine, so a server that already runs one request per core is never
oversubscribed. **The output is identical with or without the flags and
for any budget.** A panic in a helper is re-raised on the calling
goroutine, and helpers have exited when the call returns (also on errors
and cancellation). Goroutines wait for each other by blocking on channels
or condition variables, never by spinning. While processors are idle, a
decoder stage that wakes a parked one yields its processor once
(`runtime.Gosched`), so that the woken stage runs at once instead of after
the scheduler's wake-up delay (hundreds of microseconds on Linux).

The flags trade CPU for latency. Measured on an Apple M5 Pro (15 cores;
see [Benchmarks](#benchmarks) for the method; CPU time is the user and
system time of the whole process per call, garbage collection included;
the percentages compare the call with the flag to the same call on one
goroutine):

| Call (wall / CPU time) | NEON, one goroutine | NEON, with the flag | pure Go, one goroutine | pure Go, with the flag |
|---|---|---|---|---|
| Decode lossy 675x900 | 3.02 ms / 3.14 ms | 2.01 ms / 3.47 ms (−34% / +11%) | 6.63 ms / 6.76 ms | 4.40 ms / 7.04 ms (−34% / +4%) |
| Decode lossy+alpha 3000x2000 | 8.72 ms / 8.89 ms | 4.30 ms / 10.5 ms (−51% / +18%) | 22.4 ms / 22.6 ms | 13.1 ms / 24.2 ms (−42% / +7%) |
| Decode lossless 3000x2000 | 2.67 ms / 2.86 ms | 1.97 ms / 3.09 ms (−26% / +8%) | 2.67 ms / 2.85 ms | 1.95 ms / 3.06 ms (−27% / +7%) |
| Encode lossy q75 method 0, 1.2 MP | 17.3 ms / 17.3 ms | 16.5 ms / 17.5 ms (−4% / +1%) | 27.1 ms / 27.1 ms | 24.8 ms / 27.8 ms (−8% / +3%) |
| Encode lossy q75 method 4, 1.2 MP | 47.2 ms / 47.2 ms | 21.3 ms / 51.8 ms (−55% / +10%) | 120 ms / 120 ms | 39.1 ms / 131 ms (−67% / +9%) |
| Encode lossy q75 method 6, 1.2 MP | 120 ms / 120 ms | 40.2 ms / 129 ms (−67% / +7%) | 174 ms / 174 ms | 52.1 ms / 186 ms (−70% / +7%) |
| Encode lossy+alpha q75, 3000x2000 | 245 ms / 245 ms | 155 ms / 260 ms (−37% / +6%) | 458 ms / 458 ms | 158 ms / 522 ms (−65% / +14%) |
| Encode lossless level 6, 1.2 MP | 307 ms / 307 ms | 157 ms / 342 ms (−49% / +11%) | 306 ms / 306 ms | 157 ms / 341 ms (−49% / +11%) |
| Encode lossless level 0, 1.2 MP | 45.1 ms / 45.2 ms | 36.2 ms / 46.8 ms (−20% / +4%) | 45.1 ms / 45.1 ms | 36.1 ms / 46.8 ms (−20% / +4%) |

With the flags, a call takes free helper slots only. Under saturation (15
calls at a time on 15 cores, see [Throughput under
load](#throughput-under-load)) a call rarely finds one: `ThreadLevel` then
changed encode throughput by less than the run-to-run noise (about ±10%
there), while `UseThreads` lowered the throughput of lossy+alpha and
lossless decodes by about 10% (the pipeline's hand-offs cost CPU). The
flags therefore help most an application that decodes or encodes one large
picture at a time, or a server with spare cores; a server that already
runs about one call per core may leave them off, which remains the
default.

On the amd64 server of the [Benchmarks](#amd-epyc-8024p-amd64) section
(8 cores, Linux), measured the same way:

| Call (wall / CPU time) | assembly, one goroutine | assembly, with the flag | pure Go, one goroutine | pure Go, with the flag |
|---|---|---|---|---|
| Decode lossy 675x900 | 5.88 ms / 6.22 ms | 3.97 ms / 6.82 ms (−32% / +10%) | 15.6 ms / 16.1 ms | 11.4 ms / 16.7 ms (−27% / +4%) |
| Decode lossy+alpha 3000x2000 | 15.6 ms / 16.1 ms | 11.9 ms / 26.7 ms (−24% / +66%) | 60.4 ms / 61.2 ms | 37.6 ms / 65.2 ms (−38% / +7%) |
| Decode lossless 3000x2000 | 5.04 ms / 5.41 ms | 5.05 ms / 5.41 ms (+0% / +0%) | 7.74 ms / 8.21 ms | 7.94 ms / 8.42 ms (+3% / +3%) |
| Encode lossy q75 method 0, 1.2 MP | 30.0 ms / 30.0 ms | 32.3 ms / 34.6 ms (+8% / +15%) | 56.9 ms / 57.1 ms | 54.2 ms / 62.1 ms (−5% / +9%) |
| Encode lossy q75 method 4, 1.2 MP | 82.9 ms / 83.1 ms | 38.1 ms / 89.0 ms (−54% / +7%) | 303 ms / 304 ms | 82.8 ms / 309 ms (−73% / +2%) |
| Encode lossy q75 method 6, 1.2 MP | 239 ms / 239 ms | 73.7 ms / 245 ms (−69% / +3%) | 388 ms / 389 ms | 105 ms / 394 ms (−73% / +1%) |
| Encode lossy+alpha q75, 3000x2000 | 517 ms / 518 ms | 327 ms / 533 ms (−37% / +3%) | 1.20 s / 1.21 s | 366 ms / 1.22 s (−70% / +1%) |
| Encode lossless level 6, 1.2 MP | 463 ms / 464 ms | 227 ms / 493 ms (−51% / +6%) | 699 ms / 701 ms | 335 ms / 734 ms (−52% / +5%) |
| Encode lossless level 0, 1.2 MP | 56.0 ms / 56.2 ms | 42.3 ms / 65.0 ms (−24% / +16%) | 103 ms / 103 ms | 79.6 ms / 108 ms (−23% / +4%) |

There `UseThreads` started no helper for the lossless logo, because the
process may run on both of the CPU's L3 caches (see above), and
`ThreadLevel` made the method 0 encode 8% slower, with 15% more CPU time.

On Linux VMs with coarse timers (for example Docker Desktop's linux/arm64
VM) every hand-off between goroutines costs about a millisecond, so there
the flags pay off on large or slow pictures only. Measured there (Docker
Desktop on the same M5 Pro, 4 CPUs; not part of `benchmarks/run.sh`): `UseThreads` decodes the 3000x2000 lossy+alpha logo in 7.1 ms
instead of 9.5 ms and the 675x900 lossy picture in 2.95 ms instead of
3.26 ms, but the lossless logo in 3.2 ms instead of 2.8 ms; `ThreadLevel`
encodes the 1.2 MP photo at method 6 in 88 ms (about 123 ms on one
goroutine) and at method 4 in 47.5 ms (about 49 ms).

## Running on a server

The library sets no process-wide limits itself. For a service that decodes
or encodes untrusted pictures:

- Bound the number of concurrent codec calls to about `GOMAXPROCS` (a
  semaphore), and queue or shed the rest. Every call needs its working
  memory at once, and more concurrent calls than cores only add memory.
- Decode with `DecodeInto` into buffers from your own pool (one per worker,
  sized for your largest accepted picture): the output image is nearly all
  of a decode's memory (4 bytes per pixel), and reusing it removes most of
  the garbage collector's work. Check `webp.DecodeConfig` or `GetFeatures`
  against your size limits before decoding.
- Set `GOMEMLIMIT` to about 1.3-1.5x the expected working set (roughly
  4-5 bytes per pixel per concurrent decode, plus encodes), below the
  container's memory limit; the garbage collector then keeps large
  lossless encodes under it (see [Benchmarks](#benchmarks)). In our
  measurements of 15 concurrent decodes `GOMEMLIMIT` alone cost 7-33%
  more CPU; together with `DecodeInto` it cost nothing measurable.
- Between calls the encoders keep reusable buffers (the lossy and lossless
  working sets, `Encoder` snapshots, alpha planes) under one process-wide
  budget: 256 MiB (64 MiB on 32-bit platforms), or an eighth of the Go
  memory limit (`GOMEMLIMIT`, `debug.SetMemoryLimit`) when that is lower,
  re-read at most once a second. Buffers unused for 15 s are dropped at
  the next garbage collection, which the runtime forces at least every two
  minutes. A single large encode may keep its whole working set for that
  long (about 200 MB after a 12 MP lossless encode): that is what makes
  back-to-back large encodes cheap. Under a tight `GOMEMLIMIT` the eighth
  is too small to keep such a working set, and back-to-back large
  lossless encodes peak higher, though below the limit (see the memory
  table).
- The decoder keeps O(width) state besides the output. The alpha plane of
  a lossy picture is decoded through a ring of rows (about 256 KB, or
  about 2.5 MB at 3000 pixels wide when the `UseThreads` alpha helper
  runs) instead of as a whole plane; only `AlphaDitheringStrength` still
  needs the whole plane.
- Profile-guided optimization applies to dependencies: building the
  service with a CPU profile of its own workload (`default.pgo` in the main
  package) also optimizes this library. A library cannot ship a profile.
- On amd64 the codec picks its SIMD kernels at run time, so it needs no

Frequently Asked Questions

What is go-webp?

go-webp is a Images library for the Go programming language. Library for encode and decode webp pictures, using libwebp

How do I install go-webp?

Install go-webp with the Go module system using `go get kolesa-team/go-webp`. Check the repository for the current installation instructions.

What category does go-webp belong to?

go-webp is listed under Images, specifically Images.

← Back to Images