// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package decoder
import (
"image"
"sync"
"github.com/kolesa-team/go-webp/v2/internal/alpha"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/internal/vp8l"
"github.com/kolesa-team/go-webp/v2/utils"
)
// lazyAlpha decodes an ALPH chunk incrementally, up to the rows the VP8
// decoder is about to emit (libwebp's VP8DecompressAlphaRows): rows are
// decoded (lossless streams through vp8l.AlphaDecoder) and unfiltered in
// batches.
//
// Unlike libwebp, which keeps the whole alpha plane, only a ring of the
// last decoded rows is kept (ringRows; a few hundred kilobytes instead of
// one byte per pixel), since the VP8 decoder asks for rows top to bottom
// and never goes back. A request's rows that wrap around the end of the
// ring are joined by copying the wrapped part into tail rows after the
// ring. The rows decoded for one request may be decoded in two calls (at
// the end of the ring), which gives the same result and the same errors as
// one call, except for a call that reaches the last row of the plane
// (libwebp only reports running out of data before the last pixel): the
// ring is placed so that the last row of the plane is its last row, and a
// request for the last row that does not fit in the ring switches to a
// plane.
//
// The whole plane is kept when it is not larger than the ring, and with
// alpha dithering, which smooths the whole plane at once (it is then
// decoded in one pass, as libwebp does). An uncompressed plane without a
// filter is the chunk itself.
type lazyAlpha struct {
alph []byte
w, h int
crop image.Rectangle
dithering int
threads bool
started bool
hdr alpha.Header
data []byte // payload after the header byte
dec *vp8l.AlphaDecoder // nil for uncompressed alpha
pp *[]byte // pooled buffer, if any
spare *[]byte // pooled buffer taken by prefetch, not yet used
// buf holds the decoded rows: with ring > 0 frame row y is row
// (y+off)%ring of buf, followed by alphaTailRows tail rows; otherwise
// frame row y is row y-base of buf (a plane).
buf []byte
ring, off int
base int
rows int // rows [0, rows) are decoded
err error
// helperOK lets the first get start a helper goroutine (UseThreads);
// while async is set the helper owns dec, pp, spare, buf and rows,
// and get reads the published rows from hp.
helperOK bool
async bool
hp *alphaHelper
}
var (
// alphaRingBytes is the size of the ring of a sequential decode; it
// has at least minAlphaRingRows rows. Variables for tests.
alphaRingBytes = 256 << 10
minAlphaRingRows = 64
)
// alphaTailRows bounds the rows of a request served from a ring (the VP8
// decoder asks for at most 16+8+1 rows at a time).
const alphaTailRows = 32
// ringRows returns the number of ring rows for a sequential decode, or for
// one with a helper goroutine (which works up to two bands ahead, see
// alpha_helper.go), or 0 if the plane is not larger than the ring.
func (a *lazyAlpha) ringRows(helper bool) int {
r := max(minAlphaRingRows, (alphaRingBytes+a.w-1)/a.w)
if helper {
step, band := helperRows(a.w)
r = max(r, 2*band+step+2*alphaTailRows)
}
if r+alphaTailRows >= a.h {
return 0
}
return r
}
// wholePlane reports whether the plane must be decoded in one pass (alpha
// dithering of a quantized plane).
func (a *lazyAlpha) wholePlane() bool {
return a.hdr.PreProcessing == alpha.PreprocessingLevels && a.dithering > 0
}
// newLazyAlpha returns the alpha decoder of a w x h frame whose output
// region is crop. It must be released (on the calling goroutine).
func newLazyAlpha(alph []byte, w, h int, crop image.Rectangle, c *Config) *lazyAlpha {
a := &lazyAlpha{alph: alph, w: w, h: h, crop: crop, dithering: c.AlphaDitheringStrength, threads: c.UseThreads}
// With UseThreads the buffer is first needed on the worker goroutine,
// while release runs on this one: a sync.Pool Get on another P misses
// the buffer put back by the previous decode. Take a pooled buffer
// here (without allocating one: the allocation stays lazy, see alloc).
a.prefetch()
if c.UseThreads {
// Likewise the lossless alpha decoder (vp8l pools its state): set
// it up here, so that it comes from and returns to this goroutine's
// pool. An error is kept for the first get, which keeps the VP8
// errors that come before the first emitted row first.
a.start()
// The first get may hand the decoding to a helper goroutine
// (alpha_helper.go).
a.helperOK = true
}
return a
}
// get returns the alpha samples of frame rows [rowStart, rowEnd), decoding
// the plane up to rowEnd, as a window of the plane (vp8.Options.Alpha):
// frame row y is plane[(y-base)*w:]. The window is valid until the next
// call; rowStart must not decrease from one call to the next.
func (a *lazyAlpha) get(rowStart, rowEnd int) (plane []byte, base int, err error) {
if a.err != nil {
return nil, 0, a.err
}
if !a.started {
if a.start(); a.err != nil {
return nil, 0, a.err
}
}
rowEnd = min(rowEnd, a.h)
rowStart = min(rowStart, rowEnd)
if a.async {
return a.getAsync(rowStart, rowEnd)
}
if rowEnd > a.rows {
if a.helperOK {
a.helperOK = false
if a.useHelper() && a.startHelper() {
return a.getAsync(rowStart, rowEnd)
}
}
end := rowEnd
if a.wholePlane() {
end = a.h // dequantization smooths the whole plane at once
}
if a.err = a.decodeRequest(rowStart, end); a.err != nil {
return nil, 0, a.err
}
}
return a.window(a.buf, rowStart, rowEnd)
}
// start initializes the alpha decoder, keeping a failure in a.err.
func (a *lazyAlpha) start() {
a.started = true
a.err = a.init()
}
// init validates the ALPH header like libwebp's ALPHInit, which
// VP8DecompressAlphaRows reports as VP8_STATUS_OUT_OF_MEMORY on failure.
func (a *lazyAlpha) init() error {
if len(a.alph) <= 1 {
return status.New(utils.Vp8StatusOutOfMemory, "alpha decoder initialization failed: alpha chunk too short")
}
hdr, err := alpha.ParseHeader(a.alph[0])
if err != nil {
return status.New(utils.Vp8StatusOutOfMemory, "alpha decoder initialization failed: invalid ALPH header")
}
a.hdr = hdr
a.data = a.alph[1:]
if hdr.Compression == alpha.CompressionNone {
if len(a.data) < a.w*a.h {
return status.New(utils.Vp8StatusOutOfMemory, "alpha decoder initialization failed: alpha chunk too short")
}
if hdr.Filter == alpha.FilterNone && !a.wholePlane() {
// The plane is the chunk itself.
a.buf, a.ring, a.base, a.rows = a.data, 0, 0, a.h
}
return nil
}
a.dec, err = vp8l.NewAlphaDecoder(a.data, a.w, a.h)
return err
}
// alloc sets up the buffer before the first rows are decoded: a ring of
// ringRows(helper) rows, or the plane.
func (a *lazyAlpha) alloc(helper bool) {
if a.buf != nil {
return
}
w := a.w
r := 0
if !a.wholePlane() {
r = a.ringRows(helper)
}
if r == 0 {
a.grow(1)
return
}
n := (r + alphaTailRows) * w
if a.spare != nil && cap(*a.spare) >= n {
a.pp, a.spare = a.spare, nil
*a.pp = (*a.pp)[:n]
} else {
a.pp = getPlane(n)
}
a.buf = *a.pp
a.ring = r
// The last row of the plane is the last row of the ring, so that the
// request that reaches it is decoded in one call (see lazyAlpha).
a.off = (r - a.h%r) % r
}
// decodeRequest decodes the rows [a.rows, rowEnd) of the request for rows
// [rowStart, rowEnd). With a ring, a request that the ring cannot serve
// (more rows than the tail can join, or a call for the last row of the
// plane that does not fit in the ring in one piece) first switches to a
// plane of the rows from rowStart on.
func (a *lazyAlpha) decodeRequest(rowStart, rowEnd int) error {
a.alloc(false)
if a.ring > 0 && (rowEnd-rowStart > min(alphaTailRows, a.ring-1) || rowEnd == a.h && rowEnd-a.rows > a.ring-1) {
if err := a.toPlane(rowStart); err != nil {
return err
}
}
return a.decodeRows(rowEnd)
}
// toPlane replaces the ring with a plane holding the rows from
// min(rowStart, a.rows-1) (the row before the next one to decode, which
// the unfilter needs) to the end of the frame.
func (a *lazyAlpha) toPlane(rowStart int) error {
w := a.w
keep := min(rowStart, a.rows)
if a.rows > 0 {
keep = min(keep, a.rows-1)
}
if keep < a.rows-(a.ring-1) {
// Requests never go back that far (rowStart does not decrease).
return status.InvalidParam("alpha rows no longer available")
}
np := make([]byte, (a.h-keep)*w)
for y := keep; y < a.rows; y++ {
copy(np[(y-keep)*w:][:w], a.rowAt(y))
}
a.buf, a.ring, a.off, a.base = np, 0, 0, keep
return nil
}
// rowAt returns decoded frame row y (which the buffer must hold).
func (a *lazyAlpha) rowAt(y int) []byte {
if a.ring > 0 {
return a.buf[(y+a.off)%a.ring*a.w:][:a.w]
}
return a.buf[(y-a.base)*a.w:][:a.w]
}
// window returns the rows [rowStart, rowEnd) of buf (a.buf, or the buffer
// a helper published) as a plane window for get.
func (a *lazyAlpha) window(buf []byte, rowStart, rowEnd int) ([]byte, int, error) {
if a.ring == 0 {
return buf, a.base, nil
}
w := a.w
p := (rowStart + a.off) % a.ring
if k := p + rowEnd - rowStart - a.ring; k > 0 {
if k > alphaTailRows {
return nil, 0, status.InvalidParam("alpha request too large")
}
// The rows wrap around the ring: join them in the tail rows.
copy(buf[a.ring*w:(a.ring+k)*w], buf[:k*w])
}
return buf[p*w:], rowStart, nil
}
// decodeRows decodes and unfilters rows [a.rows, rowEnd) into the buffer.
func (a *lazyAlpha) decodeRows(rowEnd int) error {
w := a.w
for a.rows < rowEnd {
y0 := a.rows
n := rowEnd - y0
var dst []byte
if a.ring > 0 {
p := (y0 + a.off) % a.ring
n = min(n, a.ring-p) // the next call continues at the start of the ring
if p == 0 && n == a.ring && y0 > 0 {
n-- // keep the previous row for the unfilter
}
dst = a.buf[p*w : (p+n)*w]
} else {
if a.base == 0 {
a.grow(rowEnd)
}
dst = a.buf[(y0-a.base)*w : (rowEnd-a.base)*w]
}
if a.dec == nil {
copy(dst, a.data[y0*w:(y0+n)*w])
} else if err := a.dec.DecodeRowsAt(dst, y0, y0+n); err != nil {
if status.CodeOf(err) == utils.Vp8StatusOutOfMemory {
return err
}
return status.Bitstream("could not decode alpha data: " + err.Error())
}
if a.hdr.Filter != alpha.FilterNone {
var prev []byte
if y0 > 0 {
prev = a.rowAt(y0 - 1)
}
for i := range n {
row := dst[i*w : (i+1)*w]
alpha.UnfilterRow(a.hdr.Filter, prev, row, row)
prev = row
}
}
a.rows = y0 + n
}
if rowEnd == a.h && a.wholePlane() {
crop := a.crop
win := a.buf[crop.Min.Y*w+crop.Min.X:]
if err := alpha.Dequantize(win, crop.Dx(), crop.Dy(), w, min(a.dithering, 100)); err != nil {
return err
}
}
return nil
}
// minAlphaBand is the smallest allocation (in bytes) of a growing alpha
// plane.
const minAlphaBand = 4 << 20
// grow makes the plane (base 0) hold at least rowEnd rows. Planes up to
// maxPooledPlane bytes are taken whole from planePool. Bigger ones start
// with minAlphaBand bytes and grow by 4x (straight to the full plane once
// that is at least half of it), so that a huge frame whose VP8 data ends
// early (or a crop near the top) does not allocate the full plane, while
// a complete decode allocates little more than the plane itself.
func (a *lazyAlpha) grow(rowEnd int) {
w, h := a.w, a.h
if len(a.buf) >= rowEnd*w {
return
}
if w*h <= maxPooledPlane {
if a.spare != nil && cap(*a.spare) >= w*h {
a.pp, a.spare = a.spare, nil
*a.pp = (*a.pp)[:w*h]
} else {
a.pp = getPlane(w * h)
}
a.buf = *a.pp
return
}
rows := max(rowEnd, 4*len(a.buf)/w, minAlphaBand/w)
if 2*rows >= h {
rows = h
}
np := make([]byte, rows*w)
copy(np, a.buf[:a.rows*w])
a.buf = np
}
// prefetch takes a buffer from planePool that is big enough for the
// expected layout (the ring, or the plane), if the pool has one; it
// allocates nothing.
func (a *lazyAlpha) prefetch() {
n := a.w * a.h
if len(a.alph) > 1 {
if hdr, err := alpha.ParseHeader(a.alph[0]); err == nil {
a.hdr = hdr // for wholePlane; init sets it again
if hdr.Compression == alpha.CompressionNone && hdr.Filter == alpha.FilterNone && !a.wholePlane() {
return // the plane is the chunk itself
}
if r := a.ringRows(a.threads); r > 0 && !a.wholePlane() {
n = (r + alphaTailRows) * a.w
}
}
}
if n > maxPooledPlane {
return
}
if p, ok := planePool.Get().(*[]byte); ok {
if cap(*p) >= n {
a.spare = p
} else {
planePool.Put(p)
}
}
}
func (a *lazyAlpha) release() {
a.stopHelper()
if a.spare != nil {
planePool.Put(a.spare)
a.spare = nil
}
if a.dec != nil {
a.dec.Close()
a.dec = nil
}
if a.pp != nil {
if cap(*a.pp) <= maxPooledPlane {
planePool.Put(a.pp)
}
a.pp = nil
}
a.buf = nil
}
// maxPooledPlane bounds the alpha planes kept in planePool, so that one huge
// image does not pin its alpha plane in memory.
const maxPooledPlane = 16 << 20
var planePool sync.Pool // of *[]byte
func getPlane(n int) *[]byte {
if p, ok := planePool.Get().(*[]byte); ok && cap(*p) >= n {
*p = (*p)[:n]
return p
}
b := make([]byte, n)
return &b
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package decoder
import (
"runtime"
"sync"
"github.com/kolesa-team/go-webp/v2/internal/alpha"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/internal/workers"
"github.com/kolesa-team/go-webp/v2/utils"
)
// With UseThreads a lossy+alpha decode moves the alpha plane (lossless
// decoding and unfiltering) to a helper goroutine, which works ahead of the
// rows the VP8 decoder emits: the alpha work then overlaps the VP8 work
// instead of adding to it. The helper decodes in steps of about
// alphaStepPixels pixels and publishes each step (an uncontended lock; the
// requester is only woken up when it waits), up to two bands of
// alphaBandPixels past the last request; it then sleeps until a whole band
// of work is available again, so that hand-offs that wake a goroutine stay
// coarse. A truncated VP8 stream thus costs at most a few bands of alpha
// decoding beyond the rows it emits.
//
// The output and the errors are exactly those of the sequential lazyAlpha:
//
// - Decoding is deterministic, so the rows the helper publishes are the
// ones the sequential path decodes.
// - A failure is only known to lie in the step being decoded. The helper
// then stops; the rows before the step stay valid, and a request beyond
// them replays the requests made so far, in order, with a fresh
// decoder on the requesting goroutine, which reproduces the sequential
// outcome (including errors that depend on where a request ends, like
// libwebp's end-of-stream check at the end of each
// VP8DecompressAlphaRows call).
// - A successful step means that every sequential request ending at or
// before it succeeds: errors in the middle of a request depend only on
// the position of the faulty data, and the end-of-stream condition
// only grows as more data is read. One exception: a request that
// reaches the end of the plane succeeds even after running out of data
// (libwebp only reports that before the last pixel), so the helper
// never decodes the last row; the request for it continues on the
// requesting goroutine.
//
// Alpha dithering of quantized planes needs the whole plane at once and
// stays sequential.
//
// With a ring (see lazyAlpha), the helper's look-ahead bounds the rows it
// writes: they stay below the first row of the last request (which the
// requester may still read) plus the ring size, which ringRows makes
// larger than the look-ahead, a step and the rows of a request.
var (
// alphaBandPixels is the amount of alpha work per wake-up of the
// helper: the vp8l alpha decoder and the unfilter take 0.5 ns (palette
// planes) to a few ns per pixel, so a band is at least half a
// millisecond of work.
alphaBandPixels = 1 << 20
// alphaStepPixels is the amount of alpha work published at once.
alphaStepPixels = 64 << 10
// minHelperPixels is the smallest frame decoded with a helper: below it,
// starting the helper costs about as much as the overlap saves.
minHelperPixels = 256 << 10
)
// alphaHelper is the state shared by the helper goroutine and the
// requesting goroutine (the VP8 decoder's output stage).
type alphaHelper struct {
task *workers.Task
step int // rows decoded and published at once
band int // rows of work the sleeping helper waits for
ahead int // rows the helper may decode past the last request
limit int // the helper never decodes this row and the following ones (the last row of the plane, or the crop bottom)
procs int // GOMAXPROCS when the helper started (see handOff)
mu sync.Mutex
cond sync.Cond
// Guarded by mu.
requested int // largest rowEnd requested
published int // rows [0, published) of pub are final
pub []byte // buffer holding the published rows
idle bool // the helper sleeps (published is its row count)
waiting bool // the requester waits for rows
stop bool // set by release: exit after the current step
failed bool // the step after published failed
exited bool // the helper has returned (or panicked)
// reqs are the distinct rowEnd values requested so far, in order (only
// touched by the requesting goroutine).
reqs []int
}
// handOff yields the processor after waking the other goroutine of the
// alpha helper (the helper or the requester) while continuing to work:
// otherwise the woken goroutine waits in this goroutine's next-to-run slot,
// from which other threads only take it after a back-off (tens of
// microseconds on darwin, hundreds on Linux VMs; see the vp8 package's
// parked.handOff). It is no wait: Gosched returns at once when nothing
// else is runnable. When the UseThreads pipelines in progress (the VP8
// decode of a lossy+alpha picture is one) occupy the processors, no idle
// one would take the waker over, and it does not yield.
func (hp *alphaHelper) handOff() {
if workers.SpareProcs(hp.procs) {
runtime.Gosched()
}
}
// errHelperPanic aborts a decode whose alpha helper panicked; the panic
// itself is re-raised on the decoding goroutine by release.
var errHelperPanic = status.New(utils.Vp8StatusBitstreamError, "alpha decoder failed")
// useHelper reports whether the alpha plane may be decoded by a helper.
func (a *lazyAlpha) useHelper() bool {
if a.hdr.PreProcessing == alpha.PreprocessingLevels && a.dithering > 0 {
return false
}
// Only the rows down to the bottom of the output region are decoded.
return a.w*a.crop.Max.Y >= minHelperPixels && a.h > 1
}
// helperRows returns the rows of a step and of a band of the helper, for
// planes of width w.
func helperRows(w int) (step, band int) {
band = max((alphaBandPixels+w-1)/w, 1)
step = min(max((alphaStepPixels+w-1)/w, 1), band)
return step, band
}
// startHelper starts the helper goroutine, if the worker budget allows;
// a.rows must be 0 (nothing decoded yet).
func (a *lazyAlpha) startHelper() bool {
step, band := helperRows(a.w)
// No request goes past the bottom of the output region (crop), so the
// helper stops there instead of working ahead on rows nobody needs.
limit := min(a.h-1, a.crop.Max.Y)
hp := &alphaHelper{step: step, band: band, ahead: 2 * band, limit: limit,
procs: runtime.GOMAXPROCS(0),
// The VP8 decoder requests rows once per macroblock row.
reqs: make([]int, 0, a.h/16+4)}
hp.cond.L = &hp.mu
if hp.task = workers.Spawn(func() error { return a.runHelper(hp) }); hp.task == nil {
return false
}
a.hp = hp
a.async = true
return true
}
// testHookHelperStep, if set (tests), runs on the helper before each step.
var testHookHelperStep func()
// runHelper is the helper goroutine: it owns the decoding state (dec,
// plane, pp, spare, rows) until it has exited.
func (a *lazyAlpha) runHelper(hp *alphaHelper) error {
defer func() {
hp.mu.Lock()
hp.exited = true
hp.cond.Broadcast()
hp.mu.Unlock()
}()
// A ring sized for the look-ahead (allocated here, so that a decode
// whose helper cannot start keeps the smaller sequential ring).
a.alloc(true)
for {
hp.mu.Lock()
if !hp.stop && a.rows < hp.limit && a.rows >= hp.requested+hp.ahead {
// Far enough ahead: sleep until a band of work is available.
hp.idle = true
for !hp.stop && a.rows+hp.band > hp.requested+hp.ahead {
hp.cond.Wait()
}
hp.idle = false
}
if hp.stop || a.rows >= hp.limit {
hp.mu.Unlock()
return nil
}
hp.mu.Unlock()
if testHookHelperStep != nil {
testHookHelperStep()
}
err := a.decodeRows(min(a.rows+hp.step, hp.limit))
hp.mu.Lock()
if err != nil {
hp.failed = true
hp.mu.Unlock()
return nil
}
hp.published, hp.pub = a.rows, a.buf
wake := hp.waiting
if wake {
hp.cond.Broadcast()
}
hp.mu.Unlock()
if wake {
hp.handOff()
}
}
}
// getAsync is get while the helper decodes: it waits until the helper has
// published rowEnd rows. When the helper has exited without them (it
// reached its row limit, failed or panicked) the decode continues on the
// calling goroutine.
func (a *lazyAlpha) getAsync(rowStart, rowEnd int) ([]byte, int, error) {
hp := a.hp
if n := len(hp.reqs); n == 0 || rowEnd > hp.reqs[n-1] {
hp.reqs = append(hp.reqs, rowEnd)
}
hp.mu.Lock()
wake := false
if rowEnd > hp.requested {
hp.requested = rowEnd
// A sleeping helper has published all its rows.
if hp.idle && hp.published+hp.band <= hp.requested+hp.ahead {
hp.cond.Broadcast()
wake = true
}
}
for hp.published < rowEnd && !hp.exited {
hp.waiting = true
wake = false // waiting lets the helper run
hp.cond.Wait()
}
hp.waiting = false
if hp.published >= rowEnd {
p := hp.pub
hp.mu.Unlock()
if wake {
hp.handOff()
}
// The helper only writes rows from published on, below rowStart
// plus the ring size: not the rows of the window.
return a.window(p, rowStart, rowEnd)
}
failed := hp.failed
hp.mu.Unlock()
// The helper is gone: the decoding state belongs to this goroutine.
a.async = false
if hp.task.Panicked() {
a.err = errHelperPanic
return nil, 0, a.err
}
if failed {
a.err = a.replay(hp.reqs, rowStart)
} else {
a.err = a.decodeRequest(rowStart, rowEnd)
}
if a.err != nil {
return nil, 0, a.err
}
return a.window(a.buf, rowStart, rowEnd)
}
// replay redoes the requests reqs from the first row with a fresh decoder,
// as the sequential path would have made them, and returns the first error.
// rowStart is the first row of the last request.
func (a *lazyAlpha) replay(reqs []int, rowStart int) error {
if a.dec != nil {
a.dec.Close()
a.dec = nil
}
a.rows = 0
if err := a.init(); err != nil {
return err
}
for i, r := range reqs {
// The rows before the last request are not needed any more: any
// earlier row will do as the first row of a request.
start := min(rowStart, r)
if i < len(reqs)-1 {
start = max(r-1, 0)
}
if err := a.decodeRequest(start, r); err != nil {
return err
}
}
return nil
}
// stopHelper makes the helper exit and waits for it. If it panicked, its
// decoding state is dropped (not pooled) and the panic is re-raised here.
func (a *lazyAlpha) stopHelper() {
hp := a.hp
if hp == nil {
return
}
hp.mu.Lock()
hp.stop = true
hp.cond.Broadcast()
hp.mu.Unlock()
if hp.task.Panicked() {
a.dec, a.pp, a.spare, a.buf = nil, nil, nil, nil
}
a.hp, a.async = nil, false
_ = hp.task.Wait() // re-raises a panic of the helper
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package decoder
import (
"context"
"image"
"github.com/kolesa-team/go-webp/v2/internal/pipeline"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/utils"
)
// DecodeContext is Decode with cancellation: once ctx is cancelled or its
// deadline has passed, decoding stops at the next batch of output rows (at
// most 16 rows of the frame; a lossless picture first reads its headers),
// and the error satisfies errors.Is(err, context.Canceled) (or
// context.DeadlineExceeded); its status code is VP8_STATUS_USER_ABORT.
// Helper goroutines (UseThreads) have exited when DecodeContext returns.
func (d *Decoder) DecodeContext(ctx context.Context) (image.Image, error) {
img, err := d.decodeInto(call{ctx: ctx})
if err != nil {
return nil, err
}
return img, nil
}
// DecodeIntoContext is DecodeInto with cancellation, see DecodeContext.
func (d *Decoder) DecodeIntoContext(ctx context.Context, dst *image.NRGBA) (*image.NRGBA, error) {
return d.decodeInto(call{dst: dst, ctx: ctx})
}
// abortError is the error of a cancelled decode: it matches both the
// context's error and a VP8_STATUS_USER_ABORT status (libwebp's code for a
// decode stopped by the application).
type abortError struct {
err error // ctx.Err()
st error
}
func (e *abortError) Error() string { return e.err.Error() }
func (e *abortError) Unwrap() []error { return []error{e.err, e.st} }
// canceled returns an abortError once ctx (which may be nil) is done.
func canceled(ctx context.Context) error {
if ctx == nil {
return nil
}
if err := ctx.Err(); err != nil {
return &abortError{err: err, st: status.New(utils.Vp8StatusUserAbort, "decoding cancelled")}
}
return nil
}
// wrap returns sink, checking the context of the call after each committed
// batch of rows when it can be cancelled.
func (c call) wrap(sink pipeline.Sink) pipeline.Sink {
if c.ctx == nil || c.ctx.Done() == nil {
return sink
}
return &ctxSink{Sink: sink, ctx: c.ctx}
}
// ctxSink stops the decoder (Commit fails) once the context is done.
type ctxSink struct {
pipeline.Sink
ctx context.Context
}
func (s *ctxSink) Commit(y, n int) error {
if err := s.Sink.Commit(y, n); err != nil {
return err
}
return canceled(s.ctx)
}
// AcceptPremultiplied forwards pipeline.PremultipliedSink to the wrapped
// sink, so that a cancellable decode keeps the lossless decoder's
// palette-domain premultiplication (Scale of palette images).
func (s *ctxSink) AcceptPremultiplied() bool {
p, ok := s.Sink.(pipeline.PremultipliedSink)
return ok && p.AcceptPremultiplied()
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package decoder decodes WebP images (lossy, lossless, with alpha) with a
// pure Go implementation that produces the same pixels as libwebp.
package decoder
import (
"context"
"encoding/binary"
"errors"
"image"
"io"
"math"
"os"
"github.com/kolesa-team/go-webp/v2/internal/container"
"github.com/kolesa-team/go-webp/v2/internal/ctxio"
"github.com/kolesa-team/go-webp/v2/internal/pipeline"
"github.com/kolesa-team/go-webp/v2/internal/resample"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/internal/vp8"
"github.com/kolesa-team/go-webp/v2/internal/vp8l"
"github.com/kolesa-team/go-webp/v2/utils"
)
// Decoder stores information to decode picture
type Decoder struct {
data []byte
options *Options
config *Config
features container.Features
}
// statusError formats like v1 ("<prefix>: VP8_STATUS_...") and unwraps to
// the underlying *status.Error, which carries the libwebp status code and a
// more detailed message.
type statusError struct {
prefix string
err error
}
func (e *statusError) Error() string {
code := status.CodeOf(e.err)
if code == utils.Vp8StatusUserAbort {
// Cancelled through a context: say why.
return e.prefix + ": " + code.String() + ": " + e.err.Error()
}
return e.prefix + ": " + code.String()
}
func (e *statusError) Unwrap() error { return e.err }
// NewDecoder reads the picture from r and checks its headers like
// GetFeatures; the Decode methods decode the pixels. It reads r to EOF, so
// bound the size of untrusted inputs (http.MaxBytesReader, io.LimitReader).
//
// Only an input that is not a valid WebP file may be read in part: when r
// delivers it in pieces (a network body, a bufio.Reader), reading stops as
// soon as the bytes read so far show it (a JPEG or PNG after its first 12
// bytes, a broken header soon after it), with the error that reading all of
// r would give, unless r would have failed later on. A regular file is
// read whole unless its first 12 bytes show it; an input already in memory
// (bytes.Reader, bytes.Buffer) is copied whole, then checked. To decode a
// []byte without copying it, use NewDecoderBytes.
func NewDecoder(r io.Reader, options *Options) (d *Decoder, err error) {
// webp.DecodeContext and DecodeIntoContext pass their context inside
// the reader.
var ctx context.Context
if cr, ok := r.(*ctxio.Reader); ok {
ctx, r = cr.Ctx, cr.R
}
data, invalid, err := readAll(ctx, r)
if err == nil {
d, err = newDecoder(data, invalid, options)
}
if err != nil {
// The Read that ended the input (with io.EOF, another error of r,
// or bytes that show it invalid) may have raced with ctx: once ctx
// is done, its error is the one returned, as readAll would have
// returned it before that Read.
if cerr := canceled(ctx); cerr != nil {
err = cerr
}
if _, ok := err.(*abortError); ok {
// Cancelled while reading: report it like a decode cancelled
// later on.
return nil, &statusError{prefix: "cannot decode picture", err: err}
}
return nil, err
}
return d, nil
}
// NewDecoderBytes is NewDecoder for a picture already in memory. It checks
// data like NewDecoder checks the bytes it reads, with the same errors, but
// the Decoder then uses data itself instead of a copy: NewDecoder copies
// its whole input, which is most of what a DecodeInto into a large enough
// image still allocates.
//
// The Decoder never writes to data (nor past its length), but reads it
// again on every decode (Decode, DecodeInto, DecodeYCbCr and their
// variants), so data must not be modified while the Decoder is in use,
// until the last of these calls has returned; a change during a call is
// also a data race. DecodeInto does not write to data either when its dst
// shares memory with it: only the bytes of dst.Pix before data are used,
// and a new buffer is allocated if they are too few. Several Decoders may read the same data at once, on any
// goroutines. Once they are done, data may be reused, for example for the
// next picture: decoded images never share memory with data, and nothing
// but the Decoders refer to it.
func NewDecoderBytes(data []byte, options *Options) (*Decoder, error) {
// The full slice expression keeps the Decoder off the spare capacity
// of data, which the caller may be using.
return newDecoder(data[:len(data):len(data)], nil, options)
}
// newDecoder returns the Decoder of data, checking it like GetFeatures.
// invalid is nil, or the error of container.GetFeatures on the whole input
// when readAll stopped reading it early (data is then the part read).
func newDecoder(data []byte, invalid error, options *Options) (d *Decoder, err error) {
if len(data) == 0 {
return nil, errors.New("data is empty")
}
if options == nil {
options = &Options{}
}
d = &Decoder{data: data, options: options}
if d.config, err = d.options.GetConfig(); err != nil {
return nil, err
}
// получаем WebPBitstreamFeatures
if invalid == nil {
d.features, invalid = container.GetFeatures(d.data)
}
if invalid != nil {
return nil, &statusError{prefix: "cannot fetch features", err: invalid}
}
return d, nil
}
// readAll reads r to EOF. When the size is known in advance (bytes.Reader,
// bytes.Buffer, strings.Reader, regular files) the buffer is allocated once.
// Otherwise (bufio.Reader as used by image.Decode, network bodies) the size
// declared in the RIFF header is used only as a growth target: the first
// allocation is at most initialReadSize and the buffer then grows by at most
// readGrowth times the bytes actually received, so a short input with a
// lying header costs at most a few times its own size.
//
// Reading stops before EOF once the bytes read so far are enough for
// container.GetFeaturesPrefix to reject the input. invalid is then its
// error, which is the error of container.GetFeatures on the whole input, so
// that a stream that is not WebP is neither read nor buffered whole. An
// input already in memory (a reader with a Len method) is copied whole;
// the first 12 bytes of a regular file are read and checked before the
// buffer for the whole file is allocated.
//
// ctx (nil if reading cannot be cancelled) is checked before each Read and
// each allocation: once it is done, readAll returns its abortError without
// reading or allocating anything more.
func readAll(ctx context.Context, r io.Reader) (data []byte, invalid, err error) {
const maxHint = 1 << 30
n, file := 0, false
switch v := r.(type) {
case interface{ Len() int }:
n = v.Len()
case *os.File:
if fi, err := v.Stat(); err == nil && fi.Mode().IsRegular() && fi.Size() < maxHint {
n, file = int(fi.Size()), true
}
}
if err := canceled(ctx); err != nil {
return nil, nil, err
}
if !file && n > 0 && n < maxHint {
// Already in memory: NewDecoder checks the copy next.
return readFull(ctx, r, make([]byte, 0, n+1), n, riffHeaderSize)
}
// A file or a stream: read the RIFF header first, like io.ReadFull.
var hdr [riffHeaderSize]byte
m := 0
var rerr error
for m < len(hdr) && rerr == nil {
if rerr = canceled(ctx); rerr == nil {
var k int
k, rerr = r.Read(hdr[m:])
m += k
}
}
if m < len(hdr) {
// A short header is the whole input, also when r reports it with
// io.ErrUnexpectedEOF (a gzip.Reader of a cut stream), as it was
// when io.ReadFull read it.
if rerr == io.EOF || rerr == io.ErrUnexpectedEOF {
return hdr[:m:m], nil, nil
}
return nil, nil, rerr
}
if err := canceled(ctx); err != nil {
return nil, nil, err
}
riff := string(hdr[0:4]) == "RIFF" && string(hdr[8:12]) == "WEBP"
riffSize := binary.LittleEndian.Uint32(hdr[4:])
hint, size := 0, 0
switch {
case file:
hint, size = n, n+1
case riff:
hint = int(min(int64(riffSize)+8, maxHint))
fallthrough
default:
size = min(max(hint, riffHeaderSize), initialReadSize) + 1
}
// In a RIFF file chunks follow: a RIFF header whose size is in range
// shows nothing more, so the checks start after the next Read. A RIFF
// size out of range is checked at once, like any other header, which
// may show that the input is not WebP (a JPEG, a PNG): before the
// buffer is allocated, unless it is the whole input (see readFull). A
// RIFF size out of range fails GetFeatures whatever follows, also when
// these 12 bytes are the whole input.
check := 2 * riffHeaderSize
if riff && !container.ValidRIFFSize(riffSize) || !riff && hint != riffHeaderSize {
_, done, ferr := container.GetFeaturesPrefix(hdr[:])
switch {
case !done:
case ferr != nil:
return hdr[:], ferr, nil
default:
check = math.MaxInt
}
}
b := make([]byte, 0, size)
b = append(b, hdr[:]...)
return readFull(ctx, r, b, hint, check)
}
const (
// riffHeaderSize is the size of the RIFF header ("RIFF", size, "WEBP").
riffHeaderSize = 12
// initialReadSize bounds the first allocation for readers of unknown size.
initialReadSize = 64 << 10
// readGrowth bounds each buffer growth relative to the bytes read so far.
readGrowth = 4
)
// readFull appends the rest of r to b. hint is the expected total length
// (0 if unknown): growth aims at hint+1 so that a truthful header needs only
// a few allocations, but never exceeds readGrowth times the data received.
// One spare byte of capacity lets the final read observe io.EOF without
// growing the buffer.
//
// From len(b) >= check on, the bytes read so far go through
// container.GetFeaturesPrefix each time their length has doubled, until its
// result is final: the checks cost at most about two parses of the headers.
// None is made at len(b) == hint, where the input is presumably complete
// and NewDecoder checks all of it next.
func readFull(ctx context.Context, r io.Reader, b []byte, hint, check int) (data []byte, invalid, err error) {
for {
if len(b) >= check && len(b) != hint {
_, done, ferr := container.GetFeaturesPrefix(b)
switch {
case !done:
check = 2 * len(b)
case ferr != nil:
return b, ferr, nil
default:
// Valid headers: the rest is the image payload.
check = math.MaxInt
}
}
if err := canceled(ctx); err != nil {
return b, nil, err
}
if len(b) == cap(b) {
want := 2 * cap(b)
if hint >= len(b) {
want = min(hint+1, readGrowth*len(b))
}
nb := make([]byte, len(b), max(want, len(b)+512))
copy(nb, b)
b = nb
// The allocation may have taken a while.
if err := canceled(ctx); err != nil {
return b, nil, err
}
}
m, err := r.Read(b[len(b):cap(b)])
b = b[:len(b)+m]
if err == io.EOF {
return b, nil, nil
}
if err != nil {
return b, nil, err
}
}
}
// Decode decodes the picture into a new *image.NRGBA. To decode many
// pictures, use DecodeInto with one image for all of them: the output is
// nearly all of a decode's memory (4 bytes per pixel), and reusing it
// removes most of the garbage collector's work.
func (d *Decoder) Decode() (image.Image, error) {
img, err := d.decode(call{})
if err != nil {
return nil, &statusError{prefix: "cannot decode picture", err: err}
}
return img, nil
}
// call holds the per-call arguments of the Decode variants.
type call struct {
// dst lends its pixel memory to the output image (DecodeInto); nil
// allocates a new image.
dst *image.NRGBA
// ctx cancels the decode (DecodeContext); nil if it cannot be
// cancelled.
ctx context.Context
}
func (d *Decoder) decode(c call) (*image.NRGBA, error) {
if err := canceled(c.ctx); err != nil {
return nil, err
}
parsed, err := container.Parse(d.data)
if err != nil {
return nil, err
}
if parsed.HasAnimation {
return nil, status.Unsupported("animated WebP is not supported")
}
if parsed.VP8L != nil {
return d.decodeLossless(parsed, c)
}
return d.decodeLossy(parsed, c)
}
// GetFeatures return information about picture: width, height ...
func (d *Decoder) GetFeatures() utils.BitstreamFeatures {
return utils.BitstreamFeatures{
Width: d.features.Width,
Height: d.features.Height,
HasAlpha: d.features.HasAlpha,
HasAnimation: d.features.HasAnimation,
Format: d.features.Format,
}
}
func (d *Decoder) decodeLossless(parsed *container.Image, cl call) (*image.NRGBA, error) {
c := d.config
p := pipeline.Params{
SrcW: parsed.Width,
SrcH: parsed.Height,
Flip: c.Flip,
Premultiply: true,
Dst: cl.dst,
}
if c.UseCropping {
p.Crop = image.Rect(c.CropLeft, c.CropTop, c.CropLeft+c.CropWidth, c.CropTop+c.CropHeight)
}
if c.UseScaling {
p.ScaleW, p.ScaleH = c.ScaledWidth, c.ScaledHeight
}
sink, result, err := pipeline.NewSink(p)
if err != nil {
return nil, err
}
if err := vp8l.DecodeWithOptions(parsed.VP8L, cl.wrap(sink), &vp8l.Options{UseThreads: c.UseThreads}); err != nil {
return nil, err
}
return result(), nil
}
func (d *Decoder) decodeLossy(parsed *container.Image, cl call) (*image.NRGBA, error) {
c := d.config
w, h := parsed.Width, parsed.Height
crop := image.Rect(0, 0, w, h)
if c.UseCropping {
crop = pipeline.SnapCropForYUV(image.Rect(c.CropLeft, c.CropTop, c.CropLeft+c.CropWidth, c.CropTop+c.CropHeight))
if crop.Empty() || crop.Min.X < 0 || crop.Min.Y < 0 || crop.Max.X > w || crop.Max.Y > h {
return nil, status.InvalidParam("crop rectangle outside of the frame")
}
}
cw, ch := crop.Dx(), crop.Dy()
opts := vp8.Options{
BypassFiltering: c.BypassFiltering,
NoFancyUpsampling: c.NoFancyUpsampling,
DitheringStrength: c.DitheringStrength,
UseThreads: c.UseThreads,
}
var (
sw, sh int
sink pipeline.Sink
result func() *image.NRGBA
err error
)
if c.UseScaling {
var ok bool
if sw, sh, ok = resample.ScaledDimensions(cw, ch, c.ScaledWidth, c.ScaledHeight); !ok {
return nil, status.InvalidParam("invalid scaled dimensions")
}
// libwebp (WebPIoInitFromOptions) skips the loop filter for large
// downscaling ratios.
if sw < w*3/4 && sh < h*3/4 {
opts.BypassFiltering = true
}
}
if sink, result, err = pipeline.NewSink(pipeline.Params{SrcW: cw, SrcH: ch, ScaleW: sw, ScaleH: sh, Flip: c.Flip, Dst: cl.dst}); err != nil {
return nil, err
}
// The alpha plane is decoded incrementally, as the VP8 decoder emits
// rows (like libwebp's VP8DecompressAlphaRows), so that a truncated or
// broken VP8 stream never pays for a full-frame alpha decode.
var la *lazyAlpha
if parsed.ALPH != nil {
la = newLazyAlpha(parsed.ALPH, w, h, crop, c)
defer la.release()
opts.Alpha = la.get
}
switch {
case c.UseScaling:
ys, ok := sink.(pipeline.YUVSink)
if !ok {
return nil, status.InvalidParam("scaling sink does not accept YUV")
}
ad := &yuvAdapter{sink: ys, alpha: la, top: crop.Min.Y, left: crop.Min.X, alphaStride: w, ctx: cl.ctx}
opts.Alpha = nil
err = vp8.DecodeYUV(parsed.VP8, &opts, &crop, ad)
case cw == w && ch == h:
err = vp8.Decode(parsed.VP8, nil, &opts, cl.wrap(sink))
default:
err = vp8.DecodeRegion(parsed.VP8, nil, &opts, crop, cl.wrap(sink))
}
if err != nil {
return nil, err
}
return result(), nil
}
// yuvAdapter forwards the Y'CbCr rows of the VP8 decoder (and the matching
// alpha rows) to a scaling sink, which rescales the planes separately like
// libwebp.
type yuvAdapter struct {
sink pipeline.YUVSink
alpha *lazyAlpha // nil for opaque images
top, left int // crop origin in the alpha plane
alphaStride int
ctx context.Context // DecodeContext, may be nil
}
func (a *yuvAdapter) PutYUV(y, n int, ys []byte, yStride int, us, vs []byte, uvStride int) error {
if err := canceled(a.ctx); err != nil {
return err
}
var ap []byte
if a.alpha != nil {
plane, base, err := a.alpha.get(a.top+y, a.top+y+n)
if err != nil {
return err
}
ap = plane[(a.top+y-base)*a.alphaStride+a.left:]
}
return a.sink.CommitYUV(y, n, ys, yStride, us, vs, uvStride, ap, a.alphaStride)
}
func (a *yuvAdapter) NeedRows() int { return a.sink.NeedRows() }
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package decoder
import (
"image"
"unsafe"
)
// DecodeInto decodes the picture like Decode, but into dst, so that a caller
// decoding many pictures can reuse one output buffer instead of allocating
// (and having the garbage collector reclaim) a new image per picture. It
// returns dst.
//
// dst is treated as raw memory: its previous Rect and Stride are ignored.
// For an output of w x h pixels (after cropping and scaling), when
// cap(dst.Pix) >= 4*w*h the pixels are written to dst.Pix[:4*w*h] without
// allocating or clearing anything; otherwise a new buffer is allocated.
// When dst.Pix (up to its capacity) shares memory with the data of
// NewDecoderBytes, only its bytes before data count, so that data is never
// written to. On
// success dst.Pix is set to that w x h image (keeping the capacity of a
// reused buffer), dst.Stride to 4*w and dst.Rect to (0, 0)-(w, h); crop,
// scale and flip options apply as for Decode. Do not pass a SubImage: its
// Pix starts at the sub-image origin, so the decoded pixels would overwrite
// the rest of the parent image.
//
// On error the dst fields are left unchanged, but the bytes of the memory
// dst.Pix refers to (up to its capacity) may have been partially
// overwritten.
//
// The returned image is dst itself: decoding into dst again overwrites it.
// dst must not be used by other goroutines during the call. A nil dst
// makes DecodeInto behave like Decode (a new image is allocated).
func (d *Decoder) DecodeInto(dst *image.NRGBA) (*image.NRGBA, error) {
return d.decodeInto(call{dst: dst})
}
func (d *Decoder) decodeInto(c call) (*image.NRGBA, error) {
dst := c.dst
if dst != nil {
if n := spare(dst.Pix, d.data); n < cap(dst.Pix) {
// The decode reads data while it writes the pixels, and must
// not overwrite the input of NewDecoderBytes: lend it only the
// bytes of dst before data (a new buffer is allocated if they
// are too few).
c.dst = &image.NRGBA{Pix: dst.Pix[:0:n]}
}
}
img, err := d.decode(c)
if err != nil {
return nil, &statusError{prefix: "cannot decode picture", err: err}
}
if dst == nil {
return img, nil
}
if c.dst != dst && cap(c.dst.Pix) >= len(img.Pix) {
// Written in place: keep the whole capacity of dst.Pix.
img.Pix = dst.Pix[:len(img.Pix)]
}
dst.Pix, dst.Stride, dst.Rect = img.Pix, img.Stride, img.Rect
return dst, nil
}
// spare returns how many bytes at the start of p, up to its capacity, can
// be written without writing to data: cap(p) if they do not share memory.
// Only NewDecoderBytes gives a Decoder memory that a caller can also pass
// to DecodeInto; NewDecoder decodes its own copy of the input.
func spare(p, data []byte) int {
p = p[:cap(p)]
if len(p) == 0 || len(data) == 0 {
return len(p)
}
p0, p1 := uintptr(unsafe.Pointer(&p[0])), uintptr(unsafe.Pointer(&p[len(p)-1]))
d0, d1 := uintptr(unsafe.Pointer(&data[0])), uintptr(unsafe.Pointer(&data[len(data)-1]))
switch {
case d1 < p0 || p1 < d0: // no overlap
return len(p)
case p0 < d0: // data starts inside p
return int(d0 - p0)
}
return 0
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package decoder
import (
"image"
)
// Options specifies webp decoding parameters.
//
// Crop uses libwebp's convention: Crop.Min is the top-left corner
// (crop_left, crop_top) and Crop.Max holds the crop WIDTH and HEIGHT
// (crop_width, crop_height), not the bottom-right corner. Cropping is enabled
// when both Crop.Max.X and Crop.Max.Y are positive. For lossy images the
// corner is rounded down to even coordinates, as libwebp does.
//
// Scale.Max holds the output width and height; scaling is enabled when both
// are positive. Scaling is applied after cropping.
type Options struct {
BypassFiltering bool
NoFancyUpsampling bool
Crop image.Rectangle
Scale image.Rectangle
UseThreads bool
Flip bool
DitheringStrength int
AlphaDitheringStrength int
}
// Config is the decoding configuration built by Options.GetConfig. It mirrors
// libwebp's WebPDecoderOptions field for field (C int flags are bools). In v1
// GetConfig returned the cgo type *C.WebPDecoderConfig; v2 returns this pure
// Go equivalent.
type Config struct {
// BypassFiltering skips the in-loop deblocking filter (lossy).
BypassFiltering bool
// NoFancyUpsampling uses point-sampled chroma upsampling (lossy).
NoFancyUpsampling bool
// UseCropping enables cropping to the CropWidth x CropHeight rectangle
// whose top-left corner is (CropLeft, CropTop).
UseCropping bool
CropLeft int
CropTop int
CropWidth int
CropHeight int
// UseScaling enables rescaling of the (cropped) picture to
// ScaledWidth x ScaledHeight.
UseScaling bool
ScaledWidth int
ScaledHeight int
// UseThreads decodes with helper goroutines from the process-wide
// budget of GOMAXPROCS-1 helpers shared by all concurrent Decode and
// Encode calls:
// - lossy pictures of at least 1024 macroblocks (about 512x512):
// one helper reconstructs, filters and emits batches of macroblock
// rows while the calling goroutine parses the next ones, and parses
// the prediction modes ahead when it has nothing else to do; when
// that helper is the slower stage, a second one takes over the
// conversion to RGBA;
// - lossy pictures with alpha whose alpha rows down to the bottom of
// the output region 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
// calling goroutine entropy-decodes while one helper applies the
// inverse transforms and writes the output rows (libwebp ignores
// use_threads for lossless pictures; this is a go-webp extension).
// Smaller pictures, or a call that finds no free helper slot, decode on
// the calling goroutine. The output is identical either way. A panic
// in a helper is re-raised on the calling goroutine.
UseThreads bool
// DitheringStrength in [0, 100] dithers the chroma of lossy pictures.
DitheringStrength int
// Flip mirrors the output vertically.
Flip bool
// AlphaDitheringStrength in [0, 100] smooths quantized alpha planes.
AlphaDitheringStrength int
}
// GetConfig builds the decoder configuration (the equivalent of libwebp's
// WebPDecoderConfig options). A nil *Options yields the default
// configuration.
func (o *Options) GetConfig() (*Config, error) {
config := &Config{}
if o == nil {
return config, nil
}
config.BypassFiltering = o.BypassFiltering
config.NoFancyUpsampling = o.NoFancyUpsampling
// проверяем надо ли кропнуть
if o.Crop.Max.X > 0 && o.Crop.Max.Y > 0 {
config.UseCropping = true
config.CropLeft = o.Crop.Min.X
config.CropTop = o.Crop.Min.Y
config.CropWidth = o.Crop.Max.X
config.CropHeight = o.Crop.Max.Y
}
// проверяем надо ли заскейлить
if o.Scale.Max.X > 0 && o.Scale.Max.Y > 0 {
config.UseScaling = true
config.ScaledWidth = o.Scale.Max.X
config.ScaledHeight = o.Scale.Max.Y
}
config.UseThreads = o.UseThreads
config.DitheringStrength = o.DitheringStrength
config.Flip = o.Flip
config.AlphaDitheringStrength = o.AlphaDitheringStrength
return config, nil
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package decoder
import (
"image"
"github.com/kolesa-team/go-webp/v2/internal/container"
"github.com/kolesa-team/go-webp/v2/internal/pipeline"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/internal/vp8"
)
// DecodeYCbCr decodes a lossy picture without alpha to its Y'CbCr 4:2:0
// planes, without converting them to RGB: the output takes 1.5 bytes per
// pixel instead of 4, and decoding is faster. The planes hold the samples
// of the VP8 stream as they are (BT.601 "limited range"; libwebp's
// WebPDecodeYUV output), like the *image.YCbCr of golang.org/x/image/webp,
// so the colors that image.YCbCr's color model computes (full-range JFIF)
// differ slightly from the RGB that Decode returns, which also upsamples
// the chroma smoothly ("fancy upsampling") instead of repeating it.
//
// Options: Crop (with its top-left corner rounded down to even
// coordinates, as for Decode), Flip (each plane is mirrored separately,
// like libwebp does for Y'CbCr output), BypassFiltering, DitheringStrength
// and UseThreads apply; NoFancyUpsampling has no effect. Scale is not
// supported (VP8_STATUS_INVALID_PARAM).
//
// Pictures with alpha (use DecodeNYCbCrA), lossless pictures (they have no
// Y'CbCr form; use Decode) and animations are refused with
// VP8_STATUS_UNSUPPORTED_FEATURE: check GetFeatures first.
func (d *Decoder) DecodeYCbCr() (*image.YCbCr, error) {
s, err := d.decodeYUV(false)
if err != nil {
return nil, &statusError{prefix: "cannot decode picture", err: err}
}
return s.yuv, nil
}
// DecodeNYCbCrA is DecodeYCbCr for lossy pictures with or without alpha: the
// alpha plane (the decoded ALPH chunk, with AlphaDitheringStrength applied;
// all 0xff for an opaque picture) comes with the Y'CbCr 4:2:0 planes, 2.5
// bytes per pixel in all. Lossless pictures are refused like by
// DecodeYCbCr.
func (d *Decoder) DecodeNYCbCrA() (*image.NYCbCrA, error) {
s, err := d.decodeYUV(true)
if err != nil {
return nil, &statusError{prefix: "cannot decode picture", err: err}
}
return s.nyuv, nil
}
func (d *Decoder) decodeYUV(withAlpha bool) (*ycbcrSink, error) {
parsed, err := container.Parse(d.data)
if err != nil {
return nil, err
}
switch {
case parsed.HasAnimation:
return nil, status.Unsupported("animated WebP is not supported")
case parsed.VP8L != nil:
return nil, status.Unsupported("lossless pictures have no Y'CbCr form")
case parsed.ALPH != nil && !withAlpha:
return nil, status.Unsupported("the picture has alpha: decode it with DecodeNYCbCrA")
}
c := d.config
if c.UseScaling {
return nil, status.InvalidParam("scaling is not supported for Y'CbCr output")
}
w, h := parsed.Width, parsed.Height
crop := image.Rect(0, 0, w, h)
if c.UseCropping {
crop = pipeline.SnapCropForYUV(image.Rect(c.CropLeft, c.CropTop, c.CropLeft+c.CropWidth, c.CropTop+c.CropHeight))
if crop.Empty() || crop.Min.X < 0 || crop.Min.Y < 0 || crop.Max.X > w || crop.Max.Y > h {
return nil, status.InvalidParam("crop rectangle outside of the frame")
}
}
s := &ycbcrSink{
w: crop.Dx(), h: crop.Dy(),
flip: c.Flip,
withAlpha: withAlpha,
top: crop.Min.Y, left: crop.Min.X, alphaStride: w,
}
if parsed.ALPH != nil {
s.alpha = newLazyAlpha(parsed.ALPH, w, h, crop, c)
defer s.alpha.release()
}
opts := vp8.Options{
BypassFiltering: c.BypassFiltering,
DitheringStrength: c.DitheringStrength,
UseThreads: c.UseThreads,
}
if err := vp8.DecodeYUV(parsed.VP8, &opts, &crop, s); err != nil {
return nil, err
}
if s.yuv == nil {
return nil, status.NotEnoughData("no rows decoded")
}
return s, nil
}
// ycbcrSink copies the Y'CbCr rows of the VP8 decoder (and the alpha rows)
// into an *image.YCbCr or *image.NYCbCrA, allocated with the first rows.
type ycbcrSink struct {
w, h int // output size
flip bool
withAlpha bool
alpha *lazyAlpha // nil for opaque pictures
top, left int // crop origin in the alpha plane
alphaStride int
yuv *image.YCbCr
nyuv *image.NYCbCrA // nil without alpha output; yuv is &nyuv.YCbCr
}
// PutYUV implements vp8.YUVSink.
func (s *ycbcrSink) PutYUV(y, n int, ys []byte, yStride int, us, vs []byte, uvStride int) error {
var aplane []byte
abase := 0
if s.alpha != nil {
p, base, err := s.alpha.get(s.top+y, s.top+y+n)
if err != nil {
return err
}
aplane, abase = p, base
}
if s.yuv == nil {
r := image.Rect(0, 0, s.w, s.h)
if s.withAlpha {
s.nyuv = image.NewNYCbCrA(r, image.YCbCrSubsampleRatio420)
s.yuv = &s.nyuv.YCbCr
} else {
s.yuv = image.NewYCbCr(r, image.YCbCrSubsampleRatio420)
}
}
img := s.yuv
w := s.w
for j := range n {
copy(img.Y[s.row(y+j, s.h)*img.YStride:][:w], ys[j*yStride:][:w])
}
cw, ch := (w+1)/2, (s.h+1)/2
for k := range (n + 1) / 2 {
o := s.row(y/2+k, ch) * img.CStride
copy(img.Cb[o:][:cw], us[k*uvStride:][:cw])
copy(img.Cr[o:][:cw], vs[k*uvStride:][:cw])
}
if s.nyuv == nil {
return nil
}
a := s.nyuv
for j := range n {
dst := a.A[s.row(y+j, s.h)*a.AStride:][:w]
if aplane == nil {
for i := range dst {
dst[i] = 0xff
}
} else {
copy(dst, aplane[(s.top+y+j-abase)*s.alphaStride+s.left:][:w])
}
}
return nil
}
// row returns where row r of a plane of h rows goes.
func (s *ycbcrSink) row(r, h int) int {
if s.flip {
return h - 1 - r
}
return r
}
// NeedRows implements vp8.YUVSink.
func (s *ycbcrSink) NeedRows() int { return s.h }
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package encoder
// Alpha plane coding for lossy images (the ALPH chunk).
// Algorithm adapted from libwebp (BSD-3-Clause): src/enc/alpha_enc.c.
import (
"errors"
"image"
"sync"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/alpha"
"github.com/kolesa-team/go-webp/v2/internal/bufpool"
"github.com/kolesa-team/go-webp/v2/internal/vp8enc"
"github.com/kolesa-team/go-webp/v2/internal/vp8lenc"
"github.com/kolesa-team/go-webp/v2/internal/workers"
)
const (
alphaFilterFast = 1 // libwebp's WEBP_FILTER_FAST alpha_filtering value
// GetFilterMap thresholds (libwebp).
minColorsForFilterNone = 16
maxColorsForFilterNone = 192
// minParallelAlphaPixels is the smallest picture whose (compressed)
// alpha plane is worth a helper goroutine: about a millisecond of work
// even at method 0. It is also the smallest one whose candidate
// filters are coded concurrently.
minParallelAlphaPixels = 1 << 16
)
// pairFrameHelpers is the number of helpers of the VP8 frame's coding
// passes that the second goroutine of an alpha pair leaves to the frame at
// least while it is coded (see startAlpha): beyond, the passes gain little
// from one more helper (the frame of the 3000x2000 logo at method 4 takes
// 23.7 ms on 5 goroutines, 21.9 on 6 and 19.2 on 8; that of a 960x1280
// photo 19.9, 19.6 and 18.8 ms), while the pair halves the time of an
// alpha plane with two candidate filters.
const pairFrameHelpers = 4
// maxAlphaPairPixels is the largest picture (in pixels) whose candidate
// filters are coded two at a time with ThreadLevel. Each candidate in
// flight holds its own lossless working set (about 13 bytes per pixel, 17
// when the parallel match search of 256K pixels or more runs), so, like
// the candidate configurations of lossless level 9, the candidates of
// larger pictures are coded one after the other. A variable for the tests.
var maxAlphaPairPixels = 8 << 20
// errAlphaInterrupted is returned by encodeAlpha when its interrupt hook
// asked it to stop between two candidate filters.
var errAlphaInterrupted = errors.New("alpha encoding interrupted")
// The encoders, as variables so that tests can inject failures.
var (
vp8Encode = vp8enc.EncodeWithHeadroom
alphaEncode = encodeAlpha
)
// alphaCandidateHook, if not nil, runs before the lossless coding of each
// candidate filter, on the goroutine that codes it and with its interrupt
// hook; an error it returns fails the candidate. Tests only.
var alphaCandidateHook func(filter int, interrupt func() bool) error
// planePool holds the alpha planes (one byte per pixel) of encodeAlpha and
// the alpha snapshots of *image.NYCbCrA sources. It is a bufpool pool
// rather than a sync.Pool: the planes of large pictures (6 MB for
// 3000x2000) then survive the garbage collections that run while the VP8
// frame is being encoded.
var planePool bufpool.Pool[byte]
// alphaSource holds the alpha samples of a w x h picture for encodeAlpha:
// the A bytes of img, or, if img is nil, plane, w bytes per row (the
// snapshot that NewEncoder takes of an *image.NYCbCrA's alpha).
type alphaSource struct {
img *image.NRGBA
plane []byte
w, h int
}
// nrgbaAlpha returns the alpha samples of img.
func nrgbaAlpha(img *image.NRGBA) alphaSource {
return alphaSource{img: img, w: img.Rect.Dx(), h: img.Rect.Dy()}
}
// encodeAlpha returns the ALPH chunk payload (header byte included) of the
// alpha samples src, following libwebp's EncodeAlpha. interrupt, if not
// nil, is polled between the passes; the encode stops when it returns true.
// gates hold back helper goroutines that the budget would allow (see
// startAlpha).
func encodeAlpha(src alphaSource, c *Config, interrupt func() bool, gates alphaGates) ([]byte, error) {
method := c.AlphaCompression
if method > alpha.CompressionLossless {
return nil, errors.New("invalid alpha compression method")
}
quality := c.AlphaQuality
effort := c.Method
filter := c.AlphaFiltering
if method == alpha.CompressionNone {
filter = alpha.FilterNone
}
w, h := src.w, src.h
// The plane is quantized and filtered in place: work on a copy.
plane := planePool.Get(w * h)
defer planePool.Put(plane)
if img := src.img; img != nil {
for y := 0; y < h; y++ {
row := img.Pix[img.PixOffset(img.Rect.Min.X, img.Rect.Min.Y+y):][:4*w]
dst := plane[y*w : y*w+w]
for x := range dst {
dst[x] = row[4*x+3]
}
}
} else {
copy(plane, src.plane[:w*h])
}
reduceLevels := quality < 100
if reduceLevels {
if err := alpha.QuantizeLevels(plane, w, h, w, alpha.AlphaLevels(quality)); err != nil {
return nil, err
}
}
// Candidate filters (libwebp's GetFilterMap).
var tryMap uint
switch filter {
case alpha.FilterNone:
tryMap = 1 << alpha.FilterNone
case alphaFilterFast:
n := numColors(plane)
f := alpha.FilterNone
if n > minColorsForFilterNone {
f = alpha.EstimateBestFilter(plane, w, h, w)
}
tryMap = 1 << uint(f)
if effort > 3 || n > maxColorsForFilterNone {
tryMap |= 1 << alpha.FilterNone
}
default: // best: try all
tryMap = 1<<alpha.FilterNone | 1<<alpha.FilterHorizontal | 1<<alpha.FilterVertical | 1<<alpha.FilterGradient
}
// Like the lossless encoder, the alpha plane ignores ThreadLevel with
// LowMemory: no second working set for the pair, no 4 bytes per pixel
// for the parallel match search.
threads := c.ThreadLevel && !c.LowMemory
a := alphaCandidates{plane: plane, w: w, h: h, method: method, effort: effort, quality: quality, threads: threads, gates: gates}
for f := alpha.FilterNone; tryMap != 0; f, tryMap = f+1, tryMap>>1 {
if tryMap&1 != 0 {
a.filters[a.n] = f
a.n++
}
}
if reduceLevels {
a.pre = alpha.PreprocessingLevels
}
// With ThreadLevel, two candidates at a time, except at the brute-force
// level of the lossless encoder (method 6 with AlphaQuality 100, see
// vp8lenc.AlphaEncoder), which then encodes two configurations at a
// time itself: either way at most two lossless working sets are in
// flight, as in lossless level 9.
bruteForce := effort >= 6 && quality >= 100
if threads && method == alpha.CompressionLossless && a.n > 1 && !bruteForce &&
w*h >= minParallelAlphaPixels && w*h <= maxAlphaPairPixels {
return codePair(a, interrupt)
}
k := 0
best, _, err := a.code(func() (int, bool) { k++; return k - 1, k <= a.n }, interrupt)
return best, err
}
// alphaCandidates are the candidate filterings of an alpha plane, of which
// encodeAlpha keeps the smallest coded one.
type alphaCandidates struct {
plane []byte // the (quantized) plane, w*h bytes; only read while coding
w, h int
filters [4]int // the candidate filters (n of them), in increasing order
n int
method int // alpha.CompressionNone or alpha.CompressionLossless
effort int // Config.Method
quality int // Config.AlphaQuality
pre int // the header's pre-processing field
threads bool // ThreadLevel (without LowMemory), for the lossless encoder
gates alphaGates
}
// alphaGates hold back helper goroutines of the alpha plane that the
// budget would allow; a nil gate allows them all.
type alphaGates struct {
// pair must allow the second goroutine of a pair: of codePair, and of
// the configurations of the brute-force level (see
// vp8lenc.AlphaEncoder.PairGate).
pair func() bool
// stage must allow each helper of the parallel stages of the lossless
// encodes.
stage func() bool
// starter, if not nil, holds the function that starts the helper of
// codePair while it may still start: the gates' owner calls it when
// they open, so that the helper starts then rather than at the next
// poll of the caller's candidates (tens of milliseconds later on a 6 MP
// plane).
starter *atomic.Pointer[func()]
}
// codePair is a.code with ThreadLevel: it returns the ALPH payload of the
// smallest candidate, header byte included (the first one in filter order
// on ties, as in libwebp), coding two candidates at a time when the
// process-wide budget has a free slot. The caller and a helper goroutine
// each claim the next candidate not taken yet (the fast filtering of
// methods 4-6 tries two, the estimated filter and none, unless the
// estimate is none) and keep their smallest stream, and the two are
// compared the same way, so the result is the sequential one. The price
// is a second lossless working set while both code (see
// maxAlphaPairPixels).
//
// The helper starts at once if the budget has a free slot and the pair
// gate allows it, else when both do at the first poll of the caller's
// interrupt hook (at least once per lossless stage) or call of the gates'
// starter, while a candidate is left for it: with startAlpha's gates, once
// the VP8 frame no longer needs the slot. Until then, or when no slot ever
// frees, the caller codes the candidates itself.
//
// interrupt, if not nil, reaches the candidates of both goroutines. The
// first failure of either one (an error, an interruption or a panic) also
// stops the other, and is the one reported; a panic of the helper is
// re-raised on the caller once both have returned.
func codePair(a alphaCandidates, interrupt func() bool) ([]byte, error) {
var next atomic.Int64
claim := func() (int, bool) {
k := next.Add(1) - 1
return int(k), k < int64(a.n)
}
var failure atomic.Pointer[error]
fail := func(err error) { failure.CompareAndSwap(nil, &err) }
stop := func() bool { return failure.Load() != nil || interrupt != nil && interrupt() }
var (
helperBest []byte
helperK int
)
helper := func() error {
returned := false
defer func() {
if !returned {
// A panic (re-raised by Wait) or runtime.Goexit: stop the
// caller's candidates.
fail(errAlphaInterrupted)
}
}()
var err error
if helperBest, helperK, err = a.code(claim, stop); err != nil {
fail(err)
}
returned = true
return nil
}
// The helper's task, started by start (on the caller or on one of the
// helpers of its lossless encode, which poll its hook too) until the
// caller closes the pair.
var (
mu sync.Mutex
task *workers.Task
closed bool
waiting atomic.Bool // no helper yet, and one may still start
)
start := func() {
mu.Lock()
defer mu.Unlock()
switch {
case closed || task != nil:
case next.Load() >= int64(a.n):
waiting.Store(false) // every candidate is taken
case a.gates.pair == nil || a.gates.pair():
if task = workers.Spawn(helper); task != nil {
waiting.Store(false)
}
}
}
waiting.Store(true)
if a.gates.starter != nil {
a.gates.starter.Store(&start)
defer a.gates.starter.Store(nil)
}
start()
poll := func() bool {
if waiting.Load() {
start()
}
return stop()
}
join := func() *workers.Task {
mu.Lock()
defer mu.Unlock()
closed = true
return task
}
finished := false
defer func() {
if !finished {
// The caller is panicking: stop the helper and join it without
// raising its own panic over this one.
fail(errAlphaInterrupted)
if t := join(); t != nil {
t.Panicked()
}
}
}()
best, k, err := a.code(claim, poll)
if err != nil {
fail(err)
}
finished = true
if t := join(); t != nil {
t.Wait() // re-raises a panic of the helper
}
if p := failure.Load(); p != nil {
return nil, *p
}
if helperBest != nil && (best == nil || len(helperBest) < len(best) || len(helperBest) == len(best) && helperK < k) {
best = helperBest
}
return best, nil
}
// code codes the candidates handed out by claim (in increasing order) and
// returns the smallest ALPH payload among them, header byte included, with
// its candidate index (the lowest one on ties), or nil and -1 when claim
// handed out none.
func (a *alphaCandidates) code(claim func() (int, bool), interrupt func() bool) (best []byte, bestK int, err error) {
// One lossless encoder for all the candidates of this goroutine: its
// working buffers (hundreds of MB for large images) are allocated once.
lenc := vp8lenc.AlphaEncoder{Interrupt: interrupt, ThreadLevel: a.threads, PairGate: a.gates.pair, StageGate: a.gates.stage}
defer lenc.Release()
var filtered []byte
defer func() {
if filtered != nil {
planePool.Put(filtered)
}
}()
bestK = -1
for {
k, ok := claim()
if !ok {
return best, bestK, nil
}
if interrupt != nil && interrupt() {
return nil, -1, errAlphaInterrupted
}
f := a.filters[k]
if alphaCandidateHook != nil && a.method != alpha.CompressionNone {
if err = alphaCandidateHook(f, interrupt); err != nil {
return nil, -1, err
}
}
src := a.plane
if f != alpha.FilterNone {
if filtered == nil {
filtered = planePool.Get(len(a.plane))
}
alpha.Filter(f, a.plane, a.w, a.h, a.w, filtered, a.w)
src = filtered
}
m := a.method
data := src
var enc []byte
if m != alpha.CompressionNone {
if enc, err = lenc.Encode(src, a.w, a.h, a.w, a.effort, float32(a.quality)); err != nil {
return nil, -1, err
}
if len(enc) > len(src) {
// Compressed is larger than the source: store raw, as libwebp.
m = alpha.CompressionNone
} else {
data = enc
}
}
if best == nil || 1+len(data) < len(best) {
best = make([]byte, 1+len(data))
copy(best[1:], data)
best[0] = alpha.Header{Compression: m, Filter: f, PreProcessing: a.pre}.Byte()
bestK = k
}
// The stream has been copied: its buffer can hold the next one.
lenc.Recycle(enc)
}
}
// numColors counts the distinct values of an alpha plane.
func numColors(plane []byte) int {
var seen [256]bool
n := 0
for _, v := range plane {
if !seen[v] {
seen[v] = true
n++
}
}
return n
}
// alphaTask codes the alpha plane on a helper goroutine (see startAlpha).
type alphaTask struct {
task *workers.Task
// stop asks the helper to give up (the VP8 frame failed, or the call
// is returning).
stop atomic.Bool
// passHelpers counts the helpers the frame's coding pass in progress
// holds, and frameCoded is set once the frame is coded (see
// startAlpha); starter is the gates' starter.
passHelpers atomic.Int32
frameCoded atomic.Bool
starter atomic.Pointer[func()]
alph []byte // the result, written by the helper
}
// startAlpha starts coding the alpha samples src on a helper goroutine,
// like libwebp's alpha worker. It returns nil, and the caller must call
// encodeAlpha itself, when that is not worth it (raw or small alpha planes)
// or when the helper budget is exhausted. Otherwise the caller must call
// cancel (deferred), pass &passHelpers as the frame's
// vp8enc.Config.PassHelpers, call frameDone once the frame is coded and,
// to get the result, wait.
//
// frameHelpers is the number of helpers the VP8 frame's coding passes take
// at most (vp8enc.WavefrontHelpers). The passes take their helpers once
// each, when they start, so a slot the alpha plane holds then is lost to
// the frame for the whole pass: on a small budget (2 to 4 processors) a VP8
// frame that takes longer than the alpha plane would be coded on fewer
// goroutines, or on one, and the encode would be slower than with the
// alpha plane on one goroutine (1.5 times on a 960x1280 photo with a
// 400x400 transparent patch, at GOMAXPROCS 3). So until frameDone, the
// alpha plane starts a helper of its own only when, after it, the slots
// left free cover those the frame does not hold yet: all its helpers, or,
// for the second goroutine of a pair (which halves the alpha plane's time
// when it is the longer part), pairFrameHelpers of them. Once the frame is
// coded the alpha plane takes any free slot.
func startAlpha(src alphaSource, c *Config, interrupt func() bool, frameHelpers int) *alphaTask {
// Raw alpha is a copy and a filter: not worth a goroutine. Invalid
// methods are reported by the sequential path, which checks them first.
if c.AlphaCompression != alpha.CompressionLossless || src.w*src.h < minParallelAlphaPixels {
return nil
}
t := &alphaTask{}
stop := func() bool { return t.stop.Load() || interrupt != nil && interrupt() }
gates := t.gates(frameHelpers)
t.task = workers.Spawn(func() error {
var err error
t.alph, err = alphaEncode(src, c, stop, gates)
return err
})
if t.task == nil {
return nil
}
return t
}
// gates returns the gates of the alpha plane coded alongside a VP8 frame
// whose coding passes take frameHelpers helpers at most (see startAlpha).
func (t *alphaTask) gates(frameHelpers int) alphaGates {
if frameHelpers <= 0 {
return alphaGates{}
}
// The slots left free after one more helper must cover those of the
// frame's n helpers that it does not hold yet.
leaves := func(n int) bool {
return t.frameCoded.Load() || workers.Limit()-workers.InUse() > max(0, n-int(t.passHelpers.Load()))
}
pairNeed := min(frameHelpers, pairFrameHelpers)
return alphaGates{
pair: func() bool { return leaves(pairNeed) },
stage: func() bool { return leaves(frameHelpers) },
starter: &t.starter,
}
}
// frameDone tells the helper that the VP8 frame is coded: its slots are
// free for the alpha plane, and the second goroutine of its candidate
// pair, if it is waiting for one, starts now.
func (t *alphaTask) frameDone() {
t.frameCoded.Store(true)
// (codePair publishes its starter before it first tries to start the
// helper: either it sees frameCoded, or the starter is seen here.)
if start := t.starter.Load(); start != nil {
(*start)()
}
}
// wait joins the helper and returns its result, re-raising its panic on the
// calling goroutine. If abandon is set (the result is not needed), the
// helper is asked to stop first.
func (t *alphaTask) wait(abandon bool) ([]byte, error) {
if abandon {
t.stop.Store(true)
}
err := t.task.Wait()
return t.alph, err
}
// cancel asks the helper to stop and waits until it has returned, without
// re-raising its panic: deferred by the caller so that no helper outlives
// the call, even when the caller panics.
func (t *alphaTask) cancel() {
t.stop.Store(true)
<-t.task.Done()
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package encoder
import (
"encoding/binary"
"image"
"image/color"
"math"
"math/bits"
"runtime"
"slices"
"github.com/kolesa-team/go-webp/v2/internal/bufpool"
"github.com/kolesa-team/go-webp/v2/internal/vp8enc"
)
// toNRGBA returns src as an *image.NRGBA. An *image.NRGBA is returned as is
// (shared, as in v1); every other image is copied (see convertNRGBA), so
// that the result is a snapshot of src.
func toNRGBA(src image.Image) *image.NRGBA {
if v, ok := src.(*image.NRGBA); ok {
return v
}
b := src.Bounds()
dst := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
convertNRGBA(dst, src)
return dst
}
// pixPool holds the storage of NRGBA snapshots. It is a size-class pool
// under the process-wide budget of internal/bufpool, shared with the lossy
// encoder's buffers, so snapshots of any size are reused while the memory
// kept between calls stays bounded (see bufpool).
var pixPool bufpool.Pool[byte]
// pooledNRGBA returns a w x h *image.NRGBA whose pixels (unspecified, to be
// overwritten) may come from a pool, and the storage to hand back to
// putPix when the image is no longer used.
func pooledNRGBA(w, h int) (*image.NRGBA, []byte) {
pix := pixPool.Get(4 * w * h)
return &image.NRGBA{Pix: pix, Stride: 4 * w, Rect: image.Rect(0, 0, w, h)}, pix
}
// putPix returns storage obtained from pooledNRGBA to the pool (if the
// budget allows it). It may be called from any goroutine.
func putPix(pix []byte) {
if pix != nil {
pixPool.Put(pix)
}
}
// convertNRGBA overwrites every pixel of dst (whose size is that of src's
// bounds, origin at 0,0) with src converted to non-premultiplied RGBA, a
// row at a time (see rowConverter).
func convertNRGBA(dst *image.NRGBA, src image.Image) {
b := src.Bounds()
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 {
return // no pixel, no row of Pix to slice
}
var c rowConverter
c.init(src, b)
for y := 0; y < h; y++ {
c.convertRow(dst.Pix[y*dst.Stride:][:4*w], y)
}
}
// rowConverter converts a picture to non-premultiplied RGBA a row at a
// time: NewEncoder's snapshot (convertNRGBA) and a lossless one-shot
// encode, which converts each row straight into the encoder's working
// image (see Encoder.src), share it and so give the same bytes.
//
// The image types of package image (but *image.NRGBA, which NewEncoder
// uses in place, *image.Uniform and image.Rectangle) are converted with
// dedicated loops, whose results are color.NRGBAModel's on src.At (an
// *image.NYCbCrA is the exception, see yccRows) without its per-pixel
// interface calls and allocations; the opaque runs of an *image.RGBA,
// whose bytes are the same premultiplied or not (png.Decode returns
// opaque ones for RGB files), are copied (see unpremultiplyRow). Any other
// image, an image.RGBA64Image of another package included, goes through
// src.At and color.NRGBAModel: the model returns a color.NRGBA as it is,
// and a dedicated loop over RGBA64At, premultiplied, would not.
type rowConverter struct {
src image.Image
b image.Rectangle // src's bounds, not empty
lut [256]uint32 // an *image.Paletted's palette (paletteLUT)
ycc yccRows // *image.YCbCr and *image.NYCbCrA
}
// init prepares c to convert the rows of src, whose bounds b are not empty.
func (c *rowConverter) init(src image.Image, b image.Rectangle) {
c.src, c.b = src, b
switch v := src.(type) {
case *image.YCbCr:
c.ycc.init(v, nil)
case *image.NYCbCrA:
c.ycc.init(&v.YCbCr, v)
case *image.Paletted:
paletteLUT(&c.lut, v.Palette)
}
}
// convertRow writes row y of the picture (counted from its top, 0 <= y <
// its height) to d, 4 bytes per pixel.
func (c *rowConverter) convertRow(d []byte, y int) {
b := c.b
w := b.Dx()
switch v := c.src.(type) {
case *image.RGBA:
// No v.Opaque() first: that scan, a byte at a time, took longer
// than the copy of an opaque picture after it (0.57 vs 0.21 ms at
// 1920x1080 on Apple M5), and unpremultiplyRow copies opaque runs
// about as fast in the same pass.
unpremultiplyRow(d, v.Pix[v.PixOffset(b.Min.X, b.Min.Y+y):][:4*w])
case *image.Gray:
// A table and paletteRow's 8 pixels per iteration: about 3 times
// faster than 4 byte stores per pixel on Apple M5.
paletteRow(d, v.Pix[v.PixOffset(b.Min.X, b.Min.Y+y):][:w], &grayLUT)
case *image.Alpha:
paletteRow(d, pixRow(v.Pix, v.PixOffset(b.Min.X, b.Min.Y+y), w, true), &alphaLUT)
case *image.Gray16:
gray16Row(d, pixRow(v.Pix, v.PixOffset(b.Min.X, b.Min.Y+y), 2*w, true))
case *image.Alpha16:
alpha16Row(d, pixRow(v.Pix, v.PixOffset(b.Min.X, b.Min.Y+y), 2*w, true))
case *image.RGBA64:
rgba64Row(d, pixRow(v.Pix, v.PixOffset(b.Min.X, b.Min.Y+y), 8*w, false), rgba64Word)
case *image.NRGBA64:
rgba64Row(d, pixRow(v.Pix, v.PixOffset(b.Min.X, b.Min.Y+y), 8*w, false), nrgba64Word)
case *image.CMYK:
cmykRow(d, pixRow(v.Pix, v.PixOffset(b.Min.X, b.Min.Y+y), 4*w, false))
case *image.YCbCr, *image.NYCbCrA:
c.ycc.row(d, y)
case *image.Paletted:
paletteRow(d, v.Pix[v.PixOffset(b.Min.X, b.Min.Y+y):][:w], &c.lut)
default:
for x := 0; x < w; x++ {
n := color.NRGBAModel.Convert(c.src.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA)
p := d[4*x : 4*x+4 : 4*x+4]
p[0], p[1], p[2], p[3] = n.R, n.G, n.B, n.A
}
}
}
// paletteLUT sets lut[i] to palette entry i converted to non-premultiplied
// RGBA, as a little-endian uint32 (R in the low byte, see nrgbaWord), for
// every index a uint8 can hold: the entries of p beyond the 256th are never
// reached, and an index beyond p gives transparent black (Paletted.At
// would panic on it). The results are those of color.NRGBAModel on each
// entry; draw.Draw gives other ones for some color.NRGBA entries, which it
// converts through Paletted.RGBA64At, premultiplied (translucent colors
// lose precision, transparent ones their RGB).
func paletteLUT(lut *[256]uint32, p color.Palette) {
for i := range lut {
var c color.Color // nil beyond p
if i < len(p) {
c = p[i]
}
lut[i] = nrgbaWord(c)
}
}
// nrgbaWord returns color.NRGBAModel.Convert(c) as a little-endian uint32,
// with the model's arithmetic repeated here (nrgbaModel in image/color, see
// premulWord): Convert boxes its result in a color.Color, which allocates
// for nearly every palette entry. color.NRGBA, which the model returns as
// is, and color.RGBA, the entries of image/color/palette's palettes and of
// the palettes image/gif and image/png decode (color.NRGBA for a PNG with
// transparency), are converted without an interface call. A nil c, on
// which the model panics, gives transparent black, like an index beyond
// the palette.
func nrgbaWord(c color.Color) uint32 {
var r, g, b, a uint32
switch c := c.(type) {
case nil:
return 0
case color.NRGBA:
return uint32(c.R) | uint32(c.G)<<8 | uint32(c.B)<<16 | uint32(c.A)<<24
case color.RGBA:
r, g, b, a = c.RGBA()
default:
r, g, b, a = c.RGBA()
}
return premulWord(r, g, b, a)
}
// premulWord returns color.NRGBAModel's result for a color whose RGBA
// method returns r, g, b and a (alpha-premultiplied, 16 bits each for a
// valid color), as a little-endian uint32 (see nrgbaWord): the model's
// arithmetic, repeated.
func premulWord(r, g, b, a uint32) uint32 {
switch a {
case 0xffff:
return uint32(uint8(r>>8)) | uint32(uint8(g>>8))<<8 | uint32(uint8(b>>8))<<16 | 0xff<<24
case 0:
return 0
}
// A color above alpha (invalid premultiplied input) wraps around in
// the uint8 conversions, as in the model.
r = (r * 0xffff) / a
g = (g * 0xffff) / a
b = (b * 0xffff) / a
return uint32(uint8(r>>8)) | uint32(uint8(g>>8))<<8 | uint32(uint8(b>>8))<<16 | uint32(uint8(a>>8))<<24
}
// grayLUT and alphaLUT hold color.NRGBAModel's result for each
// color.Gray and color.Alpha, the colors of an *image.Gray and an
// *image.Alpha, for paletteRow: a gray Y gives (Y, Y, Y, 255), an alpha A
// above 0 gives (255, 255, 255, A), as the model divides A*0x101 by itself.
var grayLUT, alphaLUT = func() (gray, alpha [256]uint32) {
for i := range 256 {
gray[i] = nrgbaWord(color.Gray{uint8(i)})
alpha[i] = nrgbaWord(color.Alpha{uint8(i)})
}
return gray, alpha
}()
// pixRow returns the n bytes of pix at off, the samples of a row, sliced
// so that a malformed picture (Pix shorter than its bounds need) panics
// exactly when v2.0.3's per-pixel path did: the At methods of the types
// with 1-byte and 2-byte samples index Pix, which len(pix) bounds (clip),
// those of the types with 4-byte and 8-byte pixels slice it, which
// cap(pix) bounds.
func pixRow(pix []byte, off, n int, clip bool) []byte {
if clip {
pix = slices.Clip(pix)
}
return pix[off : off+n]
}
// gray16Row writes to d the pixels of the big-endian *image.Gray16
// samples s (2 bytes each): color.Gray16's RGBA method gives the sample as
// R, G and B with alpha 0xffff, which the model shifts down to its high
// byte (grayLUT). Four pixels go per iteration on 64-bit targets: one
// 8-byte load of their samples and two 8-byte stores (see paletteRow).
func gray16Row(d, s []byte) {
for wide64 && len(s) >= 8 && len(d) >= 16 {
u := binary.LittleEndian.Uint64(s)
binary.LittleEndian.PutUint64(d[0:], uint64(grayLUT[uint8(u)])|uint64(grayLUT[uint8(u>>16)])<<32)
binary.LittleEndian.PutUint64(d[8:], uint64(grayLUT[uint8(u>>32)])|uint64(grayLUT[uint8(u>>48)])<<32)
d, s = d[16:], s[8:]
}
for len(s) >= 2 && len(d) >= 4 {
binary.LittleEndian.PutUint32(d, grayLUT[s[0]])
d, s = d[4:], s[2:]
}
}
// alpha16Row writes to d the pixels of the big-endian *image.Alpha16
// samples s, 4 at a time on 64-bit targets like gray16Row.
func alpha16Row(d, s []byte) {
for wide64 && len(s) >= 8 && len(d) >= 16 {
u := binary.LittleEndian.Uint64(s)
binary.LittleEndian.PutUint64(d[0:], uint64(alpha16Word(uint32(u)))|uint64(alpha16Word(uint32(u>>16)))<<32)
binary.LittleEndian.PutUint64(d[8:], uint64(alpha16Word(uint32(u>>32)))|uint64(alpha16Word(uint32(u>>48)))<<32)
d, s = d[16:], s[8:]
}
for len(s) >= 2 && len(d) >= 4 {
binary.LittleEndian.PutUint32(d, alpha16Word(uint32(binary.LittleEndian.Uint16(s))))
d, s = d[4:], s[2:]
}
}
// alpha16Word returns the model's result for the color.Alpha16 whose two
// bytes, read little-endian, are the low 16 bits of v (the high byte of
// the sample is the low byte of v). Its RGBA method gives the sample A as
// all four values, which the model divides by A: (255, 255, 255, A>>8)
// for any A above 0 (white with alpha 0 for A from 1 to 255), transparent
// black for 0.
func alpha16Word(v uint32) uint32 {
v &= 0xffff
nz := -((v + 0xffff) >> 16) // all ones for A > 0, 0 for A = 0
return (v<<24 | 0xffffff) & nz
}
// rgba64Row writes to d the pixels of the samples s of an *image.RGBA64
// or *image.NRGBA64 (16 bits each, big-endian). For both types the model
// gives an opaque pixel the high bytes of its samples and a transparent
// one transparent black; the other pixels are word's (rgba64Word or
// nrgba64Word). On 64-bit targets four pixels go per iteration, and four
// opaque or four transparent ones are written with two 8-byte stores
// (pictures from 16-bit files are mostly opaque, or transparent): 40% less
// time than a pixel at a time for an opaque picture on Apple M5.
// Elsewhere a pixel's 8 bytes are read as two uint32 halves.
func rgba64Row(d, s []byte, word func(lo, hi uint32) uint32) {
for wide64 && len(s) >= 32 && len(d) >= 16 {
u0, u1 := binary.LittleEndian.Uint64(s[0:]), binary.LittleEndian.Uint64(s[8:])
u2, u3 := binary.LittleEndian.Uint64(s[16:]), binary.LittleEndian.Uint64(s[24:])
switch {
case u0&u1&u2&u3 >= 0xffff<<48:
binary.LittleEndian.PutUint64(d[0:], highBytes(u0)|highBytes(u1)<<32)
binary.LittleEndian.PutUint64(d[8:], highBytes(u2)|highBytes(u3)<<32)
case u0|u1|u2|u3 < 1<<48:
*(*[16]byte)(d) = [16]byte{}
default:
binary.LittleEndian.PutUint32(d[0:], rgba64Pixel(uint32(u0), uint32(u0>>32), word))
binary.LittleEndian.PutUint32(d[4:], rgba64Pixel(uint32(u1), uint32(u1>>32), word))
binary.LittleEndian.PutUint32(d[8:], rgba64Pixel(uint32(u2), uint32(u2>>32), word))
binary.LittleEndian.PutUint32(d[12:], rgba64Pixel(uint32(u3), uint32(u3>>32), word))
}
d, s = d[16:], s[32:]
}
for len(s) >= 8 && len(d) >= 4 {
binary.LittleEndian.PutUint32(d, rgba64Pixel(binary.LittleEndian.Uint32(s[0:]), binary.LittleEndian.Uint32(s[4:]), word))
d, s = d[4:], s[8:]
}
}
// rgba64Pixel returns the model's result for the pixel whose 8 bytes,
// read little-endian, are lo and hi (R and G in lo, B and A in hi, each
// sample high byte first): the high bytes for an opaque pixel, 0 for a
// transparent one, word's result for the others.
func rgba64Pixel(lo, hi uint32, word func(lo, hi uint32) uint32) uint32 {
switch {
case hi >= 0xffff0000:
return lo&0xff | lo>>8&0xff00 | hi<<16&0xff0000 | 0xff000000
case hi < 1<<16:
return 0
}
return word(lo, hi)
}
// highBytes returns the high bytes of the four big-endian 16-bit samples
// read little-endian into u (bytes 0, 2, 4 and 6), in the low 32 bits.
func highBytes(u uint64) uint64 {
u &= 0x00ff00ff00ff00ff
u = (u | u>>8) & 0x0000ffff0000ffff
return (u | u>>16) & 0xffffffff
}
// rgba64Word returns the model's result for the color.RGBA64 whose 8
// bytes, read little-endian, are lo and hi (see rgba64Pixel).
func rgba64Word(lo, hi uint32) uint32 {
return premulWord(swap16(lo), swap16(lo>>16), swap16(hi), swap16(hi>>16))
}
// nrgba64Word is rgba64Word for a color.NRGBA64. The model's result is
// not the samples' high bytes: color.NRGBA64's RGBA method premultiplies
// the colors (rounding them down), which the model divides back, so that
// a translucent pixel loses precision (the more the lower its alpha), and
// the colors of a transparent one are zeroed. That round trip is repeated
// here exactly, so that the snapshot stays that of v2.0.3.
func nrgba64Word(lo, hi uint32) uint32 {
a := swap16(hi >> 16)
return premulWord(swap16(lo)*a/0xffff, swap16(lo>>16)*a/0xffff, swap16(hi)*a/0xffff, a)
}
// swap16 returns the big-endian 16-bit sample read little-endian into the
// low 16 bits of v.
func swap16(v uint32) uint32 {
return uint32(bits.ReverseBytes16(uint16(v)))
}
// cmykRow writes to d the pixels of the *image.CMYK samples s (C, M, Y
// and K, a byte each). color.CMYK's RGBA method is color.CMYKToRGB at 16
// bits, opaque, so that the model's result is color.CMYKToRGB's: red is
// ((0xffff - C*0x101) * w / 0xffff) >> 8 with w = 0xffff - K*0x101, that
// is (X*0x10201 / 0xffff) >> 8 for X = (255-C)*(255-K), which equals
// X*33025 >> 23 for every X up to 255*255 (TestCMYKMultiplier checks them
// all): one multiplication per color, against two and a division by a
// constant (a third). The bytes are stored one by one: the compiler split
// the 4-byte store of a word with a constant alpha byte into three
// stores, which took 10% longer on Apple M5.
func cmykRow(d, s []byte) {
s = s[:len(d)]
for i := 0; i+3 < len(s); i += 4 {
p, q := s[i:i+4:i+4], d[i:i+4:i+4]
w := cmykK[p[3]]
q[0] = byte((255 - uint32(p[0])) * w >> 23)
q[1] = byte((255 - uint32(p[1])) * w >> 23)
q[2] = byte((255 - uint32(p[2])) * w >> 23)
q[3] = 0xff
}
}
// cmykK[K] is (255-K)*33025, the factor of a pixel's colors in cmykRow (a
// table: the compiler multiplied each color by 255-K and then by 33025).
var cmykK = func() (t [256]uint32) {
for k := range t {
t[k] = uint32(255-k) * 33025
}
return t
}()
// paletteRow sets the 4 bytes of d at 4*i to lut[s[i]] (see paletteLUT) for
// every index in s; d holds 4*len(s) bytes. Eight pixels go per iteration:
// one 8-byte load of their indices and four 8-byte stores of two pixels
// each, about three times faster than a 4-byte copy per pixel, whose bounds
// and overlap checks took most of the time. On 32-bit targets (see wide64)
// a pixel goes per iteration: there the 8-byte loads and stores are pairs
// of 4-byte ones, and that loop was slower than the copy. The full slice
// expression leaves one bounds check per pixel, where d[4*i:] and
// PutUint32 left two (on 386, 2.11 ms for 1920x1080 against 2.52 ms, and
// 2.35 ms for v2.0.2's copy).
func paletteRow(d []byte, s []uint8, lut *[256]uint32) {
for wide64 && len(s) >= 8 && len(d) >= 32 {
ix := binary.LittleEndian.Uint64(s)
binary.LittleEndian.PutUint64(d[0:], uint64(lut[uint8(ix)])|uint64(lut[uint8(ix>>8)])<<32)
binary.LittleEndian.PutUint64(d[8:], uint64(lut[uint8(ix>>16)])|uint64(lut[uint8(ix>>24)])<<32)
binary.LittleEndian.PutUint64(d[16:], uint64(lut[uint8(ix>>32)])|uint64(lut[uint8(ix>>40)])<<32)
binary.LittleEndian.PutUint64(d[24:], uint64(lut[uint8(ix>>48)])|uint64(lut[uint8(ix>>56)])<<32)
d, s = d[32:], s[8:]
}
for i, ix := range s {
binary.LittleEndian.PutUint32(d[4*i:4*i+4:4*i+4], lut[ix])
}
}
// yccRows converts the rows of an *image.YCbCr src (alpha nil: alpha 0xff)
// or of the *image.NYCbCrA alpha, whose Y'CbCr part is src, for
// rowConverter. The colors are color.YCbCrToRGB of each pixel's samples:
// for an *image.YCbCr that is also color.NRGBAModel's result (YCbCr.RGBA
// is the same formula at 16 bits); the colors of an *image.NYCbCrA are not
// premultiplied, so its alpha is copied, where color.NRGBAModel would
// multiply the color by alpha and divide it back.
//
// Neither COffset, which finds a pixel's chroma samples, nor
// color.YCbCrToRGB is inlined (their costs are above the inliner's
// budget), and the clamping of the latter compiles to branches, which
// noisy pictures mispredict. Here each row finds its chroma samples once
// and ycbcrRow converts it, with color.YCbCrToRGB's sums and branch-free
// table lookups (see yccTables).
type yccRows struct {
src *image.YCbCr
alpha *image.NYCbCrA
hs uint // a chroma sample spans 1<<hs pixels of a row
nc int // chroma samples per row, for src.Rect.Min.X >= 0
phase int // of the row's first pixel in its chroma sample
}
// init prepares r to convert the rows of src and alpha.
func (r *yccRows) init(src *image.YCbCr, alpha *image.NYCbCrA) {
b := src.Rect
// A chroma sample spans 1<<hs pixels of a row: COffset divides x by 2
// for 4:2:2 and 4:2:0, by 4 for 4:1:1 and 4:1:0 (and y by 2 for 4:2:0,
// 4:4:0 and 4:1:0, which COffset of each row's first pixel takes care
// of). For x >= 0 that is x>>hs, so the chroma column of the row's
// pixel x is (b.Min.X+x)>>hs - c0. Left of x = 0 the division rounds
// toward zero and the shift down: a picture that starts there (decoders
// return pictures at the origin) takes COffset and color.YCbCrToRGB for
// each pixel.
var hs uint
switch src.SubsampleRatio {
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
hs = 1
case image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410:
hs = 2
}
c0 := b.Min.X >> hs
*r = yccRows{src: src, alpha: alpha, hs: hs,
nc: (b.Max.X-1)>>hs - c0 + 1, phase: b.Min.X & (1<<hs - 1)}
}
// row writes row y of the picture (counted from its top) to d.
//
// A malformed picture (a plane shorter than its bounds need, or an
// *image.NYCbCrA without alpha samples) panics exactly when it did in
// earlier versions, whatever the planes' capacity: the rows of Y and alpha
// samples are sliced as those versions sliced them, and the chroma planes,
// which they indexed for each pixel, are clipped.
func (r *yccRows) row(d []byte, y int) {
src, alpha, hs := r.src, r.alpha, r.hs
b := src.Rect
w := b.Dx()
yi := y * src.YStride
ys := src.Y[yi : yi+w]
var as []byte // the row's alpha samples, nil for 0xff
if alpha != nil {
ai := y * alpha.AStride
as = alpha.A[ai : ai+w]
}
if b.Min.X < 0 {
for x, yv := range ys {
ci := src.COffset(b.Min.X+x, b.Min.Y+y)
p := d[4*x : 4*x+4 : 4*x+4]
p[0], p[1], p[2] = color.YCbCrToRGB(yv, src.Cb[ci], src.Cr[ci])
p[3] = 0xff
if as != nil {
p[3] = as[x]
}
}
return
}
ci := src.COffset(b.Min.X, b.Min.Y+y)
cb := slices.Clip(src.Cb)[ci:][:r.nc]
cr := slices.Clip(src.Cr)[ci:][:r.nc]
if w < yccBlock {
// no block fits: skip ycbcrRow's calls and setup, which made
// pictures a few pixels wide up to twice as slow
ycbcrPixels(&yccTab, d, ys, cb, cr, as, hs, r.phase)
} else {
ycbcrRow(d, ys, cb, cr, as, hs, r.phase)
}
}
// yccBlock is the number of pixels the ycbcrBlock functions convert: 32
// converts 1920x1080 7% faster than 16 on Apple M5, and no slower than 64,
// and leaves ycbcrPixels fewer than 35 pixels of a row.
const yccBlock = 32
// ycbcrRow writes to d the pixels of the luma samples ys, with alpha
// samples as (nil for 0xff), whose chroma samples cb and cr span 1<<hs
// pixels each, the first one starting phase pixels before ys. From the
// first pixel that starts a chroma sample on, the pixels are converted in
// blocks of yccBlock by the ycbcrBlock functions, whose loops need no
// bounds checks and no more registers than amd64 has; the pixels before
// (at most 3) and after the blocks by ycbcrPixels.
func ycbcrRow(d, ys, cb, cr, as []byte, hs uint, phase int) {
t := &yccTab
x := min(-phase&(1<<hs-1), len(ys))
if x > 0 {
ycbcrPixels(t, d[:4*x], ys[:x], cb, cr, as, hs, phase)
}
j := (phase + x) >> hs
for ; x+yccBlock <= len(ys); x, j = x+yccBlock, j+yccBlock>>hs {
pd, py := (*[4 * yccBlock]byte)(d[4*x:]), (*[yccBlock]byte)(ys[x:])
switch {
case hs == 0 && as == nil:
ycbcrBlock1(t, pd, py, (*[yccBlock]byte)(cb[j:]), (*[yccBlock]byte)(cr[j:]))
case hs == 0:
ycbcrBlock1A(t, pd, py, (*[yccBlock]byte)(as[x:]), (*[yccBlock]byte)(cb[j:]), (*[yccBlock]byte)(cr[j:]))
case hs == 1 && as == nil:
ycbcrBlock2(t, pd, py, (*[yccBlock / 2]byte)(cb[j:]), (*[yccBlock / 2]byte)(cr[j:]))
case hs == 1:
ycbcrBlock2A(t, pd, py, (*[yccBlock]byte)(as[x:]), (*[yccBlock / 2]byte)(cb[j:]), (*[yccBlock / 2]byte)(cr[j:]))
case as == nil:
ycbcrBlock4(t, pd, py, (*[yccBlock / 4]byte)(cb[j:]), (*[yccBlock / 4]byte)(cr[j:]))
default:
ycbcrBlock4A(t, pd, py, (*[yccBlock]byte)(as[x:]), (*[yccBlock / 4]byte)(cb[j:]), (*[yccBlock / 4]byte)(cr[j:]))
}
}
if as != nil {
as = as[x:]
}
ycbcrPixels(t, d[4*x:], ys[x:], cb[j:], cr[j:], as, hs, 0)
}
// ycbcrPixels is ycbcrRow without the blocks, for a few pixels of a row.
func ycbcrPixels(t *yccTables, d, ys, cb, cr, as []byte, hs uint, phase int) {
tr, tg, ty := &t.r, &t.g, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
hs &= 3 // lets the compiler drop the check for shifts of 64 bits and more
if as == nil {
tb := &t.ba
for x, yv := range ys {
j := (phase + x) >> hs
c, e := cb[j], cr[j]
binary.LittleEndian.PutUint32(d[4*x:4*x+4:4*x+4], yccWord(tr, tg, tb, ty[yv], crR[e], cbG[c]+crG[e], cbB[c]))
}
return
}
tb := &t.b
as = as[:len(ys)]
for x, yv := range ys {
j := (phase + x) >> hs
c, e := cb[j], cr[j]
binary.LittleEndian.PutUint32(d[4*x:4*x+4:4*x+4], yccWord(tr, tg, tb, ty[yv], crR[e], cbG[c]+crG[e], cbB[c])|uint32(as[x])<<24)
}
}
// yccTables holds the terms of color.YCbCrToRGB's sums, whose comments
// explain the constants, and their clamped results. A pixel's sum for
// red is y[Y] + crR[Cr], for green y[Y] + cbG[Cb] + crG[Cr], for blue
// y[Y] + cbB[Cb]; that is color.YCbCrToRGB's sum plus 1<<24, a bias that
// keeps every sum positive (they range from 1<<24 - 128*116130 to 1<<24
// + 255*0x10101 + 127*116130). Entry yccIndex(sum) of r, g and b holds
// color.YCbCrToRGB's result, the byte it clamps the unbiased sum to, at
// its place in a little-endian NRGBA word, which ba also sets the alpha
// of to 0xff.
type yccTables struct {
r, g, b, ba [1024]uint32
y [256]int32
crR, cbG, crG, cbB [256]int32
}
var yccTab yccTables
func init() {
t := &yccTab
for i := range 1024 {
// color.YCbCrToRGB's clamping of the unbiased sum s, for every s
// with s>>16 = i - 256.
c := uint32(min(max(i-256, 0), 255))
t.r[i], t.g[i], t.b[i], t.ba[i] = c, c<<8, c<<16, c<<16|0xff<<24
}
for i := range int32(256) {
t.y[i] = i*0x10101 + 1<<24
t.crR[i] = 91881 * (i - 128)
t.cbG[i] = -22554 * (i - 128)
t.crG[i] = -46802 * (i - 128)
t.cbB[i] = 116130 * (i - 128)
}
}
// yccIndex returns the index of the yccTables entries of biased sum s.
// The mask changes no index (s>>16 is below 1024), but lets the compiler
// drop the bounds checks.
func yccIndex(s int32) uint32 {
return uint32(s) >> 16 & 1023
}
// yccWord returns the little-endian NRGBA word, its alpha byte from tb,
// of the biased luma term yy and chroma terms r, g and b (see yccTables).
func yccWord(tr, tg, tb *[1024]uint32, yy, r, g, b int32) uint32 {
return tr[yccIndex(yy+r)] | tg[yccIndex(yy+g)] | tb[yccIndex(yy+b)]
}
// The ycbcrBlock functions write to d the yccBlock pixels of luma samples
// ys and chroma samples cb and cr, which span 1, 2 or 4 pixels, the first
// one starting at the first pixel; the ycbcrBlock*A functions take alpha
// samples a, the others write alpha 0xff. Array arguments leave their
// loops without bounds checks, and the loops are written so that their
// values fit amd64's 14 registers (the Go compiler neither weighs register
// pressure when it orders instructions nor hoists loop-invariant ones):
// - the tables are addressed from t, which amd64 does with one register
// for all of them and arm64 with one each, set up before the loop (the
// address of a global would be recomputed at every use);
// - the loop index is the pixel's, so that luma and alpha bytes load
// from base+index+offset, with no address registers;
// - a pixel's samples are loaded after the previous pixel is stored,
// which keeps the sums of all pixels of a chroma sample from being
// computed first;
// - the word is stored at once (an alpha constant in the word, instead of
// in tb, would split the store into bytes).
func ycbcrBlock1(t *yccTables, d *[4 * yccBlock]byte, ys, cb, cr *[yccBlock]byte) {
tr, tg, tb, ty := &t.r, &t.g, &t.ba, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
_, _, _, _ = d[0], ys[0], cb[0], cr[0] // the nil checks, out of the loop
for i := range yccBlock {
c, e := cb[i], cr[i]
r, g, b := crR[e], cbG[c]+crG[e], cbB[c]
binary.LittleEndian.PutUint32(d[4*i:], yccWord(tr, tg, tb, ty[ys[i]], r, g, b))
}
}
func ycbcrBlock1A(t *yccTables, d *[4 * yccBlock]byte, ys, a, cb, cr *[yccBlock]byte) {
tr, tg, tb, ty := &t.r, &t.g, &t.b, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
_, _, _, _, _ = d[0], ys[0], a[0], cb[0], cr[0]
for i := range yccBlock {
c, e := cb[i], cr[i]
r, g, b := crR[e], cbG[c]+crG[e], cbB[c]
binary.LittleEndian.PutUint32(d[4*i:], yccWord(tr, tg, tb, ty[ys[i]], r, g, b)|uint32(a[i])<<24)
}
}
func ycbcrBlock2(t *yccTables, d *[4 * yccBlock]byte, ys *[yccBlock]byte, cb, cr *[yccBlock / 2]byte) {
tr, tg, tb, ty := &t.r, &t.g, &t.ba, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
_, _, _, _ = d[0], ys[0], cb[0], cr[0]
for i := 0; i < yccBlock; i += 2 {
c, e := cb[i/2], cr[i/2]
r, g, b := crR[e], cbG[c]+crG[e], cbB[c]
binary.LittleEndian.PutUint32(d[4*i:], yccWord(tr, tg, tb, ty[ys[i]], r, g, b))
binary.LittleEndian.PutUint32(d[4*i+4:], yccWord(tr, tg, tb, ty[ys[i+1]], r, g, b))
}
}
func ycbcrBlock2A(t *yccTables, d *[4 * yccBlock]byte, ys, a *[yccBlock]byte, cb, cr *[yccBlock / 2]byte) {
tr, tg, tb, ty := &t.r, &t.g, &t.b, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
_, _, _, _, _ = d[0], ys[0], a[0], cb[0], cr[0]
for i := 0; i < yccBlock; i += 2 {
c, e := cb[i/2], cr[i/2]
r, g, b := crR[e], cbG[c]+crG[e], cbB[c]
binary.LittleEndian.PutUint32(d[4*i:], yccWord(tr, tg, tb, ty[ys[i]], r, g, b)|uint32(a[i])<<24)
binary.LittleEndian.PutUint32(d[4*i+4:], yccWord(tr, tg, tb, ty[ys[i+1]], r, g, b)|uint32(a[i+1])<<24)
}
}
func ycbcrBlock4(t *yccTables, d *[4 * yccBlock]byte, ys *[yccBlock]byte, cb, cr *[yccBlock / 4]byte) {
tr, tg, tb, ty := &t.r, &t.g, &t.ba, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
_, _, _, _ = d[0], ys[0], cb[0], cr[0]
for i := 0; i < yccBlock; i += 4 {
c, e := cb[i/4], cr[i/4]
r, g, b := crR[e], cbG[c]+crG[e], cbB[c]
binary.LittleEndian.PutUint32(d[4*i:], yccWord(tr, tg, tb, ty[ys[i]], r, g, b))
binary.LittleEndian.PutUint32(d[4*i+4:], yccWord(tr, tg, tb, ty[ys[i+1]], r, g, b))
binary.LittleEndian.PutUint32(d[4*i+8:], yccWord(tr, tg, tb, ty[ys[i+2]], r, g, b))
binary.LittleEndian.PutUint32(d[4*i+12:], yccWord(tr, tg, tb, ty[ys[i+3]], r, g, b))
}
}
func ycbcrBlock4A(t *yccTables, d *[4 * yccBlock]byte, ys, a *[yccBlock]byte, cb, cr *[yccBlock / 4]byte) {
tr, tg, tb, ty := &t.r, &t.g, &t.b, &t.y
crR, cbG, crG, cbB := &t.crR, &t.cbG, &t.crG, &t.cbB
_, _, _, _, _ = d[0], ys[0], a[0], cb[0], cr[0]
for i := 0; i < yccBlock; i += 4 {
c, e := cb[i/4], cr[i/4]
r, g, b := crR[e], cbG[c]+crG[e], cbB[c]
binary.LittleEndian.PutUint32(d[4*i:], yccWord(tr, tg, tb, ty[ys[i]], r, g, b)|uint32(a[i])<<24)
binary.LittleEndian.PutUint32(d[4*i+4:], yccWord(tr, tg, tb, ty[ys[i+1]], r, g, b)|uint32(a[i+1])<<24)
binary.LittleEndian.PutUint32(d[4*i+8:], yccWord(tr, tg, tb, ty[ys[i+2]], r, g, b)|uint32(a[i+2])<<24)
binary.LittleEndian.PutUint32(d[4*i+12:], yccWord(tr, tg, tb, ty[ys[i+3]], r, g, b)|uint32(a[i+3])<<24)
}
}
// unpremulRecip[a] = ceil(0xffff<<8 / a), and 0 for a = 0, unpremultiplies
// a color sample c of alpha a exactly like color.NRGBAModel, without its
// division: uint8(c*unpremulRecip[a]>>16), in uint32 arithmetic, is
// NRGBAModel's uint8((c*0xffff/a)>>8) for every c and a.
//
// NRGBAModel divides the 16-bit samples of color.RGBA's RGBA method,
// 0x101*c and 0x101*a; the factors 0x101 cancel, so its result is q mod 256
// with q = floor(c*0xffff / (256*a)). Write m = unpremulRecip[a] =
// (256*0xffff + k) / a with 0 <= k < a, and c*0xffff = 256*a*q + r with
// 0 <= r < 256*a. Then c*m / 2^16 = q + r/(256*a) + c*k/(2^16*a), whose
// floor is q if and only if 256*r + c*k < 2^16*a. Modulo 256*a, c*0xffff =
// 2^16*c - c is 256*u - c with u = 256*c mod a. If u > 0, r = 256*u - c
// and 256*r + c*k = 2^16*u - c*(256-k) <= 2^16*(a-1); if u = 0 and c > 0,
// r = 256*a - c and 256*r + c*k = 2^16*a - c*(256-k); both are below
// 2^16*a since k < a <= 255, and c = 0 gives 0. So floor(c*m / 2^16) = q.
// c*m <= 255*0xffff*256 < 2^32 does not wrap, and byte 2 of it is q mod
// 256, also for c > a (not a valid premultiplied color), where
// NRGBAModel's uint8 conversion wraps the same way. Alpha 255 gives c (m =
// 0x101<<8) and alpha 0 gives 0, NRGBAModel's two special cases, so no
// pixel needs a branch. As c*m < 2^32, two samples multiplied in the two
// 32-bit halves of one uint64 do not carry into each other (see
// unpremultiplyPixel). TestUnpremulRecip checks all 65536 (c, a) pairs and
// the bound; TestUnpremultiplyLanes every (R, B, alpha).
//
// internal/resample's unpremulScale, (255<<24)/a with rounding, follows
// libwebp (the nearest integer to c*255/a) and cannot serve here: it
// differs by 1 from NRGBAModel's truncation of c*0xffff/a / 256 for 7757 of
// the 32895 valid pairs (c <= a, a > 0); 1 at alpha 2 becomes 128, not 127.
var unpremulRecip = func() (t [256]uint32) {
for a := uint64(1); a < 256; a++ {
t[a] = uint32((0xffff<<8 + a - 1) / a)
}
return t
}()
// alphaBytes masks the alpha bytes of two RGBA pixels read as a
// little-endian uint64.
const alphaBytes = 0xff000000ff000000
// unpremultiplyRow converts alpha-premultiplied RGBA samples (s) to
// non-premultiplied ones (d, as long as s) exactly like color.NRGBAModel,
// 8 pixels at a time: 8 opaque pixels are copied and 8 transparent ones
// zeroed, which is what NRGBAModel makes of them, and any other 8 are
// multiplied by unpremulRecip, a pixel at a time. Opaque and transparent
// areas, the bulk of most pictures with alpha (and all of an opaque one),
// run at about the speed of copy; the other pixels cost two
// multiplications each, where NRGBAModel divides three times. 32-bit
// targets go a pixel at a time (see unpremultiplyPixels).
//
// A group of 8 opaque or 8 transparent pixels starts a run: if the group
// after it is opaque or transparent too, the 64-byte blocks after both
// are copied or zeroed by a loop of their own for as long as they are all
// opaque or all transparent, with less than half the instructions per
// pixel of the loop over groups. The group after the first one is tested
// alone: most runs of a picture with binary alpha end there, and when a
// failed test of the 64 bytes after the first group was all they got,
// such pictures took longer than with the loop over groups alone (on
// Apple M5, 6% for runs of 1 to 32 pixels, 43% for stripes of 8). When a
// block ends the run, its first half is copied or zeroed if it can be, so
// that the run does not end with a group tested twice.
//
// The groups are indexed, not resliced: s, d = s[32:], d[32:] made the
// compiler clamp both advanced pointers (a pointer past the end of an
// empty slice must not be formed), 16 instructions of loop control per
// group on amd64 against 8 now. With cap(d) = len(s), the prove pass
// drops every bounds check of the loops, once the loop conditions say
// i >= 0: the run loops advance i too, so it is no induction variable,
// and prove does not know its sign.
func unpremultiplyRow(d, s []byte) {
if !wide64 {
unpremultiplyPixels(d, s)
return
}
// With equal lengths and capacities, s and d share their slice
// arithmetic, and the checks of d[i:...] go with those of s[i:...].
n := len(s)
s, d = s[:n:n], d[:n:n]
i := 0
for i >= 0 && i < len(s)-31 {
// Capacity i+32, not len(s)-i: the compiler would share that
// difference with the opaque run's slices and compute it for
// every group (4 instructions on amd64).
ps, pd := (*[32]byte)(s[i:i+32:i+32]), (*[32]byte)(d[i:i+32:i+32])
// The compiler marks each inlined call with a NOP unless another
// instruction is on its line: here the ANDs and the ORs below.
and := binary.LittleEndian.Uint64(ps[0:]) & binary.LittleEndian.Uint64(ps[8:]) &
binary.LittleEndian.Uint64(ps[16:]) & binary.LittleEndian.Uint64(ps[24:])
switch {
case and&alphaBytes == alphaBytes:
copy32(pd, ps)
// A run of one group ends with a test of 32 bytes, not 64.
if i >= len(s)-63 {
break
}
// The next group is tested through a 64-byte view at i: on
// 64-bit targets the prove pass drops its checks, not those
// of s[i+32:i+64].
q, p := (*[64]byte)(s[i:i+64:i+64]), (*[64]byte)(d[i:i+64:i+64])
if binary.LittleEndian.Uint64(q[32:])&binary.LittleEndian.Uint64(q[40:])&
binary.LittleEndian.Uint64(q[48:])&binary.LittleEndian.Uint64(q[56:])&alphaBytes != alphaBytes {
break
}
copy32((*[32]byte)(p[32:]), (*[32]byte)(q[32:]))
// This run loop advances slices, not i: Go's amd64 backend has
// no indexed 16-byte move, and with i each move took up to two
// LEAQs for its addresses (39 instructions per block, against
// 27). With len(rs) > 64, rs[64:] is not empty, so its pointer
// is not masked; a block that ends the row is left to the loop
// over groups. len(rd) is tested too: prove does not know that
// it equals len(rs), and without it the two conversions of rd
// below kept their bounds checks.
rs, rd := s[i+64:], d[i+64:]
for len(rs) > 64 && len(rd) > 64 {
q := (*[64]byte)(rs)
lo := binary.LittleEndian.Uint64(q[0:]) & binary.LittleEndian.Uint64(q[8:]) &
binary.LittleEndian.Uint64(q[16:]) & binary.LittleEndian.Uint64(q[24:])
if lo&binary.LittleEndian.Uint64(q[32:])&binary.LittleEndian.Uint64(q[40:])&
binary.LittleEndian.Uint64(q[48:])&binary.LittleEndian.Uint64(q[56:])&alphaBytes != alphaBytes {
// The run ends in this block. An opaque first half
// is copied here, or the loop over groups would test
// it, copy it and test the next block again.
if lo&alphaBytes == alphaBytes {
copy32((*[32]byte)(rd), (*[32]byte)(q[0:]))
rs = rs[32:]
}
break
}
copy64((*[64]byte)(rd), q)
rs, rd = rs[64:], rd[64:]
}
i = len(s) - len(rs)
continue
case (binary.LittleEndian.Uint64(ps[0:])|binary.LittleEndian.Uint64(ps[8:])|
binary.LittleEndian.Uint64(ps[16:])|binary.LittleEndian.Uint64(ps[24:]))&alphaBytes == 0:
*pd = [32]byte{}
if i >= len(s)-63 {
break
}
q, p := (*[64]byte)(s[i:i+64:i+64]), (*[64]byte)(d[i:i+64:i+64])
if (binary.LittleEndian.Uint64(q[32:])|binary.LittleEndian.Uint64(q[40:])|
binary.LittleEndian.Uint64(q[48:])|binary.LittleEndian.Uint64(q[56:]))&alphaBytes != 0 {
break
}
*(*[32]byte)(p[32:]) = [32]byte{}
for i += 64; i < len(s)-63; i += 64 {
q := (*[64]byte)(s[i : i+64])
lo := binary.LittleEndian.Uint64(q[0:]) | binary.LittleEndian.Uint64(q[8:]) |
binary.LittleEndian.Uint64(q[16:]) | binary.LittleEndian.Uint64(q[24:])
if (lo|binary.LittleEndian.Uint64(q[32:])|binary.LittleEndian.Uint64(q[40:])|
binary.LittleEndian.Uint64(q[48:])|binary.LittleEndian.Uint64(q[56:]))&alphaBytes != 0 {
// As in the opaque run.
if lo&alphaBytes == 0 {
*(*[32]byte)(d[i : i+32]) = [32]byte{}
i += 32
}
break
}
*(*[64]byte)(d[i : i+64]) = [64]byte{}
}
continue
default:
// Unrolled: a loop over the 8 pixels is about 10% slower.
unpremultiplyPixel((*[4]byte)(pd[0:]), (*[4]byte)(ps[0:]))
unpremultiplyPixel((*[4]byte)(pd[4:]), (*[4]byte)(ps[4:]))
unpremultiplyPixel((*[4]byte)(pd[8:]), (*[4]byte)(ps[8:]))
unpremultiplyPixel((*[4]byte)(pd[12:]), (*[4]byte)(ps[12:]))
unpremultiplyPixel((*[4]byte)(pd[16:]), (*[4]byte)(ps[16:]))
unpremultiplyPixel((*[4]byte)(pd[20:]), (*[4]byte)(ps[20:]))
unpremultiplyPixel((*[4]byte)(pd[24:]), (*[4]byte)(ps[24:]))
unpremultiplyPixel((*[4]byte)(pd[28:]), (*[4]byte)(ps[28:]))
}
// The one increment for every path that ends with this group:
// one per path made the compiler compute i+32 before the switch.
i += 32
}
for ; i >= 0 && i < len(s)-3; i += 4 {
unpremultiplyPixel((*[4]byte)(d[i:i+4]), (*[4]byte)(s[i:i+4]))
}
}
// splitMoves is true where the compiler inlines a copy between arrays that
// may overlap (as two converted from slices may) only up to 16 bytes, and
// calls runtime.memmove for a larger one (cmd/compile's
// isInlinableMemmove): copy32 and copy64 then copy 16 bytes at a time.
// arm64 inlines up to 64 bytes; the other architectures inline less than
// 16 bytes or nothing, and one move of the whole array is one call there
// instead of several.
const splitMoves = runtime.GOARCH == "amd64" || runtime.GOARCH == "loong64"
// copy32 copies s to d, with no call on amd64 (see splitMoves). There,
// *d = *s was a call to runtime.memmove for every 8 opaque pixels, with
// five registers spilled and reloaded around it: 72 instructions per 8
// pixels, where the run loop now takes 27 per 16.
func copy32(d, s *[32]byte) {
if splitMoves {
*(*[16]byte)(d[0:]) = *(*[16]byte)(s[0:])
*(*[16]byte)(d[16:]) = *(*[16]byte)(s[16:])
} else {
*d = *s
}
}
// copy64 copies s to d like copy32.
func copy64(d, s *[64]byte) {
if splitMoves {
*(*[16]byte)(d[0:]) = *(*[16]byte)(s[0:])
*(*[16]byte)(d[16:]) = *(*[16]byte)(s[16:])
*(*[16]byte)(d[32:]) = *(*[16]byte)(s[32:])
*(*[16]byte)(d[48:]) = *(*[16]byte)(s[48:])
} else {
*d = *s
}
}
// wide64 is true where a uint64 fits in a register. There unpremultiplyRow
// and paletteRow work on 8-byte words, and unpremultiplyPixel multiplies R
// and B together. On 386 and arm a uint64 load or store takes two
// instructions, and a product two multiplications and an add (MULL,
// IMULL, ADDL; UMULL, MLA). The word loops also spilled registers there,
// and were slower than a pixel at a time.
const wide64 = bits.UintSize == 64
// unpremultiplyPixels is unpremultiplyRow a pixel at a time, for 32-bit
// targets (see wide64): a run of opaque pixels is found by its alpha
// bytes and copied at once, a transparent pixel is zeroed, and the others
// are multiplied by unpremulRecip. Each pixel is a 4-byte slice of d and
// s, which leaves one bounds check for each; the prove pass kept one for
// every byte of d[i+1] and the like there. On 386 on an AMD EPYC 8024P, an
// opaque 1920x1080 picture took 1.61 ms, against 1.65 ms for v2.0.2's
// Opaque scan and copy, and 2.59 ms for the word loops of unpremultiplyRow.
func unpremultiplyPixels(d, s []byte) {
d = d[:len(s)]
for i := 0; i+3 < len(s); {
q := s[i : i+4 : i+4]
switch a := q[3]; a {
case 0xff:
j := i + 4
for j+3 < len(s) && s[j+3] == 0xff {
j += 4
}
copy(d[i:j], s[i:j])
i = j
continue
case 0:
p := d[i : i+4 : i+4]
p[0], p[1], p[2], p[3] = 0, 0, 0, 0
default:
p := d[i : i+4 : i+4]
m := unpremulRecip[a]
p[0] = uint8(uint32(q[0]) * m >> 16)
p[1] = uint8(uint32(q[1]) * m >> 16)
p[2] = uint8(uint32(q[2]) * m >> 16)
p[3] = a
}
i += 4
}
}
// unpremultiplyPixel converts one alpha-premultiplied RGBA pixel (s) to a
// non-premultiplied one (d) like color.NRGBAModel (see unpremulRecip),
// with R and B multiplied together in the two 32-bit halves of a uint64
// (c*m < 2^32, see unpremulRecip): two multiplications per pixel, not
// three. Alpha is read before any store: d may alias s as far as the
// compiler knows, so d[3] = s[3] after the other stores read it a second
// time (one load more per pixel).
func unpremultiplyPixel(d, s *[4]byte) {
a := s[3]
m := uint64(unpremulRecip[a])
rb := (uint64(s[0]) | uint64(s[2])<<32) * m
d[0] = byte(rb >> 16)
d[1] = byte(uint32(s[1]) * uint32(m) >> 16)
d[2] = byte(rb >> 48)
d[3] = a
}
// importNYCbCrA converts src for a lossy encode: its Y'CbCr part to the
// encoder's YUV 4:2:0 picture as vp8enc.FromYCbCr converts an
// *image.YCbCr, with the chroma averaged under its alpha
// (vp8enc.FromYCbCrAlpha), and its alpha samples, as they are, to a
// snapshot plane from planePool (Dx() bytes per row), or to nil if they
// are all 0xff: the picture is then coded without alpha, as before.
//
// Up to v2.0.3 the picture went through an NRGBA snapshot (convertYCbCr),
// which every Encode converted to YUV again (vp8enc.FromNRGBADithered):
// two conversions of every pixel, the second one at each encode, and a
// round trip through RGB that rounded and clamped the colors and averaged
// the chroma of each 2x2 block again (gamma-compressed) even when src
// already had one chroma sample per block, as the pictures of
// DecodeNYCbCrA and golang.org/x/image/webp do. At 1920x1080 on Apple M5
// Pro the snapshot took 3.2 ms and the conversion of each Encode 8.8 ms
// (opaque) to 15 ms (alpha in random 8x8 blocks); importNYCbCrA takes 1.2
// to 3.1 ms, once (BenchmarkNYCbCrAToYUV). The alpha plane, and so the
// ALPH chunk, is the same as before.
//
// The colors under transparent pixels are handled as the RGB path handles
// them. Without exact, the luma under fully transparent pixels and the
// fully transparent 8x8 blocks are flattened by the function that
// FromNRGBADithered calls (libwebp's WebPCleanupTransparentArea works on
// the YUV and alpha planes whether the picture came as RGBA or as YUVA);
// with exact, the samples are kept. With or without exact, the RGB path
// weights the colors of each 2x2 block by its pixels' alpha (libwebp's
// RGBA import), so that what transparent pixels hide does not tint the
// visible ones; FromYCbCrAlpha weights the chroma samples of a block the
// same way where it has more than one: for every ratio but 4:2:0, and for
// a 4:2:0 picture at an odd origin, such as a sub-image of a decoded one
// (or a negative one). A 4:2:0 picture at the origin, as DecodeNYCbCrA
// and golang.org/x/image/webp return, has one sample per block, which is
// taken as it is, as libwebp takes the chroma of a YUVA picture.
func importNYCbCrA(src *image.NYCbCrA, exact bool) (*vp8enc.Picture, []byte) {
w, h := src.Rect.Dx(), src.Rect.Dy()
// The rows of alpha samples are sliced as convertYCbCr slices them, so
// that a malformed picture (an A plane too short or missing) panics as
// it did when it was converted to NRGBA.
opaque := true
for y := range h {
if !opaqueAlpha(src.A[y*src.AStride : y*src.AStride+w]) {
opaque = false
break
}
}
if opaque {
return vp8enc.FromYCbCr(&src.YCbCr), nil
}
plane := planePool.Get(w * h)
for y := range h {
copy(plane[y*w:y*w+w], src.A[y*src.AStride:y*src.AStride+w])
}
pic := vp8enc.FromYCbCrAlpha(&src.YCbCr, plane, w)
if !exact {
pic.CleanupTransparentArea(plane, w)
}
return pic, plane
}
// opaqueAlpha reports whether every alpha sample of a is 0xff, eight at a
// time on 64-bit targets (see wide64).
func opaqueAlpha(a []byte) bool {
for wide64 && len(a) >= 8 {
if binary.LittleEndian.Uint64(a) != math.MaxUint64 {
return false
}
a = a[8:]
}
for _, v := range a {
if v != 0xff {
return false
}
}
return true
}
// hasTransparency reports whether any pixel of img has alpha below 255
// (libwebp's WebPPictureHasTransparency).
func hasTransparency(img *image.NRGBA) bool {
b := img.Rect
w := b.Dx()
for y := b.Min.Y; y < b.Max.Y; y++ {
row := img.Pix[img.PixOffset(b.Min.X, y):][:4*w]
for x := 3; x < len(row); x += 4 {
if row[x] != 0xff {
return true
}
}
}
return false
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package encoder encodes images to WebP, lossy (VP8) or lossless (VP8L),
// with a pure Go implementation of libwebp's encoders.
package encoder
import (
"context"
"errors"
"fmt"
"image"
"io"
"sync"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/container"
"github.com/kolesa-team/go-webp/v2/internal/oneshot"
"github.com/kolesa-team/go-webp/v2/internal/vp8enc"
"github.com/kolesa-team/go-webp/v2/internal/vp8lenc"
)
// maxDimension is the largest width or height of a WebP image.
const maxDimension = 16383
// ErrReleased is returned by Encode and EncodeContext when they are called
// after Release.
var ErrReleased = errors.New("encoder: Encode called after Release")
// Encoder stores information to encode image
type Encoder struct {
options *Options
config *Config
// img is the picture to encode. Like v1 (which imported the source into
// a WebPPicture in NewEncoder), it is a snapshot taken by NewEncoder,
// except for an *image.NRGBA source, which is used in place (v1 shared
// its pixels too): changes made to any other source after NewEncoder
// do not affect Encode.
img *image.NRGBA
// pic is set instead of img for *image.YCbCr and *image.NYCbCrA
// sources encoded lossy: they are converted in NewEncoder straight to
// the encoder's YUV 4:2:0 (cheaper than going through NRGBA, which
// Encode would convert to YUV every time; see importNYCbCrA). The
// alpha plane of an *image.NYCbCrA, if any, is in snap.
pic *vp8enc.Picture
// src is set instead of img for the source of a lossless one-shot
// encode (webp.Encode, webp.EncodeContext; see oneshot.Source) that is
// not an *image.NRGBA: the encode converts it a row at a time straight
// into the lossless encoder's working image, which a snapshot would
// only be copied into. A 12 MP encode then holds one 48 MB copy of
// the picture instead of two.
src image.Image
// bounds of the source image
bounds image.Rectangle
// mu is held for reading by every encode and for writing by Release,
// which therefore waits for the encodes in progress.
mu sync.RWMutex
released bool
// snap is the pooled storage of the snapshot (img's pixels, or pic and
// its alpha plane), if any. Release hands it back to the pools; if
// Release is never called, it is ordinary garbage once the Encoder is
// unreachable. Slices live here, behind a pointer, and not in the
// Encoder itself, so that Encoder values stay comparable, as they were
// up to v2.0.3.
snap *snapshot
}
// snapshot is the pooled storage of an Encoder's copy of its source.
//
// Up to v2.0.2 a runtime.AddCleanup cleanup on the Encoder also handed it
// back to the pools once the Encoder was unreachable, as a safety net for
// code that never calls Release. That net made such code's heap grow
// without bound: a cleanup's argument (the snapshot) is a GC root until the
// cleanup has run, so the collection that finds an Encoder unreachable
// still marks its snapshot. Every snapshot made in a cycle counted as live
// heap, on top of the pools' contents, and the heap goal rose by about the
// pools' contents at each collection (a finalizer on the snapshot does the
// same). NewEncoder without Release on a 256x256 picture reached about
// 8 GiB of heap within 8 s, against a few MiB without the net. Cleanups
// could also stay queued after a GOMAXPROCS decrease (golang/go#83361).
// Without the net, a snapshot that is not released is collected like any
// other memory, as v1's were.
type snapshot struct {
pix []byte // storage of Encoder.img, from pooledNRGBA
pic *vp8enc.Picture // Encoder.pic, from vp8enc.FromYCbCr
// alpha is the snapshot of an *image.NYCbCrA's alpha plane that goes
// with pic, Dx() bytes per row, from planePool; nil if every sample is
// 0xff.
alpha []byte
}
func (s *snapshot) release() {
putPix(s.pix)
s.pix = nil
s.pic.Release()
s.pic = nil
planePool.Put(s.alpha)
s.alpha = nil
snapshotsReleased.Add(1)
}
// snapshotsReleased counts the snapshots handed back by Release, for the
// tests.
var snapshotsReleased atomic.Int64
// NewEncoder return new encoder instance
func NewEncoder(src image.Image, options *Options) (e *Encoder, err error) {
var config *Config
if options == nil {
options, _ = NewLossyEncoderOptions(PresetDefault, 75)
}
if config, err = options.GetConfig(); err != nil {
return nil, err
}
oneShot := false
if s, ok := src.(oneshot.Source); ok {
src, oneShot = s.Image, true
}
if src == nil {
return nil, errors.New("cannot encode webppicture: nil image")
}
e = &Encoder{options: options, config: config, bounds: src.Bounds()}
if !validDimensions(e.bounds) {
// Reported by Encode, as libwebp's WebPEncode does; skip converting
// a picture that cannot be encoded.
return e, nil
}
// The snapshot's storage comes from pools. Encode does not consume it
// (Encode may be called several times); Release returns it.
s := &snapshot{}
if v, ok := src.(*image.NRGBA); ok {
e.img = v
} else if ycc, ok := src.(*image.YCbCr); ok && !config.Lossless {
e.pic = vp8enc.FromYCbCr(ycc)
s.pic = e.pic
} else if nycca, ok := src.(*image.NYCbCrA); ok && !config.Lossless {
e.pic, s.alpha = importNYCbCrA(nycca, config.Exact)
s.pic = e.pic
} else if oneShot && config.Lossless {
e.src = src
} else {
e.img, s.pix = pooledNRGBA(e.bounds.Dx(), e.bounds.Dy())
convertNRGBA(e.img, src)
}
if s.pix != nil || s.pic != nil {
e.snap = s
}
return e, nil
}
func validDimensions(r image.Rectangle) bool {
w, h := r.Dx(), r.Dy()
return w > 0 && h > 0 && w <= maxDimension && h <= maxDimension
}
// Encode picture and flush to io.Writer
func (e *Encoder) Encode(w io.Writer) error {
out, err := e.encode(nil)
if err != nil {
return err
}
_, err = w.Write(out)
return err
}
// EncodeContext is Encode, but gives up when ctx is done: the encoders
// check ctx about once per macroblock row (lossy) and between their passes
// and search rows (lossless), stop together with their helper goroutines,
// and EncodeContext returns ctx.Err() (not wrapped). Nothing is written to
// w unless ctx is still not done once the file is complete. Converting the
// source picture, which NewEncoder does, is not covered.
func (e *Encoder) EncodeContext(ctx context.Context, w io.Writer) error {
if err := ctx.Err(); err != nil {
return err
}
var interrupt func() bool
if ctx.Done() != nil { // nil for contexts that can never be canceled
interrupt = func() bool { return ctx.Err() != nil }
}
out, err := e.encode(interrupt)
if cerr := ctx.Err(); cerr != nil && (err == nil || interrupted(err)) {
return cerr
}
if err != nil {
return err
}
_, err = w.Write(out)
return err
}
// Release hands the Encoder's copy of its source picture back to internal
// pools, so that later encodes can reuse the memory. Encode and
// EncodeContext return ErrReleased afterwards. Release waits for the encodes
// in progress on other goroutines; calling it again does nothing.
//
// Calling Release is optional: otherwise the garbage collector reclaims the
// copy like any other memory once the Encoder is unreachable, as with v1,
// which had no Release; only Release lets later encodes reuse it.
func (e *Encoder) Release() {
if e == nil {
return
}
e.mu.Lock()
defer e.mu.Unlock()
if e.released {
return
}
e.released = true
if e.snap != nil {
e.snap.release()
e.snap = nil
}
e.img, e.pic, e.src = nil, nil, nil
}
// encode returns the WebP file. interrupt, if not nil, is polled by the
// encoders (see EncodeContext).
func (e *Encoder) encode(interrupt func() bool) ([]byte, error) {
// The read lock, held until the snapshot is no longer used, makes
// Release wait for this encode before it hands the storage back.
e.mu.RLock()
defer e.mu.RUnlock()
if e.released {
return nil, ErrReleased
}
if !validDimensions(e.bounds) {
return nil, &encodeError{fmt.Errorf("bad dimension %dx%d", e.bounds.Dx(), e.bounds.Dy())}
}
var (
out []byte
err error
)
if e.config.Lossless {
out, err = e.encodeLossless(interrupt)
} else {
out, err = e.encodeLossy(interrupt)
}
if err != nil {
return nil, &encodeError{err}
}
return out, nil
}
// interrupted reports whether err comes from an encoder that stopped
// because its interrupt hook asked it to.
func interrupted(err error) bool {
return errors.Is(err, vp8enc.ErrInterrupted) || errors.Is(err, vp8lenc.ErrInterrupted) ||
errors.Is(err, errAlphaInterrupted)
}
// encodeError reports an encoding failure with exactly v1's message,
// "cannot encode webppicture" (v1 returned it for every libwebp failure),
// and unwraps to the detailed cause.
type encodeError struct{ err error }
func (e *encodeError) Error() string { return "cannot encode webppicture" }
func (e *encodeError) Unwrap() error { return e.err }
// sliceWriter collects the container output in a single, pre-sized buffer,
// so that the destination io.Writer receives exactly one Write call.
type sliceWriter struct{ b []byte }
func (s *sliceWriter) Write(p []byte) (int, error) {
s.b = append(s.b, p...)
return len(p), nil
}
func (e *Encoder) encodeLossless(interrupt func() bool) ([]byte, error) {
c := e.config
cfg := &vp8lenc.Config{
Quality: c.Quality,
Method: c.Method,
Exact: c.Exact,
NearLossless: c.NearLossless,
UseDeltaPalette: c.UseDeltaPalette,
LowMemory: c.LowMemory,
ThreadLevel: c.ThreadLevel,
ImageHint: int(c.ImageHint),
Interrupt: interrupt,
}
var (
buf []byte
err error
)
if e.src != nil {
var rc rowConverter
rc.init(e.src, e.bounds)
w := e.bounds.Dx()
row := pixPool.Get(4 * w)
defer putPix(row)
buf, err = vp8lenc.EncodeRowsWithHeadroom(w, e.bounds.Dy(), func(y int) []byte {
rc.convertRow(row[:4*w], y)
return row
}, cfg, container.LosslessHeaderSize)
} else {
buf, err = vp8lenc.EncodeWithHeadroom(e.img, cfg, container.LosslessHeaderSize)
}
if err != nil {
return nil, err
}
// The payload was written after LosslessHeaderSize bytes of headroom:
// add the RIFF headers in place instead of copying it.
return container.FrameLossless(buf)
}
func (e *Encoder) encodeLossy(interrupt func() bool) ([]byte, error) {
c := e.config
cfg := vp8enc.Config{
Quality: c.Quality,
Method: c.Method,
ImageHint: int(c.ImageHint),
TargetSize: c.TargetSize,
TargetPSNR: c.TargetPSNR,
Pass: c.Pass,
Segments: c.Segments,
SNSStrength: c.SNSStrength,
FilterStrength: c.FilterStrength,
FilterSharpness: c.FilterSharpness,
FilterType: c.FilterType,
Autofilter: c.Autofilter,
Preprocessing: c.Preprocessing,
Partitions: c.Partitions,
PartitionLimit: c.PartitionLimit,
EmulateJPEGSize: c.EmulateJPEGSize,
ThreadLevel: c.ThreadLevel,
LowMemory: c.LowMemory,
Interrupt: interrupt,
}
var (
payload []byte
alph []byte
err error
)
// Without alpha the file is a simple one: the VP8 payload is written
// after room for the RIFF and chunk headers, which are then filled in
// place instead of copying the payload into a new buffer.
headroom := container.LossyHeaderSize
var (
src alphaSource // the alpha samples, if any is below 0xff
hasAlpha bool
)
if e.pic != nil {
// e.snap holds e.pic, so it is set too.
if a := e.snap.alpha; a != nil {
src, hasAlpha = alphaSource{plane: a, w: e.bounds.Dx(), h: e.bounds.Dy()}, true
}
} else if hasTransparency(e.img) {
src, hasAlpha = nrgbaAlpha(e.img), true
}
var at *alphaTask
if hasAlpha {
headroom = 0
if c.ThreadLevel {
// Like libwebp's alpha worker (thread_level > 0), code the
// alpha plane concurrently with the VP8 frame when a helper
// goroutine is available.
at = startAlpha(src, c, interrupt, vp8enc.WavefrontHelpers(e.bounds.Dx(), e.bounds.Dy(), &cfg))
}
if at != nil {
// Joins the helper on every return path, panics included.
defer at.cancel()
cfg.PassHelpers = &at.passHelpers
} else if alph, err = alphaEncode(src, c, interrupt, alphaGates{}); err != nil {
return nil, err
}
}
if e.pic != nil {
payload, err = vp8Encode(e.pic, &cfg, headroom)
} else {
dithering := vp8enc.DitheringFor(&vp8enc.Config{Quality: c.Quality, Preprocessing: c.Preprocessing})
pic := vp8enc.FromNRGBADithered(e.img, c.UseSharpYUV || c.Preprocessing&4 != 0, c.Exact, dithering)
payload, err = vp8Encode(pic, &cfg, headroom)
pic.Release()
}
if at != nil {
if err == nil {
// The frame's slots are free for the alpha plane.
at.frameDone()
}
// The sequential order codes the alpha plane first, so its errors
// take precedence, except an interruption caused by the failure of
// the VP8 frame.
var aerr error
alph, aerr = at.wait(err != nil)
if aerr != nil && (err == nil || !interrupted(aerr)) {
return nil, aerr
}
}
if err != nil {
return nil, err
}
if headroom > 0 {
return container.FrameLossy(payload)
}
sw := sliceWriter{b: make([]byte, 0, len(payload)+len(alph)+64)}
if err := container.WriteLossy(&sw, e.bounds.Dx(), e.bounds.Dy(), payload, alph); err != nil {
return nil, err
}
return sw.b, nil
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package encoder
import (
"errors"
"fmt"
)
// Default libwebp image hints
const (
HintDefault ImageHint = iota
HintPicture
HintPhoto
HintGraph
HintLast
)
// Default libwebp presets
const (
PresetDefault EncodingPreset = iota
PresetPicture
PresetPhoto
PresetDrawing
PresetIcon
PresetText
)
type (
// ImageHint hint of picture
ImageHint int
// EncodingPreset using Preset
EncodingPreset int
// Options specifies webp encoding parameters. The field semantics are
// those of libwebp's WebPConfig.
Options struct {
Lossless bool
Quality float32
Method int
ImageHint ImageHint
TargetSize int
TargetPsnr float32
Segments int
SnsStrength int
FilterStrength int
FilterSharpness int
FilterType int
Autofilter bool
AlphaCompression int
AlphaFiltering int
alphaQuality int
Pass int
// Disabled for compatibility with old version libwebp
// QMin int
// QMax int
ShowCompressed bool
Preprocessing int
Partitions int
PartitionLimit int
EmulateJpegSize bool
ThreadLevel bool
LowMemory bool
NearLossless int
Exact int
UseDeltaPalette bool
UseSharpYuv bool
}
)
// Config is the validated encoding configuration built by Options.GetConfig.
// It mirrors libwebp's WebPConfig field for field (C int flags are bools).
// In v1 GetConfig returned the cgo type *C.WebPConfig; v2 returns this pure
// Go equivalent.
type Config struct {
// Lossless selects lossless (VP8L) instead of lossy (VP8) coding.
Lossless bool
// Quality is in [0, 100]. For lossy coding it trades size for quality;
// for lossless coding it is the compression effort.
Quality float32
// Method is the speed/quality trade-off in [0, 6] (0 = fastest).
Method int
// ImageHint is a hint about the picture type (lossless only).
ImageHint ImageHint
// TargetSize, if non-zero, is the desired output size in bytes (lossy).
// As in libwebp it is only honored with Pass > 1.
TargetSize int
// TargetPSNR, if non-zero, is the desired PSNR in dB (lossy). As in
// libwebp it is only honored with Pass > 1.
TargetPSNR float32
// Segments is the number of segments in [1, 4] (lossy).
Segments int
// SNSStrength is the spatial noise shaping strength in [0, 100] (lossy).
SNSStrength int
// FilterStrength is the loop filter strength in [0, 100] (lossy).
FilterStrength int
// FilterSharpness is the loop filter sharpness in [0, 7] (lossy).
FilterSharpness int
// FilterType is 0 for the simple and 1 for the strong loop filter (lossy).
FilterType int
// Autofilter adjusts the filter strength automatically (lossy).
Autofilter bool
// AlphaCompression is 0 for raw and 1 for lossless-compressed alpha.
AlphaCompression int
// AlphaFiltering is 0 (none), 1 (fast) or 2 (best) alpha prediction filtering.
AlphaFiltering int
// AlphaQuality in [0, 100]: below 100 the alpha plane is quantized.
AlphaQuality int
// Pass is the number of entropy-analysis passes in [1, 10] (lossy).
Pass int
// ShowCompressed is accepted for compatibility; it has no effect.
ShowCompressed bool
// Preprocessing in [0, 7]: bit 0 segment smoothing, bit 1 dithering,
// bit 2 sharp YUV conversion (lossy). Bits 1 and 2 change the
// conversion from RGB, which *image.YCbCr and *image.NYCbCrA sources
// skip, also with PresetPhoto, which sets bit 1 (up to v2.0.3, an
// *image.NYCbCrA went through RGB and was dithered). To have them
// apply, convert the picture to *image.NRGBA first; v2.0.3 converted
// each pixel with color.YCbCrToRGB and kept its alpha sample as is,
// while draw.Draw and At go through premultiplied colors.
Preprocessing int
// Partitions is log2 of the number of token partitions in [0, 3]
// (lossy). As in libwebp it is ignored (a single partition is written)
// for Method >= 3 unless LowMemory is set.
Partitions int
// PartitionLimit in [0, 100] allows quality degradation to fit the
// 512k limit on the first partition (lossy).
PartitionLimit int
// EmulateJPEGSize maps the quality like a JPEG encoder would (lossy).
EmulateJPEGSize bool
// ThreadLevel allows the encoder to use helper goroutines from the
// process-wide budget of GOMAXPROCS-1 helpers shared by all concurrent
// Encode and Decode calls:
// - lossy: the analysis pass runs in row bands (pictures of at least
// 384 macroblocks, 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 it (about 0.3 MP at methods 3-6, several
// MP at methods 0-2), and the compressed alpha plane of a
// transparent picture (64K pixels or more) is coded while the VP8
// frame is, two of its candidate filters at a time (up to 8 MP; at
// method 6 with AlphaQuality 100 its lossless encode codes two
// configurations at a time instead); until the frame is coded,
// the alpha plane's own helpers leave the frame the slots its
// coding passes need (all but at most one when they need more
// than 4), so that the frame is not slowed down on small budgets;
// - 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, and level 9 codes at
// most two candidate configurations at a time (one above 8 MP).
// When no helper slot is free the calling goroutine does the work. The
// output is byte-identical with or without ThreadLevel and for any
// budget. ThreadLevel lowers latency at some extra CPU cost, and at
// the cost of a second working set where two candidates are coded at a
// time; servers that already encode concurrently may prefer to leave
// it off. With LowMemory, the lossless encoder and the alpha plane
// ignore ThreadLevel.
ThreadLevel bool
// LowMemory lowers the peak memory of lossless coding where the
// encoder would hold more than one candidate at a time, at some cost
// in speed or size:
// - levels 8 and 9 (Method 5 at Quality 75 or more, Method 6 at
// Quality 100) skip their trial parse without color cache, whose
// two more lists of backward references (up to 8 bytes per pixel
// each) about double their peak;
// - pictures of at most 16 colors skip the box parse (a second match
// table);
// - ThreadLevel is ignored: its match search keeps a second match
// table (4 bytes per pixel), and level 9 codes two candidates at a
// time.
// At levels 0 to 7 without ThreadLevel, the peak of a picture of more
// than 16 colors stays the same. LowMemory also limits LZ77 matches to
// the last 65536 pixels, which saves no memory and can make the output
// larger. For lossy coding it only re-enables Partitions at
// Method >= 3, as libwebp's low_memory does, and, with ThreadLevel,
// keeps the alpha plane on one goroutine.
LowMemory bool
// NearLossless in [0, 100] enables near-lossless preprocessing (100 = off).
NearLossless int
// Exact preserves the RGB values (the Y'CbCr samples of an
// *image.NYCbCrA encoded lossy) under fully transparent pixels.
Exact bool
// UseDeltaPalette is accepted for compatibility; it has no effect.
UseDeltaPalette bool
// UseSharpYUV uses the slower but sharper RGB->YUV conversion (lossy),
// which *image.YCbCr and *image.NYCbCrA sources skip (see
// Preprocessing).
UseSharpYUV bool
}
// validate reproduces libwebp's WebPValidateConfig. Like libwebp (whose
// range checks are comparisons that are false for NaN), a NaN Quality or
// TargetPSNR is accepted: the lossy encoder then codes at the best quality
// (quantizer index 0), which is what libwebp does.
func (c *Config) validate() bool {
switch {
case c.Quality < 0 || c.Quality > 100,
c.TargetSize < 0,
c.TargetPSNR < 0,
c.Method < 0 || c.Method > 6,
c.Segments < 1 || c.Segments > 4,
c.SNSStrength < 0 || c.SNSStrength > 100,
c.FilterStrength < 0 || c.FilterStrength > 100,
c.FilterSharpness < 0 || c.FilterSharpness > 7,
c.FilterType < 0 || c.FilterType > 1,
c.Pass < 1 || c.Pass > 10,
c.Preprocessing < 0 || c.Preprocessing > 7,
c.Partitions < 0 || c.Partitions > 3,
c.PartitionLimit < 0 || c.PartitionLimit > 100,
c.AlphaCompression < 0,
c.AlphaFiltering < 0,
c.AlphaQuality < 0 || c.AlphaQuality > 100,
c.NearLossless < 0 || c.NearLossless > 100,
c.ImageHint < 0 || c.ImageHint >= HintLast:
return false
}
return true
}
// presetConfig reproduces libwebp's WebPConfigPreset (without validation).
func presetConfig(preset EncodingPreset, quality float32) Config {
c := Config{
Quality: quality,
Method: 4,
SNSStrength: 50,
FilterStrength: 60,
FilterType: 1,
Segments: 4,
Pass: 1,
AlphaCompression: 1,
AlphaFiltering: 1,
AlphaQuality: 100,
NearLossless: 100,
}
switch preset {
case PresetPicture:
c.SNSStrength = 80
c.FilterSharpness = 4
c.FilterStrength = 35
c.Preprocessing &^= 2
case PresetPhoto:
c.SNSStrength = 80
c.FilterSharpness = 3
c.FilterStrength = 30
c.Preprocessing |= 2
case PresetDrawing:
c.SNSStrength = 25
c.FilterSharpness = 6
c.FilterStrength = 10
case PresetIcon:
c.SNSStrength = 0
c.FilterStrength = 0
c.Preprocessing &^= 2
case PresetText:
c.SNSStrength = 0
c.FilterStrength = 0
c.Preprocessing &^= 2
c.Segments = 2
}
return c
}
// losslessPresets maps the lossless level (cwebp -z) to (method, quality),
// as libwebp's WebPConfigLosslessPreset.
var losslessPresets = [10]struct {
method int
quality float32
}{
{0, 0}, {1, 20}, {2, 25}, {3, 30}, {3, 50},
{4, 50}, {4, 75}, {4, 90}, {5, 90}, {6, 100},
}
// NewLossyEncoderOptions build lossy encoding options
func NewLossyEncoderOptions(preset EncodingPreset, quality float32) (options *Options, err error) {
c := presetConfig(preset, quality)
if !c.validate() {
return nil, errors.New("cannot init encoder config")
}
options = &Options{}
options.sync(&c)
return options, nil
}
// NewLosslessEncoderOptions build lossless encoding options
func NewLosslessEncoderOptions(preset EncodingPreset, level int) (options *Options, err error) {
if options, err = NewLossyEncoderOptions(preset, 0); err != nil {
return nil, err
}
if level < 0 || level >= len(losslessPresets) {
return nil, errors.New("cannot init lossless preset")
}
options.Lossless = true
options.Method = losslessPresets[level].method
options.Quality = losslessPresets[level].quality
return options, nil
}
func (o *Options) sync(c *Config) {
o.Lossless = c.Lossless
o.Quality = c.Quality
o.Method = c.Method
o.ImageHint = c.ImageHint
o.TargetSize = c.TargetSize
o.TargetPsnr = c.TargetPSNR
o.Segments = c.Segments
o.SnsStrength = c.SNSStrength
o.FilterStrength = c.FilterStrength
o.FilterSharpness = c.FilterSharpness
o.FilterType = c.FilterType
o.Autofilter = c.Autofilter
o.AlphaCompression = c.AlphaCompression
o.AlphaFiltering = c.AlphaFiltering
o.alphaQuality = c.AlphaQuality
o.Pass = c.Pass
o.ShowCompressed = c.ShowCompressed
o.Preprocessing = c.Preprocessing
o.Partitions = c.Partitions
o.PartitionLimit = c.PartitionLimit
o.EmulateJpegSize = c.EmulateJPEGSize
o.ThreadLevel = c.ThreadLevel
o.LowMemory = c.LowMemory
o.NearLossless = c.NearLossless
o.Exact = 0
if c.Exact {
o.Exact = 1
}
o.UseDeltaPalette = c.UseDeltaPalette
o.UseSharpYuv = c.UseSharpYUV
}
// GetConfig builds and validates the encoder configuration (the equivalent of
// libwebp's WebPConfig after WebPValidateConfig). A nil *Options yields the
// lossless preset of level 0.
func (o *Options) GetConfig() (*Config, error) {
var err error
if o == nil {
o, err = NewLosslessEncoderOptions(PresetDefault, 0)
if err != nil {
return nil, fmt.Errorf("cannot validate default config: [%w]", err)
}
}
c := &Config{
Lossless: o.Lossless,
Quality: o.Quality,
Method: o.Method,
ImageHint: o.ImageHint,
TargetSize: o.TargetSize,
TargetPSNR: o.TargetPsnr,
Segments: o.Segments,
SNSStrength: o.SnsStrength,
FilterStrength: o.FilterStrength,
FilterSharpness: o.FilterSharpness,
FilterType: o.FilterType,
Autofilter: o.Autofilter,
AlphaCompression: o.AlphaCompression,
AlphaFiltering: o.AlphaFiltering,
AlphaQuality: o.alphaQuality,
Pass: o.Pass,
ShowCompressed: o.ShowCompressed,
Preprocessing: o.Preprocessing,
Partitions: o.Partitions,
PartitionLimit: o.PartitionLimit,
EmulateJPEGSize: o.EmulateJpegSize,
ThreadLevel: o.ThreadLevel,
LowMemory: o.LowMemory,
NearLossless: o.NearLossless,
Exact: o.Exact == 1,
UseDeltaPalette: o.UseDeltaPalette,
UseSharpYUV: o.UseSharpYuv,
}
if o.Exact < 0 || o.Exact > 1 || !c.validate() {
return nil, errors.New("cannot validate config")
}
return c, nil
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package alpha implements the helpers around the WebP ALPH chunk: header
// byte, spatial prediction filters, level quantization (encoder) and level
// dequantization smoothing (decoder "alpha dithering"), with libwebp's exact
// semantics.
//
// Algorithm adapted from libwebp (BSD-3-Clause): src/dsp/filters.c,
// src/utils/filters_utils.c, src/utils/quant_levels_utils.c,
// src/utils/quant_levels_dec_utils.c, src/enc/alpha_enc.c and
// src/dec/alpha_dec.c.
package alpha
import (
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// Prediction filters of the ALPH chunk.
const (
FilterNone = 0
FilterHorizontal = 1
FilterVertical = 2
FilterGradient = 3
)
// Compression methods of the ALPH chunk.
const (
CompressionNone = 0 // raw alpha bytes
CompressionLossless = 1 // VP8L-compressed green channel
)
// PreprocessingLevels marks an alpha plane quantized by QuantizeLevels; a
// decoder may then smooth it with Dequantize.
const PreprocessingLevels = 1
// Header is the decoded first byte of an ALPH chunk.
type Header struct {
Compression int // 0: none, 1: lossless
Filter int // FilterNone .. FilterGradient
PreProcessing int // 0: none, 1: quantized levels
}
// ParseHeader decodes the ALPH header byte
// (compression | filter<<2 | preprocessing<<4, bits 6-7 reserved), with the
// same validation as libwebp's ALPHInit.
func ParseHeader(b byte) (Header, error) {
h := Header{
Compression: int(b & 3),
Filter: int(b>>2) & 3,
PreProcessing: int(b>>4) & 3,
}
if h.Compression > CompressionLossless || h.PreProcessing > PreprocessingLevels || b>>6 != 0 {
return Header{}, status.Bitstream("invalid ALPH header")
}
return h, nil
}
// Byte encodes the header.
func (h Header) Byte() byte {
return byte(h.Compression&3) | byte(h.Filter&3)<<2 | byte(h.PreProcessing&3)<<4
}
// AlphaLevels returns the number of quantization levels libwebp's encoder
// uses for the given alpha_quality (0..100); 256 or more means "no
// quantization" (alpha_quality == 100).
func AlphaLevels(quality int) int {
if quality <= 70 {
return 2 + quality/5
}
return 16 + (quality-70)*8
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package alpha
// Algorithm adapted from libwebp (BSD-3-Clause): src/dsp/filters.c and src/utils/filters_utils.c
// (WebPFilters, WebPUnfilters, GradientPredictor, WebPEstimateBestFilter).
import "encoding/binary"
const (
hiBits = 0x8080808080808080
)
// addBytes sets out[i] = a[i] + b[i] (mod 256) for i < n, eight bytes at a
// time.
func addBytes(out, a, b []byte, n int) {
out, a, b = out[:n], a[:n], b[:n]
i := 0
for ; i+8 <= n; i += 8 {
x := binary.LittleEndian.Uint64(a[i:])
y := binary.LittleEndian.Uint64(b[i:])
binary.LittleEndian.PutUint64(out[i:], ((x&^hiBits)+(y&^hiBits))^((x^y)&hiBits))
}
for ; i < n; i++ {
out[i] = a[i] + b[i]
}
}
// subBytes sets out[i] = a[i] - b[i] (mod 256) for i < n, eight bytes at a
// time.
func subBytes(out, a, b []byte, n int) {
out, a, b = out[:n], a[:n], b[:n]
i := 0
for ; i+8 <= n; i += 8 {
x := binary.LittleEndian.Uint64(a[i:])
y := binary.LittleEndian.Uint64(b[i:])
binary.LittleEndian.PutUint64(out[i:], ((x|hiBits)-(y&^hiBits))^((x^^y)&hiBits))
}
for ; i < n; i++ {
out[i] = a[i] - b[i]
}
}
// gradientPredictor is libwebp's GradientPredictor: clip(a + b - c).
func gradientPredictor(a, b, c byte) byte {
g := int(a) + int(b) - int(c)
if g&^0xff == 0 {
return byte(g)
}
if g < 0 {
return 0
}
return 255
}
// UnfilterRow reverses filter on one row: out = unfilter(in) using prev as
// the previous (already reconstructed) row, or nil for the first row. in and
// out may be the same slice; prev must not alias out. This is the streaming
// form used by alpha decoders (libwebp's WebPUnfilters).
func UnfilterRow(filter int, prev, in, out []byte) {
width := len(in)
if width == 0 {
return
}
out = out[:width]
switch filter {
case FilterHorizontal:
var pred byte
if prev != nil {
pred = prev[0]
}
unfilterHorizontal(pred, in, out)
case FilterVertical:
if prev == nil {
unfilterHorizontal(0, in, out)
} else {
unfilterVertical(prev, in, out)
}
case FilterGradient:
if prev == nil {
unfilterHorizontal(0, in, out)
} else {
gradientUnfilter(prev[:width], in, out)
}
default:
if &out[0] != &in[0] {
copy(out, in)
}
}
}
// unfilterHorizontalGo is the reference of unfilterHorizontal
// (unfilter_*.go): out[i] = pred + in[0] + ... + in[i] (mod 256), libwebp's
// HorizontalUnfilter_C with pred the left prediction of the first pixel.
// in may alias out.
func unfilterHorizontalGo(pred byte, in, out []byte) {
out = out[:len(in)]
for i, v := range in {
pred += v
out[i] = pred
}
}
// unfilterVerticalGo is the reference of unfilterVertical (unfilter_*.go):
// out[i] = prev[i] + in[i] (mod 256) for i < len(in). in may alias out.
func unfilterVerticalGo(prev, in, out []byte) {
addBytes(out, prev, in, len(in))
}
func gradientUnfilter(prev, in, out []byte) {
prev = prev[:len(in)]
out = out[:len(in)]
top := prev[0]
topLeft, left := top, top
for i, v := range in {
top = prev[i]
left = v + gradientPredictor(left, top, topLeft)
topLeft = top
out[i] = left
}
}
// Unfilter reverses the prediction filter in place on a width x height
// plane, row by row, with libwebp's semantics (first row is
// left-predicted from 0, first column of the other rows predicted from
// above).
func Unfilter(filter int, plane []byte, width, height, stride int) {
if filter == FilterNone || width <= 0 || height <= 0 {
return
}
var prev []byte
for y := 0; y < height; y++ {
row := plane[y*stride : y*stride+width]
UnfilterRow(filter, prev, row, row)
prev = row
}
}
// Filter applies the forward prediction filter to the width x height plane
// src and writes the residuals to dst (libwebp's WebPFilters). With
// FilterNone the plane is copied.
func Filter(filter int, src []byte, width, height, srcStride int, dst []byte, dstStride int) {
if width <= 0 || height <= 0 {
return
}
if filter == FilterNone {
for y := 0; y < height; y++ {
copy(dst[y*dstStride:y*dstStride+width], src[y*srcStride:y*srcStride+width])
}
return
}
// Top row: first pixel copied, the rest left-predicted, for all filters.
in := src[:width]
out := dst[:width]
out[0] = in[0]
subBytes(out[1:], in[1:], in, width-1)
for y := 1; y < height; y++ {
in := src[y*srcStride : y*srcStride+width]
up := src[(y-1)*srcStride : (y-1)*srcStride+width]
out := dst[y*dstStride : y*dstStride+width]
switch filter {
case FilterHorizontal:
out[0] = in[0] - up[0]
subBytes(out[1:], in[1:], in, width-1)
case FilterVertical:
subBytes(out, in, up, width)
default: // FilterGradient
out[0] = in[0] - up[0]
gradientFilterRow(in, up, out)
}
}
}
// gradientFilterRow computes out[x] = in[x] - clip(in[x-1] + up[x] - up[x-1])
// for x >= 1. There is no dependency between iterations, so the clipping is
// done branch-free.
func gradientFilterRow(in, up, out []byte) {
n := len(in)
up = up[:n]
out = out[:n]
for x := 1; x < n; x++ {
g := min(max(int(in[x-1])+int(up[x])-int(up[x-1]), 0), 255)
out[x] = in[x] - byte(g)
}
}
// EstimateBestFilter mirrors libwebp's WebPEstimateBestFilter: it samples
// every other pixel and picks the filter with the most compact residual
// histogram. (libwebp addresses the row above with the width; it is only
// ever called with stride == width, where both agree.)
func EstimateBestFilter(plane []byte, width, height, stride int) int {
const smax = 16
var bins [4][smax]bool
for j := 2; j < height-1; j += 2 {
p := plane[j*stride : j*stride+width]
up := plane[(j-1)*stride : (j-1)*stride+width]
mean := int(p[0])
for i := 2; i < width-1; i += 2 {
v := int(p[i])
bins[FilterNone][sdiff(v, mean)] = true
bins[FilterHorizontal][sdiff(v, int(p[i-1]))] = true
bins[FilterVertical][sdiff(v, int(up[i]))] = true
bins[FilterGradient][sdiff(v, int(gradientPredictor(p[i-1], up[i], up[i-1])))] = true
mean = (3*mean + v + 2) >> 2
}
}
best, bestScore := FilterNone, int(^uint(0)>>1)
for f := FilterNone; f <= FilterGradient; f++ {
score := 0
for i, used := range bins[f] {
if used {
score += i
}
}
if score < bestScore {
best, bestScore = f, score
}
}
return best
}
func sdiff(a, b int) int {
d := a - b
if d < 0 {
d = -d
}
return (d >> 4) & 15
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package alpha
// Algorithm adapted from libwebp (BSD-3-Clause): src/utils/quant_levels_utils.c (QuantizeLevels) and
// src/utils/quant_levels_dec_utils.c (WebPDequantizeLevels).
import (
"sync"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// QuantizeLevels reduces the width x height plane in place to at most
// numLevels (2..256) distinct values with libwebp's k-means
// (QuantizeLevels in src/utils/quant_levels_utils.c). The encoder uses it
// when alpha_quality < 100, with numLevels = AlphaLevels(alpha_quality).
func QuantizeLevels(plane []byte, width, height, stride, numLevels int) error {
if width <= 0 || height <= 0 || stride < width || numLevels < 2 || numLevels > 256 {
return status.InvalidParam("alpha: invalid QuantizeLevels arguments")
}
if len(plane) < (height-1)*stride+width {
return status.InvalidParam("alpha: plane too small")
}
const (
maxIter = 6
errorThreshold = 1e-4
)
var freq [256]int
var qLevel [256]int
var invQLevel [256]float64
minS, maxS := 255, 0
numLevelsIn := 0
for y := 0; y < height; y++ {
for _, v := range plane[y*stride : y*stride+width] {
freq[v]++
}
}
for s, f := range freq {
if f == 0 {
continue
}
numLevelsIn++
minS = min(minS, s)
maxS = max(maxS, s)
}
if numLevelsIn <= numLevels {
return nil
}
for i := 0; i < numLevels; i++ {
invQLevel[i] = float64(minS) + float64(float64(maxS-minS)*float64(i))/float64(numLevels-1)
}
qLevel[minS] = 0
qLevel[maxS] = numLevels - 1
errThreshold := errorThreshold * float64(width*height)
lastErr := 1e38
for iter := 0; iter < maxIter; iter++ {
var qSum, qCount [256]float64
slot := 0
for s := minS; s <= maxS; s++ {
for slot < numLevels-1 && float64(2*s) > invQLevel[slot]+invQLevel[slot+1] {
slot++
}
if freq[s] > 0 {
qSum[slot] += float64(s * freq[s])
qCount[slot] += float64(freq[s])
}
qLevel[s] = slot
}
if numLevels > 2 {
for slot := 1; slot < numLevels-1; slot++ {
if c := qCount[slot]; c > 0 {
invQLevel[slot] = qSum[slot] / c
}
}
}
e := 0.0
for s := minS; s <= maxS; s++ {
d := float64(s) - invQLevel[qLevel[s]]
// Explicit conversions forbid fused multiply-add, keeping the
// rounding identical to libwebp's C code.
e += float64(float64(float64(freq[s])*d) * d)
}
if lastErr-e < errThreshold {
break
}
lastErr = e
}
var m [256]byte
for s := minS; s <= maxS; s++ {
m[s] = byte(int(invQLevel[qLevel[s]] + .5))
}
for y := 0; y < height; y++ {
row := plane[y*stride : y*stride+width]
for i, v := range row {
row[i] = m[v]
}
}
return nil
}
// Dequantization smoothing parameters (libwebp quant_levels_dec_utils.c).
const (
fix = 16 // fixed-point precision for averaging
lfix = 2 // extra precision for look-up table
lutSize = (1 << (8 + lfix)) - 1
)
type smoother struct {
scratch []uint16 // (2*radius+2) rows of width: R circular rows + output row
average []uint16
correction [1 + 2*lutSize]int16
}
var smootherPool = sync.Pool{New: func() any { return new(smoother) }}
// Dequantize smooths the width x height alpha plane in place to hide
// quantization banding, exactly like libwebp's WebPDequantizeLevels (the
// decoder's alpha_dithering_strength, 0..100). It should only be applied to
// planes whose ALPH header has PreProcessing == 1.
func Dequantize(plane []byte, width, height, stride, strength int) error {
if strength < 0 || strength > 100 || width <= 0 || height <= 0 || stride < width {
return status.InvalidParam("alpha: invalid Dequantize arguments")
}
if len(plane) < (height-1)*stride+width {
return status.InvalidParam("alpha: plane too small")
}
radius := 4 * strength / 100
if 2*radius+1 > width {
radius = (width - 1) >> 1
}
if 2*radius+1 > height {
radius = (height - 1) >> 1
}
if radius <= 0 {
return nil
}
// Level statistics.
var used [256]bool
minV, maxV := 255, 0
for y := 0; y < height; y++ {
for _, v := range plane[y*stride : y*stride+width] {
used[v] = true
}
}
numLevels := 0
for i, u := range used {
if u {
numLevels++
minV = min(minV, i)
maxV = max(maxV, i)
}
}
if numLevels <= 2 {
return nil
}
// Smallest distance between two consecutive used levels.
minDist, last := maxV-minV, -1
for i, u := range used {
if u {
if last >= 0 && i-last < minDist {
minDist = i - last
}
last = i
}
}
sm := smootherPool.Get().(*smoother)
defer smootherPool.Put(sm)
r := 2*radius + 1
need := (r + 1) * width
if cap(sm.scratch) < need {
sm.scratch = make([]uint16, need)
}
if cap(sm.average) < width {
sm.average = make([]uint16, width)
}
scratch := sm.scratch[:need]
average := sm.average[:width]
initCorrectionLUT(&sm.correction, minDist)
correction := sm.correction[:]
// Circular buffer of r rows [0, r*width) plus the output row "end".
end := scratch[r*width : (r+1)*width]
cur := 0
top := (r - 1) * width
clear(scratch[top : top+width])
scale := uint32((1 << (fix + lfix)) / (r * r))
src := 0
dst := 0
for row := -radius; row < height; row++ {
// VFilter: vertical accumulation (all arithmetic modulo 2^16).
{
in := plane[src : src+width]
c := scratch[cur : cur+width]
t := scratch[top : top+width]
out := end[:width]
var sum uint16
for x, v := range in {
sum += uint16(v)
nv := t[x] + sum
out[x] = nv - c[x]
c[x] = nv
}
top = cur
cur += width
if cur == r*width {
cur = 0
}
if row >= 0 && row < height-1 {
src += stride
}
}
if row < radius {
continue
}
// HFilter: horizontal accumulation with mirrored borders.
{
in := end[:width]
out := average[:width]
w := width
x := 0
for ; x <= radius; x++ {
delta := in[x+radius-1] + in[radius-x]
out[x] = uint16((uint32(delta) * scale) >> fix)
}
for ; x < w-radius; x++ {
delta := in[x+radius] - in[x-radius-1]
out[x] = uint16((uint32(delta) * scale) >> fix)
}
for ; x < w; x++ {
delta := 2*in[w-1] - in[2*w-2-radius-x] - in[x-radius-1]
out[x] = uint16((uint32(delta) * scale) >> fix)
}
}
// ApplyFilter.
{
d := plane[dst : dst+width]
avg := average[:width]
for x, v8 := range d {
v := int(v8)
if v < maxV && v > minV {
c := v + int(correction[lutSize+int(avg[x])-(v<<lfix)])
if c&^0xff != 0 {
if c < 0 {
c = 0
} else {
c = 255
}
}
d[x] = byte(c)
}
}
dst += stride
}
}
return nil
}
// initCorrectionLUT builds libwebp's correction curve: f(x) = x for
// x <= threshold2, 0 for x >= threshold1, linear in between, odd symmetric.
// Index lutSize is x = 0.
func initCorrectionLUT(lut *[1 + 2*lutSize]int16, minDist int) {
threshold1 := minDist << lfix
threshold2 := (3 * threshold1) >> 2
maxThreshold := threshold2
delta := threshold1 - threshold2
for i := 1; i <= lutSize; i++ {
var c int
switch {
case i <= threshold2:
c = i
case i < threshold1:
c = maxThreshold * (threshold1 - i) / delta
}
c >>= lfix
lut[lutSize+i] = int16(c)
lut[lutSize-i] = int16(-c)
}
lut[lutSize] = 0
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package alpha
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// SSE4.1 and AVX2 kernels of the horizontal and vertical unfilters
// (unfilter_amd64.s), selected by x86Level. The wrappers check the lengths
// and give the assembly whole blocks of 16 bytes; the last len(in)%16 bytes
// are done in Go. (The gradient unfilter stays in Go: its serial chain per
// byte is no shorter in vector registers, see libwebp's
// GradientPredictInverse_SSE2.)
//go:noescape
func unfilterHorizontalSSE41(in, out *byte, n, pred int)
//go:noescape
func unfilterHorizontalAVX2(in, out *byte, n, pred int)
//go:noescape
func unfilterVerticalSSE41(prev, in, out *byte, n int)
//go:noescape
func unfilterVerticalAVX2(prev, in, out *byte, n int)
// unfilterHorizontal sets out[i] = pred + in[0] + ... + in[i] (mod 256).
// in may alias out.
func unfilterHorizontal(pred byte, in, out []byte) {
out = out[:len(in)]
n := len(in) &^ 15
if n == 0 || x86Level < cpuinfo.SSE41 {
unfilterHorizontalGo(pred, in, out)
return
}
if x86Level >= cpuinfo.AVX2 {
unfilterHorizontalAVX2(&in[0], &out[0], n, int(pred))
} else {
unfilterHorizontalSSE41(&in[0], &out[0], n, int(pred))
}
unfilterHorizontalGo(out[n-1], in[n:], out[n:])
}
// unfilterVertical sets out[i] = prev[i] + in[i] (mod 256) for i < len(in).
// in may alias out.
func unfilterVertical(prev, in, out []byte) {
out, prev = out[:len(in)], prev[:len(in)]
n := len(in) &^ 15
if n == 0 || x86Level < cpuinfo.SSE41 {
unfilterVerticalGo(prev, in, out)
return
}
if x86Level >= cpuinfo.AVX2 {
unfilterVerticalAVX2(&prev[0], &in[0], &out[0], n)
} else {
unfilterVerticalSSE41(&prev[0], &in[0], &out[0], n)
}
unfilterVerticalGo(prev[n:], in[n:], out[n:])
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package bufpool keeps reusable buffers, and other objects holding large
// buffers, under one process-wide budget of retained bytes.
//
// It replaces "pool only below N pixels" rules: buffers of large images are
// reused too, while the memory the pools hold between calls stays bounded:
//
// - A Pool keeps free buffers in size classes (four per power of two of
// the element count). Get returns a buffer of the class that is large
// enough, or of the next class, or allocates one of the exact size.
// - A List keeps free objects of any type (for example the working
// buffers of an encode, held by one structure), each with the number of
// bytes it retains. Get returns the most recently put object that a fit
// function accepts.
// - All pools and lists of the process share one budget (Limit): Put drops
// the object, leaving it to the garbage collector, when keeping it
// would exceed the budget. The default budget is 256 MiB (64 MiB on
// 32-bit platforms), or an eighth of the Go memory limit (GOMEMLIMIT,
// debug.SetMemoryLimit) when that is lower; the memory limit is read
// again at most once a second, by Put and after garbage collections.
// A single object may take the whole budget: that is what lets a large
// encode reuse the working set of the previous one instead of
// allocating it again before the garbage collector has reclaimed it
// (the collector paces itself on the heap it found live, so back to
// back allocations of a large working set can double the peak memory).
// - Objects that stay unused for MaxIdle (15 s by default) are dropped at
// the next garbage collection, so the memory retained after a burst of
// work is released even if no further call comes (the runtime forces a
// collection at least every two minutes).
//
// Only objects in a pool or list are accounted: one obtained with Get and
// never returned is simply garbage collected.
package bufpool
import (
"math"
"math/bits"
"reflect"
"runtime"
"runtime/debug"
"sync"
"sync/atomic"
"time"
)
const (
// DefaultLimit is the default budget of retained bytes (when no lower
// Go memory limit is set): 256 MiB, or 64 MiB on 32-bit platforms, where
// the address space is much smaller.
DefaultLimit = 64 << 20 << (^uintptr(0) >> 63 * 2)
// DefaultMaxIdle is the default time after which an unused buffer is
// dropped.
DefaultMaxIdle = 15 * time.Second
// memLimitShare is the share of the Go memory limit the default budget
// is capped at.
memLimitShare = 8
// limitRefresh is the time after which the default budget reads the Go
// memory limit again.
limitRefresh = int64(time.Second)
)
var (
// setting is the limit set by SetLimit, or -1 for the default.
setting atomic.Int64
limit atomic.Int64 // the budget in effect
limitAt atomic.Int64 // now() when the default budget was last computed
limitMu sync.Mutex // serializes the updates of setting and limit
retained atomic.Int64
maxIdle atomic.Int64 // nanoseconds
epoch = time.Now() // origin of the monotonic timestamps
registry struct {
sync.Mutex
pools []trimmer
}
armOnce sync.Once
)
func init() {
setting.Store(-1)
limit.Store(defaultLimit())
maxIdle.Store(int64(DefaultMaxIdle))
}
// defaultLimit returns the default budget: DefaultLimit, or an eighth of the
// Go memory limit when that is lower.
func defaultLimit() int64 {
l := int64(DefaultLimit)
if m := debug.SetMemoryLimit(-1); m < math.MaxInt64 {
l = min(l, max(m/memLimitShare, 0))
}
return l
}
// SetLimit sets the budget of bytes retained by all pools and lists
// together and returns the previous setting. A limit of 0 disables pooling;
// a negative one restores the default budget, which follows the Go memory
// limit (SetLimit returns -1 when the default was in effect, so that
// SetLimit(SetLimit(n)) restores it). When the new budget is below the
// bytes currently retained, everything is dropped.
func SetLimit(bytes int64) int64 {
limitMu.Lock()
prev := setting.Swap(max(bytes, -1))
if bytes < 0 {
bytes = defaultLimit()
limitAt.Store(now())
}
limit.Store(bytes)
limitMu.Unlock()
if retained.Load() > bytes {
Trim()
}
return prev
}
// Limit returns the budget of retained bytes in effect.
func Limit() int64 { return limit.Load() }
// refreshLimit returns the budget in effect at the time at (a now()
// timestamp). The default budget follows the Go memory limit, read again
// once limitRefresh has passed since the last time; when it drops below
// the bytes retained, everything is dropped.
func refreshLimit(at int64) int64 {
if setting.Load() >= 0 || at-limitAt.Load() < limitRefresh {
return limit.Load()
}
limitMu.Lock()
if setting.Load() >= 0 || at-limitAt.Load() < limitRefresh {
limitMu.Unlock()
return limit.Load()
}
limitAt.Store(at)
l := defaultLimit()
limit.Store(l)
limitMu.Unlock()
if retained.Load() > l {
Trim()
}
return l
}
// Retained returns the number of bytes held by all pools and lists.
func Retained() int64 { return retained.Load() }
// SetMaxIdle sets how long an object may stay unused in a pool or list
// before a garbage collection drops it, and returns the previous value.
// d <= 0 drops every unused object at each collection.
func SetMaxIdle(d time.Duration) time.Duration {
return time.Duration(maxIdle.Swap(int64(max(d, 0))))
}
// Trim empties all pools and lists.
func Trim() {
trimAll(-1)
}
// now returns a monotonic timestamp in nanoseconds.
func now() int64 { return int64(time.Since(epoch)) }
// reserve accounts size more retained bytes, for an object put at the time
// at, if the budget allows it.
func reserve(size, at int64) bool {
lim := refreshLimit(at)
if size > lim {
return false
}
for {
r := retained.Load()
if r+size > lim {
return false
}
if retained.CompareAndSwap(r, r+size) {
return true
}
}
}
type trimmer interface {
// trim drops the objects put before the timestamp cutoff (all of
// them if cutoff < 0).
trim(cutoff int64)
}
func register(t trimmer) {
registry.Lock()
registry.pools = append(registry.pools, t)
registry.Unlock()
armOnce.Do(armGC)
}
func trimAll(cutoff int64) {
registry.Lock()
pools := registry.pools
registry.Unlock()
for _, p := range pools {
p.trim(cutoff)
}
}
// gcSentinel is allocated to detect the end of a garbage collection cycle:
// its finalizer runs once it has been collected. It holds a pointer so that
// it is not batched by the tiny allocator (whose finalizers may not run).
type gcSentinel struct{ _ *byte }
// armGC arranges for onGC to run after the next garbage collection.
//
// It sets a finalizer rather than a runtime.AddCleanup cleanup: the runtime
// queues cleanups in per-P blocks until the sweep ends, and a GOMAXPROCS
// decrease in the middle of a sweep strands the blocks of the destroyed Ps
// until GOMAXPROCS grows back (Go 1.27). A stranded cleanup would end this
// chain, and with it the trimming of idle objects, for good. Finalizers go
// to one global queue.
func armGC() {
runtime.SetFinalizer(new(gcSentinel), func(*gcSentinel) { onGC() })
}
// onGC follows the Go memory limit, drops the objects idle for longer than
// MaxIdle and re-arms itself. It runs on the runtime's finalizer goroutine.
func onGC() {
gcTrims.Add(1)
at := now()
refreshLimit(at)
trimAll(max(at-maxIdle.Load(), 0))
armGC()
}
// gcTrims counts the runs of onGC.
var gcTrims atomic.Int64
// GCTrims returns how many times the trimming after a garbage collection
// has run (for tests).
func GCTrims() int64 { return gcTrims.Load() }
// numClasses covers element counts up to the largest int.
const numClasses = 4 * 64
// classOf returns the size class of a buffer of n elements: n itself below
// 8, then four classes per power of two.
func classOf(n int) int {
if n < 8 {
return n
}
b := bits.Len(uint(n)) - 1 // n is in [2^b, 2^(b+1))
return 4*b + int(n>>(b-2))&3
}
type entry[T any] struct {
buf []T
at int64 // time of the Put
}
// Pool is a size-class pool of []T buffers. The zero value is ready to use;
// a Pool must not be copied after first use.
type Pool[T any] struct {
mu sync.Mutex
registered bool
// classes[c] holds the free buffers of class c (by capacity), in the
// order they were put back: oldest first.
classes [numClasses][]entry[T]
}
func (p *Pool[T]) elemSize() int64 { return int64(reflect.TypeFor[T]().Size()) }
// Get returns a buffer of length n. Its contents are unspecified (a reused
// buffer is not cleared). The buffer may be returned with Put when no
// longer used.
func (p *Pool[T]) Get(n int) []T {
if n <= 0 {
return nil
}
c := classOf(n)
p.mu.Lock()
for cc := c; cc <= c+1 && cc < numClasses; cc++ {
st := p.classes[cc]
for i := len(st) - 1; i >= 0; i-- {
b := st[i].buf
if cap(b) < n {
continue
}
// Remove entry i, keeping the order (oldest first). The
// backing array of the list is kept for the next Puts (trim
// releases it).
copy(st[i:], st[i+1:])
st[len(st)-1] = entry[T]{}
p.classes[cc] = st[:len(st)-1]
p.mu.Unlock()
retained.Add(-int64(cap(b)) * p.elemSize())
return b[:n]
}
}
p.mu.Unlock()
return make([]T, n)
}
// Put returns b to the pool, if the budget allows it. b must not be used
// afterwards.
func (p *Pool[T]) Put(b []T) {
c := cap(b)
if c == 0 {
return
}
at := now()
if !reserve(int64(c)*p.elemSize(), at) {
return
}
p.mu.Lock()
cl := classOf(c)
p.classes[cl] = append(p.classes[cl], entry[T]{buf: b[:0], at: at})
reg := !p.registered
p.registered = true
p.mu.Unlock()
if reg {
register(p)
}
}
func (p *Pool[T]) trim(cutoff int64) {
size := p.elemSize()
var freed int64
p.mu.Lock()
for c, st := range p.classes {
k := 0
for k < len(st) && (cutoff < 0 || st[k].at < cutoff) {
freed += int64(cap(st[k].buf)) * size
k++
}
if k < len(st) {
if k > 0 {
n := copy(st, st[k:])
clear(st[n:])
p.classes[c] = st[:n]
}
continue
}
p.classes[c] = nil // empty: release the list too
}
p.mu.Unlock()
retained.Add(-freed)
}
type listEntry[T any] struct {
v T
bytes int64
at int64 // time of the Put
}
// List is a list of free objects of type T, each retaining a given number
// of bytes (typically a structure holding several buffers, reused as a
// whole). The zero value is ready to use; a List must not be copied after
// first use.
type List[T any] struct {
mu sync.Mutex
registered bool
entries []listEntry[T] // oldest first
}
// Get removes and returns the most recently put object for which fit (if
// not nil) reports true. ok is false when there is none.
func (l *List[T]) Get(fit func(T) bool) (v T, ok bool) {
l.mu.Lock()
for i := len(l.entries) - 1; i >= 0; i-- {
e := l.entries[i]
if fit != nil && !fit(e.v) {
continue
}
n := copy(l.entries[i:], l.entries[i+1:])
l.entries[i+n] = listEntry[T]{}
l.entries = l.entries[:i+n]
l.mu.Unlock()
retained.Add(-e.bytes)
return e.v, true
}
l.mu.Unlock()
return v, false
}
// Put keeps v, which retains the given number of bytes, if the budget
// allows it, and reports whether it did. When it did not, v is left to the
// caller (or the garbage collector).
func (l *List[T]) Put(v T, bytes int64) bool {
bytes = max(bytes, 0)
at := now()
if !reserve(bytes, at) {
return false
}
l.mu.Lock()
l.entries = append(l.entries, listEntry[T]{v: v, bytes: bytes, at: at})
reg := !l.registered
l.registered = true
l.mu.Unlock()
if reg {
register(l)
}
return true
}
// Len returns the number of objects in the list.
func (l *List[T]) Len() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.entries)
}
func (l *List[T]) trim(cutoff int64) {
var freed int64
l.mu.Lock()
k := 0
for k < len(l.entries) && (cutoff < 0 || l.entries[k].at < cutoff) {
freed += l.entries[k].bytes
k++
}
if k == len(l.entries) {
l.entries = nil // empty: release the list too
} else if k > 0 {
n := copy(l.entries, l.entries[k:])
clear(l.entries[n:])
l.entries = l.entries[:n]
}
l.mu.Unlock()
retained.Add(-freed)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package container parses and writes the RIFF/WebP container.
//
// Parsing follows libwebp's ParseHeadersInternal (src/dec/webp_dec.c) step by
// step, so that the returned status codes and features match what
// WebPGetFeatures / WebPDecode report for the same input, including the
// "internal" inputs libwebp accepts: raw VP8 / VP8L bitstreams without a RIFF
// header and "ALPH + VP8" sequences.
//
// Algorithm adapted from libwebp (BSD-3-Clause).
package container
import (
"encoding/binary"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/utils"
)
const (
tagSize = 4
chunkHeaderSize = 8
riffHeaderSize = 12
vp8xChunkSize = 10
vp8FrameHeaderSize = 10
vp8lFrameHeaderSize = 5
vp8lMagicByte = 0x2f
// maxChunkPayload mirrors libwebp's MAX_CHUNK_PAYLOAD.
maxChunkPayload = ^uint32(0) - chunkHeaderSize - 1
// maxImageArea mirrors libwebp's MAX_IMAGE_AREA.
maxImageArea = uint64(1) << 32
// VP8X feature flags.
animationFlag = 0x02
xmpFlag = 0x04
exifFlag = 0x08
alphaFlag = 0x10
iccpFlag = 0x20
// MaxDimension is the largest width or height of a VP8 frame (and of a
// VP8X canvas written by WriteLossy). VP8L headers can encode 16384,
// which libwebp accepts.
MaxDimension = 16383
)
// Features describes a WebP file, with the same semantics as libwebp's
// WebPBitstreamFeatures as filled by WebPGetFeatures.
type Features struct {
Width, Height int
// HasAlpha is set from the VP8X alpha flag, overridden by the VP8L
// header alpha bit for lossless frames, and forced on by the presence of
// an ALPH chunk.
HasAlpha bool
// HasAnimation is set from the VP8X animation flag.
HasAnimation bool
// Format is FormatLossy for VP8, FormatLossless for VP8L and
// FormatUndefined for animated files.
Format utils.FormatType
}
// Image is a parsed WebP file. The payload slices alias the input passed to
// Parse; nothing is copied.
type Image struct {
Features
// VP8 is the lossy bitstream, nil for lossless images. Like libwebp
// (ParseHeadersInternal hands the frame decoder io->data_size = the
// remaining input), it starts at the "VP8 " chunk payload and extends
// to the end of the input, past the declared chunk size; ChunkSize
// holds the declared size.
VP8 []byte
// VP8L is the lossless bitstream, nil for lossy images. It extends to
// the end of the input like VP8.
VP8L []byte
// ChunkSize is the declared size of the image chunk (or the size of
// the raw bitstream).
ChunkSize int
// ALPH is the payload of the last ALPH chunk found before the image
// chunk, including its 1-byte header; nil if there is none. libwebp only
// uses it for lossy images.
ALPH []byte
}
// Chunk returns the image chunk payload limited to its declared size (VP8
// or VP8L without the bytes that follow the chunk).
func (img *Image) Chunk() []byte {
p := img.VP8
if p == nil {
p = img.VP8L
}
if img.ChunkSize < len(p) {
p = p[:img.ChunkSize:img.ChunkSize]
}
return p
}
// Parse parses a WebP file (or a raw VP8/VP8L bitstream) and locates the
// image payload. The whole file must be available (like libwebp's
// WebPDecode): truncated chunks yield a NotEnoughData error.
//
// For animated files (VP8X with the animation flag) only Features is filled
// and the payload slices are nil; the caller should report
// status.Unsupported like libwebp's WebPDecode does.
//
// Errors are *status.Error with the code libwebp would return.
func Parse(data []byte) (*Image, error) {
img := new(Image)
if err := parse(data, true, img, nil); err != nil {
return nil, err
}
return img, nil
}
// GetFeatures returns the features of a WebP file, like libwebp's
// WebPGetFeatures. It only needs the headers: a file truncated inside the
// image payload is still accepted.
func GetFeatures(data []byte) (Features, error) {
var img Image
if err := parse(data, false, &img, nil); err != nil {
return Features{}, err
}
return img.Features, nil
}
// ValidRIFFSize reports whether size, the size field of a RIFF header, is
// in the range GetFeatures accepts: room for the "WEBP" tag and a chunk
// header, and at most libwebp's MAX_CHUNK_PAYLOAD. Out of that range
// GetFeatures fails whatever follows the header; the size is not checked
// against the length of the input here.
func ValidRIFFSize(size uint32) bool {
return size >= tagSize+chunkHeaderSize && size <= maxChunkPayload
}
// GetFeaturesPrefix is GetFeatures for a prefix of a file that is still
// being read. done reports whether the prefix was long enough for the result
// to be final, i.e. to equal GetFeatures of the whole file: parsing reached
// the VP8/VP8L frame header (and checked it against the VP8X canvas), found
// an animation, or failed with an error other than NotEnoughData. When done
// is false the caller should read more data, or call GetFeatures at the end
// of the input. For a raw VP8 bitstream (no RIFF header), whose size is that
// of the whole input, the prefix must extend past the first partition
// length declared in the frame header before the result is final.
func GetFeaturesPrefix(prefix []byte) (f Features, done bool, err error) {
var img Image
err = parse(prefix, false, &img, &done)
if err != nil {
return Features{}, status.CodeOf(err) != utils.Vp8StatusNotEnoughData, err
}
return img.Features, done || img.HasAnimation, nil
}
func le24(b []byte) uint32 {
_ = b[2]
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16
}
func tagIs(b []byte, tag string) bool {
return len(b) >= tagSize && b[0] == tag[0] && b[1] == tag[1] && b[2] == tag[2] && b[3] == tag[3]
}
// parse mirrors ParseHeadersInternal (and WebPParseHeaders when haveAll is
// set). haveAll selects the WebPDecode behaviour (headers != NULL,
// have_all_data = 1) versus the WebPGetFeatures one (headers == NULL).
func parse(data []byte, haveAll bool, img *Image, reached *bool) error {
var anim Features
err := parseHeaders(data, haveAll, img, &anim, reached)
if haveAll && anim.HasAnimation && (err == nil || status.CodeOf(err) == utils.Vp8StatusNotEnoughData) {
// WebPParseHeaders reports UNSUPPORTED_FEATURE here; we hand back the
// VP8X features and let the caller decide.
*img = Image{Features: anim}
return nil
}
return err
}
// reached, if not nil, is set when the frame header has been parsed.
func parseHeaders(data []byte, haveAll bool, img *Image, anim *Features, reached *bool) error {
if len(data) < riffHeaderSize {
return status.NotEnoughData("not enough data for a WebP header")
}
// RIFF header.
riffSize := uint32(0)
if tagIs(data, "RIFF") {
if !tagIs(data[8:], "WEBP") {
return status.Bitstream("wrong RIFF signature")
}
size := binary.LittleEndian.Uint32(data[4:])
if size < tagSize+chunkHeaderSize {
return status.Bitstream("RIFF size too small")
}
if size > maxChunkPayload {
return status.Bitstream("RIFF size too large")
}
if haveAll && uint64(size) > uint64(len(data)-chunkHeaderSize) {
return status.NotEnoughData("truncated RIFF")
}
riffSize = size
data = data[riffHeaderSize:]
}
foundRIFF := riffSize > 0
// VP8X.
if len(data) < chunkHeaderSize {
return status.NotEnoughData("not enough data for a chunk header")
}
foundVP8X := false
animation := false
canvasW, canvasH := 0, 0
if tagIs(data, "VP8X") {
if binary.LittleEndian.Uint32(data[4:]) != vp8xChunkSize {
return status.Bitstream("wrong VP8X chunk size")
}
if len(data) < chunkHeaderSize+vp8xChunkSize {
return status.NotEnoughData("truncated VP8X chunk")
}
flags := binary.LittleEndian.Uint32(data[8:])
canvasW = 1 + int(le24(data[12:]))
canvasH = 1 + int(le24(data[15:]))
if uint64(canvasW)*uint64(canvasH) >= maxImageArea {
return status.Bitstream("canvas too large")
}
data = data[chunkHeaderSize+vp8xChunkSize:]
foundVP8X = true
animation = flags&animationFlag != 0
img.HasAlpha = flags&alphaFlag != 0
}
if !foundRIFF && foundVP8X {
return status.Bitstream("VP8X chunk without RIFF header")
}
img.HasAnimation = animation
img.Format = utils.FormatUndefined
img.Width, img.Height = canvasW, canvasH
if foundVP8X && animation {
*anim = img.Features
if !haveAll {
// WebPGetFeatures returns the VP8X features right away.
return nil
}
}
// finish implements libwebp's "ReturnWidthHeight" exit.
finish := func(err error, alpha []byte) error {
if err == nil || (!haveAll && foundVP8X && status.CodeOf(err) == utils.Vp8StatusNotEnoughData) {
if alpha != nil {
img.HasAlpha = true
}
return nil
}
return err
}
if len(data) < tagSize {
return finish(status.NotEnoughData("not enough data for a chunk tag"), nil)
}
// Optional chunks (only after RIFF+VP8X, or for a raw "ALPH" sequence).
var alpha []byte
if (foundRIFF && foundVP8X) || (!foundRIFF && !foundVP8X && tagIs(data, "ALPH")) {
// libwebp accumulates total_size in a uint32_t, which wraps for
// chunk sizes close to MAX_CHUNK_PAYLOAD; do the same so that the
// same files are accepted.
totalSize := uint32(tagSize + chunkHeaderSize + vp8xChunkSize)
for {
if len(data) < chunkHeaderSize {
return finish(status.NotEnoughData("truncated chunk header"), alpha)
}
chunkSize := binary.LittleEndian.Uint32(data[4:])
if chunkSize > maxChunkPayload {
return finish(status.Bitstream("invalid chunk size"), alpha)
}
diskSize := (uint64(chunkHeaderSize) + uint64(chunkSize) + 1) &^ 1
totalSize += uint32(diskSize)
if riffSize > 0 && totalSize > riffSize {
return finish(status.Bitstream("chunk exceeds RIFF size"), alpha)
}
if tagIs(data, "VP8 ") || tagIs(data, "VP8L") {
break
}
if uint64(len(data)) < diskSize {
return finish(status.NotEnoughData("truncated chunk"), alpha)
}
if tagIs(data, "ALPH") {
alpha = data[chunkHeaderSize : chunkHeaderSize+int(chunkSize) : chunkHeaderSize+int(chunkSize)]
}
data = data[diskSize:]
}
}
// VP8 / VP8L chunk header.
if len(data) < chunkHeaderSize {
return finish(status.NotEnoughData("truncated image chunk header"), alpha)
}
var compressedSize uint64
lossless := false
// raw is set for a bitstream without a chunk header, whose size is the
// size of the input.
raw := false
if isVP8, isVP8L := tagIs(data, "VP8 "), tagIs(data, "VP8L"); isVP8 || isVP8L {
size := binary.LittleEndian.Uint32(data[4:])
const minimalSize = tagSize + chunkHeaderSize
if riffSize >= minimalSize && size > riffSize-minimalSize {
return finish(status.Bitstream("image chunk exceeds RIFF size"), alpha)
}
if haveAll && uint64(size) > uint64(len(data)-chunkHeaderSize) {
return finish(status.NotEnoughData("truncated image chunk"), alpha)
}
compressedSize = uint64(size)
data = data[chunkHeaderSize:]
lossless = isVP8L
} else {
lossless = isVP8LSignature(data)
compressedSize = uint64(len(data))
raw = true
}
if compressedSize > uint64(maxChunkPayload) {
return status.Bitstream("image chunk too large")
}
if !animation {
if lossless {
img.Format = utils.FormatLossless
} else {
img.Format = utils.FormatLossy
}
}
var w, h int
if !lossless {
if len(data) < vp8FrameHeaderSize {
return finish(status.NotEnoughData("truncated VP8 frame header"), alpha)
}
var ok bool
if w, h, ok = vp8Info(data, compressedSize); !ok {
if raw && reached != nil {
// GetFeaturesPrefix: the size of a raw bitstream is that
// of the whole input, which may be longer than this
// prefix. If only the first partition length check
// failed, more data is needed to decide.
if _, _, valid := vp8Info(data, ^uint64(0)); valid {
return status.NotEnoughData("raw VP8 bitstream shorter than its first partition so far")
}
}
return status.Bitstream("invalid VP8 frame header")
}
} else {
if len(data) < vp8lFrameHeaderSize {
return finish(status.NotEnoughData("truncated VP8L header"), alpha)
}
var a, ok bool
if w, h, a, ok = vp8lInfo(data); !ok {
return status.Bitstream("invalid VP8L header")
}
img.HasAlpha = a
}
if foundVP8X && (canvasW != w || canvasH != h) {
return status.Bitstream("VP8X canvas size does not match the frame size")
}
img.Width, img.Height = w, h
if reached != nil {
*reached = true
}
img.ChunkSize = int(compressedSize)
payload := data
if lossless {
img.VP8L = payload
} else {
img.VP8 = payload
}
img.ALPH = alpha
return finish(nil, alpha)
}
// isVP8LSignature mirrors VP8LCheckSignature.
func isVP8LSignature(b []byte) bool {
return len(b) >= vp8lFrameHeaderSize && b[0] == vp8lMagicByte && b[4]>>5 == 0
}
// vp8Info mirrors VP8GetInfo: it validates the 10-byte VP8 frame header and
// returns the frame dimensions (scale bits dropped).
func vp8Info(b []byte, chunkSize uint64) (w, h int, ok bool) {
if len(b) < vp8FrameHeaderSize {
return 0, 0, false
}
_ = b[9]
if b[3] != 0x9d || b[4] != 0x01 || b[5] != 0x2a {
return 0, 0, false
}
bits := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16
w = int(uint32(b[6])|uint32(b[7])<<8) & 0x3fff
h = int(uint32(b[8])|uint32(b[9])<<8) & 0x3fff
switch {
case bits&1 != 0: // not a key frame
return 0, 0, false
case (bits>>1)&7 > 3: // unknown profile
return 0, 0, false
case (bits>>4)&1 == 0: // invisible frame
return 0, 0, false
case uint64(bits>>5) >= chunkSize: // partition length
return 0, 0, false
case w == 0 || h == 0:
return 0, 0, false
}
return w, h, true
}
// vp8lInfo mirrors VP8LGetInfo: 0x2f signature, 14-bit width-1, 14-bit
// height-1, alpha bit, 3-bit version (must be 0).
func vp8lInfo(b []byte) (w, h int, alpha, ok bool) {
if !isVP8LSignature(b) {
return 0, 0, false, false
}
v := binary.LittleEndian.Uint32(b[1:5])
w = int(v&0x3fff) + 1
h = int((v>>14)&0x3fff) + 1
alpha = (v>>28)&1 != 0
if v>>29 != 0 {
return 0, 0, false, false
}
return w, h, alpha, true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package container
import (
"encoding/binary"
"io"
"strings"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// maxRIFFPayload bounds the total RIFF payload so that its size fits in the
// 32-bit RIFF size field (same limit as libwebp's MAX_CHUNK_PAYLOAD).
const maxRIFFPayload = uint64(maxChunkPayload)
// WriteLossy writes a lossy WebP file. With alph == nil it is a simple
// "RIFF/WEBP/VP8 " file; otherwise an extended file made of a VP8X chunk
// (alpha flag, canvas width x height), the ALPH chunk (alph must include its
// 1-byte header) and the "VP8 " chunk, as libwebp's encoder lays it out.
// Odd-sized chunks are padded with a zero byte.
func WriteLossy(w io.Writer, width, height int, vp8, alph []byte) error {
if len(vp8) == 0 {
return status.InvalidParam("empty VP8 payload")
}
if alph == nil {
riff := uint64(tagSize) + chunkHeaderSize + padded(len(vp8))
if riff > maxRIFFPayload {
return status.InvalidParam("VP8 payload too large")
}
var hdr [riffHeaderSize + chunkHeaderSize]byte
putRIFF(hdr[:], uint32(riff))
putChunkHeader(hdr[riffHeaderSize:], "VP8 ", len(vp8))
return writeAll(w, hdr[:], vp8, pad(len(vp8)))
}
if width < 1 || height < 1 || width > MaxDimension || height > MaxDimension {
return status.InvalidParam("invalid canvas dimensions")
}
if len(alph) == 0 {
return status.InvalidParam("empty ALPH payload")
}
riff := uint64(tagSize) + chunkHeaderSize + vp8xChunkSize +
chunkHeaderSize + padded(len(alph)) + chunkHeaderSize + padded(len(vp8))
if riff > maxRIFFPayload {
return status.InvalidParam("payload too large")
}
var hdr [riffHeaderSize + chunkHeaderSize + vp8xChunkSize + chunkHeaderSize]byte
putRIFF(hdr[:], uint32(riff))
b := hdr[riffHeaderSize:]
putChunkHeader(b, "VP8X", vp8xChunkSize)
b[8] = alphaFlag
putLE24(b[12:], uint32(width-1))
putLE24(b[15:], uint32(height-1))
putChunkHeader(b[chunkHeaderSize+vp8xChunkSize:], "ALPH", len(alph))
// The padding byte of ALPH (if any) and the "VP8 " chunk header go in a
// single small write between the two payloads.
var mid [1 + chunkHeaderSize]byte
m := mid[:0]
if len(alph)&1 != 0 {
m = append(m, 0)
}
m = m[:len(m)+chunkHeaderSize]
putChunkHeader(m[len(m)-chunkHeaderSize:], "VP8 ", len(vp8))
return writeAll(w, hdr[:], alph, m, vp8, pad(len(vp8)))
}
// WriteLossless writes a simple lossless "RIFF/WEBP/VP8L" file.
func WriteLossless(w io.Writer, vp8l []byte) error {
if len(vp8l) == 0 {
return status.InvalidParam("empty VP8L payload")
}
riff := uint64(tagSize) + chunkHeaderSize + padded(len(vp8l))
if riff > maxRIFFPayload {
return status.InvalidParam("VP8L payload too large")
}
var hdr [riffHeaderSize + chunkHeaderSize]byte
putRIFF(hdr[:], uint32(riff))
putChunkHeader(hdr[riffHeaderSize:], "VP8L", len(vp8l))
return writeAll(w, hdr[:], vp8l, pad(len(vp8l)))
}
// LosslessHeaderSize is the size of the RIFF header plus the VP8L chunk
// header of a simple lossless file.
const LosslessHeaderSize = riffHeaderSize + chunkHeaderSize
// LossyHeaderSize is the size of the RIFF header plus the "VP8 " chunk
// header of a simple lossy file (no alpha).
const LossyHeaderSize = riffHeaderSize + chunkHeaderSize
// FrameLossless turns buf, made of LosslessHeaderSize bytes of headroom
// followed by a VP8L chunk payload, into a complete lossless WebP file in
// place: it fills in the headers and appends the padding byte if needed
// (reusing buf's capacity when possible). The result is what WriteLossless
// writes for the same payload, without copying it.
func FrameLossless(buf []byte) ([]byte, error) {
return frameSimple(buf, "VP8L")
}
// FrameLossy is FrameLossless for a simple lossy file: buf is
// LossyHeaderSize bytes of headroom followed by a "VP8 " chunk payload, and
// the result is what WriteLossy writes for that payload without alpha.
func FrameLossy(buf []byte) ([]byte, error) {
return frameSimple(buf, "VP8 ")
}
// frameSimple frames the payload buf[riffHeaderSize+chunkHeaderSize:] as
// the only chunk (tag) of a simple WebP file, in place.
func frameSimple(buf []byte, tag string) ([]byte, error) {
const hdr = riffHeaderSize + chunkHeaderSize
name := strings.TrimSpace(tag)
if len(buf) <= hdr {
return nil, status.InvalidParam("empty " + name + " payload")
}
n := len(buf) - hdr
riff := uint64(tagSize) + chunkHeaderSize + padded(n)
if riff > maxRIFFPayload {
return nil, status.InvalidParam(name + " payload too large")
}
putRIFF(buf, uint32(riff))
putChunkHeader(buf[riffHeaderSize:], tag, n)
if n&1 != 0 {
buf = append(buf, 0)
}
return buf, nil
}
var zeroPad = []byte{0}
func pad(n int) []byte {
if n&1 != 0 {
return zeroPad
}
return nil
}
func padded(n int) uint64 { return (uint64(n) + 1) &^ 1 }
func putRIFF(b []byte, size uint32) {
copy(b, "RIFF")
binary.LittleEndian.PutUint32(b[4:], size)
copy(b[8:], "WEBP")
}
func putChunkHeader(b []byte, tag string, size int) {
copy(b, tag)
binary.LittleEndian.PutUint32(b[4:], uint32(size))
}
func putLE24(b []byte, v uint32) {
_ = b[2]
b[0] = byte(v)
b[1] = byte(v >> 8)
b[2] = byte(v >> 16)
}
// writeAll writes the non-empty parts in order. The headers are already
// assembled into as few parts as possible, so a file costs 3 to 5 Write calls.
func writeAll(w io.Writer, parts ...[]byte) error {
for _, p := range parts {
if len(p) == 0 {
continue
}
if err := write(w, p); err != nil {
return err
}
}
return nil
}
func write(w io.Writer, b []byte) error {
n, err := w.Write(b)
if err == nil && n != len(b) {
err = io.ErrShortWrite
}
return err
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package cpuinfo reports which x86 SIMD extensions the assembly kernels of
// the codec may use. On amd64 it is filled from golang.org/x/sys/cpu (which
// also checks that the operating system saves the vector registers); on
// every other architecture all fields are false and Max is Go.
//
// Kernels pick an implementation by Level. Each package keeps its own
// selected level in a variable initialized from Max, so that tests can run
// every level the machine supports (see Levels) against the pure Go code.
package cpuinfo
// Level is an x86-64 SIMD level, from the pure Go code up.
type Level int
const (
// Go is the pure Go code (no assembly).
Go Level = iota
// SSE41 is SSE2 through SSE4.1 (SSSE3 included).
SSE41
// AVX2 is x86-64-v3: AVX, AVX2, BMI1, BMI2, FMA, with the OS saving
// the ymm registers.
AVX2
// AVX512 is x86-64-v4: AVX2 plus AVX-512 F, BW, CD, DQ and VL, with
// the OS saving the zmm and mask registers. Optional extensions
// (VBMI, VBMI2, VNNI, GFNI) are reported separately in X86.
AVX512
)
func (l Level) String() string {
switch l {
case Go:
return "go"
case SSE41:
return "sse41"
case AVX2:
return "avx2"
case AVX512:
return "avx512"
}
return "unknown"
}
// X86 holds the extensions available beyond the levels; all false on
// other architectures.
var X86 struct {
HasSSE41 bool // SSE2, SSE3, SSSE3, SSE4.1
HasAVX2 bool // the AVX2 level (x86-64-v3)
HasAVX512 bool // the AVX512 level (x86-64-v4)
HasAVX512VBMI bool // VPERMB, VPERMT2B, VPMULTISHIFTQB (needs HasAVX512)
HasAVX512VBMI2 bool // VPEXPANDB/VPCOMPRESSB, VPSHLDV... (needs HasAVX512)
HasAVX512VNNI bool // VPDPBUSD, VPDPWSSD (needs HasAVX512)
HasAVX512GFNI bool // GF2P8AFFINEQB... (needs HasAVX512)
}
// Max is the highest level this machine supports.
var Max = Go
// Levels returns the levels this machine supports, Go first.
func Levels() []Level {
ls := []Level{Go}
for l := SSE41; l <= Max; l++ {
ls = append(ls, l)
}
return ls
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64
package cpuinfo
import "golang.org/x/sys/cpu"
func init() {
c := &cpu.X86
X86.HasSSE41 = c.HasSSE2 && c.HasSSE3 && c.HasSSSE3 && c.HasSSE41
// x/sys/cpu reports AVX/AVX2/AVX-512 only when the OS saves the
// corresponding register state (XGETBV), so no further check is needed.
X86.HasAVX2 = X86.HasSSE41 && c.HasAVX && c.HasAVX2 && c.HasBMI1 && c.HasBMI2 && c.HasFMA
X86.HasAVX512 = X86.HasAVX2 && c.HasAVX512F && c.HasAVX512BW && c.HasAVX512CD && c.HasAVX512DQ && c.HasAVX512VL
X86.HasAVX512VBMI = X86.HasAVX512 && c.HasAVX512VBMI
X86.HasAVX512VBMI2 = X86.HasAVX512 && c.HasAVX512VBMI2
X86.HasAVX512VNNI = X86.HasAVX512 && c.HasAVX512VNNI
X86.HasAVX512GFNI = X86.HasAVX512 && c.HasAVX512GFNI
switch {
case X86.HasAVX512:
Max = AVX512
case X86.HasAVX2:
Max = AVX2
case X86.HasSSE41:
Max = SSE41
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package ctxio hands the context of webp.DecodeContext and
// webp.DecodeIntoContext to decoder.NewDecoder, which reads the whole input
// before decoding, so that the read stops once the context is done. Passing
// the context inside the reader keeps it out of the API of package decoder.
package ctxio
import (
"context"
"io"
)
// Reader is R read under Ctx: once Ctx is done, Read returns Ctx.Err()
// instead of calling R.Read. A Read already blocked in R is not
// interrupted.
//
// decoder.NewDecoder unwraps a *Reader: it sizes its buffer from R (so a
// bytes.Reader or a regular file is still read into one allocation), checks
// Ctx itself before each Read of R and reports a cancelled read like a
// cancelled decode. Read is what any other reader of a *Reader gets.
type Reader struct {
Ctx context.Context
R io.Reader
}
// Read implements io.Reader.
func (r *Reader) Read(p []byte) (int, error) {
if err := r.Ctx.Err(); err != nil {
return 0, err
}
return r.R.Read(p)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package pipeline
// PremultipliedSink is implemented by sinks that alpha-premultiply the rows
// they receive before resampling them (Params.Premultiply). A decoder that
// can premultiply more cheaply than per pixel, such as a palette image that
// premultiplies its palette once, calls AcceptPremultiplied before its first
// Buffer call: when it returns true, the sink no longer premultiplies, and
// every row the decoder delivers must already be premultiplied exactly as
// resample.PremultiplyRGBA would do it.
type PremultipliedSink interface {
AcceptPremultiplied() bool
}
// AcceptPremultiplied implements PremultipliedSink.
func (s *scaleSink) AcceptPremultiplied() bool {
if !s.premult || s.scratch != nil || s.done {
// Not premultiplying, or rows were already delivered.
return false
}
s.preDone = true
return true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package pipeline
import "image"
// newOutput returns the w x h output image of a sink. When reuse is not nil
// and its Pix has the capacity for 4*w*h bytes, the image is backed by that
// memory (reuse.Pix[:4*w*h], keeping its capacity so that a later, larger
// decode can reuse it too) and is not cleared: every sink writes each output
// pixel exactly once before the decode succeeds, so stale bytes never show.
// Otherwise a new image is allocated. reuse itself (its Pix slice header,
// Stride and Rect) is never modified; the decoder copies the result into it
// only once decoding has succeeded.
func newOutput(w, h int, reuse *image.NRGBA) *image.NRGBA {
n := 4 * w * h
if reuse != nil && cap(reuse.Pix) >= n {
return &image.NRGBA{Pix: reuse.Pix[:n], Stride: 4 * w, Rect: image.Rect(0, 0, w, h)}
}
return image.NewNRGBA(image.Rect(0, 0, w, h))
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package pipeline connects frame decoders (lossy VP8, lossless VP8L) to the
// final output image. Decoders produce full-width, non-premultiplied RGBA rows
// (4 bytes per pixel, R,G,B,A order) strictly top to bottom; a Sink decides
// where those rows go (straight into the output image, or through
// crop / scale stages).
//
// Zero-copy protocol: the decoder asks the sink for a destination buffer for
// the next n source rows via Buffer, writes the pixels there, then calls
// Commit with the same (y, n). For the common "no crop, no scale" case the
// returned buffer is a slice of the final image's Pix, so no copy happens.
package pipeline
import "image"
// Sink receives decoded rows.
type Sink interface {
// Buffer returns a writable byte slice able to hold n full-width source
// rows starting at source row y. Row r (0 <= r < n) starts at offset
// r*Stride(). The slice is valid until the matching Commit call.
// y must equal the y+n of the previous Commit (rows arrive in order).
Buffer(y, n int) []byte
// Stride returns the row stride, in bytes, of slices returned by Buffer.
Stride() int
// Commit marks rows [y, y+n) previously obtained from Buffer as final.
Commit(y, n int) error
// NeedRows reports how many source rows (from the top) the sink still
// needs in total; decoders MAY stop after producing that many rows
// (e.g. when cropping away the bottom of the image).
NeedRows() int
}
// Direct writes rows straight into an *image.NRGBA whose bounds equal the
// source frame size (Min must be 0,0). It performs no copy.
type Direct struct {
Img *image.NRGBA
}
// NewDirect returns a Direct sink for img.
func NewDirect(img *image.NRGBA) *Direct { return &Direct{Img: img} }
// Buffer implements Sink.
func (d *Direct) Buffer(y, n int) []byte {
s := d.Img.Stride
end := (y + n) * s
if end > len(d.Img.Pix) {
end = len(d.Img.Pix)
}
return d.Img.Pix[y*s : end]
}
// Stride implements Sink.
func (d *Direct) Stride() int { return d.Img.Stride }
// Commit implements Sink.
func (d *Direct) Commit(y, n int) error { return nil }
// NeedRows implements Sink.
func (d *Direct) NeedRows() int { return d.Img.Rect.Dy() }
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package pipeline
import (
"image"
"sync"
"github.com/kolesa-team/go-webp/v2/internal/resample"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/utils"
)
// maxAllocableMemory is libwebp's WEBP_MAX_ALLOCABLE_MEMORY (default
// build): 1<<34 bytes where size_t is 64-bit, (1<<31) - (1<<16) on 32-bit
// targets (below INT_MAX). On 32-bit Go targets this also keeps the output
// image below math.MaxInt bytes, which image.NewNRGBA would panic on. wasm
// takes the 32-bit value, as libwebp built for wasm32 does, although its
// int is 64-bit: its heap is a linear memory of at most 4 GiB, so without
// the limit a larger output ended in a makeslice panic, or in a fatal out
// of memory once it no longer fitted beside the rest of the heap, instead
// of VP8_STATUS_OUT_OF_MEMORY.
const maxAllocableMemory = uint64(1<<34)*(sizeTBits/64) + uint64(1<<31-1<<16)*(1-sizeTBits/64)
// maxOutputBytes bounds the output image allocation: libwebp's
// WebPAllocateDecBuffer reports VP8_STATUS_OUT_OF_MEMORY above
// WEBP_MAX_ALLOCABLE_MEMORY. It is a variable so that tests can lower it.
var maxOutputBytes = maxAllocableMemory
// Params describes the transformations applied to a decoded frame, in
// libwebp's order: crop, then scale, then vertical flip.
type Params struct {
// SrcW, SrcH are the dimensions of the decoded frame.
SrcW, SrcH int
// Crop selects the rectangle to keep (proper rectangle semantics: Min is
// the top-left corner, Dx/Dy the size). An empty rectangle disables
// cropping. A rectangle not fully inside the frame is an InvalidParam
// error, like libwebp's WebPCheckCropDimensions. For lossy (VP8)
// frames libwebp snaps the corner to even coordinates first; apply
// SnapCropForYUV before calling NewSink to match it.
Crop image.Rectangle
// ScaleW, ScaleH > 0 enable libwebp's rescaler on the (cropped) frame.
// When exactly one of them is 0 it is derived from the other keeping
// the aspect ratio (WebPRescalerGetScaledDimensions). Negative values
// are an InvalidParam error.
ScaleW, ScaleH int
// Flip mirrors the output vertically.
Flip bool
// Premultiply rescales alpha-premultiplied samples (then
// un-premultiplies the result), which is what libwebp does for lossless
// (VP8L) frames. libwebp rescales lossy frames in the YUV domain with
// non-premultiplied alpha; leave Premultiply false for them.
Premultiply bool
// Dst, if not nil, lends its pixel memory to the output image (see
// newOutput): no allocation when cap(Dst.Pix) is large enough. Dst
// itself is never modified.
Dst *image.NRGBA
}
// SnapCropForYUV returns r with its top-left corner rounded down to even
// coordinates and the same size, as libwebp does for crops of lossy (YUV
// 4:2:0) frames ("crop_left & ~1", "crop_top & ~1").
func SnapCropForYUV(r image.Rectangle) image.Rectangle {
if r.Empty() {
return r
}
x, y := r.Min.X&^1, r.Min.Y&^1
return image.Rect(x, y, x+r.Dx(), y+r.Dy())
}
// CropFromV1 converts the v1 decoder.Options.Crop convention (Min = left/top,
// Max = width/height, passed to libwebp as crop_left/crop_top/crop_width/
// crop_height) to a proper rectangle for Params.Crop.
func CropFromV1(r image.Rectangle) image.Rectangle {
return image.Rectangle{Min: r.Min, Max: r.Min.Add(r.Max)}
}
// NewSink returns a sink receiving the full-width rows of a SrcW x SrcH frame
// and producing the final image, which the returned function gives back once
// all needed rows are committed.
//
// Without crop, scale or flip the sink is a Direct sink over a freshly
// allocated image (zero copy). Flip alone also decodes in place and mirrors
// the rows once the last one is committed. Crop copies only the kept part of
// the needed rows (or writes in place when the full width is kept) and
// NeedRows reports the crop bottom. Scaling keeps only O(width) state besides
// the output image.
func NewSink(p Params) (Sink, func() *image.NRGBA, error) {
if p.SrcW <= 0 || p.SrcH <= 0 {
return nil, nil, status.InvalidParam("invalid source dimensions")
}
crop := image.Rect(0, 0, p.SrcW, p.SrcH)
if !p.Crop.Empty() {
x, y, w, h := p.Crop.Min.X, p.Crop.Min.Y, p.Crop.Dx(), p.Crop.Dy()
if x < 0 || y < 0 || x >= p.SrcW || w > p.SrcW-x || y >= p.SrcH || h > p.SrcH-y {
return nil, nil, status.InvalidParam("crop rectangle outside of the frame")
}
crop = p.Crop
}
cw, ch := crop.Dx(), crop.Dy()
if p.ScaleW < 0 || p.ScaleH < 0 {
return nil, nil, status.InvalidParam("negative scaled dimensions")
}
if p.ScaleW > 0 || p.ScaleH > 0 {
w, h, ok := resample.ScaledDimensions(cw, ch, p.ScaleW, p.ScaleH)
if !ok {
return nil, nil, status.InvalidParam("invalid scaled dimensions")
}
if err := checkImageSize(w, h); err != nil {
return nil, nil, err
}
if err := checkRescalerSize(w); err != nil {
return nil, nil, err
}
s := &scaleSink{
base: newBase(p.SrcW, crop, w, h),
flip: p.Flip,
premult: p.Premultiply,
}
s.reuse = p.Dst
s.work = getWork(resample.BufferSize(w, 4))
if err := s.rs.Init(cw, ch, w, h, 4, *s.work); err != nil {
s.releaseWork()
return nil, nil, status.InvalidParam("invalid scaled dimensions")
}
return s, s.image, nil
}
if err := checkImageSize(cw, ch); err != nil {
return nil, nil, err
}
if !p.Flip && cw == p.SrcW && ch == p.SrcH {
d := &lazyDirect{w: cw, h: ch, reuse: p.Dst}
return d, d.image, nil
}
s := &cropSink{
base: newBase(p.SrcW, crop, cw, ch),
flip: p.Flip,
fullWidth: cw == p.SrcW,
}
s.reuse = p.Dst
return s, s.image, nil
}
// checkImageSize reports an OutOfMemory error for output images libwebp
// would refuse to allocate.
func checkImageSize(w, h int) error {
if uint64(w)*uint64(h)*4 > maxOutputBytes {
return status.New(utils.Vp8StatusOutOfMemory, "output image too large")
}
return nil
}
// checkRescalerSize reports an OutOfMemory error when the rescaler state
// for an output w pixels wide exceeds maxOutputBytes: libwebp allocates it
// with WebPSafeMalloc (2 * 4 channels * w uint32 work cells, plus a row of
// w RGBA pixels), which fails above WEBP_MAX_ALLOCABLE_MEMORY. Both the RGBA
// and the Y'CbCr(A) rescalers below need that much.
func checkRescalerSize(w int) error {
if uint64(w)*(4*uint64(resample.WorkSize(1, 4))+4) > maxOutputBytes {
return status.New(utils.Vp8StatusOutOfMemory, "rescaler too large")
}
return nil
}
// lazyDirect is a Direct sink whose image is allocated on the first Buffer
// call, so that a bitstream rejected before its first row is decoded never
// allocates the (possibly huge) output frame. libwebp likewise validates the
// frame headers before WebPAllocateDecBuffer.
type lazyDirect struct {
img *image.NRGBA
w, h int
reuse *image.NRGBA // Params.Dst
}
func (d *lazyDirect) image() *image.NRGBA {
if d.img == nil {
d.img = newOutput(d.w, d.h, d.reuse)
}
return d.img
}
// Buffer implements Sink.
func (d *lazyDirect) Buffer(y, n int) []byte {
img := d.image()
s := img.Stride
end := min((y+n)*s, len(img.Pix))
return img.Pix[y*s : end]
}
// Stride implements Sink.
func (d *lazyDirect) Stride() int { return d.w * 4 }
// Commit implements Sink.
func (d *lazyDirect) Commit(y, n int) error { return nil }
// NeedRows implements Sink.
func (d *lazyDirect) NeedRows() int { return d.h }
// scratchPool recycles row-batch buffers between decodes.
var scratchPool sync.Pool // of *[]byte
// workPool recycles rescaler work buffers (rows and column tables, see
// resample.BufferSize) between decodes.
var workPool sync.Pool // of *[]uint32
// getWork returns a pooled rescaler work buffer of at least n cells.
func getWork(n int) *[]uint32 {
w, ok := workPool.Get().(*[]uint32)
if !ok {
w = new([]uint32)
}
if cap(*w) < n {
*w = make([]uint32, n)
}
return w
}
// base holds the geometry and scratch buffer shared by the sinks.
type base struct {
srcStride int
left4, w4 int // crop left and width, in bytes
top, bottom int
scratch *[]byte
done bool
// dst is the output image, allocated on first use (see lazyDirect).
dst *image.NRGBA
dstW, dstH int
reuse *image.NRGBA // Params.Dst
}
func newBase(srcW int, crop image.Rectangle, dstW, dstH int) base {
return base{
srcStride: srcW * 4,
left4: crop.Min.X * 4,
w4: crop.Dx() * 4,
top: crop.Min.Y,
bottom: crop.Max.Y,
dstW: dstW,
dstH: dstH,
}
}
// out returns the output image, allocating it on the first call.
func (b *base) out() *image.NRGBA {
if b.dst == nil {
b.dst = newOutput(b.dstW, b.dstH, b.reuse)
}
return b.dst
}
// Stride implements Sink.
func (b *base) Stride() int { return b.srcStride }
// NeedRows implements Sink.
func (b *base) NeedRows() int { return b.bottom }
// scratchRows returns a scratch buffer for n full-width rows.
func (b *base) scratchRows(n int) []byte {
need := n * b.srcStride
if b.scratch == nil {
if v, ok := scratchPool.Get().(*[]byte); ok {
b.scratch = v
} else {
b.scratch = new([]byte)
}
}
if cap(*b.scratch) < need {
*b.scratch = make([]byte, need)
}
return (*b.scratch)[:need]
}
// release returns the scratch buffer to the pool.
func (b *base) release() {
if b.scratch != nil {
scratchPool.Put(b.scratch)
b.scratch = nil
}
}
// keptRows returns the source rows of the batch [y, y+n) that lie inside the
// crop.
func (b *base) keptRows(y, n int) (int, int) {
return max(y, b.top), min(y+n, b.bottom)
}
// cropSink implements crop and/or flip without scaling.
type cropSink struct {
base
flip bool
fullWidth bool
direct bool // the last Buffer call returned dst memory
}
func (s *cropSink) image() *image.NRGBA { return s.out() }
// Buffer implements Sink.
func (s *cropSink) Buffer(y, n int) []byte {
if s.fullWidth && y >= s.top && y+n <= s.bottom {
// Rows land at their final place (flip is applied at the end).
s.direct = true
off := (y - s.top) * s.srcStride
return s.out().Pix[off : off+n*s.srcStride]
}
s.direct = false
return s.scratchRows(n)
}
// Commit implements Sink.
func (s *cropSink) Commit(y, n int) error {
if !s.direct && s.scratch != nil {
src := *s.scratch
dst := s.out()
ch := dst.Rect.Dy()
from, to := s.keptRows(y, n)
for r := from; r < to; r++ {
dy := r - s.top
if s.flip && !s.fullWidth {
dy = ch - 1 - dy
}
o := (r - y) * s.srcStride
copy(dst.Pix[dy*dst.Stride:dy*dst.Stride+s.w4], src[o+s.left4:o+s.left4+s.w4])
}
}
if !s.done && y+n >= s.bottom {
s.done = true
s.release()
if s.flip && s.fullWidth {
flipRows(s.out())
}
}
return nil
}
// flipRows mirrors img vertically in place.
func flipRows(img *image.NRGBA) {
h, w4 := img.Rect.Dy(), img.Rect.Dx()*4
tmp := make([]byte, w4)
for a, b := 0, h-1; a < b; a, b = a+1, b-1 {
ra := img.Pix[a*img.Stride : a*img.Stride+w4]
rb := img.Pix[b*img.Stride : b*img.Stride+w4]
copy(tmp, ra)
copy(ra, rb)
copy(rb, tmp)
}
}
// scaleSink implements crop + rescale (+ flip).
type scaleSink struct {
base
flip bool
premult bool
preDone bool // rows arrive premultiplied (see PremultipliedSink)
rs resample.Rescaler
yuv yuvScaler // YUV-domain path, see YUVSink
// work backs the rescalers of rs or yuv (from workPool); nil once
// released.
work *[]uint32
}
// releaseWork returns the rescaler work buffer to the pool once the last
// output row is out. The rescalers are reset first: a zero Rescaler
// imports and exports nothing, so a late call cannot touch the buffer
// after another decode took it.
func (s *scaleSink) releaseWork() {
if s.work == nil {
return
}
s.rs = resample.Rescaler{}
q := &s.yuv
q.ry, q.ru, q.rv, q.ra = resample.Rescaler{}, resample.Rescaler{}, resample.Rescaler{}, resample.Rescaler{}
workPool.Put(s.work)
s.work = nil
}
func (s *scaleSink) image() *image.NRGBA { return s.out() }
// Buffer implements Sink.
func (s *scaleSink) Buffer(y, n int) []byte { return s.scratchRows(n) }
// Commit implements Sink.
func (s *scaleSink) Commit(y, n int) error {
if s.scratch == nil || s.done {
return nil
}
src := *s.scratch
from, to := s.keptRows(y, n)
for r := from; r < to; r++ {
o := (r-y)*s.srcStride + s.left4
row := src[o : o+s.w4]
if s.premult && !s.preDone {
resample.PremultiplyRGBA(row)
}
s.rs.ImportRow(row)
s.export()
}
if y+n >= s.bottom {
s.done = true
s.release()
s.releaseWork()
}
return nil
}
// export drains the rescaler's pending output rows into dst.
func (s *scaleSink) export() {
dst := s.out()
h, w4 := dst.Rect.Dy(), dst.Rect.Dx()*4
for s.rs.HasPendingOutput() {
dy := s.rs.DstY()
if s.flip {
dy = h - 1 - dy
}
out := dst.Pix[dy*dst.Stride : dy*dst.Stride+w4]
s.rs.ExportRow(out)
if s.premult {
resample.UnpremultiplyRGBA(out)
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package pipeline
// Algorithm adapted from libwebp (BSD-3-Clause): src/dec/io_dec.c (EmitRescaledRGB) and
// src/dsp/yuv.h (VP8YuvToRgba, VP8Clip8).
import (
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
"github.com/kolesa-team/go-webp/v2/internal/resample"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// yuvLevel selects the x86 SIMD level of yuvToRGBARow (yuv_amd64.go);
// tests lower it to cover every level. Other builds ignore it.
var yuvLevel = cpuinfo.Max
// YUVSink is implemented by the scaling sinks returned by NewSink. A lossy
// (VP8) decoder can hand its YUV 4:2:0 (+ alpha) output to CommitYUV instead
// of converting to RGBA and using Buffer/Commit: the planes are then rescaled
// separately and converted afterwards, which is bit-exact with libwebp's
// scaled RGBA output (EmitRescaledRGB / EmitRescaledAlphaRGB in
// src/dec/io_dec.c). To fully match libwebp the decoder must also, when
// scaling, bypass the loop filter when both scaled dimensions are below 3/4
// of the frame's (WebPIoInitFromOptions); crop rectangles should be snapped
// with SnapCropForYUV.
//
// A sink receives either RGBA rows (Buffer/Commit) or YUV rows (CommitYUV)
// for a given frame, never both. NeedRows applies to both.
type YUVSink interface {
Sink
// CommitYUV consumes the full-width luma rows [y, y+n) (row i at
// yp[i*yStride:]), the chroma rows [y/2, (y+n+1)/2) (row j at
// u[j*uvStride:] and v[j*uvStride:], (SrcW+1)/2 samples each) and the
// alpha rows [y, y+n) (a, aStride; a == nil on the first call for frames
// without alpha, which then yields opaque output). Batches must arrive
// in order; a chroma row already passed with the previous batch (odd y)
// is ignored. The buffers are not retained after the call returns.
CommitYUV(y, n int, yp []byte, yStride int, u, v []byte, uvStride int, a []byte, aStride int) error
}
// yuvScaler holds the state of the YUV-domain rescaling path.
type yuvScaler struct {
ry, ru, rv, ra resample.Rescaler
init bool
hasAlpha bool
uvLeft int // crop left, in chroma samples
uvTop, uvH int // crop top and height, in chroma rows
cw, cuw int // cropped luma / chroma widths
yDone, uvDone int // rows imported, relative to the crop
rowY, rowU []byte
rowV, rowA []byte
// Rows that could not be imported during their batch (the U/V rescalers
// may lag one row behind the Y one, or the reverse). carryY/carryA hold
// rows yDone.., carryU/carryV rows uvDone...
carryY, carryA [][]byte
carryU, carryV [][]byte
}
func (s *scaleSink) initYUV(hasAlpha bool) error {
q := &s.yuv
q.init = true
q.hasAlpha = hasAlpha
cw, ch := s.w4/4, s.bottom-s.top
dw, dh := s.dstW, s.dstH
q.cw = cw
q.cuw = (cw + 1) >> 1
q.uvLeft = (s.left4 / 4) >> 1
q.uvTop = s.top >> 1
q.uvH = (ch + 1) >> 1
// The RGBA rescaler is not used on this path: reset it (a zero
// Rescaler does nothing) and reuse its work buffer for the planes.
s.rs = resample.Rescaler{}
ws := resample.BufferSize(dw, 1)
planes := 3
if hasAlpha {
planes = 4
}
if s.work == nil {
s.work = getWork(0)
}
if cap(*s.work) < planes*ws {
*s.work = make([]uint32, planes*ws)
}
work := (*s.work)[:planes*ws]
err := q.ry.Init(cw, ch, dw, dh, 1, work[0:ws:ws])
if err == nil {
err = q.ru.Init(q.cuw, q.uvH, dw, dh, 1, work[ws:2*ws:2*ws])
}
if err == nil {
err = q.rv.Init(q.cuw, q.uvH, dw, dh, 1, work[2*ws:3*ws:3*ws])
}
if err == nil && hasAlpha {
err = q.ra.Init(cw, ch, dw, dh, 1, work[3*ws:])
}
if err != nil {
return status.InvalidParam("invalid scaled dimensions")
}
rows := make([]byte, 4*dw)
q.rowY, q.rowU, q.rowV, q.rowA = rows[:dw:dw], rows[dw:2*dw:2*dw], rows[2*dw:3*dw:3*dw], rows[3*dw:]
return nil
}
// CommitYUV implements YUVSink.
func (s *scaleSink) CommitYUV(y, n int, yp []byte, yStride int, u, v []byte, uvStride int, a []byte, aStride int) error {
q := &s.yuv
if !q.init {
if err := s.initYUV(a != nil); err != nil {
return err
}
}
if s.done || n <= 0 {
return nil
}
if q.hasAlpha && a == nil {
return status.InvalidParam("missing alpha rows")
}
left := s.left4 / 4
// Rows of this batch inside the crop, relative to the crop.
yFrom, yTo := s.keptRows(y, n)
yFrom, yTo = yFrom-s.top, yTo-s.top
uvFirst := y >> 1 // chroma row at u[0]
uvFrom := max(uvFirst, q.uvTop) - q.uvTop
uvTo := min((y+n+1)>>1, q.uvTop+q.uvH) - q.uvTop
if y+n >= s.bottom {
uvTo = q.uvH
}
batchY := func(k int) []byte {
o := (k+s.top-y)*yStride + left
return yp[o : o+q.cw]
}
batchA := func(k int) []byte {
o := (k+s.top-y)*aStride + left
return a[o : o+q.cw]
}
batchU := func(k int) []byte {
o := (k+q.uvTop-uvFirst)*uvStride + q.uvLeft
return u[o : o+q.cuw]
}
batchV := func(k int) []byte {
o := (k+q.uvTop-uvFirst)*uvStride + q.uvLeft
return v[o : o+q.cuw]
}
// Carried rows come first: luma/alpha rows [startY, carryYEnd), chroma
// rows [startUV, carryUVEnd); the batch supplies the following ones.
startY, startUV := q.yDone, q.uvDone
carryYEnd, carryUVEnd := startY+len(q.carryY), startUV+len(q.carryU)
if (yTo > yFrom && yFrom > carryYEnd) || (uvTo > uvFrom && uvFrom > carryUVEnd) {
return status.InvalidParam("YUV rows out of order")
}
yAvail, uvAvail := max(yTo, carryYEnd), max(uvTo, carryUVEnd)
for progress := true; progress; {
progress = false
for !q.ry.HasPendingOutput() && q.yDone < yAvail {
k := q.yDone
if k < carryYEnd {
q.ry.ImportRow(q.carryY[k-startY])
if q.hasAlpha {
q.ra.ImportRow(q.carryA[k-startY])
}
} else {
q.ry.ImportRow(batchY(k))
if q.hasAlpha {
q.ra.ImportRow(batchA(k))
}
}
q.yDone++
progress = true
}
for !q.ru.HasPendingOutput() && q.uvDone < uvAvail {
k := q.uvDone
if k < carryUVEnd {
q.ru.ImportRow(q.carryU[k-startUV])
q.rv.ImportRow(q.carryV[k-startUV])
} else {
q.ru.ImportRow(batchU(k))
q.rv.ImportRow(batchV(k))
}
q.uvDone++
progress = true
}
for q.ry.HasPendingOutput() && q.ru.HasPendingOutput() {
s.exportYUV()
progress = true
}
}
q.carryY = carry(q.carryY, q.yDone-startY, carryYEnd, yAvail, batchY)
if q.hasAlpha {
q.carryA = carry(q.carryA, q.yDone-startY, carryYEnd, yAvail, batchA)
}
q.carryU = carry(q.carryU, q.uvDone-startUV, carryUVEnd, uvAvail, batchU)
q.carryV = carry(q.carryV, q.uvDone-startUV, carryUVEnd, uvAvail, batchV)
if q.ry.OutputDone() {
s.done = true
s.release()
s.releaseWork()
}
return nil
}
// carry returns the rows still to import: the unconsumed tail of old (its
// first consumed rows were imported, possibly followed by batch rows) and
// copies of the remaining batch rows up to to. batchFrom is the index of
// the first row that was not in old.
func carry(old [][]byte, consumed, batchFrom, to int, batch func(int) []byte) [][]byte {
if consumed >= len(old) {
batchFrom += consumed - len(old)
old = old[:0]
} else {
old = old[consumed:]
}
if batchFrom >= to {
return old
}
out := make([][]byte, 0, len(old)+to-batchFrom)
out = append(out, old...)
for k := batchFrom; k < to; k++ {
out = append(out, append([]byte(nil), batch(k)...))
}
return out
}
// exportYUV exports one row from each rescaler and converts it to RGBA
// (libwebp's VP8YuvToRgba).
func (s *scaleSink) exportYUV() {
q := &s.yuv
dy := q.ry.DstY()
q.ry.ExportRow(q.rowY)
q.ru.ExportRow(q.rowU)
q.rv.ExportRow(q.rowV)
dst := s.out()
h, w := dst.Rect.Dy(), dst.Rect.Dx()
if s.flip {
dy = h - 1 - dy
}
out := dst.Pix[dy*dst.Stride : dy*dst.Stride+w*4]
var ar []byte
if q.hasAlpha {
q.ra.ExportRow(q.rowA)
ar = q.rowA[:w]
}
yuvToRGBARow(q.rowY[:w], q.rowU[:w], q.rowV[:w], ar, out)
}
// yuvToRGBARowGo converts full resolution Y, U and V rows to RGBA
// (libwebp's VP8YuvToRgba) into out[:4*len(yr)]. ar holds the alpha
// values, or is nil for opaque output. This is the portable reference;
// yuvToRGBARow (yuv_arm64.go, yuv_generic.go) is the entry point.
func yuvToRGBARowGo(yr, ur, vr, ar, out []byte) {
w := len(yr)
ur, vr = ur[:w], vr[:w]
out = out[:4*w]
if ar != nil {
ar = ar[:w]
}
for x := range yr {
o := out[x*4 : x*4+4 : x*4+4]
yy, uu, vv := int(yr[x]), int(ur[x]), int(vr[x])
yh := (yy * 19077) >> 8
o[0] = clip8YUV(yh + (vv*26149)>>8 - 14234)
o[1] = clip8YUV(yh - (uu*6419)>>8 - (vv*13320)>>8 + 8708)
o[2] = clip8YUV(yh + (uu*33050)>>8 - 17685)
o[3] = 255
if ar != nil {
o[3] = ar[x]
}
}
}
// clip8YUV is libwebp's VP8Clip8 (YUV_FIX2 = 6).
func clip8YUV(v int) byte {
const mask = (256 << 6) - 1
if v&^mask == 0 {
return byte(v >> 6)
}
if v < 0 {
return 0
}
return 255
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package pipeline
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// yuvToRGBARowSSE41 converts pixels [0, n) of full resolution Y, U, V rows
// (and alpha, or opaque when a is nil) to RGBA, n >= 16;
// yuvToRGBARowAVX2 needs n >= 32. They read y, u, v and a [:n] and write
// dst[:4*n].
//
//go:noescape
func yuvToRGBARowSSE41(y, u, v, a, dst *byte, n int)
//go:noescape
func yuvToRGBARowAVX2(y, u, v, a, dst *byte, n int)
// yuvToRGBARow converts full resolution Y'CbCr rows to RGBA with SSE4.1 or
// AVX2 (selected by yuvLevel); it matches yuvToRGBARowGo bit for bit.
func yuvToRGBARow(yr, ur, vr, ar, out []byte) {
w := len(yr)
if w < 16 || yuvLevel < cpuinfo.SSE41 {
yuvToRGBARowGo(yr, ur, vr, ar, out)
return
}
ur, vr = ur[:w], vr[:w]
out = out[:4*w]
var pa *byte
if ar != nil {
ar = ar[:w]
pa = &ar[0]
}
if w >= 32 && yuvLevel >= cpuinfo.AVX2 {
yuvToRGBARowAVX2(&yr[0], &ur[0], &vr[0], pa, &out[0], w)
} else {
yuvToRGBARowSSE41(&yr[0], &ur[0], &vr[0], pa, &out[0], w)
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package resample
// Algorithm adapted from libwebp (BSD-3-Clause): src/dsp/alpha_processing.c (WebPMultARGBRow and
// the GetScale tables).
const (
mfix = 24
half = uint32(1) << (mfix - 1)
kInv255 = uint32((1 << mfix) / 255)
)
// premulScale[a] = a * KINV_255 and unpremulScale[a] = (255 << 24) / a, as
// in libwebp's GetScale (USE_TABLES_FOR_ALPHA_MULT == 0).
var premulScale, unpremulScale [256]uint32
func init() {
for a := uint32(1); a < 256; a++ {
premulScale[a] = a * kInv255
unpremulScale[a] = (255 << mfix) / a
}
}
// mult is libwebp's Mult (32-bit arithmetic, wrapping like the C code).
func mult(x byte, scale uint32) byte { return byte((uint32(x)*scale + half) >> mfix) }
// PremultiplyRGBA multiplies the R, G and B samples of an RGBA row by alpha,
// exactly like libwebp's WebPMultARGBRow(..., inverse=0); fully transparent
// pixels become 0,0,0,0.
func PremultiplyRGBA(row []byte) { premultiplyRow(row) }
// UnpremultiplyRGBA reverses PremultiplyRGBA, exactly like libwebp's
// WebPMultARGBRow(..., inverse=1).
func UnpremultiplyRGBA(row []byte) { unpremultiplyRow(row) }
func multRGBA(row []byte, table *[256]uint32) {
for i := 0; i+4 <= len(row); i += 4 {
p := row[i : i+4 : i+4]
a := p[3]
if a == 255 {
continue
}
if a == 0 {
p[0], p[1], p[2] = 0, 0, 0
continue
}
s := table[a]
p[0] = mult(p[0], s)
p[1] = mult(p[1], s)
p[2] = mult(p[2], s)
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package resample
// Row kernels in pure Go. They are the reference for the assembly ones and
// the implementation on other architectures (see rescaler_generic.go).
// Algorithm adapted from libwebp (BSD-3-Clause): src/dsp/rescaler.c.
//
// All of them work on whole rows. The import kernels walk the column table
// built by initCols; acc, when not nil, receives the new row added to it
// (the irow accumulation of a vertical shrink).
// shrinkRowRef imports a row of a horizontal shrink with the Go kernels.
func (r *Rescaler) shrinkRowRef(src []byte, acc []uint32) {
xSub := uint32(r.xSub)
switch r.numChannels {
case 1:
shrinkRow1Go(r.frow, acc, src, r.cols, xSub, r.fxScale, 0)
case 4:
shrinkRow4Go(r.frow, acc, src, r.cols, xSub, r.fxScale, [4]uint32{})
default:
shrinkRowGo(r.frow, acc, src, r.cols, r.numChannels, xSub, r.fxScale)
}
}
// expandRowRef imports a row of a horizontal expansion with the Go kernels.
func (r *Rescaler) expandRowRef(src []byte, acc []uint32) {
xAdd := uint32(r.xAdd)
if r.srcWidth > 1 {
switch r.numChannels {
case 1:
expandRow1Go(r.frow, acc, src, r.cols, xAdd)
return
case 4:
expandRow4Go(r.frow, acc, src, r.cols, xAdd)
return
}
}
right := r.numChannels
if r.srcWidth == 1 {
right = 0
}
expandRowGo(r.frow, acc, src, r.cols, r.numChannels, right, xAdd)
}
// shrinkRowGo is WebPRescalerImportRowShrink_C for ch interleaved channels,
// starting at destination pixel 0 with zero carries.
func shrinkRowGo(frow, acc []uint32, src []byte, cols []uint32, ch int, xSub, fx uint32) {
nOut := len(cols) / 2
for c := 0; c < ch; c++ {
xIn := c
var sum uint32
for x := 0; x < nOut; x++ {
n, na := int(cols[2*x]), cols[2*x+1]
var base uint32
for ; n > 0; n-- {
base = uint32(src[xIn])
sum += base
xIn += ch
}
fr := base * na
v := sum*xSub - fr
frow[x*ch+c] = v
if acc != nil {
acc[x*ch+c] += v
}
sum = multFix(fr, fx)
}
}
}
// shrinkRow1Go is shrinkRowGo for one channel. It resumes at the
// destination pixel the slices start at: src starts at that pixel's first
// source pixel and carry is the rounded fractional part left over by the
// previous destination pixel (0 at the start of a row).
func shrinkRow1Go(frow, acc []uint32, src []byte, cols []uint32, xSub, fx, carry uint32) {
nOut := len(cols) / 2
cols = cols[:2*nOut]
frow = frow[:nOut]
if acc != nil {
acc = acc[:nOut]
}
sum := carry
for x := range frow {
n, na := int(cols[2*x]), cols[2*x+1]
p := src[:n]
src = src[n:]
for _, v := range p[:n-1] {
sum += uint32(v)
}
base := uint32(p[n-1])
sum += base
fr := base * na
v := sum*xSub - fr
frow[x] = v
if acc != nil {
acc[x] += v
}
sum = multFix(fr, fx)
}
}
// shrinkRow4Go is shrinkRowGo for four channels, resuming like
// shrinkRow1Go (carry holds the four channels' carries).
func shrinkRow4Go(frow, acc []uint32, src []byte, cols []uint32, xSub, fx uint32, carry [4]uint32) {
nOut := len(cols) / 2
cols = cols[:2*nOut]
frow = frow[:4*nOut]
if acc != nil {
acc = acc[:4*nOut]
}
s0, s1, s2, s3 := carry[0], carry[1], carry[2], carry[3]
for x := 0; x < nOut; x++ {
n, na := int(cols[2*x]), cols[2*x+1]
p := src[:4*n]
src = src[4*n:]
for ; len(p) > 4; p = p[4:] {
s0 += uint32(p[0])
s1 += uint32(p[1])
s2 += uint32(p[2])
s3 += uint32(p[3])
}
p = p[:4]
b0, b1, b2, b3 := uint32(p[0]), uint32(p[1]), uint32(p[2]), uint32(p[3])
s0 += b0
s1 += b1
s2 += b2
s3 += b3
fr0, fr1, fr2, fr3 := b0*na, b1*na, b2*na, b3*na
f := frow[4*x : 4*x+4 : 4*x+4]
f[0] = s0*xSub - fr0
f[1] = s1*xSub - fr1
f[2] = s2*xSub - fr2
f[3] = s3*xSub - fr3
if acc != nil {
a := acc[4*x : 4*x+4 : 4*x+4]
a[0] += f[0]
a[1] += f[1]
a[2] += f[2]
a[3] += f[3]
}
s0, s1, s2, s3 = multFix(fr0, fx), multFix(fr1, fx), multFix(fr2, fx), multFix(fr3, fx)
}
}
// expandRowGo is WebPRescalerImportRowExpand_C for ch interleaved channels.
// right is the offset of the right source pixel from the left one: ch, or
// 0 for a one pixel wide source.
func expandRowGo(frow, acc []uint32, src []byte, cols []uint32, ch, right int, xAdd uint32) {
nOut := len(cols) / 2
for x := 0; x < nOut; x++ {
l, w := int(cols[2*x])*ch, cols[2*x+1]
for c := 0; c < ch; c++ {
left, rt := uint32(src[l+c]), uint32(src[l+c+right])
v := rt*xAdd + (left-rt)*w
frow[x*ch+c] = v
if acc != nil {
acc[x*ch+c] += v
}
}
}
}
// expandRow4Go is expandRowGo for four channels and a source at least two
// pixels wide.
func expandRow4Go(frow, acc []uint32, src []byte, cols []uint32, xAdd uint32) {
nOut := len(cols) / 2
cols = cols[:2*nOut]
frow = frow[:4*nOut]
if acc != nil {
acc = acc[:4*nOut]
}
for x := 0; x < nOut; x++ {
l, w := int(cols[2*x])*4, cols[2*x+1]
p := src[l : l+8 : l+8]
f := frow[4*x : 4*x+4 : 4*x+4]
r0, r1, r2, r3 := uint32(p[4]), uint32(p[5]), uint32(p[6]), uint32(p[7])
f[0] = r0*xAdd + (uint32(p[0])-r0)*w
f[1] = r1*xAdd + (uint32(p[1])-r1)*w
f[2] = r2*xAdd + (uint32(p[2])-r2)*w
f[3] = r3*xAdd + (uint32(p[3])-r3)*w
if acc != nil {
a := acc[4*x : 4*x+4 : 4*x+4]
a[0] += f[0]
a[1] += f[1]
a[2] += f[2]
a[3] += f[3]
}
}
}
// expandRow1Go is expandRowGo for one channel and a source at least two
// pixels wide.
func expandRow1Go(frow, acc []uint32, src []byte, cols []uint32, xAdd uint32) {
nOut := len(cols) / 2
cols = cols[:2*nOut]
frow = frow[:nOut]
if acc != nil {
acc = acc[:nOut]
}
for x := range frow {
l, w := int(cols[2*x]), cols[2*x+1]
p := src[l : l+2 : l+2]
rt := uint32(p[1])
v := rt*xAdd + (uint32(p[0])-rt)*w
frow[x] = v
if acc != nil {
acc[x] += v
}
}
}
// exportExpandGo is the y_accum == 0 branch of
// WebPRescalerExportRowExpand_C: dst = clip8(frow * fy).
func exportExpandGo(dst []byte, frow []uint32, fy uint32) {
frow = frow[:len(dst)]
for i, v := range frow {
dst[i] = clip8(multFix(v, fy))
}
}
// exportExpandMixGo is the interpolating branch of
// WebPRescalerExportRowExpand_C: dst = clip8(((a*frow + b*irow) >> 32) *
// fy), both products rounded. a + b == 2^32.
func exportExpandMixGo(dst []byte, frow, irow []uint32, a, b, fy uint32) {
n := len(dst)
frow, irow = frow[:n], irow[:n]
a64, b64, fy64 := uint64(a), uint64(b), uint64(fy)
i := 0
for ; i+4 <= n; i += 4 {
f := frow[i : i+4 : i+4]
g := irow[i : i+4 : i+4]
d := dst[i : i+4 : i+4]
j0 := (a64*uint64(f[0]) + b64*uint64(g[0]) + rounder) >> rfix
j1 := (a64*uint64(f[1]) + b64*uint64(g[1]) + rounder) >> rfix
j2 := (a64*uint64(f[2]) + b64*uint64(g[2]) + rounder) >> rfix
j3 := (a64*uint64(f[3]) + b64*uint64(g[3]) + rounder) >> rfix
d[0] = clip8(uint32((uint64(uint32(j0))*fy64 + rounder) >> rfix))
d[1] = clip8(uint32((uint64(uint32(j1))*fy64 + rounder) >> rfix))
d[2] = clip8(uint32((uint64(uint32(j2))*fy64 + rounder) >> rfix))
d[3] = clip8(uint32((uint64(uint32(j3))*fy64 + rounder) >> rfix))
}
for ; i < n; i++ {
j := uint32((a64*uint64(frow[i]) + b64*uint64(irow[i]) + rounder) >> rfix)
dst[i] = clip8(uint32((uint64(j)*fy64 + rounder) >> rfix))
}
}
// exportShrinkGo is WebPRescalerExportRowShrink_C with a non-zero yscale:
// the fraction of the last row that belongs to the next output row moves
// from irow to the next accumulation.
func exportShrinkGo(dst []byte, irow, frow []uint32, yscale, fxy uint32) {
n := len(dst)
irow, frow = irow[:n], frow[:n]
for i := range dst {
fr := uint32((uint64(frow[i]) * uint64(yscale)) >> rfix)
dst[i] = clip8(multFix(irow[i]-fr, fxy))
irow[i] = fr
}
}
// exportShrinkZeroGo is WebPRescalerExportRowShrink_C with yscale == 0.
func exportShrinkZeroGo(dst []byte, irow []uint32, fxy uint32) {
irow = irow[:len(dst)]
for i, v := range irow {
dst[i] = clip8(multFix(v, fxy))
irow[i] = 0
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package resample implements libwebp's fixed-point image rescaler
// (WebPRescaler): area-averaging when shrinking, bilinear interpolation when
// expanding, processed one source row at a time with O(width) state.
//
// Results are bit-exact with libwebp's C implementation
// (src/utils/rescaler_utils.c, src/dsp/rescaler.c).
//
// The horizontal geometry is the same for every row, so Init computes it
// once into a column table (see initCols) and the row kernels in
// kernels.go only walk that table. On arm64 the hot kernels are NEON
// assembly (rescaler_arm64.s), on amd64 SSE4.1 or AVX2 assembly picked at
// run time (rescaler_amd64.s); both are bit-exact with the Go ones.
//
// Algorithm adapted from libwebp (BSD-3-Clause).
package resample
import (
"errors"
"math"
)
const (
rfix = 32
one = uint64(1) << rfix
rounder = one >> 1
)
// frac is WEBP_RESCALER_FRAC(x, y).
func frac(x, y uint64) uint32 { return uint32((x << rfix) / y) }
// multFix is MULT_FIX: rounded 32.32 fixed-point product.
func multFix(x, y uint32) uint32 { return uint32((uint64(x)*uint64(y) + rounder) >> rfix) }
// Rescaler scales an image with numChannels interleaved 8-bit channels from
// srcWidth x srcHeight to dstWidth x dstHeight. Rows are fed with
// ImportRow and produced with ExportRow; the zero value is not usable, see
// New and Init.
type Rescaler struct {
xExpand, yExpand bool
numChannels int
fxScale uint32
fyScale uint32
fxyScale uint32
yAccum int
yAdd, ySub int
xAdd, xSub int
srcWidth int
srcHeight int
dstWidth int
dstHeight int
srcY, dstY int
irow, frow []uint32
work []uint32
// cols is the column table, two cells per destination pixel x:
// shrinking: cols[2x] = number of source pixels whose sum makes up
// pixel x (at least 1), cols[2x+1] = libwebp's -accum after them, the
// weight of the last one that belongs to pixel x+1;
// expanding: cols[2x] = index of the left source pixel,
// cols[2x+1] = libwebp's accum, the weight of that pixel.
cols []uint32
arch archState // per-architecture kernel state, see initArch
}
// ErrInvalid is returned for invalid rescaler dimensions.
var ErrInvalid = errors.New("resample: invalid dimensions")
// WorkSize returns the number of uint32 row cells a rescaler with the given
// destination width and channel count needs, like libwebp's work buffer
// (2 rows of dstWidth*numChannels accumulators).
func WorkSize(dstWidth, numChannels int) int { return 2 * dstWidth * numChannels }
// BufferSize returns the number of uint32 cells Init uses from its work
// buffer: the WorkSize row cells plus the column tables. A work buffer of
// that capacity spares Init any allocation.
func BufferSize(dstWidth, numChannels int) int {
return WorkSize(dstWidth, numChannels) + 2*dstWidth + archTableSize(dstWidth, numChannels)
}
// New returns a rescaler with a freshly allocated work buffer.
func New(srcWidth, srcHeight, dstWidth, dstHeight, numChannels int) (*Rescaler, error) {
r := new(Rescaler)
if err := r.Init(srcWidth, srcHeight, dstWidth, dstHeight, numChannels, nil); err != nil {
return nil, err
}
return r, nil
}
// Init (re)initializes r, like WebPRescalerInit. work is reused when its
// capacity is at least BufferSize(dstWidth, numChannels); otherwise a new
// buffer is allocated.
func (r *Rescaler) Init(srcWidth, srcHeight, dstWidth, dstHeight, numChannels int, work []uint32) error {
if srcWidth <= 0 || srcHeight <= 0 || dstWidth <= 0 || dstHeight <= 0 ||
numChannels <= 0 || numChannels > 4 ||
srcWidth > math.MaxInt32/2 || srcHeight > math.MaxInt32/2 ||
dstWidth > math.MaxInt32/2 || dstHeight > math.MaxInt32/2 {
return ErrInvalid
}
n := WorkSize(dstWidth, numChannels)
size := BufferSize(dstWidth, numChannels)
if cap(work) < size {
work = make([]uint32, size)
} else {
work = work[:size]
clear(work[:n])
}
*r = Rescaler{
xExpand: srcWidth < dstWidth,
yExpand: srcHeight < dstHeight,
numChannels: numChannels,
srcWidth: srcWidth,
srcHeight: srcHeight,
dstWidth: dstWidth,
dstHeight: dstHeight,
work: work,
irow: work[: n/2 : n/2],
frow: work[n/2 : n : n],
cols: work[n : n+2*dstWidth : n+2*dstWidth],
}
xAdd, xSub := srcWidth, dstWidth
yAdd, ySub := srcHeight, dstHeight
if r.xExpand {
r.xAdd, r.xSub = xSub-1, xAdd-1
} else {
r.xAdd, r.xSub = xAdd, xSub
r.fxScale = frac(1, uint64(r.xSub))
}
if r.yExpand {
r.yAdd, r.ySub = yAdd-1, ySub-1
r.yAccum = r.ySub
r.fyScale = frac(1, uint64(r.xAdd))
} else {
r.yAdd, r.ySub = yAdd, ySub
r.yAccum = r.yAdd
num := uint64(dstHeight) * one
den := uint64(r.xAdd) * uint64(r.yAdd)
ratio := num / den
if ratio != uint64(uint32(ratio)) {
r.fxyScale = 0 // special-cased in ExportRow
} else {
r.fxyScale = uint32(ratio)
}
r.fyScale = frac(1, uint64(r.ySub))
}
r.initCols()
r.initArch(work[n+2*dstWidth:])
return nil
}
// initCols fills the column table by running libwebp's horizontal loops
// (WebPRescalerImportRowExpand_C / _Shrink_C) once without the pixels.
func (r *Rescaler) initCols() {
cols := r.cols
if r.xExpand {
// accum starts at x_add; whenever it drops below zero the left
// pixel advances by one (x_sub < x_add, so by one at most).
accum, left := r.xAdd, 0
for x := 0; x < r.dstWidth; x++ {
cols[2*x], cols[2*x+1] = uint32(left), uint32(accum)
accum -= r.xSub
if accum < 0 {
left++
accum += r.xAdd
}
}
return
}
// accum gains x_add per output pixel and loses x_sub per source pixel
// summed; it stays in (-x_sub, 0] between output pixels, and since
// x_add >= x_sub at least one source pixel is summed per output pixel.
accum := 0
for x := 0; x < r.dstWidth; x++ {
accum += r.xAdd
k := (accum + r.xSub - 1) / r.xSub
accum -= k * r.xSub
cols[2*x], cols[2*x+1] = uint32(k), uint32(-accum)
}
}
// SrcY returns the number of source rows imported so far.
func (r *Rescaler) SrcY() int { return r.srcY }
// DstY returns the number of destination rows exported so far.
func (r *Rescaler) DstY() int { return r.dstY }
// DstWidth returns the destination width in pixels.
func (r *Rescaler) DstWidth() int { return r.dstWidth }
// DstHeight returns the destination height in pixels.
func (r *Rescaler) DstHeight() int { return r.dstHeight }
// InputDone reports whether all source rows were imported.
func (r *Rescaler) InputDone() bool { return r.srcY >= r.srcHeight }
// OutputDone reports whether all destination rows were exported.
func (r *Rescaler) OutputDone() bool { return r.dstY >= r.dstHeight }
// HasPendingOutput reports whether a destination row is ready to be
// exported. While it is, no more rows may be imported.
func (r *Rescaler) HasPendingOutput() bool { return !r.OutputDone() && r.yAccum <= 0 }
// NeededLines returns how many source rows must be imported before the next
// output row is ready, capped at maxLines (WebPRescaleNeededLines).
func (r *Rescaler) NeededLines(maxLines int) int {
n := (r.yAccum + r.ySub - 1) / r.ySub
return min(n, maxLines)
}
// Import imports up to numLines rows of src (row stride srcStride), stopping
// early when an output row becomes pending. It returns the number of rows
// imported (WebPRescalerImport).
func (r *Rescaler) Import(numLines int, src []byte, srcStride int) int {
total := 0
for total < numLines && !r.HasPendingOutput() && !r.InputDone() {
r.ImportRow(src[total*srcStride:])
total++
}
return total
}
// ImportRow imports one source row of srcWidth*numChannels bytes. It must
// not be called while HasPendingOutput is true or after InputDone.
func (r *Rescaler) ImportRow(src []byte) {
if r.InputDone() {
return
}
src = src[:r.srcWidth*r.numChannels]
// When shrinking vertically the new row is also added to the irow
// accumulators (libwebp does that in a second pass, the sum is the
// same); when expanding, irow and frow are the two latest rows.
var acc []uint32
if r.yExpand {
r.irow, r.frow = r.frow, r.irow
} else {
acc = r.irow
}
if r.xExpand {
r.expandRow(src, acc)
} else {
r.shrinkRow(src, acc)
}
r.srcY++
r.yAccum -= r.ySub
}
// ExportRow writes the next destination row (dstWidth*numChannels bytes)
// into dst if one is pending, and reports whether it did
// (WebPRescalerExportRow).
func (r *Rescaler) ExportRow(dst []byte) bool {
if !r.HasPendingOutput() {
return false
}
n := r.dstWidth * r.numChannels
dst = dst[:n]
irow := r.irow[:n]
frow := r.frow[:n]
switch {
case r.yExpand:
if r.yAccum == 0 {
exportExpand(dst, frow, r.fyScale)
} else {
b := frac(uint64(-r.yAccum), uint64(r.ySub))
// -yAccum >= 1 and ySub < 2^32, so b >= 1 and a fits 32 bits.
a := uint32(one - uint64(b))
exportExpandMix(dst, frow, irow, a, b, r.fyScale)
}
case r.fxyScale != 0:
if yscale := r.fyScale * uint32(-r.yAccum); yscale != 0 {
exportShrink(dst, irow, frow, yscale, r.fxyScale)
} else {
exportShrinkZero(dst, irow, r.fxyScale)
}
default:
// Special case src_height == dst_height, x_add == 1.
for i, v := range irow {
dst[i] = byte(v)
irow[i] = 0
}
}
r.yAccum += r.yAdd
r.dstY++
return true
}
func clip8(v uint32) byte {
if v > 255 {
return 255
}
return byte(v)
}
// Export exports all pending rows into dst (row stride dstStride) and
// returns their number (WebPRescalerExport).
func (r *Rescaler) Export(dst []byte, dstStride int) int {
n := 0
for r.HasPendingOutput() {
r.ExportRow(dst[n*dstStride:])
n++
}
return n
}
// ScaledDimensions resolves the requested output size like libwebp's
// WebPRescalerGetScaledDimensions: a zero width (or height) is derived from
// the other dimension keeping the aspect ratio (rounding up). It reports
// false when the result is not a valid size.
func ScaledDimensions(srcWidth, srcHeight, width, height int) (int, int, bool) {
const maxSize = math.MaxInt32 / 2
if width < 0 || height < 0 || srcWidth <= 0 || srcHeight <= 0 {
return 0, 0, false
}
if width == 0 {
width = int((uint64(srcWidth)*uint64(height) + uint64(srcHeight) - 1) / uint64(srcHeight))
}
if height == 0 {
height = int((uint64(srcHeight)*uint64(width) + uint64(srcWidth) - 1) / uint64(srcWidth))
}
if width <= 0 || height <= 0 || width > maxSize || height > maxSize {
return 0, 0, false
}
return width, height, true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package resample
import (
"encoding/binary"
"sync"
"unsafe"
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
)
// SSE4.1, AVX2 and AVX-512 kernels (rescaler_amd64.s), bit-exact with the
// Go ones. The level is picked at run time: x86Level (the machine's best
// level; tests lower it to run every level against the Go kernels). A
// rescaler records the level it was initialized with, so that its kernels
// and its record tables always agree. The AVX512 level has one kernel of
// its own, the 4-channel shrink of spans of up to 16 pixels
// (shrink4Z16VBMI), which needs AVX512-VBMI too; everything else, and that
// shrink without VBMI, runs the AVX2 kernels (wider forms of the other
// kernels would not show in a whole decode: see the AVX-512 notes in
// rescaler_amd64.s).
//
// shrink4Z16VBMI runs on every CPU with AVX512-VBMI but has only been
// measured on Zen 5 (EPYC 4345P, full-width 512-bit units): 221 ns per
// 3000 -> 320 row against 332-334 ns for shrink4W16AVX2 (-34%), and 8.7-9.2%
// off a lossless 3000x2000 decode scaled to 320x240. It has not been
// measured on Zen 4, which runs a 512-bit op as two 256-bit halves, nor on
// Intel CPUs. On Zen 4c (EPYC 8024P) earlier zmm forms of the windowed
// shrink (four destination pixels per step) measured 6-7% slower than
// AVX2, and one of them, re-built on Zen 5 (one 64-byte window per span,
// VPERMI2B transpose and VPSADBW), took 27% less time than AVX2 there; so
// this kernel may be slower than AVX2 on Zen 4 too.
//
// The Go wrappers below check every length the assembly relies on; the
// column-table invariants they depend on (spans of at least one pixel that
// tile the source row, see initCols) are established by Init and checked
// by TestColumnTable, and initArch only hands the kernels the destination
// pixels whose loads stay inside the source row.
// x86Level is the SIMD level of the kernels.
var x86Level = cpuinfo.Max
// x86VBMI enables shrink4Z16VBMI, which needs AVX512-VBMI (VPERMI2B), at
// x86Level AVX512. A variable for tests.
var x86VBMI = cpuinfo.X86.HasAVX512VBMI
// Kernel selection, see initArch.
const (
kindGo = iota
kindShrink4
kindShrink4W8
kindShrink4W16
kindShrink1
kindShrink1P
kindShrink1S
kindExpand1
kindExpand4
kindShrink4Z16
)
const (
// maxShrink4Span is the longest span shrinkRow4SSE41 handles: it sums
// each channel in 16-bit lanes, two pixels per lane and per 16 bytes.
maxShrink4Span = 511
// maxShrink4W8Span and maxShrink4W16Span are the longest spans of the
// windowed AVX2 kernels: one or two 32-byte windows per span.
maxShrink4W8Span = 8
maxShrink4W16Span = 16
// maxShrink1PSpan and maxShrink1SSpan are the longest spans of the
// record kernels: two spans of 8 bytes (P) or one of 16 bytes (S)
// per 16-byte window.
maxShrink1PSpan = 8
maxShrink1SSpan = 16
// shrink1PRecordSize and shrink1SRecordSize are the record sizes, in
// bytes, per 8 destination pixels (see buildShrink1P/SRecords).
shrink1PRecordSize = 128
shrink1SRecordSize = 192
// expand1RecordSize is the record size, in bytes, of the 1-channel
// expansion per 8 destination pixels (see buildExpand1Records).
expand1RecordSize = 96
// shrink4Z16RecordSize is the record size, in bytes, of the AVX-512
// 4-channel shrink per 4 destination pixels (see
// buildShrink4Z16Records).
shrink4Z16RecordSize = 32
// z16TailMax is the longest end of a source row, in bytes, whose
// regions shrink4Z16VBMI reads from a copy (see
// buildShrink4Z16Records); the copy has room for a whole region after
// it, z16TailSize bytes in all.
z16TailMax = 4 * 96
z16TailSize = z16TailMax + 128
)
// archState records which assembly kernel a rescaler uses and how far:
// the kernel handles destination pixels [0, asmOuts), whose spans cover
// source pixels [0, asmSrc); the Go kernels finish the row.
type archState struct {
kind uint8
level cpuinfo.Level
asmOuts int
asmSrc int
records []byte // kindShrink1P/S, kindExpand1: one record per 8 destination pixels; kindShrink4Z16: per 4
// kindShrink4Z16: the leading records whose 4 pixels exist and whose
// regions are inside the row, the offset in the row from which the
// regions of the others are read from tail (a copy), and the tables.
inside int
tailAt int
tail []byte
z16 *z16Tables
}
// archTableSize is the room for the record tables, in uint32 cells.
func archTableSize(dstWidth, numChannels int) int {
switch {
case numChannels == 1:
return dstWidth / 8 * shrink1SRecordSize / 4
case numChannels == 4 && x86Level >= cpuinfo.AVX512 && x86VBMI:
return ((dstWidth+3)/4*shrink4Z16RecordSize + z16TailSize) / 4
}
return 0
}
// initArch picks the kernel for r's geometry at the current x86Level; tab
// holds archTableSize cells.
func (r *Rescaler) initArch(tab []uint32) {
lvl := x86Level
if lvl < cpuinfo.SSE41 {
return
}
a := &r.arch
a.level = lvl
cols := r.cols
if r.xExpand {
// The left pixels never decrease; the kernel loads each one with
// its right neighbour.
switch {
case r.numChannels == 4 && int(cols[2*r.dstWidth-2])+2 <= r.srcWidth:
a.kind, a.asmOuts, a.asmSrc = kindExpand4, r.dstWidth, r.srcWidth
case r.numChannels == 1 && r.srcWidth >= 16 && r.dstWidth >= 8:
r.initExpand1Records(tab)
}
if a.kind == kindGo {
*a = archState{}
}
return
}
if r.numChannels != 1 && r.numChannels != 4 {
*a = archState{}
return
}
nmax := 0
for x := 0; x < r.dstWidth; x++ {
nmax = max(nmax, int(cols[2*x]))
}
// lead counts the destination pixels whose span starts at least room
// pixels before the end of the source row.
lead := func(room int) (x, start int) {
for x < r.dstWidth && start+room <= r.srcWidth {
start += int(cols[2*x])
x++
}
return x, start
}
switch {
case r.numChannels == 4:
// The windowed kernels do pairs of destination pixels and read
// 8 or 16 pixels from each span start.
switch {
case lvl >= cpuinfo.AVX512 && x86VBMI && nmax <= maxShrink4W16Span && r.initShrink4Z16Records(tab):
// Records of four destination pixels, the whole row.
return
case lvl >= cpuinfo.AVX2 && nmax <= maxShrink4W8Span:
a.kind = kindShrink4W8
a.asmOuts, a.asmSrc = lead(8)
case lvl >= cpuinfo.AVX2 && nmax <= maxShrink4W16Span:
a.kind = kindShrink4W16
a.asmOuts, a.asmSrc = lead(16)
}
if a.asmOuts%2 != 0 {
a.asmOuts--
a.asmSrc -= int(cols[2*a.asmOuts])
}
if a.asmOuts == 0 && nmax <= maxShrink4Span {
a.kind = kindShrink4
a.asmOuts, a.asmSrc = lead(4)
}
case nmax <= maxShrink1SSpan && r.srcWidth >= 16 && r.dstWidth >= 8:
r.initShrink1Records(tab, nmax)
default:
a.kind = kindShrink1
a.asmOuts, a.asmSrc = lead(16)
}
if a.asmOuts == 0 {
*a = archState{}
}
}
// initShrink1Records builds the records of the 1-channel record kernels
// for every whole block of 8 destination pixels.
func (r *Rescaler) initShrink1Records(tab []uint32, nmax int) {
a := &r.arch
blocks := r.dstWidth / 8
size := shrink1SRecordSize
a.kind = kindShrink1S
if nmax <= maxShrink1PSpan {
size = shrink1PRecordSize
a.kind = kindShrink1P
}
n := blocks * size
if 4*len(tab) < n {
panic("resample: short record table")
}
rec := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(tab))), n)
cols := r.cols[:16*blocks]
if a.kind == kindShrink1P {
buildShrink1PRecords(rec, cols, r.srcWidth)
} else {
buildShrink1SRecords(rec, cols, r.srcWidth)
}
a.records = rec
a.asmOuts = 8 * blocks
for x := 0; x < a.asmOuts; x++ {
a.asmSrc += int(cols[2*x])
}
}
// buildShrink1PRecords fills one 128-byte record per 8 destination pixels
// of cols (spans of at most 8 pixels, a source row of srcWidth >= 16
// bytes). The 8 pixels make two groups of 4 (0-3 and 4-7), each group two
// pairs, A (pixels 0, 1) and B (pixels 2, 3), each pair a 16-byte window
// of the source row that holds both spans:
//
// [ 0: 32) PSHUFB indices of pair A of groups 0 and 1
// [ 32: 64) PSHUFB indices of pair B of groups 0 and 1
// [ 64: 96) the 8 -accum values (na), as words
// [ 96:112) window offsets: A0, A1, B0, B1, as words
// [112:128) zero
//
// The indices put the first span of a pair right-aligned in bytes 0-7 and
// the second one in bytes 8-15 (0x80, i.e. zero, elsewhere), so that
// PSADBW sums each span and its last pixel is the top byte of its half.
func buildShrink1PRecords(rec []byte, cols []uint32, srcWidth int) {
start := 0
for b := 0; b < len(cols)/16; b++ {
r := rec[b*shrink1PRecordSize : (b+1)*shrink1PRecordSize]
clear(r)
for j := 0; j < 8; j += 2 {
grp, pair := j/4, (j%4)/2
w := min(start, srcWidth-16)
idx := r[32*pair+16*grp : 32*pair+16*grp+16]
for h := 0; h < 2; h++ {
n := int(cols[2*(8*b+j+h)])
for k := 0; k < 8; k++ {
idx[8*h+k] = 0x80
if k >= 8-n {
idx[8*h+k] = byte(start - w + k - (8 - n))
}
}
binary.LittleEndian.PutUint32(r[64+4*(j+h):], cols[2*(8*b+j+h)+1])
start += n
}
binary.LittleEndian.PutUint32(r[96+8*pair+4*grp:], uint32(w))
}
}
}
// buildShrink1SRecords fills one 192-byte record per 8 destination pixels
// of cols (spans of at most 16 pixels, a source row of srcWidth >= 16
// bytes), one 16-byte window of the source row per pixel:
//
// [ 0:128) PSHUFB indices of pixel j at 32*(j%4) + 16*(j/4)
// [128:160) the 8 -accum values (na), as words
// [160:192) the 8 window offsets, as words
//
// The indices put the span right-aligned in the window (0x80, i.e. zero,
// before it), so that PSADBW sums it and its last pixel is byte 15.
func buildShrink1SRecords(rec []byte, cols []uint32, srcWidth int) {
start := 0
for b := 0; b < len(cols)/16; b++ {
r := rec[b*shrink1SRecordSize : (b+1)*shrink1SRecordSize]
for j := 0; j < 8; j++ {
n := int(cols[2*(8*b+j)])
w := min(start, srcWidth-16)
idx := r[32*(j%4)+16*(j/4) : 32*(j%4)+16*(j/4)+16]
for k := range idx {
idx[k] = 0x80
if k >= 16-n {
idx[k] = byte(start - w + k - (16 - n))
}
}
binary.LittleEndian.PutUint32(r[128+4*j:], cols[2*(8*b+j)+1])
binary.LittleEndian.PutUint32(r[160+4*j:], uint32(w))
start += n
}
}
}
// initShrink4Z16Records builds the records of shrink4Z16VBMI for the whole
// row, one per 4 destination pixels (the last one possibly partial), and
// sets the kernel up; it reports whether it did, which it always does when
// the spans tile the row (as the column table's do).
func (r *Rescaler) initShrink4Z16Records(tab []uint32) bool {
a := &r.arch
n := (r.dstWidth + 3) / 4 * shrink4Z16RecordSize
if 4*len(tab) < n+z16TailSize {
panic("resample: short record table")
}
b := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(tab))), n+z16TailSize)
inside, tailAt := buildShrink4Z16Records(b[:n], r.cols[:2*r.dstWidth], r.srcWidth)
if 4*r.srcWidth-tailAt > z16TailMax {
return false
}
a.kind = kindShrink4Z16
a.records, a.tail = b[:n:n], b[n:]
a.inside, a.tailAt = inside, tailAt
a.asmOuts, a.asmSrc = r.dstWidth, r.srcWidth
a.z16 = z16Tabs()
return true
}
// buildShrink4Z16Records fills one 32-byte record per 4 destination pixels
// of cols (spans of 1 to 16 pixels of a 4-channel source row of srcWidth
// pixels). The 4 pixels make two pairs, A (pixels 0, 1) and B (2, 3); the
// spans of a pair are read as one 128-byte region from the start of its
// first span, and permuted by the entry of z16Tables for their lengths:
//
// [ 0: 8) the byte offsets of the regions of pairs A and B
// [ 8:16) the byte offsets of the entries of pairs A and B in z16Tables
// [16:32) the 4 na
//
// The pixels past the end of cols, in the last record, count as spans of
// one pixel starting at the end of the spans, with na 0.
//
// It returns the number of leading records whose 4 pixels exist and whose
// regions are inside the row, whose region offsets are offsets in the row,
// and the byte offset in the row of the first region of the other records
// (4*srcWidth if there are none), from which their region offsets count:
// the kernel reads their regions from a copy of the end of the row, so
// that it never reads past the row. (Masked loads would not fault there,
// but on Zen 5 a masked load whose left-out bytes reach into a page that
// is not mapped yet is slow every time: a 1024 -> 300 row ending at a page
// end took 2.8 times as long as other rows.) When the spans tile the row,
// that end is under 64 pixels long: the first record left has a region
// that starts in the last 32 pixels, or is a partial quad of at most 3
// spans.
func buildShrink4Z16Records(rec []byte, cols []uint32, srcWidth int) (inside, tailAt int) {
n := len(cols) / 2
quads := (n + 3) / 4
inside = quads
start := 0
for q := 0; q < quads; q++ {
r := rec[q*shrink4Z16RecordSize : (q+1)*shrink4Z16RecordSize]
var k [4]int
for j := range k {
x := 4*q + j
k[j] = 1
var na uint32
if x < n {
k[j], na = int(cols[2*x]), cols[2*x+1]
}
if j%2 == 0 {
binary.LittleEndian.PutUint32(r[2*j:], uint32(4*start))
if start+32 > srcWidth {
inside = min(inside, q)
}
}
binary.LittleEndian.PutUint32(r[16+4*j:], na)
if x < n {
start += k[j]
}
}
if 4*q+4 > n {
inside = min(inside, q)
}
binary.LittleEndian.PutUint32(r[8:], uint32(z16PairOffset(k[0], k[1])))
binary.LittleEndian.PutUint32(r[12:], uint32(z16PairOffset(k[2], k[3])))
}
tailAt = 4 * srcWidth
if inside < quads {
tailAt = int(binary.LittleEndian.Uint32(rec[inside*shrink4Z16RecordSize:]))
}
for q := inside; q < quads; q++ {
r := rec[q*shrink4Z16RecordSize:]
for p := 0; p < 2; p++ {
binary.LittleEndian.PutUint32(r[4*p:], binary.LittleEndian.Uint32(r[4*p:])-uint32(tailAt))
}
}
return inside, tailAt
}
// z16Tables are the lookup tables of shrink4Z16VBMI: an entry of
// z16PairSize bytes for each pair of span lengths k0, k1 (1 to 16), at
// z16PairOffset(k0, k1):
//
// [ 0:128) VPERMI2B indices taking pixels 0-7 (the first 64 bytes),
// then 8-15, of both spans from their 128-byte region: byte
// 8g+j (g = 4s+c) selects channel c of pixel j (or 8+j) of
// span s
// [128:192) VPERMI2B indices of the last pixels of the spans: 32-bit
// lane 4s+c, and 8+4s+c, holds in its low byte the position of
// channel c of the last pixel of span s in the region
// [192:208) the zeroing masks of the permutations of pixels 0-7 and of
// pixels 8-15: per span, 32 bits (the low half for the first
// span) keeping the first min(k, 8), then k-8, bytes of each
// of its four 8-byte channel groups
type z16Tables [16 * 16 * z16PairSize]byte
const z16PairSize = 256
// z16PairOffset returns the offset of the entry for spans of k0 and k1
// pixels.
func z16PairOffset(k0, k1 int) int { return ((k0-1)*16 + k1 - 1) * z16PairSize }
// z16Tabs builds the tables on first use (only machines with AVX512-VBMI
// need them).
var z16Tabs = sync.OnceValue(func() *z16Tables {
t := new(z16Tables)
group := func(k int) uint64 { return (uint64(1)<<max(min(k, 8), 0) - 1) * 0x01010101 }
for k0 := 1; k0 <= 16; k0++ {
for k1 := 1; k1 <= 16; k1++ {
e := t[z16PairOffset(k0, k1):][:z16PairSize]
for half := 0; half < 2; half++ {
for i := 0; i < 64; i++ {
g, j := i/8, i%8
s, c := g/4, g%4
e[64*half+i] = byte(4*(s*k0+8*half+j) + c)
}
}
for c := 0; c < 4; c++ {
for h := 0; h < 2; h++ {
e[128+4*(8*h+c)] = byte(4*(k0-1) + c)
e[128+4*(8*h+4+c)] = byte(4*(k0+k1-1) + c)
}
}
binary.LittleEndian.PutUint64(e[192:], group(k0)|group(k1)<<32)
binary.LittleEndian.PutUint64(e[200:], group(k0-8)|group(k1-8)<<32)
}
}
return t
})
// initExpand1Records builds the records of the 1-channel expansion kernels
// for every whole block of 8 destination pixels.
func (r *Rescaler) initExpand1Records(tab []uint32) {
a := &r.arch
blocks := r.dstWidth / 8
n := blocks * expand1RecordSize
if 4*len(tab) < n {
panic("resample: short record table")
}
rec := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(tab))), n)
buildExpand1Records(rec, r.cols[:16*blocks], r.srcWidth)
a.kind = kindExpand1
a.records = rec
a.asmOuts, a.asmSrc = 8*blocks, r.srcWidth
}
// buildExpand1Records fills one 96-byte record per 8 destination pixels of
// cols (a 1-channel expansion of a source row of srcWidth >= 16 bytes):
//
// [ 0:32) PSHUFB indices: pixel j's left source pixel, as word j
// [32:64) the 8 weights (w), as words
// [64:68) the offset of the 16-byte source window the indices refer to
// [68:96) zero
//
// The left pixels of 8 destination pixels span at most 8 source pixels
// (they advance by at most one per destination pixel when expanding), so
// they and their right neighbours fit one 16-byte window; the right
// neighbours' indices are the left ones plus one.
func buildExpand1Records(rec []byte, cols []uint32, srcWidth int) {
for b := 0; b < len(cols)/16; b++ {
r := rec[b*expand1RecordSize : (b+1)*expand1RecordSize]
clear(r)
w := min(int(cols[16*b]), srcWidth-16)
for j := 0; j < 8; j++ {
l := int(cols[2*(8*b+j)])
r[4*j], r[4*j+1], r[4*j+2], r[4*j+3] = byte(l-w), 0x80, 0x80, 0x80
binary.LittleEndian.PutUint32(r[32+4*j:], cols[2*(8*b+j)+1])
}
binary.LittleEndian.PutUint32(r[64:], uint32(w))
}
}
func (r *Rescaler) shrinkRow(src []byte, acc []uint32) {
switch r.arch.kind {
case kindShrink4, kindShrink4W8, kindShrink4W16, kindShrink4Z16:
r.shrinkRow4(src, acc)
case kindShrink1, kindShrink1P, kindShrink1S:
r.shrinkRow1(src, acc)
default:
r.shrinkRowRef(src, acc)
}
}
// asmRows returns src, frow and acc cut to the row lengths, and the
// pointer to pass for acc (nil when not accumulating). It panics if the
// kernel geometry does not fit the row.
func (r *Rescaler) asmRows(src []byte, acc []uint32) ([]byte, []uint32, []uint32, *uint32) {
ch, a := r.numChannels, &r.arch
src = src[:ch*r.srcWidth]
frow := r.frow[:ch*r.dstWidth]
if a.asmOuts < 1 || a.asmOuts > r.dstWidth || a.asmSrc > r.srcWidth {
panic("resample: bad assembly geometry")
}
var ap *uint32
if acc != nil {
acc = acc[:ch*r.dstWidth]
ap = &acc[0]
}
return src, frow, acc, ap
}
// shrinkRow4 runs the 4-channel kernel on the first asmOuts destination
// pixels and shrinkRow4Go on the rest.
func (r *Rescaler) shrinkRow4(src []byte, acc []uint32) {
n, s := r.arch.asmOuts, r.arch.asmSrc
xSub, fx := uint32(r.xSub), r.fxScale
// The last span the kernel handles starts at most at pixel
// srcWidth-4 (16-byte loads), srcWidth-8 (W8, 32-byte loads) or
// srcWidth-16 (W16, two 32-byte loads), see initArch; all other reads
// are inside the spans, src[:4*s]. The AVX-512 kernel reads whole
// regions inside src or inside a copy of its end (below).
src, frow, acc, ap := r.asmRows(src, acc)
cols := r.cols[:2*r.dstWidth]
switch r.arch.kind {
case kindShrink4W8, kindShrink4W16:
if n%2 != 0 {
panic("resample: odd pair count")
}
if r.arch.kind == kindShrink4W8 {
shrink4W8AVX2(&frow[0], ap, &src[0], &cols[0], n/2, xSub, fx)
} else {
shrink4W16AVX2(&frow[0], ap, &src[0], &cols[0], n/2, xSub, fx)
}
case kindShrink4Z16:
// The records hold whole regions inside src for the first a.inside
// records and, for the others, whole regions inside the copy of
// src[a.tailAt:] in a.tail, and entry offsets inside z16Tables
// (buildShrink4Z16Records, initShrink4Z16Records); the kernel masks
// the stores of the last record at n pixels.
a := &r.arch
if n != r.dstWidth || len(a.records) != (n+3)/4*shrink4Z16RecordSize || a.inside > n/4 ||
len(a.tail) != z16TailSize || len(src)-a.tailAt > z16TailMax || a.z16 == nil {
panic("resample: bad record table")
}
copy(a.tail, src[a.tailAt:])
shrink4Z16VBMI(&frow[0], ap, &src[0], &a.tail[0], &a.records[0], a.inside, n, xSub, fx, a.z16)
default:
shrinkRow4SSE41(&frow[0], ap, &src[0], &cols[0], n, xSub, fx)
}
if n == r.dstWidth {
return
}
// Resume at destination pixel n: its carry is the rounded part of the
// last source pixel of pixel n-1 that belongs to it.
var carry [4]uint32
na := cols[2*n-1]
for c := range carry {
carry[c] = multFix(uint32(src[4*(s-1)+c])*na, fx)
}
if acc != nil {
acc = acc[4*n:]
}
shrinkRow4Go(frow[4*n:], acc, src[4*s:], cols[2*n:], xSub, fx, carry)
}
// shrinkRow1 runs the 1-channel kernel on the first asmOuts destination
// pixels and shrinkRow1Go on the rest.
func (r *Rescaler) shrinkRow1(src []byte, acc []uint32) {
a := &r.arch
n, s := a.asmOuts, a.asmSrc
xSub, fx := uint32(r.xSub), r.fxScale
src, frow, acc, ap := r.asmRows(src, acc)
cols := r.cols[:2*r.dstWidth]
switch a.kind {
case kindShrink1:
// initArch only hands the kernel destination pixels whose span
// starts at least 16 bytes before the end of src; all other reads
// are inside the spans, src[:s].
shrinkRow1SSE41(&frow[0], ap, &src[0], &cols[0], n, xSub, fx)
default:
// The records only hold windows inside a source row of
// r.srcWidth >= 16 bytes (buildShrink1P/SRecords).
size := shrink1SRecordSize
if a.kind == kindShrink1P {
size = shrink1PRecordSize
}
if n%8 != 0 || len(a.records) != n/8*size || len(src) < 16 {
panic("resample: bad record table")
}
blocks := n / 8
switch {
case a.kind == kindShrink1P && a.level >= cpuinfo.AVX2:
shrink1PAVX2(&frow[0], ap, &src[0], &a.records[0], blocks, xSub, fx)
case a.kind == kindShrink1P:
shrink1PSSE41(&frow[0], ap, &src[0], &a.records[0], blocks, xSub, fx)
case a.level >= cpuinfo.AVX2:
shrink1SAVX2(&frow[0], ap, &src[0], &a.records[0], blocks, xSub, fx)
default:
shrink1SSSE41(&frow[0], ap, &src[0], &a.records[0], blocks, xSub, fx)
}
}
if n == r.dstWidth {
return
}
carry := multFix(uint32(src[s-1])*cols[2*n-1], fx)
if acc != nil {
acc = acc[n:]
}
shrinkRow1Go(frow[n:], acc, src[s:], cols[2*n:], xSub, fx, carry)
}
// shrinkRow4SSE41 imports destination pixels [0, n) of a 4-channel
// shrink: frow[0:4n] (and acc[0:4n] when acc is not nil) from src,
// starting at source pixel 0. It reads cols[0:2n] and, for each
// destination pixel, the 16 bytes at the start of its span: every span
// must start at least 4 pixels before the end of src, and hold at most
// maxShrink4Span pixels.
//
//go:noescape
func shrinkRow4SSE41(frow, acc *uint32, src *byte, cols *uint32, n int, xSub, fx uint32)
// shrink4W8AVX2 and shrink4W16AVX2 are shrinkRow4SSE41 for pairs of
// destination pixels [0, 2*pairs), reading 32 (W8) or 64 (W16) bytes from
// each span start: every span must start at least 8 (W8) or 16 (W16)
// pixels before the end of src and hold at most maxShrink4W8Span or
// maxShrink4W16Span pixels.
//
//go:noescape
func shrink4W8AVX2(frow, acc *uint32, src *byte, cols *uint32, pairs int, xSub, fx uint32)
//go:noescape
func shrink4W16AVX2(frow, acc *uint32, src *byte, cols *uint32, pairs int, xSub, fx uint32)
// shrink4Z16VBMI imports destination pixels [0, n) of a 4-channel shrink
// from the (n+3)/4 records at rec (see buildShrink4Z16Records): the first
// inside ones with their regions in the source row at src, the others with
// their regions in tail and their stores masked at n pixels. It reads 128
// bytes at each region offset. tab is z16Tabs().
//
//go:noescape
func shrink4Z16VBMI(frow, acc *uint32, src, tail *byte, rec *byte, inside, n int, xSub, fx uint32, tab *z16Tables)
// shrinkRow1SSE41 is shrinkRow4SSE41 for 1 channel and spans of any
// length: every span must start at least 16 bytes before the end of src.
//
//go:noescape
func shrinkRow1SSE41(frow, acc *uint32, src *byte, cols *uint32, n int, xSub, fx uint32)
// shrink1P{SSE41,AVX2} and shrink1S{SSE41,AVX2} import destination pixels
// [0, 8*blocks) of a 1-channel shrink from the records at rec (see
// buildShrink1PRecords and buildShrink1SRecords). They read the 16-byte
// windows of src the records name.
//
//go:noescape
func shrink1PSSE41(frow, acc *uint32, src *byte, rec *byte, blocks int, xSub, fx uint32)
//go:noescape
func shrink1PAVX2(frow, acc *uint32, src *byte, rec *byte, blocks int, xSub, fx uint32)
//go:noescape
func shrink1SSSE41(frow, acc *uint32, src *byte, rec *byte, blocks int, xSub, fx uint32)
//go:noescape
func shrink1SAVX2(frow, acc *uint32, src *byte, rec *byte, blocks int, xSub, fx uint32)
// expandRow4SSE41 imports a 4-channel horizontal expansion of n
// destination pixels: frow[0:4n] (and acc[0:4n] when acc is not nil). It
// reads cols[0:2n] and the 8 bytes (left and right pixel) at each left
// source pixel, which must be at most the last but one of src.
//
//go:noescape
func expandRow4SSE41(frow, acc *uint32, src *byte, cols *uint32, n int, xAdd uint32)
// expand1SSE41 and expand1AVX2 import destination pixels [0, 8*blocks) of
// a 1-channel horizontal expansion from the records at rec (see
// buildExpand1Records). They read the 16-byte windows of src the records
// name.
//
//go:noescape
func expand1SSE41(frow, acc *uint32, src *byte, rec *byte, blocks int, xAdd uint32)
//go:noescape
func expand1AVX2(frow, acc *uint32, src *byte, rec *byte, blocks int, xAdd uint32)
func (r *Rescaler) expandRow(src []byte, acc []uint32) {
a := &r.arch
switch a.kind {
case kindExpand4:
// initArch checked that the left pixels end before the last one,
// so every 8-byte load is inside src.
src, frow, _, ap := r.asmRows(src, acc)
cols := r.cols[:2*r.dstWidth]
expandRow4SSE41(&frow[0], ap, &src[0], &cols[0], r.dstWidth, uint32(r.xAdd))
case kindExpand1:
// The records only hold windows inside a source row of
// r.srcWidth >= 16 bytes (buildExpand1Records).
n := a.asmOuts
src, frow, acc, ap := r.asmRows(src, acc)
if n%8 != 0 || len(a.records) != n/8*expand1RecordSize || len(src) < 16 {
panic("resample: bad record table")
}
if a.level >= cpuinfo.AVX2 {
expand1AVX2(&frow[0], ap, &src[0], &a.records[0], n/8, uint32(r.xAdd))
} else {
expand1SSE41(&frow[0], ap, &src[0], &a.records[0], n/8, uint32(r.xAdd))
}
if n == r.dstWidth {
return
}
if acc != nil {
acc = acc[n:]
}
expandRow1Go(frow[n:], acc, src, r.cols[2*n:2*r.dstWidth], uint32(r.xAdd))
default:
r.expandRowRef(src, acc)
}
}
// The export kernels process n values, n > 0 and a multiple of 8; the
// wrappers below run the Go kernels on the rest of the row.
//go:noescape
func exportShrinkSSE41(dst *byte, irow, frow *uint32, n int, yscale, fxy uint32)
//go:noescape
func exportShrinkAVX2(dst *byte, irow, frow *uint32, n int, yscale, fxy uint32)
//go:noescape
func exportShrinkZeroSSE41(dst *byte, irow *uint32, n int, fxy uint32)
//go:noescape
func exportShrinkZeroAVX2(dst *byte, irow *uint32, n int, fxy uint32)
//go:noescape
func exportExpandSSE41(dst *byte, frow *uint32, n int, fy uint32)
//go:noescape
func exportExpandAVX2(dst *byte, frow *uint32, n int, fy uint32)
//go:noescape
func exportExpandMixSSE41(dst *byte, frow, irow *uint32, n int, a, b, fy uint32)
//go:noescape
func exportExpandMixAVX2(dst *byte, frow, irow *uint32, n int, a, b, fy uint32)
func exportExpand(dst []byte, frow []uint32, fy uint32) {
n := len(dst)
frow = frow[:n]
if m := n &^ 7; m > 0 && x86Level >= cpuinfo.SSE41 {
if x86Level >= cpuinfo.AVX2 {
exportExpandAVX2(&dst[0], &frow[0], m, fy)
} else {
exportExpandSSE41(&dst[0], &frow[0], m, fy)
}
dst, frow = dst[m:], frow[m:]
}
exportExpandGo(dst, frow, fy)
}
func exportExpandMix(dst []byte, frow, irow []uint32, a, b, fy uint32) {
n := len(dst)
frow, irow = frow[:n], irow[:n]
if m := n &^ 7; m > 0 && x86Level >= cpuinfo.SSE41 {
if x86Level >= cpuinfo.AVX2 {
exportExpandMixAVX2(&dst[0], &frow[0], &irow[0], m, a, b, fy)
} else {
exportExpandMixSSE41(&dst[0], &frow[0], &irow[0], m, a, b, fy)
}
dst, frow, irow = dst[m:], frow[m:], irow[m:]
}
exportExpandMixGo(dst, frow, irow, a, b, fy)
}
func exportShrink(dst []byte, irow, frow []uint32, yscale, fxy uint32) {
n := len(dst)
irow, frow = irow[:n], frow[:n]
if m := n &^ 7; m > 0 && x86Level >= cpuinfo.SSE41 {
if x86Level >= cpuinfo.AVX2 {
exportShrinkAVX2(&dst[0], &irow[0], &frow[0], m, yscale, fxy)
} else {
exportShrinkSSE41(&dst[0], &irow[0], &frow[0], m, yscale, fxy)
}
dst, irow, frow = dst[m:], irow[m:], frow[m:]
}
exportShrinkGo(dst, irow, frow, yscale, fxy)
}
func exportShrinkZero(dst []byte, irow []uint32, fxy uint32) {
n := len(dst)
irow = irow[:n]
if m := n &^ 7; m > 0 && x86Level >= cpuinfo.SSE41 {
if x86Level >= cpuinfo.AVX2 {
exportShrinkZeroAVX2(&dst[0], &irow[0], m, fxy)
} else {
exportShrinkZeroSSE41(&dst[0], &irow[0], m, fxy)
}
dst, irow = dst[m:], irow[m:]
}
exportShrinkZeroGo(dst, irow, fxy)
}
// premultiply{SSE41,AVX2} are PremultiplyRGBA on n bytes, n > 0 and a
// multiple of 16.
//
//go:noescape
func premultiplySSE41(row *byte, n int)
//go:noescape
func premultiplyAVX2(row *byte, n int)
func premultiplyRow(row []byte) {
if n := len(row) &^ 15; n > 0 && x86Level >= cpuinfo.SSE41 {
if x86Level >= cpuinfo.AVX2 {
premultiplyAVX2(&row[0], n)
} else {
premultiplySSE41(&row[0], n)
}
row = row[n:]
}
multRGBA(row, &premulScale)
}
// unpremultiplySSE41 is UnpremultiplyRGBA on n bytes, n > 0 and a
// multiple of 16, with the scales of table (unpremulScale). It serves the
// AVX2 level too: it only runs on output rows (under 2% of a scaled
// lossless decode on Zen 4), so a wider form would not show.
//
//go:noescape
func unpremultiplySSE41(row *byte, n int, table *[256]uint32)
func unpremultiplyRow(row []byte) {
if n := len(row) &^ 15; n > 0 && x86Level >= cpuinfo.SSE41 {
unpremultiplySSE41(&row[0], n, &unpremulScale)
row = row[n:]
}
multRGBA(row, &unpremulScale)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package status carries libwebp-compatible VP8 status codes through Go errors,
// so the public API can keep reporting e.g. "VP8_STATUS_BITSTREAM_ERROR".
package status
import (
"errors"
"github.com/kolesa-team/go-webp/v2/utils"
)
// Error is an error tagged with a libwebp VP8StatusCode.
type Error struct {
Code utils.VP8StatusCode
Msg string
}
func (e *Error) Error() string {
if e.Msg == "" {
return e.Code.String()
}
return e.Code.String() + ": " + e.Msg
}
// New returns an *Error with the given code and message.
func New(code utils.VP8StatusCode, msg string) error {
return &Error{Code: code, Msg: msg}
}
// Bitstream is shorthand for New(utils.Vp8StatusBitstreamError, msg).
func Bitstream(msg string) error { return New(utils.Vp8StatusBitstreamError, msg) }
// NotEnoughData is shorthand for New(utils.Vp8StatusNotEnoughData, msg).
func NotEnoughData(msg string) error { return New(utils.Vp8StatusNotEnoughData, msg) }
// Unsupported is shorthand for New(utils.Vp8StatusUnsupportedFeature, msg).
func Unsupported(msg string) error { return New(utils.Vp8StatusUnsupportedFeature, msg) }
// InvalidParam is shorthand for New(utils.Vp8StatusInvalidParam, msg).
func InvalidParam(msg string) error { return New(utils.Vp8StatusInvalidParam, msg) }
// CodeOf returns the status code of err: Vp8StatusOk for nil, the tagged code
// for *Error (also when wrapped), and Vp8StatusBitstreamError otherwise.
func CodeOf(err error) utils.VP8StatusCode {
if err == nil {
return utils.Vp8StatusOk
}
var e *Error
if errors.As(err, &e) {
return e.Code
}
return utils.Vp8StatusBitstreamError
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
// Algorithm adapted from libwebp (BSD-3-Clause): utils/bit_reader_utils.[ch].
import (
"encoding/binary"
"math/bits"
)
// bitReader is the VP8 boolean entropy decoder. It mirrors libwebp's
// VP8BitReader: value holds up to 56+8 pending bits, rng stores range-1 in
// [127, 255], and nbits counts the bits buffered beyond the 8 bits that are
// always needed for the next comparison.
type bitReader struct {
value uint64
rng uint32
nbits int
buf []byte
pos int
eof bool
}
// init prepares br to decode data.
func (br *bitReader) init(data []byte) {
br.rng = 255 - 1
br.value = 0
br.nbits = -8 // to load the very first 8 bits
br.eof = false
br.buf = data
br.pos = 0
br.loadNewBytes()
}
// loadNewBytes refills the value buffer with 56 bits when possible.
func (br *bitReader) loadNewBytes() {
if br.pos+8 <= len(br.buf) {
v := binary.BigEndian.Uint64(br.buf[br.pos:]) >> 8
br.pos += 7
br.value = v | br.value<<56
br.nbits += 56
return
}
br.loadFinalBytes()
}
// loadFinalBytes reads the trailing bytes one at a time. Once the data is
// exhausted it feeds 8 zero bits once and flags eof.
func (br *bitReader) loadFinalBytes() {
if br.pos < len(br.buf) {
br.nbits += 8
br.value = uint64(br.buf[br.pos]) | br.value<<8
br.pos++
} else if !br.eof {
br.value <<= 8
br.nbits += 8
br.eof = true
} else {
br.nbits = 0 // avoid undefined shifts
}
}
// decodeBit decodes one boolean whose probability of being 0 is prob/256
// (libwebp's VP8GetBit) on register copies of the reader state. Hot loops
// keep value/rng/nbits in locals and call it (it is inlined) to avoid a
// memory round trip on the bit decoding dependency chain. nbits must be >= 0
// (refill first).
//
// The new range r (not minus one) is split+1 or rng-split, both in [1, 255]
// because rng stays in [127, 255] (255 only after decodeSigned). It is
// renormalized into [128, 255] by a left shift of 7-floor(log2(r)) =
// clz32(r)-24, which is one CLZ instruction instead of a table lookup on the
// dependency chain (libwebp computes it the same way, with BitsLog2Floor).
func decodeBit(value uint64, rng uint32, nbits int, prob uint8) (uint64, uint32, int, bool) {
split := (rng * uint32(prob)) >> 8
pos := uint(nbits) & 63
// Unsigned "value > split" as in libwebp's VP8GetBit: a 32-bit signed
// difference would disagree on corrupt streams where value-split >= 2^31.
bit := uint32(value>>pos) > split
r := split + 1
if bit {
r = rng - split
value -= uint64(split+1) << pos
}
// r is in [1, 255], so the shift is in [0, 7]; the mask only tells the
// compiler that it is a valid 32-bit shift amount.
sh := uint(bits.LeadingZeros32(r)-24) & 31
return value, (r << sh) - 1, nbits - int(sh), bit
}
// decodeSigned returns v or -v using one bit of probability 1/2 (libwebp's
// VP8GetSigned) on register copies of the reader state. nbits must be >= 0.
// Unlike VP8GetBit, VP8GetSigned compares with a signed 32-bit difference,
// which is kept here for bit-exactness on corrupt streams. The range does
// not need renormalizing: it loses exactly one bit.
func decodeSigned(value uint64, rng uint32, nbits int, v int) (uint64, uint32, int, int) {
pos := uint(nbits) & 63
split := rng >> 1
mask := int32(split-uint32(value>>pos)) >> 31 // -1 if value > split
rng = (rng + uint32(mask)) | 1
value -= uint64((split+1)&uint32(mask)) << pos
return value, rng, nbits - 1, (v ^ int(mask)) - int(mask)
}
// refill stores the register state back, loads new bytes and returns the
// updated state (slow path of the register-based decoding).
func (br *bitReader) refill(value uint64, nbits int) (uint64, int) {
br.value, br.nbits = value, nbits
br.loadNewBytes()
return br.value, br.nbits
}
// getBit decodes one boolean whose probability of being 0 is prob/256.
func (br *bitReader) getBit(prob uint8) int {
if br.nbits < 0 {
br.loadNewBytes()
}
var bit bool
br.value, br.rng, br.nbits, bit = decodeBit(br.value, br.rng, br.nbits, prob)
return b2i(bit)
}
// getSigned returns v or -v using one bit of probability 1/2 (libwebp's
// VP8GetSigned).
func (br *bitReader) getSigned(v int) int {
if br.nbits < 0 {
br.loadNewBytes()
}
br.value, br.rng, br.nbits, v = decodeSigned(br.value, br.rng, br.nbits, v)
return v
}
// getValue reads an n-bit unsigned literal, most significant bit first.
func (br *bitReader) getValue(n int) int {
v := 0
for ; n > 0; n-- {
v |= br.getBit(0x80) << uint(n-1)
}
return v
}
// getSignedValue reads an n-bit magnitude followed by a sign bit.
func (br *bitReader) getSignedValue(n int) int {
v := br.getValue(n)
if br.getBit(0x80) != 0 {
return -v
}
return v
}
// get reads a single flag bit of probability 1/2.
func (br *bitReader) get() bool { return br.getBit(0x80) != 0 }
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package vp8 implements a pure Go VP8 (lossy WebP) key frame decoder that is
// bit-exact with libwebp 1.6 for RGBA output, including fancy upsampling,
// point sampling, filter bypass and chroma dithering.
//
// The decoder works one macroblock row at a time with a small rolling cache
// (16 luma rows plus the rows the loop filter still has to touch), so its
// memory use is O(width) and independent of the image height.
package vp8
// Algorithm adapted from libwebp (BSD-3-Clause): dec/vp8_dec.c,
// dec/tree_dec.c, dec/frame_dec.c and dec/io_dec.c.
import (
"image"
"sync"
"github.com/kolesa-team/go-webp/v2/internal/pipeline"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// Options controls decoding. The zero value (or a nil *Options) selects
// libwebp's defaults.
type Options struct {
// BypassFiltering skips the in-loop deblocking filter (dwebp -nofilter).
BypassFiltering bool
// NoFancyUpsampling uses point-sampled chroma instead of the bilinear
// "fancy" upsampler (dwebp -nofancy).
NoFancyUpsampling bool
// DitheringStrength in [0, 100] adds libwebp's deterministic chroma
// dithering on macroblocks quantized hard enough (dwebp -dither).
DitheringStrength int
// UseThreads parses the bitstream in the calling goroutine while a
// helper goroutine reconstructs, filters and converts the previously
// parsed batch of macroblock rows (libwebp's mt_method 2); when that
// helper is the slower stage, the conversion moves to a second helper
// (threads.go). The helpers come from the process-wide budget of
// internal/workers; when none is free, or the picture is too small to
// gain from it (less than 1024 macroblocks, about 512x512 pixels), the
// frame is decoded on the calling goroutine. Output is identical
// either way.
UseThreads bool
// Alpha, if not nil and no alpha plane is passed to Decode or
// DecodeRegion, is called before each batch of output rows is emitted
// to obtain the alpha samples of frame rows [rowStart, rowEnd) (rows
// counted from the top of the frame). It returns a window of the alpha
// plane (stride width) and the frame row it starts at: frame row y is
// plane[(y-base)*width:][:width], base <= rowStart (a whole plane has
// base 0). The window is only read until the next call, and rowStart
// never decreases, so the caller may keep just the rows still needed
// instead of the whole plane. A nil plane means opaque. rowEnd is
// also the number of frame rows whose alpha has to be decoded: like
// libwebp, which decodes the ALPH chunk while emitting rows
// (VP8DecompressAlphaRows), this lets the caller decode alpha only as
// far as the VP8 data goes. An error it returns aborts decoding.
Alpha func(rowStart, rowEnd int) (plane []byte, base int, err error)
}
// kFilterExtraRows is the number of rows the loop filter may still modify
// below a decoded macroblock row, per filter type (none, simple, complex).
var kFilterExtraRows = [3]int{0, 2, 8}
type quantMatrix struct {
y1, y2, uv [2]int32
uvQuant int // for dithering strength evaluation
dither int // dithering amplitude (0 = off)
}
// fInfo holds the loop filter parameters of one macroblock.
type fInfo struct {
limit, ilevel, inner, hevThresh uint8
}
// topSamples are the unfiltered bottom samples of the macroblock above.
type topSamples struct {
y [16]uint8
u, v [8]uint8
}
// mbModes is the part of a parsed macroblock that comes from the first
// partition (parseIntraMode): the token parser needs it, and with UseThreads
// it may be parsed ahead on another goroutine (threads.go).
type mbModes struct {
imodes [16]uint8
segment uint8
uvmode uint8
isI4x4 bool
skip bool
}
// mbBlock is the parsed data of one macroblock.
type mbBlock struct {
coeffs [384]int16
mbModes
nonZeroY uint32
nonZeroUV uint32
hasCoeffs bool // at least one non-zero coefficient (inner edge filtering)
dither uint8
}
// decoder holds the whole decoding state. Instances are pooled; every field
// is (re)initialized per frame.
type decoder struct {
br bitReader
parts [maxNumPartitions]bitReader
numPartsMinusOne int
width, height, mbW, mbH int
// segment header
useSegment, updateMap, absoluteDelta bool
quantizer, filterStrength [numMBSegments]int
segProba [3]uint8
// filter header
simple bool
level, sharpness int
useLFDelta bool
refLFDelta [numRefLFDeltas]int
modeLFDelta [numModeLFDeltas]int
filterType int
fstrengths [numMBSegments][2]fInfo
proba [numTypes][16 + 1][numCtx][numProbas]uint8
useSkipProba bool
skipP uint8
dqm [numMBSegments]quantMatrix
dither bool
rng vp8Random
ditherRow []uint8 // per-macroblock dither amplitude of the row
intraT []uint8 // 4 sub-block modes per macroblock column
intraL [4]uint8
nzT []uint8 // top non-zero context per column
nzDCT []uint8
nzL, nzDCL uint8
yuvT []topSamples
blk mbBlock
mt *mtState // UseThreads pipeline (threads.go), allocated on first use
yuvB [yuvSize]byte
cacheY, cacheU, cacheV []byte
cacheYStride int
cacheUVStride int
cacheYOff, cacheUVOff int
extraRows int
// output
sink pipeline.Sink
ysink YUVSink // non-nil for DecodeYUV
alpha []byte
alphaBase int // the frame row alpha starts at
alphaFn func(rowStart, rowEnd int) ([]byte, int, error)
fancy bool
tmpY, tmpU, tmpV []byte
uvT, uvB []uint32 // upsampled chroma scratch rows
rowsOut int // number of output rows committed
// Output region (libwebp's crop_*), the macroblock area that must be
// filtered/dithered for it (tl/br, as in VP8EnterCritical) and the
// output width.
cropLeft, cropTop, cropRight, cropBottom int
tlMbX, tlMbY, brMbX, brMbY int
outW int
}
var decoderPool = sync.Pool{New: func() any { return new(decoder) }}
// grow returns s resized to n bytes, reusing its storage when possible.
func grow(s []byte, n int) []byte {
if cap(s) < n {
return make([]byte, n)
}
return s[:n]
}
// Decode decodes the VP8 chunk payload and writes non-premultiplied RGBA rows
// into sink, top to bottom. alpha is nil (opaque, A=255) or a width*height
// plane (stride=width) whose values become the A channel.
func Decode(data []byte, alpha []byte, opts *Options, sink pipeline.Sink) error {
return decode(data, alpha, opts, nil, sink)
}
// DecodeRegion is like Decode but only produces the crop rectangle, with
// libwebp's cropping semantics (WebPDecoderOptions.use_cropping):
// crop.Min is rounded down to even coordinates (keeping crop.Dx() and
// crop.Dy()), the cropped Y'CbCr area is converted as if it were the whole
// picture (fancy upsampling mirrors chroma at the crop borders), and sink
// receives crop.Dy() rows of crop.Dx() pixels numbered from 0. Decoding stops
// below the crop rectangle. alpha, if not nil, is still the full
// width*height plane. The rectangle must lie inside the frame.
func DecodeRegion(data []byte, alpha []byte, opts *Options, crop image.Rectangle, sink pipeline.Sink) error {
return decode(data, alpha, opts, &crop, sink)
}
// YUVSink receives decoded Y'CbCr rows instead of RGBA (libwebp's VP8Io
// "put" callback), e.g. to implement libwebp-exact rescaling, which works on
// the Y, U and V planes. Rows arrive top to bottom in batches.
type YUVSink interface {
// PutYUV receives luma rows [y, y+n) of the output region, n > 0. Luma
// row j (0 <= j < n) is ys[j*yStride:][:width]. The batch carries
// (n+1)/2 chroma rows of (width+1)/2 samples: row k is
// us[k*uvStride:] and vs[k*uvStride:]; luma row j uses chroma row j/2
// (y is always even). The slices are only valid during the call.
PutYUV(y, n int, ys []byte, yStride int, us, vs []byte, uvStride int) error
// NeedRows reports how many rows (from the top of the output region)
// are still needed in total; decoding may stop once they are produced.
NeedRows() int
}
// DecodeYUV decodes the VP8 chunk payload like DecodeRegion (crop may be nil
// for the whole frame) but delivers the filtered and dithered Y'CbCr rows to
// sink. NoFancyUpsampling has no effect.
func DecodeYUV(data []byte, opts *Options, crop *image.Rectangle, sink YUVSink) error {
if sink == nil {
return status.InvalidParam("nil sink")
}
return decode(data, nil, opts, crop, yuvAdapter{sink})
}
// yuvAdapter lets a YUVSink travel through the RGBA code path; finishRow
// recognizes it and hands it the Y'CbCr rows.
type yuvAdapter struct{ YUVSink }
func (yuvAdapter) Buffer(y, n int) []byte { return nil }
func (yuvAdapter) Stride() int { return 0 }
func (yuvAdapter) Commit(y, n int) error { return nil }
func decode(data, alpha []byte, opts *Options, crop *image.Rectangle, sink pipeline.Sink) error {
if sink == nil {
return status.InvalidParam("nil sink")
}
var o Options
if opts != nil {
o = *opts
}
d := decoderPool.Get().(*decoder)
err := d.decode(data, alpha, &o, crop, sink)
d.sink = nil
d.ysink = nil
d.alpha = nil
d.alphaFn = nil
d.br.buf = nil
for i := range d.parts {
d.parts[i].buf = nil
}
decoderPool.Put(d)
return err
}
func (d *decoder) decode(data, alpha []byte, o *Options, crop *image.Rectangle, sink pipeline.Sink) error {
if err := d.parseHeaders(data); err != nil {
return err
}
if alpha != nil && len(alpha) < d.width*d.height {
return status.InvalidParam("alpha plane too small")
}
d.alphaFn = nil
if alpha == nil {
d.alphaFn = o.Alpha
}
d.cropLeft, d.cropTop, d.cropRight, d.cropBottom = 0, 0, d.width, d.height
if crop != nil {
// WebPIoInitFromOptions + WebPCheckCropDimensions.
x, y := crop.Min.X&^1, crop.Min.Y&^1
w, h := crop.Dx(), crop.Dy()
if x < 0 || y < 0 || w <= 0 || h <= 0 || x >= d.width || w > d.width-x || y >= d.height || h > d.height-y {
return status.InvalidParam("crop rectangle outside the frame")
}
d.cropLeft, d.cropTop, d.cropRight, d.cropBottom = x, y, x+w, y+h
}
d.outW = d.cropRight - d.cropLeft
if o.BypassFiltering {
d.filterType = 0
}
d.enterCritical()
d.precomputeFilterStrengths()
d.initDithering(o.DitheringStrength)
d.sink = sink
d.ysink = nil
if ya, ok := sink.(yuvAdapter); ok {
d.ysink = ya.YUVSink
}
d.alpha, d.alphaBase = alpha, 0
d.fancy = !o.NoFancyUpsampling
d.rowsOut = 0
d.initFrame()
if o.UseThreads && d.brMbY > 1 {
return d.decodeFrameThreaded()
}
return d.decodeFrame()
}
// initFrame sizes and resets the per-frame state.
func (d *decoder) initFrame() {
mbW := d.mbW
d.intraT = grow(d.intraT, 4*mbW)
clear(d.intraT) // B_DC_PRED
d.nzT = grow(d.nzT, mbW)
clear(d.nzT)
d.nzDCT = grow(d.nzDCT, mbW)
clear(d.nzDCT)
if cap(d.yuvT) < mbW {
d.yuvT = make([]topSamples, mbW)
}
d.yuvT = d.yuvT[:mbW]
if d.dither {
d.ditherRow = grow(d.ditherRow, mbW)
}
d.extraRows = kFilterExtraRows[d.filterType]
d.cacheYStride = 16 * mbW
d.cacheUVStride = 8 * mbW
d.cacheYOff = d.extraRows * d.cacheYStride
d.cacheUVOff = (d.extraRows / 2) * d.cacheUVStride
d.cacheY = grow(d.cacheY, (d.extraRows+16)*d.cacheYStride)
d.cacheU = grow(d.cacheU, (d.extraRows/2+8)*d.cacheUVStride)
d.cacheV = grow(d.cacheV, (d.extraRows/2+8)*d.cacheUVStride)
if d.fancy {
w := d.outW
d.tmpY = grow(d.tmpY, w)
d.tmpU = grow(d.tmpU, (w+1)/2)
d.tmpV = grow(d.tmpV, (w+1)/2)
if cap(d.uvT) < w {
d.uvT = make([]uint32, w)
d.uvB = make([]uint32, w)
}
d.uvT, d.uvB = d.uvT[:w], d.uvB[:w]
}
}
// enterCritical computes the macroblock area that needs filtering and the
// last macroblock row to decode for the output region (VP8EnterCritical).
func (d *decoder) enterCritical() {
extra := kFilterExtraRows[d.filterType]
if d.filterType == 2 {
// The complex filter must preserve the dependency chain.
d.tlMbX, d.tlMbY = 0, 0
} else {
d.tlMbX = max((d.cropLeft-extra)>>4, 0)
d.tlMbY = max((d.cropTop-extra)>>4, 0)
}
d.brMbY = min((d.cropBottom+15+extra)>>4, d.mbH)
d.brMbX = min((d.cropRight+15+extra)>>4, d.mbW)
}
// decodeFrame runs the single-goroutine row loop.
func (d *decoder) decodeFrame() error {
for mbY := 0; mbY < d.brMbY; mbY++ {
if d.rowsOut >= d.sink.NeedRows() {
return nil
}
if err := d.decodeRow(mbY); err != nil {
return err
}
if err := d.finishRow(mbY); err != nil {
return err
}
}
return nil
}
// finishRow emits the rows of the row cache that are final after decoding
// macroblock row mbY, then rotates the cache (libwebp's FinishRow).
func (d *decoder) finishRow(mbY int) error {
if err := d.emitRow(mbY, d.cacheY, d.cacheU, d.cacheV); err != nil {
return err
}
if extra := d.extraRows; mbY < d.brMbY-1 && extra > 0 {
// Keep the rows the next row's filter still modifies.
ysz := extra * d.cacheYStride
uvsz := (extra / 2) * d.cacheUVStride
copy(d.cacheY[:ysz], d.cacheY[16*d.cacheYStride:])
copy(d.cacheU[:uvsz], d.cacheU[8*d.cacheUVStride:])
copy(d.cacheV[:uvsz], d.cacheV[8*d.cacheUVStride:])
}
return nil
}
// decodeRow parses, reconstructs and filters one macroblock row into the
// cache.
func (d *decoder) decodeRow(mbY int) error {
tokenBR := &d.parts[mbY&d.numPartsMinusOne]
d.startParseRow()
d.initRowEdges(mbY)
blk := &d.blk
for mbX := 0; mbX < d.mbW; mbX++ {
if err := d.parseMB(mbX, blk, tokenBR); err != nil {
return err
}
d.reconMB(mbX, mbY, blk)
}
return d.endRow()
}
// startParseRow resets the left contexts at the start of a macroblock row.
func (d *decoder) startParseRow() {
d.nzL, d.nzDCL = 0, 0
d.intraL = [4]uint8{}
}
// parseMB parses the modes and coefficients of the macroblock at mbX.
func (d *decoder) parseMB(mbX int, blk *mbBlock, tokenBR *bitReader) error {
d.parseIntraMode(mbX, &blk.mbModes)
return d.parseTokens(mbX, blk, tokenBR)
}
// parseTokens parses the coefficients of the macroblock at mbX, whose modes
// are already in blk.
func (d *decoder) parseTokens(mbX int, blk *mbBlock, tokenBR *bitReader) error {
skip := d.useSkipProba && blk.skip
if !skip {
skip = d.parseResiduals(mbX, blk, tokenBR)
} else {
d.nzL, d.nzT[mbX] = 0, 0
if !blk.isI4x4 {
d.nzDCL, d.nzDCT[mbX] = 0, 0
}
blk.nonZeroY = 0
blk.nonZeroUV = 0
blk.dither = 0
}
blk.hasCoeffs = !skip
if tokenBR.eof {
return status.NotEnoughData("premature end-of-file encountered")
}
return nil
}
// reconMB reconstructs and filters a parsed macroblock into the cache.
func (d *decoder) reconMB(mbX, mbY int, blk *mbBlock) {
d.reconstructMB(mbX, mbY, blk)
if d.filterType > 0 && mbX >= d.tlMbX && mbX < d.brMbX && mbY >= d.tlMbY {
f := d.fstrengths[blk.segment][b2i(blk.isI4x4)]
if blk.hasCoeffs {
f.inner = 1
}
d.filterMB(mbX, mbY, f)
}
if d.dither {
d.ditherRow[mbX] = blk.dither
}
}
// endRow checks the first partition and dithers the finished row.
func (d *decoder) endRow() error {
if d.br.eof {
return status.NotEnoughData("premature end-of-partition0 encountered")
}
if d.dither {
d.ditherCurrentRow()
}
return nil
}
func b2i(b bool) int {
if b {
return 1
}
return 0
}
func (d *decoder) ditherCurrentRow() {
uvs := d.cacheUVStride
for mbX := d.tlMbX; mbX < d.brMbX; mbX++ {
if amp := d.ditherRow[mbX]; amp >= minDitherAmp {
o := d.cacheUVOff + mbX*8
d.rng.dither8x8(d.cacheU, o, uvs, int(amp))
d.rng.dither8x8(d.cacheV, o, uvs, int(amp))
}
}
}
// emitRow emits the rows that are final after decoding macroblock row mbY.
// cy, cu and cv hold the samples from frame row 16*mbY-extraRows on (with
// the cache strides): the extraRows rows above the macroblock row, which
// the row's filter finished, then the macroblock row itself.
func (d *decoder) emitRow(mbY int, cy, cu, cv []byte) error {
extra := d.extraRows
isFirst := mbY == 0
isLast := mbY >= d.brMbY-1
yStart := 16 * mbY
yEnd := 16 * (mbY + 1)
ys, us, vs := cy, cu, cv
if !isFirst {
yStart -= extra
} else {
ys = cy[extra*d.cacheYStride:]
us = cu[(extra/2)*d.cacheUVStride:]
vs = cv[(extra/2)*d.cacheUVStride:]
}
if !isLast {
yEnd -= extra
}
if yEnd > d.cropBottom {
yEnd = d.cropBottom
}
if yStart < d.cropTop {
delta := d.cropTop - yStart
yStart = d.cropTop
if yStart < yEnd {
ys = ys[delta*d.cacheYStride:]
us = us[(delta>>1)*d.cacheUVStride:]
vs = vs[(delta>>1)*d.cacheUVStride:]
}
}
if yStart < yEnd {
ys, us, vs = ys[d.cropLeft:], us[d.cropLeft>>1:], vs[d.cropLeft>>1:]
y0, y1 := yStart-d.cropTop, yEnd-d.cropTop
var err error
if d.ysink != nil {
err = d.ysink.PutYUV(y0, y1-y0, ys, d.cacheYStride, us, vs, d.cacheUVStride)
d.rowsOut = y1
} else if d.fancy {
err = d.emitFancy(ys, us, vs, y0, y1, yEnd >= d.cropBottom)
} else {
err = d.emitSampled(ys, us, vs, y0, y1)
}
if err != nil {
return err
}
}
return nil
}
// loadAlpha obtains the deferred alpha samples (Options.Alpha) of output
// rows [yStart, yEnd).
func (d *decoder) loadAlpha(yStart, yEnd int) error {
if d.alphaFn == nil {
return nil
}
rowStart, rowEnd := d.cropTop+yStart, min(d.cropTop+yEnd, d.height)
a, base, err := d.alphaFn(rowStart, rowEnd)
if err != nil {
return err
}
if a == nil {
d.alphaFn = nil // opaque
} else if base < 0 || base > rowStart || len(a) < (rowEnd-base)*d.width {
return status.InvalidParam("alpha plane too small")
}
d.alpha, d.alphaBase = a, base
return nil
}
// alphaRow returns the alpha samples of output row y, or nil when the
// output is opaque.
func (d *decoder) alphaRow(y int) []byte {
if d.alpha == nil {
return nil
}
o := (d.cropTop+y-d.alphaBase)*d.width + d.cropLeft
return d.alpha[o : o+d.outW]
}
// emitSampled converts rows [yStart, yEnd) with point-sampled chroma.
func (d *decoder) emitSampled(ys, us, vs []byte, yStart, yEnd int) error {
n := yEnd - yStart
if err := d.loadAlpha(yStart, yEnd); err != nil {
return err
}
dst := d.sink.Buffer(yStart, n)
ds := d.sink.Stride()
w := d.outW
for j := 0; j < n; j++ {
uo := (j >> 1) * d.cacheUVStride
sampleRow(ys[j*d.cacheYStride:], us[uo:], vs[uo:], d.alphaRow(yStart+j), dst[j*ds:], w)
}
d.rowsOut = yEnd
return d.sink.Commit(yStart, n)
}
// emitFancy converts output rows [yStart, yEnd) with libwebp's fancy
// upsampler (EmitFancyRGB). The last luma row of a non-final batch is kept
// back until the next chroma row is available.
func (d *decoder) emitFancy(ys, us, vs []byte, yStart, yEnd int, isLast bool) error {
w := d.outW
uvW := (w + 1) >> 1
yS, uvS := d.cacheYStride, d.cacheUVStride
outStart := yStart
if yStart > 0 {
outStart--
}
outEnd := yEnd
if !isLast {
outEnd--
}
n := outEnd - outStart
if n <= 0 {
return nil
}
if err := d.loadAlpha(outStart, yEnd); err != nil {
return err
}
dst := d.sink.Buffer(outStart, n)
ds := d.sink.Stride()
row := func(y int) []byte { return dst[(y-outStart)*ds:] }
y := yStart
cy, cu := 0, 0
if y == 0 {
// First line is special cased: mirror the chroma at the boundary.
upsamplePair(ys, nil, us, vs, us, vs, row(0), nil, d.alphaRow(0), nil, d.uvT, d.uvB, w)
} else {
// Finish the left-over line from the previous call.
upsamplePair(d.tmpY, ys, d.tmpU, d.tmpV, us, vs, row(y-1), row(y), d.alphaRow(y-1), d.alphaRow(y), d.uvT, d.uvB, w)
}
for ; y+2 < yEnd; y += 2 {
tu, tv := us[cu:], vs[cu:]
cu += uvS
cy += 2 * yS
upsamplePair(ys[cy-yS:], ys[cy:], tu, tv, us[cu:], vs[cu:], row(y+1), row(y+2), d.alphaRow(y+1), d.alphaRow(y+2), d.uvT, d.uvB, w)
}
cy += yS
if !isLast {
copy(d.tmpY, ys[cy:cy+w])
copy(d.tmpU, us[cu:cu+uvW])
copy(d.tmpV, vs[cu:cu+uvW])
} else if yEnd&1 == 0 {
// The very last row of an even-height picture.
upsamplePair(ys[cy:], nil, us[cu:], vs[cu:], us[cu:], vs[cu:], row(yEnd-1), nil, d.alphaRow(yEnd-1), nil, d.uvT, d.uvB, w)
}
d.rowsOut = outEnd
return d.sink.Commit(outStart, n)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
import "encoding/binary"
// Algorithm adapted from libwebp (BSD-3-Clause): dsp/dec.c (inverse
// transforms, intra predictors and in-loop filters).
// bps is the stride of the reconstruction work buffer.
const bps = 32
// Offsets of the Y, U and V blocks inside the work buffer. One row and a
// few columns of context are kept above and to the left of each block.
const (
yOff = bps*1 + 8
uOff = yOff + bps*16 + bps
vOff = uOff + 16
yuvSize = bps*17 + bps*9
)
// Intra prediction modes, in libwebp order.
const (
bDCPred = iota
bTMPred
bVEPred
bHEPred
bRDPred
bVRPred
bLDPred
bVLPred
bHDPred
bHUPred
// Special DC modes used at frame edges (16x16 and chroma only).
bDCPredNoTop = 4
bDCPredNoLeft = 5
bDCPredNoTopLeft = 6
)
func clip8(v int) uint8 {
if uint(v) <= 255 {
return uint8(v)
}
if v < 0 {
return 0
}
return 255
}
// --- inverse transforms ---------------------------------------------------
func mul1(a int) int { return ((a * 20091) >> 16) + a }
func mul2(a int) int { return (a * 35468) >> 16 }
// transformOne adds the inverse DCT of in to the 4x4 block at b[o:].
func transformOne(in *[16]int16, b []byte, o int) {
var tmp [16]int
for i := 0; i < 4; i++ { // vertical pass
i0, i4, i8, i12 := int(in[i]), int(in[4+i]), int(in[8+i]), int(in[12+i])
a := i0 + i8
bb := i0 - i8
c := mul2(i4) - mul1(i12)
d := mul1(i4) + mul2(i12)
tmp[4*i+0] = a + d
tmp[4*i+1] = bb + c
tmp[4*i+2] = bb - c
tmp[4*i+3] = a - d
}
dst := (*[3*bps + 4]byte)(b[o:])
for i := 0; i < 4; i++ { // horizontal pass
dc := tmp[i] + 4
t4, t8, t12 := tmp[4+i], tmp[8+i], tmp[12+i]
a := dc + t8
bb := dc - t8
c := mul2(t4) - mul1(t12)
d := mul1(t4) + mul2(t12)
r := i * bps
dst[r+0] = clip8(int(dst[r+0]) + ((a + d) >> 3))
dst[r+1] = clip8(int(dst[r+1]) + ((bb + c) >> 3))
dst[r+2] = clip8(int(dst[r+2]) + ((bb - c) >> 3))
dst[r+3] = clip8(int(dst[r+3]) + ((a - d) >> 3))
}
}
// transformAC3 handles blocks whose only non-zero coefficients are in[0],
// in[1] and in[4].
func transformAC3(in *[16]int16, b []byte, o int) {
a := int(in[0]) + 4
c4 := mul2(int(in[4]))
d4 := mul1(int(in[4]))
c1 := mul2(int(in[1]))
d1 := mul1(int(in[1]))
dst := (*[3*bps + 4]byte)(b[o:])
store2 := func(r, dc int) {
dst[r+0] = clip8(int(dst[r+0]) + ((dc + d1) >> 3))
dst[r+1] = clip8(int(dst[r+1]) + ((dc + c1) >> 3))
dst[r+2] = clip8(int(dst[r+2]) + ((dc - c1) >> 3))
dst[r+3] = clip8(int(dst[r+3]) + ((dc - d1) >> 3))
}
store2(0, a+d4)
store2(bps, a+c4)
store2(2*bps, a-c4)
store2(3*bps, a-d4)
}
// transformDC handles blocks with only a DC coefficient.
func transformDC(in *[16]int16, b []byte, o int) {
dc := (int(in[0]) + 4) >> 3
dst := (*[3*bps + 4]byte)(b[o:])
for r := 0; r < 4*bps; r += bps {
dst[r+0] = clip8(int(dst[r+0]) + dc)
dst[r+1] = clip8(int(dst[r+1]) + dc)
dst[r+2] = clip8(int(dst[r+2]) + dc)
dst[r+3] = clip8(int(dst[r+3]) + dc)
}
}
// transformWHTRef computes the inverse Walsh-Hadamard transform of the luma
// DC coefficients and scatters them into the 16 luma blocks of out (the
// reference of the transformWHT entry point).
func transformWHTRef(in *[16]int16, out *[384]int16) {
var tmp [16]int
for i := 0; i < 4; i++ {
a0 := int(in[0+i]) + int(in[12+i])
a1 := int(in[4+i]) + int(in[8+i])
a2 := int(in[4+i]) - int(in[8+i])
a3 := int(in[0+i]) - int(in[12+i])
tmp[0+i] = a0 + a1
tmp[8+i] = a0 - a1
tmp[4+i] = a3 + a2
tmp[12+i] = a3 - a2
}
for i := 0; i < 4; i++ {
dc := tmp[0+i*4] + 3 // w/ rounder
a0 := dc + tmp[3+i*4]
a1 := tmp[1+i*4] + tmp[2+i*4]
a2 := tmp[1+i*4] - tmp[2+i*4]
a3 := dc - tmp[3+i*4]
o := i * 64
out[o+0] = int16((a0 + a1) >> 3)
out[o+16] = int16((a3 + a2) >> 3)
out[o+32] = int16((a0 - a1) >> 3)
out[o+48] = int16((a3 - a2) >> 3)
}
}
// doTransform dispatches on the 2-bit non-zero code of a block.
func doTransform(code uint32, in *[16]int16, b []byte, o int) {
switch code {
case 3:
transformOne(in, b, o)
case 2:
transformAC3(in, b, o)
case 1:
transformDC(in, b, o)
}
}
// doUVTransform reconstructs the four 4x4 blocks of one chroma plane.
func doUVTransform(bits uint32, in *[384]int16, first int, b []byte, o int) {
if bits&0xff == 0 {
return
}
b0 := (*[16]int16)(in[first:])
b1 := (*[16]int16)(in[first+16:])
b2 := (*[16]int16)(in[first+32:])
b3 := (*[16]int16)(in[first+48:])
if bits&0xaa != 0 { // any non-zero AC coefficient
transformOne(b0, b, o)
transformOne(b1, b, o+4)
transformOne(b2, b, o+4*bps)
transformOne(b3, b, o+4*bps+4)
return
}
if b0[0] != 0 {
transformDC(b0, b, o)
}
if b1[0] != 0 {
transformDC(b1, b, o+4)
}
if b2[0] != 0 {
transformDC(b2, b, o+4*bps)
}
if b3[0] != 0 {
transformDC(b3, b, o+4*bps+4)
}
}
// --- per-macroblock reconstruction -------------------------------------------
//
// These are the reference implementations of the macroblock-level entry
// points reconI4, reconI16 and reconUV. Architectures with an assembly
// kernel (recon_arm64.s) bind the entry points to it; the others, and the
// purego build, bind them to these functions (recon_generic.go). The
// assembly must stay bit-exact with them for every input, which the
// differential tests in recon_test.go check.
// reconI4Ref predicts and reconstructs the 16 luma sub-blocks of an
// intra-4x4 macroblock in raster order. The top-right samples of the
// macroblock must already be in place (and replicated below, see
// reconstructMB). bits holds the 2-bit transform code of each sub-block,
// sub-block 0 in the top bits.
func reconI4Ref(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, modes *[16]uint8) {
for n := 0; n < 16; n++ {
o := yOff + kScan[n]
predLuma4(modes[n], b[:], o)
doTransform(bits>>30, (*[16]int16)(coeffs[n*16:]), b[:], o)
bits <<= 2
}
}
// reconI16Ref runs the 16x16 luma predictor mode (after checkMode) and adds
// the residuals of the 16 luma blocks.
func reconI16Ref(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, mode int) {
predLuma16(mode, b[:])
if bits != 0 {
for n := 0; n < 16; n++ {
doTransform(bits>>30, (*[16]int16)(coeffs[n*16:]), b[:], yOff+kScan[n])
bits <<= 2
}
}
}
// reconUVRef runs the 8x8 chroma predictor mode (after checkMode) on both
// chroma planes and adds their residuals; bits is mbBlock.nonZeroUV.
func reconUVRef(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, mode int) {
predChroma8(mode, b[:], uOff)
predChroma8(mode, b[:], vOff)
doUVTransform(bits>>0, coeffs, 16*16, b[:], uOff)
doUVTransform(bits>>8, coeffs, 20*16, b[:], vOff)
}
// loadEdges flags.
const (
edgeRotate = 1 << iota // copy the right samples of the previous macroblock to the left
edgeTop // load the top samples
edgeTopRight // store tr as the top-right samples (intra 4x4)
edgeI4 // replicate the top-right samples below (intra 4x4)
)
// loadEdgesRef sets up the context samples of the next macroblock in the
// work buffer (the first half of libwebp's ReconstructRow loop body): the
// left column from the previous macroblock, the top row from top and the
// four top-right samples tr (little endian), replicated on the rows above
// sub-block rows 1-3 for intra 4x4.
func loadEdgesRef(b *[yuvSize]byte, top *topSamples, tr, flags uint32) {
if flags&edgeRotate != 0 {
for j := -1; j < 16; j++ {
o := yOff + j*bps
*(*[4]byte)(b[o-4:]) = *(*[4]byte)(b[o+12:])
}
for j := -1; j < 8; j++ {
o := uOff + j*bps
*(*[4]byte)(b[o-4:]) = *(*[4]byte)(b[o+4:])
o = vOff + j*bps
*(*[4]byte)(b[o-4:]) = *(*[4]byte)(b[o+4:])
}
}
if flags&edgeTop != 0 {
*(*[16]byte)(b[yOff-bps:]) = top.y
*(*[8]byte)(b[uOff-bps:]) = top.u
*(*[8]byte)(b[vOff-bps:]) = top.v
}
if flags&edgeI4 != 0 {
const tro = yOff - bps + 16
if flags&edgeTopRight != 0 {
binary.LittleEndian.PutUint32(b[tro:], tr)
}
for k := 1; k <= 3; k++ {
*(*[4]byte)(b[tro+4*k*bps:]) = *(*[4]byte)(b[tro:])
}
}
}
// storeMBRowsRef saves the bottom samples of the reconstructed macroblock
// in top (unless it is nil) and copies the macroblock into the row cache:
// luma row j to cy[j*ys:], chroma row j to cu[j*uvs:] and cv[j*uvs:].
func storeMBRowsRef(b *[yuvSize]byte, top *topSamples, cy, cu, cv []byte, ys, uvs int) {
if top != nil {
top.y = *(*[16]byte)(b[yOff+15*bps:])
top.u = *(*[8]byte)(b[uOff+7*bps:])
top.v = *(*[8]byte)(b[vOff+7*bps:])
}
for j := 0; j < 16; j++ {
*(*[16]byte)(cy[j*ys:]) = *(*[16]byte)(b[yOff+j*bps:])
}
for j := 0; j < 8; j++ {
*(*[8]byte)(cu[j*uvs:]) = *(*[8]byte)(b[uOff+j*bps:])
*(*[8]byte)(cv[j*uvs:]) = *(*[8]byte)(b[vOff+j*bps:])
}
}
// --- intra prediction -------------------------------------------------------
func avg3(a, b, c int) uint8 { return uint8((a + 2*b + c + 2) >> 2) }
func avg2(a, b int) uint8 { return uint8((a + b + 1) >> 1) }
// trueMotion implements TM prediction for a size x size block at b[o:].
func trueMotion(b []byte, o, size int) {
tl := int(b[o-bps-1])
top := b[o-bps : o-bps+size]
for y := 0; y < size; y++ {
row := b[o+y*bps : o+y*bps+size]
l := int(b[o+y*bps-1]) - tl
for x := range row {
row[x] = clip8(int(top[x]) + l)
}
}
}
// put8 stores an 8-byte word at b[o:].
func put8(b []byte, o int, v uint64) {
binary.LittleEndian.PutUint64((*[8]byte)(b[o : o+8])[:], v)
}
// fill sets a size x size block (size is 8 or 16) to v.
func fill(b []byte, o, size int, v uint8) {
v64 := uint64(v) * 0x0101010101010101
for y := 0; y < size; y++ {
put8(b, o+y*bps, v64)
if size == 16 {
put8(b, o+y*bps+8, v64)
}
}
}
func verticalPred(b []byte, o, size int) {
t0 := binary.LittleEndian.Uint64(b[o-bps:])
t1 := uint64(0)
if size == 16 {
t1 = binary.LittleEndian.Uint64(b[o-bps+8:])
}
for y := 0; y < size; y++ {
put8(b, o+y*bps, t0)
if size == 16 {
put8(b, o+y*bps+8, t1)
}
}
}
func horizontalPred(b []byte, o, size int) {
for y := 0; y < size; y++ {
v64 := uint64(b[o+y*bps-1]) * 0x0101010101010101
put8(b, o+y*bps, v64)
if size == 16 {
put8(b, o+y*bps+8, v64)
}
}
}
func sumTop(b []byte, o, size int) int {
s := 0
for _, v := range b[o-bps : o-bps+size] {
s += int(v)
}
return s
}
func sumLeft(b []byte, o, size int) int {
s := 0
for y := 0; y < size; y++ {
s += int(b[o+y*bps-1])
}
return s
}
// predLuma16 runs the 16x16 predictor for mode (after checkMode).
func predLuma16(mode int, b []byte) {
const o = yOff
switch mode {
case bDCPred:
fill(b, o, 16, uint8((sumTop(b, o, 16)+sumLeft(b, o, 16)+16)>>5))
case bTMPred:
trueMotion(b, o, 16)
case bVEPred:
verticalPred(b, o, 16)
case bHEPred:
horizontalPred(b, o, 16)
case bDCPredNoTop:
fill(b, o, 16, uint8((sumLeft(b, o, 16)+8)>>4))
case bDCPredNoLeft:
fill(b, o, 16, uint8((sumTop(b, o, 16)+8)>>4))
default: // bDCPredNoTopLeft
fill(b, o, 16, 0x80)
}
}
// predChroma8 runs the 8x8 chroma predictor for mode (after checkMode).
func predChroma8(mode int, b []byte, o int) {
switch mode {
case bDCPred:
fill(b, o, 8, uint8((sumTop(b, o, 8)+sumLeft(b, o, 8)+8)>>4))
case bTMPred:
trueMotion(b, o, 8)
case bVEPred:
verticalPred(b, o, 8)
case bHEPred:
horizontalPred(b, o, 8)
case bDCPredNoTop:
fill(b, o, 8, uint8((sumLeft(b, o, 8)+4)>>3))
case bDCPredNoLeft:
fill(b, o, 8, uint8((sumTop(b, o, 8)+4)>>3))
default:
fill(b, o, 8, 0x80)
}
}
// pred4 window layout: s[0] is the top-left pixel, s[1+i] the top row
// (8 pixels incl. top-right), s[bps*(j+1)] the left column, and
// s[bps*(y+1)+1+x] the destination pixel (x, y).
type pred4Win = [4*bps + 8]byte
const (
p4X = 0 // top-left
p4A = 1 // top[0]
p4I = bps
p4J = 2 * bps
p4K = 3 * bps
p4L = 4 * bps
)
func p4(x, y int) int { return bps*(y+1) + 1 + x }
func putRow4(s *pred4Win, y int, v uint8) {
o := bps*(y+1) + 1
s[o], s[o+1], s[o+2], s[o+3] = v, v, v, v
}
// predLuma4 runs the 4x4 predictor for mode on the sub-block at b[o:].
func predLuma4(mode uint8, b []byte, o int) {
s := (*pred4Win)(b[o-bps-1:])
switch mode {
case bDCPred:
dc := 4
for i := 0; i < 4; i++ {
dc += int(s[p4A+i]) + int(s[bps*(i+1)])
}
v := uint8(dc >> 3)
for y := 0; y < 4; y++ {
putRow4(s, y, v)
}
case bTMPred:
tl := int(s[p4X])
for y := 0; y < 4; y++ {
l := int(s[bps*(y+1)]) - tl
r := bps*(y+1) + 1
s[r+0] = clip8(int(s[1]) + l)
s[r+1] = clip8(int(s[2]) + l)
s[r+2] = clip8(int(s[3]) + l)
s[r+3] = clip8(int(s[4]) + l)
}
case bVEPred:
v0 := avg3(int(s[0]), int(s[1]), int(s[2]))
v1 := avg3(int(s[1]), int(s[2]), int(s[3]))
v2 := avg3(int(s[2]), int(s[3]), int(s[4]))
v3 := avg3(int(s[3]), int(s[4]), int(s[5]))
for y := 0; y < 4; y++ {
r := bps*(y+1) + 1
s[r], s[r+1], s[r+2], s[r+3] = v0, v1, v2, v3
}
case bHEPred:
A, B, C, D, E := int(s[p4X]), int(s[p4I]), int(s[p4J]), int(s[p4K]), int(s[p4L])
putRow4(s, 0, avg3(A, B, C))
putRow4(s, 1, avg3(B, C, D))
putRow4(s, 2, avg3(C, D, E))
putRow4(s, 3, avg3(D, E, E))
case bRDPred:
I, J, K, L, X := int(s[p4I]), int(s[p4J]), int(s[p4K]), int(s[p4L]), int(s[p4X])
A, B, C, D := int(s[1]), int(s[2]), int(s[3]), int(s[4])
s[p4(0, 3)] = avg3(J, K, L)
v := avg3(I, J, K)
s[p4(1, 3)], s[p4(0, 2)] = v, v
v = avg3(X, I, J)
s[p4(2, 3)], s[p4(1, 2)], s[p4(0, 1)] = v, v, v
v = avg3(A, X, I)
s[p4(3, 3)], s[p4(2, 2)], s[p4(1, 1)], s[p4(0, 0)] = v, v, v, v
v = avg3(B, A, X)
s[p4(3, 2)], s[p4(2, 1)], s[p4(1, 0)] = v, v, v
v = avg3(C, B, A)
s[p4(3, 1)], s[p4(2, 0)] = v, v
s[p4(3, 0)] = avg3(D, C, B)
case bVRPred:
I, J, K, X := int(s[p4I]), int(s[p4J]), int(s[p4K]), int(s[p4X])
A, B, C, D := int(s[1]), int(s[2]), int(s[3]), int(s[4])
v := avg2(X, A)
s[p4(0, 0)], s[p4(1, 2)] = v, v
v = avg2(A, B)
s[p4(1, 0)], s[p4(2, 2)] = v, v
v = avg2(B, C)
s[p4(2, 0)], s[p4(3, 2)] = v, v
s[p4(3, 0)] = avg2(C, D)
s[p4(0, 3)] = avg3(K, J, I)
s[p4(0, 2)] = avg3(J, I, X)
v = avg3(I, X, A)
s[p4(0, 1)], s[p4(1, 3)] = v, v
v = avg3(X, A, B)
s[p4(1, 1)], s[p4(2, 3)] = v, v
v = avg3(A, B, C)
s[p4(2, 1)], s[p4(3, 3)] = v, v
s[p4(3, 1)] = avg3(B, C, D)
case bLDPred:
A, B, C, D := int(s[1]), int(s[2]), int(s[3]), int(s[4])
E, F, G, H := int(s[5]), int(s[6]), int(s[7]), int(s[8])
s[p4(0, 0)] = avg3(A, B, C)
v := avg3(B, C, D)
s[p4(1, 0)], s[p4(0, 1)] = v, v
v = avg3(C, D, E)
s[p4(2, 0)], s[p4(1, 1)], s[p4(0, 2)] = v, v, v
v = avg3(D, E, F)
s[p4(3, 0)], s[p4(2, 1)], s[p4(1, 2)], s[p4(0, 3)] = v, v, v, v
v = avg3(E, F, G)
s[p4(3, 1)], s[p4(2, 2)], s[p4(1, 3)] = v, v, v
v = avg3(F, G, H)
s[p4(3, 2)], s[p4(2, 3)] = v, v
s[p4(3, 3)] = avg3(G, H, H)
case bVLPred:
A, B, C, D := int(s[1]), int(s[2]), int(s[3]), int(s[4])
E, F, G, H := int(s[5]), int(s[6]), int(s[7]), int(s[8])
s[p4(0, 0)] = avg2(A, B)
v := avg2(B, C)
s[p4(1, 0)], s[p4(0, 2)] = v, v
v = avg2(C, D)
s[p4(2, 0)], s[p4(1, 2)] = v, v
v = avg2(D, E)
s[p4(3, 0)], s[p4(2, 2)] = v, v
s[p4(0, 1)] = avg3(A, B, C)
v = avg3(B, C, D)
s[p4(1, 1)], s[p4(0, 3)] = v, v
v = avg3(C, D, E)
s[p4(2, 1)], s[p4(1, 3)] = v, v
v = avg3(D, E, F)
s[p4(3, 1)], s[p4(2, 3)] = v, v
s[p4(3, 2)] = avg3(E, F, G)
s[p4(3, 3)] = avg3(F, G, H)
case bHDPred:
I, J, K, L, X := int(s[p4I]), int(s[p4J]), int(s[p4K]), int(s[p4L]), int(s[p4X])
A, B, C := int(s[1]), int(s[2]), int(s[3])
v := avg2(I, X)
s[p4(0, 0)], s[p4(2, 1)] = v, v
v = avg2(J, I)
s[p4(0, 1)], s[p4(2, 2)] = v, v
v = avg2(K, J)
s[p4(0, 2)], s[p4(2, 3)] = v, v
s[p4(0, 3)] = avg2(L, K)
s[p4(3, 0)] = avg3(A, B, C)
s[p4(2, 0)] = avg3(X, A, B)
v = avg3(I, X, A)
s[p4(1, 0)], s[p4(3, 1)] = v, v
v = avg3(J, I, X)
s[p4(1, 1)], s[p4(3, 2)] = v, v
v = avg3(K, J, I)
s[p4(1, 2)], s[p4(3, 3)] = v, v
s[p4(1, 3)] = avg3(L, K, J)
default: // bHUPred
I, J, K, L := int(s[p4I]), int(s[p4J]), int(s[p4K]), int(s[p4L])
s[p4(0, 0)] = avg2(I, J)
v := avg2(J, K)
s[p4(2, 0)], s[p4(0, 1)] = v, v
v = avg2(K, L)
s[p4(2, 1)], s[p4(0, 2)] = v, v
s[p4(1, 0)] = avg3(I, J, K)
v = avg3(J, K, L)
s[p4(3, 0)], s[p4(1, 1)] = v, v
v = avg3(K, L, L)
s[p4(3, 1)], s[p4(1, 2)] = v, v
l := uint8(L)
s[p4(3, 2)], s[p4(2, 2)] = l, l
s[p4(0, 3)], s[p4(1, 3)], s[p4(2, 3)], s[p4(3, 3)] = l, l, l, l
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// Algorithm adapted from libwebp (BSD-3-Clause): dsp/dec.c (simple and
// complex in-loop filters).
//
// Each filter comes in two flavours: "V" filters a horizontal edge (the
// pixels across the edge are one stride apart, the loop walks along a row)
// and "H" filters a vertical edge (pixels across the edge are adjacent, the
// loop walks down a column).
// filterLevel selects the x86 SIMD level of filterMB (filter_amd64.go);
// tests lower it to cover every level. Other builds ignore it.
var filterLevel = cpuinfo.Max
func abs(x int) int { return max(x, -x) }
func sclip1(x int) int { return min(max(x, -128), 127) }
func sclip2(x int) int { return min(max(x, -16), 15) }
func clip1(x int) uint8 {
return uint8(min(max(x, 0), 255))
}
// filterTables are lookup tables replacing clamps in the filter kernels.
type filterTables struct {
clip1 [1024]uint8 // clip1[(x+256)&1023] = clamp(x, 0, 255), x in [-256, 767]
sclip2 [256]int8 // sclip2[uint8(x)] = clamp(x, -16, 15), x in [-128, 127]
}
// fTab is a pointer variable so that hot loops keep it in a register.
var fTab = func() *filterTables {
t := new(filterTables)
for i := range t.clip1 {
t.clip1[i] = clip1(i - 256)
}
for i := range t.sclip2 {
t.sclip2[i] = int8(sclip2(int(int8(i))))
}
return t
}()
// --- simple filter ----------------------------------------------------------
func simpleV(buf []byte, o, stride, n, thresh2 int) {
t := fTab
r1 := buf[o-2*stride:][:n]
r2 := buf[o-stride:][:n]
r3 := buf[o:][:n]
r4 := buf[o+stride:][:n]
for i := range r1 {
p1, p0, q0, q1 := int(r1[i]), int(r2[i]), int(r3[i]), int(r4[i])
if 4*abs(p0-q0)+abs(p1-q1) > thresh2 {
continue
}
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
r2[i] = t.clip1[(p0+a2+256)&1023]
r3[i] = t.clip1[(q0-a1+256)&1023]
}
}
func simpleH(buf []byte, o, stride, n, thresh2 int) {
t := fTab
row := buf[o-2:]
for j := 0; j < n; j++ {
if j > 0 {
row = row[stride:]
}
w := (*[4]byte)(row)
p1, p0, q0, q1 := int(w[0]), int(w[1]), int(w[2]), int(w[3])
if 4*abs(p0-q0)+abs(p1-q1) > thresh2 {
continue
}
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
w[1] = t.clip1[(p0+a2+256)&1023]
w[2] = t.clip1[(q0-a1+256)&1023]
}
}
// --- complex filter -----------------------------------------------------------
// loop26V filters a macroblock edge (up to 3 pixels modified on each side).
func loop26V(buf []byte, o, stride, n, thresh2, ithresh, hevT int) {
t := fTab
r0 := buf[o-4*stride:][:n]
r1 := buf[o-3*stride:][:n]
r2 := buf[o-2*stride:][:n]
r3 := buf[o-stride:][:n]
r4 := buf[o:][:n]
r5 := buf[o+stride:][:n]
r6 := buf[o+2*stride:][:n]
r7 := buf[o+3*stride:][:n]
for i := range r0 {
p3, p2, p1, p0 := int(r0[i]), int(r1[i]), int(r2[i]), int(r3[i])
q0, q1, q2, q3 := int(r4[i]), int(r5[i]), int(r6[i]), int(r7[i])
if p0 == q0 && p1 == q1 {
continue // the filter would leave this line unchanged
}
dp, dq := abs(p1-p0), abs(q1-q0)
if 4*abs(p0-q0)+abs(p1-q1) > thresh2 ||
max(abs(p3-p2), abs(p2-p1), dp, abs(q3-q2), abs(q2-q1), dq) > ithresh {
continue
}
if max(dp, dq) > hevT {
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
r3[i] = t.clip1[(p0+a2+256)&1023]
r4[i] = t.clip1[(q0-a1+256)&1023]
} else {
a := sclip1(3*(q0-p0) + sclip1(p1-q1))
a1 := (27*a + 63) >> 7
a2 := (18*a + 63) >> 7
a3 := (9*a + 63) >> 7
r1[i] = t.clip1[(p2+a3+256)&1023]
r2[i] = t.clip1[(p1+a2+256)&1023]
r3[i] = t.clip1[(p0+a1+256)&1023]
r4[i] = t.clip1[(q0-a1+256)&1023]
r5[i] = t.clip1[(q1-a2+256)&1023]
r6[i] = t.clip1[(q2-a3+256)&1023]
}
}
}
func loop26H(buf []byte, o, stride, n, thresh2, ithresh, hevT int) {
t := fTab
row := buf[o-4:]
for j := 0; j < n; j++ {
if j > 0 {
row = row[stride:]
}
w := (*[8]byte)(row)
p3, p2, p1, p0 := int(w[0]), int(w[1]), int(w[2]), int(w[3])
q0, q1, q2, q3 := int(w[4]), int(w[5]), int(w[6]), int(w[7])
if p0 == q0 && p1 == q1 {
continue // the filter would leave this line unchanged
}
dp, dq := abs(p1-p0), abs(q1-q0)
if 4*abs(p0-q0)+abs(p1-q1) > thresh2 ||
max(abs(p3-p2), abs(p2-p1), dp, abs(q3-q2), abs(q2-q1), dq) > ithresh {
continue
}
if max(dp, dq) > hevT {
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
w[3] = t.clip1[(p0+a2+256)&1023]
w[4] = t.clip1[(q0-a1+256)&1023]
} else {
a := sclip1(3*(q0-p0) + sclip1(p1-q1))
a1 := (27*a + 63) >> 7
a2 := (18*a + 63) >> 7
a3 := (9*a + 63) >> 7
w[1] = t.clip1[(p2+a3+256)&1023]
w[2] = t.clip1[(p1+a2+256)&1023]
w[3] = t.clip1[(p0+a1+256)&1023]
w[4] = t.clip1[(q0-a1+256)&1023]
w[5] = t.clip1[(q1-a2+256)&1023]
w[6] = t.clip1[(q2-a3+256)&1023]
}
}
}
// loop24V filters an inner edge (up to 2 pixels modified on each side).
func loop24V(buf []byte, o, stride, n, thresh2, ithresh, hevT int) {
t := fTab
r0 := buf[o-4*stride:][:n]
r1 := buf[o-3*stride:][:n]
r2 := buf[o-2*stride:][:n]
r3 := buf[o-stride:][:n]
r4 := buf[o:][:n]
r5 := buf[o+stride:][:n]
r6 := buf[o+2*stride:][:n]
r7 := buf[o+3*stride:][:n]
for i := range r0 {
p3, p2, p1, p0 := int(r0[i]), int(r1[i]), int(r2[i]), int(r3[i])
q0, q1, q2, q3 := int(r4[i]), int(r5[i]), int(r6[i]), int(r7[i])
if p0 == q0 && p1 == q1 {
continue // the filter would leave this line unchanged
}
dp, dq := abs(p1-p0), abs(q1-q0)
if 4*abs(p0-q0)+abs(p1-q1) > thresh2 ||
max(abs(p3-p2), abs(p2-p1), dp, abs(q3-q2), abs(q2-q1), dq) > ithresh {
continue
}
if max(dp, dq) > hevT {
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
r3[i] = t.clip1[(p0+a2+256)&1023]
r4[i] = t.clip1[(q0-a1+256)&1023]
} else {
a := 3 * (q0 - p0)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
a3 := (a1 + 1) >> 1
r2[i] = t.clip1[(p1+a3+256)&1023]
r3[i] = t.clip1[(p0+a2+256)&1023]
r4[i] = t.clip1[(q0-a1+256)&1023]
r5[i] = t.clip1[(q1-a3+256)&1023]
}
}
}
func loop24H(buf []byte, o, stride, n, thresh2, ithresh, hevT int) {
t := fTab
row := buf[o-4:]
for j := 0; j < n; j++ {
if j > 0 {
row = row[stride:]
}
w := (*[8]byte)(row)
p3, p2, p1, p0 := int(w[0]), int(w[1]), int(w[2]), int(w[3])
q0, q1, q2, q3 := int(w[4]), int(w[5]), int(w[6]), int(w[7])
if p0 == q0 && p1 == q1 {
continue // the filter would leave this line unchanged
}
dp, dq := abs(p1-p0), abs(q1-q0)
if 4*abs(p0-q0)+abs(p1-q1) > thresh2 ||
max(abs(p3-p2), abs(p2-p1), dp, abs(q3-q2), abs(q2-q1), dq) > ithresh {
continue
}
if max(dp, dq) > hevT {
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
w[3] = t.clip1[(p0+a2+256)&1023]
w[4] = t.clip1[(q0-a1+256)&1023]
} else {
a := 3 * (q0 - p0)
a1 := int(t.sclip2[uint8((a+4)>>3)])
a2 := int(t.sclip2[uint8((a+3)>>3)])
a3 := (a1 + 1) >> 1
w[2] = t.clip1[(p1+a3+256)&1023]
w[3] = t.clip1[(p0+a2+256)&1023]
w[4] = t.clip1[(q0-a1+256)&1023]
w[5] = t.clip1[(q1-a3+256)&1023]
}
}
}
// Edge selection flags of a macroblock (the NEON filters take them as
// one argument).
const (
filterEdgeLeft = 1 // left macroblock edge (mbX > 0)
filterEdgeTop = 2 // top macroblock edge (mbY > 0)
filterEdgeInner = 4 // the inner 4x4 block edges
)
// filterMBGo applies the in-loop filter to the macroblock at column mbX of
// the current cache row (libwebp's DoFilter). This is the portable
// reference; filterMB (filter_arm64.go, filter_amd64.go, filter_generic.go)
// is the entry point used by the decoder.
func (d *decoder) filterMBGo(mbX, mbY int, f fInfo) {
limit := int(f.limit)
if limit == 0 {
return
}
ys := d.cacheYStride
yo := d.cacheYOff + mbX*16
cy := d.cacheY
if d.filterType == 1 { // simple
if mbX > 0 {
simpleH(cy, yo, ys, 16, 2*(limit+4)+1)
}
if f.inner != 0 {
for k := 4; k < 16; k += 4 {
simpleH(cy, yo+k, ys, 16, 2*limit+1)
}
}
if mbY > 0 {
simpleV(cy, yo, ys, 16, 2*(limit+4)+1)
}
if f.inner != 0 {
for k := 4; k < 16; k += 4 {
simpleV(cy, yo+k*ys, ys, 16, 2*limit+1)
}
}
return
}
// complex
uvs := d.cacheUVStride
uvo := d.cacheUVOff + mbX*8
cu, cv := d.cacheU, d.cacheV
il := int(f.ilevel)
hevT := int(f.hevThresh)
t2 := 2*(limit+4) + 1
ti2 := 2*limit + 1
if mbX > 0 {
loop26H(cy, yo, ys, 16, t2, il, hevT)
loop26H(cu, uvo, uvs, 8, t2, il, hevT)
loop26H(cv, uvo, uvs, 8, t2, il, hevT)
}
if f.inner != 0 {
loop24H(cy, yo+4, ys, 16, ti2, il, hevT)
loop24H(cy, yo+8, ys, 16, ti2, il, hevT)
loop24H(cy, yo+12, ys, 16, ti2, il, hevT)
loop24H(cu, uvo+4, uvs, 8, ti2, il, hevT)
loop24H(cv, uvo+4, uvs, 8, ti2, il, hevT)
}
if mbY > 0 {
loop26V(cy, yo, ys, 16, t2, il, hevT)
loop26V(cu, uvo, uvs, 8, t2, il, hevT)
loop26V(cv, uvo, uvs, 8, t2, il, hevT)
}
if f.inner != 0 {
loop24V(cy, yo+4*ys, ys, 16, ti2, il, hevT)
loop24V(cy, yo+8*ys, ys, 16, ti2, il, hevT)
loop24V(cy, yo+12*ys, ys, 16, ti2, il, hevT)
loop24V(cu, uvo+4*uvs, uvs, 8, ti2, il, hevT)
loop24V(cv, uvo+4*uvs, uvs, 8, ti2, il, hevT)
}
}
// blockInBounds reports whether the n x n block at offset o of a plane of
// size bytes with the given stride lies inside the plane, together with
// the k rows above it (filterEdgeTop) and the k columns to its left
// (filterEdgeLeft) when flags select those edges.
func blockInBounds(size, o, stride, n, k, flags int) bool {
if o < 0 || stride < n {
return false
}
lo := o
if flags&filterEdgeTop != 0 {
lo -= k * stride
}
if flags&filterEdgeLeft != 0 {
lo = min(lo, o-k)
}
return lo >= 0 && o+(n-1)*stride+n <= size
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// SSE4.1 and AVX2 loop filters (filter_amd64.s), one call per macroblock,
// selected by filterLevel. The simple filter has an SSE4.1 kernel only
// (the AVX2 level uses it).
// filterMBComplexSSE41 filters the edges of one macroblock selected by
// flags (filterEdgeLeft, filterEdgeTop, filterEdgeInner) with the complex
// filter, luma then U and V. y, u and v point at the macroblock's top-left
// samples; rows -4..15 / -4..7 and columns -4..15 / -4..7 around them must
// be accessible for the filtered edges (see blockInBounds). thrMB =
// limit+4 and thrIn = limit must be at most 254.
//
//go:noescape
func filterMBComplexSSE41(y, u, v *byte, yStride, uvStride, thrMB, thrIn, ilevel, hevThresh, flags int)
// filterMBComplexAVX2 is filterMBComplexSSE41 filtering luma and chroma
// together in the two lanes of ymm registers.
//
//go:noescape
func filterMBComplexAVX2(y, u, v *byte, yStride, uvStride, thrMB, thrIn, ilevel, hevThresh, flags int)
// filterMBSimpleSSE41 filters the luma edges selected by flags with the
// simple filter; rows -2..15 and columns -2..15 must be accessible for the
// filtered edges.
//
//go:noescape
func filterMBSimpleSSE41(y *byte, yStride, thrMB, thrIn, flags int)
// filterMB applies the in-loop filter to the macroblock at column mbX of
// the current cache row (libwebp's DoFilter); it matches filterMBGo bit for
// bit.
func (d *decoder) filterMB(mbX, mbY int, f fInfo) {
limit := int(f.limit)
if limit == 0 {
return
}
flags := 0
if mbX > 0 {
flags |= filterEdgeLeft
}
if mbY > 0 {
flags |= filterEdgeTop
}
if f.inner != 0 {
flags |= filterEdgeInner
}
if flags == 0 {
return
}
// The kernels compare thresholds as bytes; VP8 limits are at most
// 2*63+63 = 189, so the fallback is never taken by valid streams.
if limit > 250 || filterLevel < cpuinfo.SSE41 {
d.filterMBGo(mbX, mbY, f)
return
}
ys := d.cacheYStride
yo := d.cacheYOff + mbX*16
cy := d.cacheY
if d.filterType == 1 {
if !blockInBounds(len(cy), yo, ys, 16, 2, flags) {
d.filterMBGo(mbX, mbY, f)
return
}
filterMBSimpleSSE41(&cy[yo], ys, limit+4, limit, flags)
return
}
uvs := d.cacheUVStride
uvo := d.cacheUVOff + mbX*8
cu, cv := d.cacheU, d.cacheV
if !blockInBounds(len(cy), yo, ys, 16, 4, flags) || !blockInBounds(min(len(cu), len(cv)), uvo, uvs, 8, 4, flags) {
d.filterMBGo(mbX, mbY, f)
return
}
if filterLevel >= cpuinfo.AVX2 {
filterMBComplexAVX2(&cy[yo], &cu[uvo], &cv[uvo], ys, uvs, limit+4, limit, int(f.ilevel), int(f.hevThresh), flags)
} else {
filterMBComplexSSE41(&cy[yo], &cu[uvo], &cv[uvo], ys, uvs, limit+4, limit, int(f.ilevel), int(f.hevThresh), flags)
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
// Algorithm adapted from libwebp (BSD-3-Clause): dec/vp8_dec.c, dec/quant_dec.c,
// dec/tree_dec.c (header, segment, filter, partition, quantizer and
// probability parsing).
import "github.com/kolesa-team/go-webp/v2/internal/status"
const (
numMBSegments = 4
numRefLFDeltas = 4
numModeLFDeltas = 4
maxNumPartitions = 8
numTypes = 4
numBands = 8
numCtx = 3
numProbas = 11
numBModes = 10
// frameHeaderSize is the size of the key frame tag plus start code and
// dimensions.
frameHeaderSize = 10
)
// kBands maps a coefficient index to its probability band. The 17th entry
// is a sentinel used when looking one coefficient ahead.
var kBands = [16 + 1]uint8{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0}
// frameInfo is the result of validating the uncompressed key frame header.
type frameInfo struct {
width, height int
partLen int // size of the first partition
}
// parseFrameTag validates the 10-byte key frame header like libwebp's
// VP8GetInfo; as in WebPDecode, every failure except a short buffer is
// reported as a bitstream error.
func parseFrameTag(data []byte) (frameInfo, error) {
var fi frameInfo
if len(data) < frameHeaderSize {
return fi, status.NotEnoughData("truncated VP8 frame header")
}
b := data[:frameHeaderSize]
tag := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16
if b[3] != 0x9d || b[4] != 0x01 || b[5] != 0x2a {
return fi, status.Bitstream("bad VP8 start code")
}
if tag&1 != 0 {
return fi, status.Bitstream("not a key frame")
}
if (tag>>1)&7 > 3 {
return fi, status.Bitstream("incorrect keyframe parameters")
}
if (tag>>4)&1 == 0 {
return fi, status.Bitstream("frame not displayable")
}
fi.partLen = int(tag >> 5)
if fi.partLen >= len(data) {
return fi, status.Bitstream("bad partition length")
}
fi.width = int(uint16(b[7])<<8|uint16(b[6])) & 0x3fff
fi.height = int(uint16(b[9])<<8|uint16(b[8])) & 0x3fff
if fi.width == 0 || fi.height == 0 {
return fi, status.Bitstream("invalid VP8 dimensions")
}
return fi, nil
}
// DecodeHeader parses the VP8 frame header of a VP8 chunk payload (starting
// at the 3-byte frame tag) and returns the frame size.
func DecodeHeader(data []byte) (width, height int, err error) {
fi, err := parseFrameTag(data)
if err != nil {
return 0, 0, err
}
return fi.width, fi.height, nil
}
// parseHeaders parses the frame header and the first partition's global
// parameters, and sets up the token partitions.
func (d *decoder) parseHeaders(data []byte) error {
fi, err := parseFrameTag(data)
if err != nil {
return err
}
d.width, d.height = fi.width, fi.height
d.mbW = (d.width + 15) >> 4
d.mbH = (d.height + 15) >> 4
// Reset the segment header and probabilities (key frame).
d.useSegment = false
d.updateMap = false
d.absoluteDelta = true
d.quantizer = [numMBSegments]int{}
d.filterStrength = [numMBSegments]int{}
d.segProba = [3]uint8{255, 255, 255}
d.refLFDelta = [numRefLFDeltas]int{}
d.modeLFDelta = [numModeLFDeltas]int{}
buf := data[frameHeaderSize:]
if fi.partLen > len(buf) {
return status.NotEnoughData("bad partition length")
}
br := &d.br
br.init(buf[:fi.partLen])
buf = buf[fi.partLen:]
br.get() // color space
br.get() // clamping type
if !d.parseSegmentHeader() {
return status.Bitstream("cannot parse segment header")
}
if !d.parseFilterHeader() {
return status.Bitstream("cannot parse filter header")
}
if err := d.parsePartitions(buf); err != nil {
return err
}
d.parseQuant()
br.get() // ignore the value of update_proba
d.parseProba()
return nil
}
func (d *decoder) parseSegmentHeader() bool {
br := &d.br
d.useSegment = br.get()
if d.useSegment {
d.updateMap = br.get()
if br.get() { // update data
d.absoluteDelta = br.get()
for s := range d.quantizer {
d.quantizer[s] = 0
if br.get() {
d.quantizer[s] = br.getSignedValue(7)
}
}
for s := range d.filterStrength {
d.filterStrength[s] = 0
if br.get() {
d.filterStrength[s] = br.getSignedValue(6)
}
}
}
if d.updateMap {
for s := range d.segProba {
d.segProba[s] = 255
if br.get() {
d.segProba[s] = uint8(br.getValue(8))
}
}
}
} else {
d.updateMap = false
}
return !br.eof
}
func (d *decoder) parseFilterHeader() bool {
br := &d.br
d.simple = br.get()
d.level = br.getValue(6)
d.sharpness = br.getValue(3)
d.useLFDelta = br.get()
if d.useLFDelta {
if br.get() { // update lf-delta?
for i := range d.refLFDelta {
if br.get() {
d.refLFDelta[i] = br.getSignedValue(6)
}
}
for i := range d.modeLFDelta {
if br.get() {
d.modeLFDelta[i] = br.getSignedValue(6)
}
}
}
}
switch {
case d.level == 0:
d.filterType = 0
case d.simple:
d.filterType = 1
default:
d.filterType = 2
}
return !br.eof
}
func (d *decoder) parsePartitions(buf []byte) error {
d.numPartsMinusOne = (1 << uint(d.br.getValue(2))) - 1
last := d.numPartsMinusOne
if len(buf) < 3*last {
return status.NotEnoughData("cannot parse partitions")
}
sz := buf
part := buf[3*last:]
for p := 0; p < last; p++ {
psize := int(sz[0]) | int(sz[1])<<8 | int(sz[2])<<16
if psize > len(part) {
psize = len(part)
}
d.parts[p].init(part[:psize])
part = part[psize:]
sz = sz[3:]
}
d.parts[last].init(part)
if len(part) == 0 {
return status.NotEnoughData("cannot parse partitions")
}
return nil
}
func clipQ(v, m int) int {
return min(max(v, 0), m)
}
func (d *decoder) parseQuant() {
br := &d.br
baseQ0 := br.getValue(7)
opt := func() int {
if br.get() {
return br.getSignedValue(4)
}
return 0
}
dqy1DC := opt()
dqy2DC := opt()
dqy2AC := opt()
dquvDC := opt()
dquvAC := opt()
for i := 0; i < numMBSegments; i++ {
var q int
if d.useSegment {
q = d.quantizer[i]
if !d.absoluteDelta {
q += baseQ0
}
} else {
if i > 0 {
d.dqm[i] = d.dqm[0]
continue
}
q = baseQ0
}
m := &d.dqm[i]
m.y1[0] = int32(kDcTable[clipQ(q+dqy1DC, 127)])
m.y1[1] = int32(kAcTable[clipQ(q, 127)])
m.y2[0] = int32(kDcTable[clipQ(q+dqy2DC, 127)]) * 2
// For all x in [0..284], x*155/100 is bitwise equal to (x*101581) >> 16.
m.y2[1] = (int32(kAcTable[clipQ(q+dqy2AC, 127)]) * 101581) >> 16
if m.y2[1] < 8 {
m.y2[1] = 8
}
m.uv[0] = int32(kDcTable[clipQ(q+dquvDC, 117)])
m.uv[1] = int32(kAcTable[clipQ(q+dquvAC, 127)])
m.uvQuant = q + dquvAC
m.dither = 0
}
}
func (d *decoder) parseProba() {
br := &d.br
for t := 0; t < numTypes; t++ {
var bands [numBands][numCtx][numProbas]uint8
for b := 0; b < numBands; b++ {
for c := 0; c < numCtx; c++ {
for p := 0; p < numProbas; p++ {
v := coeffsProba0[t][b][c][p]
if br.getBit(coeffsUpdateProba[t][b][c][p]) != 0 {
v = uint8(br.getValue(8))
}
bands[b][c][p] = v
}
}
}
for n := 0; n < 17; n++ {
d.proba[t][n] = bands[kBands[n]]
}
}
d.useSkipProba = br.get()
if d.useSkipProba {
d.skipP = uint8(br.getValue(8))
}
}
// precomputeFilterStrengths mirrors libwebp's PrecomputeFilterStrengths.
func (d *decoder) precomputeFilterStrengths() {
if d.filterType == 0 {
return
}
for s := 0; s < numMBSegments; s++ {
baseLevel := d.level
if d.useSegment {
baseLevel = d.filterStrength[s]
if !d.absoluteDelta {
baseLevel += d.level
}
}
for i4x4 := 0; i4x4 <= 1; i4x4++ {
info := &d.fstrengths[s][i4x4]
level := baseLevel
if d.useLFDelta {
level += d.refLFDelta[0]
if i4x4 != 0 {
level += d.modeLFDelta[0]
}
}
level = min(max(level, 0), 63)
if level > 0 {
ilevel := level
if d.sharpness > 0 {
if d.sharpness > 4 {
ilevel >>= 2
} else {
ilevel >>= 1
}
if ilevel > 9-d.sharpness {
ilevel = 9 - d.sharpness
}
}
if ilevel < 1 {
ilevel = 1
}
info.ilevel = uint8(ilevel)
info.limit = uint8(2*level + ilevel)
switch {
case level >= 40:
info.hevThresh = 2
case level >= 15:
info.hevThresh = 1
default:
info.hevThresh = 0
}
} else {
info.limit = 0 // no filtering
}
info.inner = uint8(i4x4)
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
// Algorithm adapted from libwebp (BSD-3-Clause): dec/tree_dec.c
// (ParseIntraMode), dec/vp8_dec.c (GetCoeffs, ParseResiduals) and
// dec/frame_dec.c (ReconstructRow).
import "encoding/binary"
// kZigzag maps the coefficient scan order to raster positions.
var kZigzag = [16]uint8{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15}
// Extra bits probabilities for DCT_CAT3..DCT_CAT6, zero terminated.
var (
kCat3 = []uint8{173, 148, 140}
kCat4 = []uint8{176, 155, 140, 135}
kCat5 = []uint8{180, 157, 141, 134, 130}
kCat6 = []uint8{254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129}
kCat3456 = [4][]uint8{kCat3, kCat4, kCat5, kCat6}
)
// kYModesIntra4 is the intra 4x4 mode decoding tree: positive entries are
// the next node, other entries are negated modes.
var kYModesIntra4 = [18]int8{
-bDCPred, 1,
-bTMPred, 2,
-bVEPred, 3,
4, 6,
-bHEPred, 5,
-bRDPred, -bVRPred,
-bLDPred, 7,
-bVLPred, 8,
-bHDPred, -bHUPred,
}
// kScan is the offset of each luma 4x4 sub-block inside the work buffer.
var kScan = [16]int{
0 + 0*bps, 4 + 0*bps, 8 + 0*bps, 12 + 0*bps,
0 + 4*bps, 4 + 4*bps, 8 + 4*bps, 12 + 4*bps,
0 + 8*bps, 4 + 8*bps, 8 + 8*bps, 12 + 8*bps,
0 + 12*bps, 4 + 12*bps, 8 + 12*bps, 12 + 12*bps,
}
// parseIntraMode reads the segment, skip flag and prediction modes of the
// macroblock at column mbX from the first partition.
func (d *decoder) parseIntraMode(mbX int, blk *mbModes) {
br := &d.br
top := (*[4]uint8)(d.intraT[4*mbX:])
left := &d.intraL
if d.updateMap {
if br.getBit(d.segProba[0]) == 0 {
blk.segment = uint8(br.getBit(d.segProba[1]))
} else {
blk.segment = uint8(br.getBit(d.segProba[2]) + 2)
}
} else {
blk.segment = 0 // default for intra
}
blk.skip = false
if d.useSkipProba {
blk.skip = br.getBit(d.skipP) != 0
}
blk.isI4x4 = br.getBit(145) == 0
if !blk.isI4x4 {
var ymode uint8
if br.getBit(156) != 0 {
if br.getBit(128) != 0 {
ymode = bTMPred
} else {
ymode = bHEPred
}
} else {
if br.getBit(163) != 0 {
ymode = bVEPred
} else {
ymode = bDCPred
}
}
blk.imodes[0] = ymode
*top = [4]uint8{ymode, ymode, ymode, ymode}
*left = [4]uint8{ymode, ymode, ymode, ymode}
} else {
modes := &blk.imodes
value, rng, nbits := br.value, br.rng, br.nbits
var bit bool
for y := 0; y < 4; y++ {
ymode := left[y]
for x := 0; x < 4; x++ {
prob := &kBModesProba[top[x]][ymode]
// Generic tree-parsing
i := 0
for {
if nbits < 0 {
value, nbits = br.refill(value, nbits)
}
value, rng, nbits, bit = decodeBit(value, rng, nbits, prob[i])
i = int(kYModesIntra4[2*i+b2i(bit)])
if i <= 0 {
break
}
}
ymode = uint8(-i)
top[x] = ymode
}
modes[4*y+0], modes[4*y+1], modes[4*y+2], modes[4*y+3] = top[0], top[1], top[2], top[3]
left[y] = ymode
}
br.value, br.rng, br.nbits = value, rng, nbits
}
switch {
case br.getBit(142) == 0:
blk.uvmode = bDCPred
case br.getBit(114) == 0:
blk.uvmode = bVEPred
case br.getBit(183) != 0:
blk.uvmode = bTMPred
default:
blk.uvmode = bHEPred
}
}
// getLargeValue decodes a coefficient magnitude >= 2.
func getLargeValue(br *bitReader, p *[numProbas]uint8) int {
if br.getBit(p[3]) == 0 {
if br.getBit(p[4]) == 0 {
return 2
}
return 3 + br.getBit(p[5])
}
if br.getBit(p[6]) == 0 {
if br.getBit(p[7]) == 0 {
return 5 + br.getBit(159)
}
v := 7 + 2*br.getBit(165)
return v + br.getBit(145)
}
bit1 := br.getBit(p[8])
bit0 := br.getBit(p[9+bit1])
cat := 2*bit1 + bit0
v := 0
for _, pr := range kCat3456[cat] {
v += v + br.getBit(pr)
}
return v + 3 + (8 << uint(cat))
}
// getCoeffs decodes the tokens of one 4x4 block starting at coefficient n
// and returns the index after the last non-zero coefficient (16 at most).
func getCoeffs(br *bitReader, prob *[16 + 1][numCtx][numProbas]uint8, ctx int, dq *[2]int32, n int, out *[16]int16) int {
value, rng, nbits := br.value, br.rng, br.nbits
var bit bool
p := &prob[n&15][ctx]
for ; n < 16; n++ {
if nbits < 0 {
value, nbits = br.refill(value, nbits)
}
if value, rng, nbits, bit = decodeBit(value, rng, nbits, p[0]); !bit {
break // previous coeff was last non-zero coefficient
}
for {
if nbits < 0 {
value, nbits = br.refill(value, nbits)
}
if value, rng, nbits, bit = decodeBit(value, rng, nbits, p[1]); bit {
break
}
// zero coefficient
n++
if n == 16 {
br.value, br.rng, br.nbits = value, rng, nbits
return 16
}
p = &prob[n][0]
}
// non-zero coefficient
var v int
next := &prob[n+1]
if nbits < 0 {
value, nbits = br.refill(value, nbits)
}
if value, rng, nbits, bit = decodeBit(value, rng, nbits, p[2]); !bit {
v = 1
p = &next[1]
} else {
br.value, br.rng, br.nbits = value, rng, nbits
v = getLargeValue(br, p)
value, rng, nbits = br.value, br.rng, br.nbits
p = &next[2]
}
if nbits < 0 {
value, nbits = br.refill(value, nbits)
}
value, rng, nbits, v = decodeSigned(value, rng, nbits, v)
q := dq[1]
if n == 0 {
q = dq[0]
}
out[kZigzag[n&15]] = int16(int32(v) * q)
}
br.value, br.rng, br.nbits = value, rng, nbits
return n
}
// nzCodeBits appends the 2-bit transform selector of a block.
func nzCodeBits(nzCoeffs uint32, nz int, dcNZ bool) uint32 {
nzCoeffs <<= 2
switch {
case nz > 3:
nzCoeffs |= 3
case nz > 1:
nzCoeffs |= 2
case dcNZ:
nzCoeffs |= 1
}
return nzCoeffs
}
// parseResiduals decodes all coefficients of the macroblock and reports
// whether every coefficient is zero.
func (d *decoder) parseResiduals(mbX int, blk *mbBlock, br *bitReader) bool {
q := &d.dqm[blk.segment]
dst := &blk.coeffs
clear(dst[:])
var acProba *[16 + 1][numCtx][numProbas]uint8
first := 0
if !blk.isI4x4 { // parse DC
var dc [16]int16
ctx := int(d.nzDCT[mbX] + d.nzDCL)
nz := getCoeffs(br, &d.proba[1], ctx, &q.y2, 0, &dc)
v := uint8(0)
if nz > 0 {
v = 1
}
d.nzDCT[mbX], d.nzDCL = v, v
if nz > 1 { // more than just the DC -> perform the full transform
transformWHT(&dc, dst)
} else { // only DC is non-zero -> inlined simplified transform
dc0 := int16((int(dc[0]) + 3) >> 3)
for i := 0; i < 16*16; i += 16 {
dst[i] = dc0
}
}
first = 1
acProba = &d.proba[0]
} else {
acProba = &d.proba[3]
}
tnz := uint32(d.nzT[mbX] & 0x0f)
lnz := uint32(d.nzL & 0x0f)
var nonZeroY, nonZeroUV uint32
for y := 0; y < 4; y++ {
l := lnz & 1
var nzCoeffs uint32
for x := 0; x < 4; x++ {
ctx := int(l + (tnz & 1))
blkc := (*[16]int16)(dst[(y*4+x)*16:])
nz := getCoeffs(br, acProba, ctx, &q.y1, first, blkc)
l = 0
if nz > first {
l = 1
}
tnz = (tnz >> 1) | (l << 7)
nzCoeffs = nzCodeBits(nzCoeffs, nz, blkc[0] != 0)
}
tnz >>= 4
lnz = (lnz >> 1) | (l << 7)
nonZeroY = (nonZeroY << 8) | nzCoeffs
}
outTNZ := tnz
outLNZ := lnz >> 4
for ch := 0; ch < 4; ch += 2 {
var nzCoeffs uint32
tnz = uint32(d.nzT[mbX]) >> uint(4+ch)
lnz = uint32(d.nzL) >> uint(4+ch)
for y := 0; y < 2; y++ {
l := lnz & 1
for x := 0; x < 2; x++ {
ctx := int(l + (tnz & 1))
blkc := (*[16]int16)(dst[16*16+(ch*2+y*2+x)*16:])
nz := getCoeffs(br, &d.proba[2], ctx, &q.uv, 0, blkc)
l = 0
if nz > 0 {
l = 1
}
tnz = (tnz >> 1) | (l << 3)
nzCoeffs = nzCodeBits(nzCoeffs, nz, blkc[0] != 0)
}
tnz >>= 2
lnz = (lnz >> 1) | (l << 5)
}
// Note: we don't really need the per-4x4 uv bits
nonZeroUV |= nzCoeffs << uint(4*ch)
outTNZ |= (tnz << 4) << uint(ch)
outLNZ |= (lnz & 0xf0) << uint(ch)
}
d.nzT[mbX] = uint8(outTNZ)
d.nzL = uint8(outLNZ)
blk.nonZeroY = nonZeroY
blk.nonZeroUV = nonZeroUV
blk.dither = 0
if nonZeroUV&0xaaaa == 0 {
blk.dither = uint8(q.dither)
}
return nonZeroY|nonZeroUV == 0
}
// checkMode substitutes the DC predictor variants used at frame edges.
func checkMode(mbX, mbY int, mode uint8) int {
if mode == bDCPred {
if mbX == 0 {
if mbY == 0 {
return bDCPredNoTopLeft
}
return bDCPredNoLeft
}
if mbY == 0 {
return bDCPredNoTop
}
return bDCPred
}
return int(mode)
}
// initRowEdges prepares the work buffer borders at the start of a row.
func (d *decoder) initRowEdges(mbY int) {
b := d.yuvB[:]
for j := 0; j < 16; j++ {
b[yOff+j*bps-1] = 129
}
for j := 0; j < 8; j++ {
b[uOff+j*bps-1] = 129
b[vOff+j*bps-1] = 129
}
if mbY > 0 {
b[yOff-1-bps], b[uOff-1-bps], b[vOff-1-bps] = 129, 129, 129
} else {
for i := yOff - bps - 1; i < yOff-bps-1+16+4+1; i++ {
b[i] = 127
}
for i := uOff - bps - 1; i < uOff-bps-1+8+1; i++ {
b[i] = 127
}
for i := vOff - bps - 1; i < vOff-bps-1+8+1; i++ {
b[i] = 127
}
}
}
// reconstructMB predicts the macroblock, adds the residuals and copies the
// result into the row cache.
func (d *decoder) reconstructMB(mbX, mbY int, blk *mbBlock) {
d.loadMBEdges(mbX, mbY, blk.isI4x4)
reconBlock(&d.yuvB, mbX, mbY, blk)
d.storeMB(mbX, mbY)
}
// reconBlock runs the prediction and residual kernels of the macroblock on
// the work buffer, whose edges loadMBEdges has set up.
func reconBlock(b *[yuvSize]byte, mbX, mbY int, blk *mbBlock) {
if blk.isI4x4 {
reconI4(b, &blk.coeffs, blk.nonZeroY, &blk.imodes)
} else {
reconI16(b, &blk.coeffs, blk.nonZeroY, checkMode(mbX, mbY, blk.imodes[0]))
}
reconUV(b, &blk.coeffs, blk.nonZeroUV, checkMode(mbX, mbY, blk.uvmode))
}
// loadMBEdges sets up the left, top and (for intra 4x4) top-right samples
// of the macroblock in the work buffer.
func (d *decoder) loadMBEdges(mbX, mbY int, isI4x4 bool) {
top := &d.yuvT[mbX]
var flags, tr uint32
if mbX > 0 {
flags |= edgeRotate
}
if mbY > 0 {
flags |= edgeTop
}
if isI4x4 {
flags |= edgeI4
if mbY > 0 {
flags |= edgeTopRight
if mbX >= d.mbW-1 { // on rightmost edge
tr = uint32(top.y[15]) * 0x01010101
} else {
tr = binary.LittleEndian.Uint32(d.yuvT[mbX+1].y[:4])
}
}
}
loadEdges(&d.yuvB, top, tr, flags)
}
// storeMB saves the bottom samples of the reconstructed macroblock for the
// next row and copies it into the row cache.
func (d *decoder) storeMB(mbX, mbY int) {
var top *topSamples
if mbY < d.mbH-1 {
top = &d.yuvT[mbX]
}
yo := d.cacheYOff + mbX*16
uvo := d.cacheUVOff + mbX*8
storeMBRows(&d.yuvB, top, d.cacheY[yo:], d.cacheU[uvo:], d.cacheV[uvo:], d.cacheYStride, d.cacheUVStride)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
// Algorithm adapted from libwebp (BSD-3-Clause): utils/random_utils.[ch] and
// the dithering code of dec/frame_dec.c and dsp/dec.c.
const (
randomTableSize = 55
randomDitherFix = 8 // fixed-point precision for dithering
ditherAmpBits = 7
ditherAmpCenter = 1 << ditherAmpBits
ditherDescale = 4
ditherRounder = 1 << (ditherDescale - 1)
minDitherAmp = 4
ditherAmpTabSize = 12
)
// kQuantToDitherAmp maps the chroma AC quantizer to a dithering amplitude.
var kQuantToDitherAmp = [ditherAmpTabSize]uint8{8, 7, 6, 4, 4, 2, 2, 2, 1, 1, 1, 1}
// kRandomTable is libwebp's 31-bit subtractive generator seed table.
var kRandomTable = [randomTableSize]uint32{
0x0de15230, 0x03b31886, 0x775faccb, 0x1c88626a, 0x68385c55, 0x14b3b828,
0x4a85fef8, 0x49ddb84b, 0x64fcf397, 0x5c550289, 0x4a290000, 0x0d7ec1da,
0x5940b7ab, 0x5492577d, 0x4e19ca72, 0x38d38c69, 0x0c01ee65, 0x32a1755f,
0x5437f652, 0x5abb2c32, 0x0faa57b1, 0x73f533e7, 0x685feeda, 0x7563cce2,
0x6e990e83, 0x4730a7ed, 0x4fc0d9c6, 0x496b153c, 0x4f1403fa, 0x541afb0c,
0x73990b32, 0x26d7cb1c, 0x6fcc3706, 0x2cbb77d8, 0x75762f2a, 0x6425ccdd,
0x24b35461, 0x0a7d8715, 0x220414a8, 0x141ebf67, 0x56b41583, 0x73e502e3,
0x44cab16f, 0x28264d42, 0x73baaefb, 0x0a50ebed, 0x1d6ab6fb, 0x0d3ad40b,
0x35db3b68, 0x2b081e83, 0x77ce6b95, 0x5181e5f0, 0x78853bbc, 0x009f9494,
0x27e5ed3c,
}
// vp8Random is libwebp's VP8Random.
type vp8Random struct {
index1, index2 int
tab [randomTableSize]uint32
}
func (rg *vp8Random) init() {
rg.tab = kRandomTable
rg.index1 = 0
rg.index2 = 31
}
// bits2 returns a centered random value of numBits bits scaled by amp.
func (rg *vp8Random) bits2(numBits, amp int) int {
diff := int64(rg.tab[rg.index1]) - int64(rg.tab[rg.index2])
if diff < 0 {
diff += 1 << 31
}
rg.tab[rg.index1] = uint32(diff)
if rg.index1++; rg.index1 == randomTableSize {
rg.index1 = 0
}
if rg.index2++; rg.index2 == randomTableSize {
rg.index2 = 0
}
// sign-extend, 0-center
v := int(int32(uint32(diff)<<1) >> (32 - numBits))
v = (v * amp) >> randomDitherFix // restrict range
v += 1 << (numBits - 1) // shift back to 0.5-center
return v
}
// dither8x8 adds random noise of amplitude amp to an 8x8 block.
func (rg *vp8Random) dither8x8(buf []byte, o, stride, amp int) {
var dither [64]uint8
for i := range dither {
dither[i] = uint8(rg.bits2(ditherAmpBits+1, amp))
}
for j := 0; j < 8; j++ {
row := buf[o+j*stride : o+j*stride+8]
for i := range row {
delta0 := int(dither[j*8+i]) - ditherAmpCenter
delta1 := (delta0 + ditherRounder) >> ditherDescale
row[i] = clip1(int(row[i]) + delta1)
}
}
}
// initDithering mirrors libwebp's VP8InitDithering.
func (d *decoder) initDithering(strength int) {
d.dither = false
if strength <= 0 {
return
}
const maxAmp = (1 << randomDitherFix) - 1
f := strength * maxAmp / 100
if strength > 100 {
f = maxAmp
}
if f <= 0 {
return
}
allAmp := 0
for s := range d.dqm {
dqm := &d.dqm[s]
if dqm.uvQuant < ditherAmpTabSize {
idx := max(dqm.uvQuant, 0)
dqm.dither = (f * int(kQuantToDitherAmp[idx])) >> 3
}
allAmp |= dqm.dither
}
if allAmp != 0 {
d.rng.init()
d.dither = true
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// x86 kernels for the macroblock reconstruction (recon_amd64.s), chosen at
// run time by reconLevel: AVX2 (x86-64-v3) and SSE4.1 versions of the three
// per-macroblock entry points, an SSE4.1 inverse WHT and SSE2 edge setup and
// row cache copy. Levels without a kernel use the next lower one, down to
// the Go reference.
//
// The inverse DCT runs in 16-bit lanes as in libwebp, which is exact only
// while the coefficients it uses stay within [-4095, 4095] (a valid encoder
// stays far below: the transform of 8-bit residuals is bounded by 2040, plus
// the quantization error). The kernels check that bound and return false
// before they use a coefficient outside it; the wrappers then rerun the
// macroblock with the Go reference, which recomputes every pixel the kernel
// may have written from context the kernels never write. The DC-only path
// saturates instead and needs no check.
// reconLevel is the SIMD level the wrappers use; tests set it to every level
// of cpuinfo.Levels.
var reconLevel = cpuinfo.Max
//go:noescape
func reconI4AVX2(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, modes *[16]uint8) bool
//go:noescape
func reconI16AVX2(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, mode int) bool
//go:noescape
func reconUVAVX2(b *[yuvSize]byte, coeffs *[384]int16, codes uint32, mode int) bool
//go:noescape
func reconI4SSE41(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, modes *[16]uint8) bool
//go:noescape
func reconI16SSE41(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, mode int) bool
//go:noescape
func reconUVSSE41(b *[yuvSize]byte, coeffs *[384]int16, codes uint32, mode int) bool
//go:noescape
func transformWHTSSE41(in *[16]int16, out *[384]int16)
//go:noescape
func loadEdgesSSE2(b *[yuvSize]byte, top *topSamples, tr, flags uint32)
//go:noescape
func storeMBRowsSSE2(b *[yuvSize]byte, top *topSamples, cy, cu, cv *byte, ys, uvs int)
func reconI4(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, modes *[16]uint8) {
switch {
case reconLevel >= cpuinfo.AVX2:
if reconI4AVX2(b, coeffs, bits, modes) {
return
}
case reconLevel >= cpuinfo.SSE41:
if reconI4SSE41(b, coeffs, bits, modes) {
return
}
}
reconI4Ref(b, coeffs, bits, modes)
}
func reconI16(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, mode int) {
switch {
case reconLevel >= cpuinfo.AVX2:
if reconI16AVX2(b, coeffs, bits, mode) {
return
}
case reconLevel >= cpuinfo.SSE41:
if reconI16SSE41(b, coeffs, bits, mode) {
return
}
}
reconI16Ref(b, coeffs, bits, mode)
}
func reconUV(b *[yuvSize]byte, coeffs *[384]int16, bits uint32, mode int) {
switch {
case reconLevel >= cpuinfo.AVX2:
if reconUVAVX2(b, coeffs, uvPlaneCodes(bits)|uvPlaneCodes(bits>>8)<<8, mode) {
return
}
case reconLevel >= cpuinfo.SSE41:
if reconUVSSE41(b, coeffs, uvPlaneCodes(bits)|uvPlaneCodes(bits>>8)<<8, mode) {
return
}
}
reconUVRef(b, coeffs, bits, mode)
}
// uvPlaneCodes maps the non-zero bits of one chroma plane (the low byte of
// bits) to the transform code the kernels apply to all four of its blocks,
// following doUVTransform: none (0) without any bit, the full transform (3)
// if any block has AC coefficients, otherwise the DC-only transform (1),
// which leaves a block with a zero DC coefficient unchanged just as the
// reference's skipping it does. The result repeats the code for the four
// blocks (0x00, 0x55 or 0xff).
func uvPlaneCodes(bits uint32) uint32 {
switch {
case bits&0xff == 0:
return 0
case bits&0xaa != 0:
return 0xff
}
return 0x55
}
func transformWHT(in *[16]int16, out *[384]int16) {
if reconLevel >= cpuinfo.SSE41 {
transformWHTSSE41(in, out)
return
}
transformWHTRef(in, out)
}
func loadEdges(b *[yuvSize]byte, top *topSamples, tr, flags uint32) {
if reconLevel >= cpuinfo.SSE41 {
loadEdgesSSE2(b, top, tr, flags)
return
}
loadEdgesRef(b, top, tr, flags)
}
// storeMBRows checks the cache geometry once and lets the kernel copy the
// rows; anything unusual goes to the reference (which panics on a cache
// that is too small).
func storeMBRows(b *[yuvSize]byte, top *topSamples, cy, cu, cv []byte, ys, uvs int) {
if reconLevel < cpuinfo.SSE41 || ys < 0 || uvs < 0 || ys > len(cy) || uvs > len(cu) ||
len(cy) < 15*ys+16 || len(cu) < 7*uvs+8 || len(cv) < 7*uvs+8 {
storeMBRowsRef(b, top, cy, cu, cv, ys, uvs)
return
}
storeMBRowsSSE2(b, top, &cy[0], &cu[0], &cv[0], ys, uvs)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
// Algorithm adapted from libwebp (BSD-3-Clause): src/dec/frame_dec.c (mt_method 2 worker split).
import (
"runtime"
"sync"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/internal/workers"
)
// The UseThreads pipeline (decodeFrameThreaded) has up to three stages:
//
// - the calling goroutine parses the coefficient tokens of batches of
// macroblock rows;
// - a reconstruction helper predicts, adds the residuals, filters and
// dithers each batch, and converts its rows to the output (libwebp's
// mt_method 2 split);
// - when the reconstruction helper is the slower stage (the parser has to
// wait for it), the conversion moves to a second, emit helper, which
// converts a batch while the next one is reconstructed into the other
// of two row caches.
//
// The first partition (the per-macroblock modes, which the token parser
// needs) is parsed ahead by whichever helper is idle: with SIMD kernels the
// token parser is the slowest stage, and moving the mode parsing off it
// shortens the critical path by about a fifth. A row whose modes no helper
// has parsed yet is parsed by the token parser itself, so the helpers only
// ever use idle time.
//
// Every stage runs the same operations in the same order as decodeFrame and
// the sink sees the same calls, so the output, and the rows delivered
// before an error or an early stop, are identical. The helpers come from
// the process-wide budget of internal/workers; without a free slot the frame
// is decoded on the calling goroutine (and without a second one, the
// conversion stays on the reconstruction helper).
//
// Every wait is a blocking channel receive. A stage that wakes a blocked
// one hands it the processor while the process has idle ones (see
// parked.handOff).
// mtSlots is the number of macroblock row batches in the UseThreads ring:
// the parser fills one batch while the helper reconstructs the other. It is
// also the number of row caches of the emit stage.
const mtSlots = 2
// mtBatchMBs is the number of macroblocks (rounded up to whole rows) handed
// from the parser to the helper goroutine at a time. Each hand-off may park
// and wake an OS thread (tens of microseconds, much more on some Linux VMs),
// so a batch must carry enough work, about a millisecond, to amortize it.
// Pictures with less than two batches are decoded without a helper.
// Variable for tests.
var mtBatchMBs = 512
// mtEmitWaits is the number of batches for which the parser must wait for
// the reconstruction helper before the conversion moves to an emit helper;
// 0 starts the emit helper with the first batch, a negative value never
// starts it. Variable for tests.
var mtEmitWaits = 2
// mtBatchRows returns the number of rows of the batch that starts at row y,
// for full batches of k rows. The first batches ramp up (1, 1, 2, 4, ...
// rows) so that the helper starts early, and the last ones ramp down (half
// of the remaining rows) so that the parser does not wait for a long last
// batch: the pipeline fills and drains in about one row instead of one
// batch, which matters for pictures of a few batches.
func (d *decoder) mtBatchRows(y, k int) int {
return min(k, max(1, y), max(1, (d.brMbY-y+1)/2))
}
// mtJob is a batch of parsed macroblock rows [y, y+n) handed to the
// reconstruction helper: row i is blocks[i*mbW:][:mbW]. A non-nil emit
// hands the conversion of this batch and the following ones to the emit
// helper.
type mtJob struct {
y, n int
blocks []mbBlock
emit *mtEmitter
}
// mtEmitter is the emit helper: it converts the batches of reconstructed
// rows [y, y+n) that the reconstruction helper leaves in the row cache
// slots[slot].
type mtEmitter struct {
task *workers.Task
jobs chan mtEmitJob // closed by its owner
free chan int // slots the emit helper has converted
parked parked // the emit helper waits for a batch
// owned is set when the reconstruction helper has received the
// emitter: it then closes jobs when it returns. Until then the parser
// does, after the reconstruction helper has returned.
owned bool
}
type mtEmitJob struct{ y, n, slot int }
// mtCache is one row cache of the emit stage: the extraRows rows the next
// batch's filter still modifies, then 16 rows per macroblock row of the
// batch (same strides as the decoder's own cache).
type mtCache struct{ y, u, v []byte }
// mtState is the state shared by the stages of decodeFrameThreaded.
type mtState struct {
jobs chan mtJob
free chan struct{}
stop atomic.Bool // set when a stage stops early: the others stop too
// The parser waits for a free batch, the reconstruction helper for a
// batch or a free row cache.
parserParked, reconParked parked
blocks []mbBlock // ring of parsed row batches
caches [mtSlots]mtCache
// Mode parsing: rows [0, modeNext) of the first partition are parsed,
// into modes (a ring of modeRows rows of macroblock modes; eof tells
// whether the partition was exhausted after the row). Any goroutine may
// parse the next row while holding modeMu; modeReady publishes
// modeNext, modeUsed the number of rows the token parser has consumed.
modeMu sync.Mutex
modeNext int
modeReady atomic.Int64
modeUsed atomic.Int64
modeRows int
modes []mbModes
eof []bool
procs int // GOMAXPROCS when the decode started (see parked.handOff)
}
// parked is set while a pipeline stage is blocked waiting for another
// stage.
//
// When a goroutine wakes a blocked one (a channel send) and keeps running,
// the runtime queues the woken goroutine in the waker's own next-to-run
// slot, from which other threads only take it after a back-off: the woken
// stage then starts tens of microseconds late on darwin, and hundreds on
// Linux (measured: a median of 160-440 us in Docker linux/arm64 with 4
// CPUs, against 7-9 us with handOff). The waker therefore yields once
// after waking a parked stage, so that the woken stage runs at once on
// this thread while the waker continues on another one (idle threads take
// it from the global run queue without the back-off). This is no wait:
// Gosched returns at once when nothing else is runnable.
type parked struct{ atomic.Bool }
// wait runs the blocking receive f with p set.
func (p *parked) wait(f func()) {
p.Store(true)
f()
p.Store(false)
}
// handOff is called after a send that may have woken the stage that p
// belongs to. procs is the decode's GOMAXPROCS: when about as many
// pipelines run as there are processors, none is idle to take the waker
// over, and the yield would only add a context switch (see
// workers.SpareProcs).
func (p *parked) handOff(procs int) {
if p.Load() && workers.SpareProcs(procs) {
runtime.Gosched()
}
}
// testHookTokenRow, if set (tests), runs before the token parser parses a
// row with UseThreads.
var testHookTokenRow func(d *decoder, mbY int)
// decodeFrameThreaded is the UseThreads variant of decodeFrame (see the
// comment at the top of the file). When the process-wide helper budget is
// exhausted the frame is decoded by decodeFrame on the calling goroutine.
func (d *decoder) decodeFrameThreaded() error {
k := max(1, (mtBatchMBs+d.mbW-1)/d.mbW) // rows per batch
if d.brMbY < 2*k {
return d.decodeFrame() // nothing to overlap
}
if d.mt == nil {
d.mt = new(mtState)
}
m := d.mt
m.init(d.mbW, k)
m.procs = runtime.GOMAXPROCS(0)
workers.BeginHandOffs()
defer workers.EndHandOffs()
t := workers.Spawn(d.reconBatches)
if t == nil {
return d.decodeFrame()
}
var e *mtEmitter // the emit helper, if started
sendEmit := false
joined := false
join := func() {
close(m.jobs)
t.Panicked()
if e != nil {
if !e.owned {
close(e.jobs)
}
e.task.Panicked()
}
joined = true
}
defer func() {
if !joined { // the parser panicked: stop and join the helpers, keep the panic
m.stop.Store(true)
join()
}
}()
batch := k * d.mbW
var perr error
inFlight, slot, waits := 0, 0, 0
parse:
for y := 0; y < d.brMbY && perr == nil && !m.stop.Load(); {
if e == nil && mtEmitWaits >= 0 && waits >= mtEmitWaits {
// The reconstruction helper is the slower stage: move the
// conversion to a helper of its own, if the budget allows.
if e = d.startEmitter(); e != nil {
sendEmit = true
} else {
waits = -1 << 30 // do not try again
}
}
if inFlight == mtSlots {
// Wait for the oldest batch; the helper may also have returned
// (error, early stop or panic) without freeing it.
select {
case <-m.free:
default:
if y >= 2*k {
// Past the first, short batches, which are mostly
// waiting for the helper to wake up.
waits++
}
done := false
m.parserParked.wait(func() {
select {
case <-m.free:
case <-t.Done():
done = true
}
})
if done {
break parse
}
}
inFlight--
}
blocks := m.blocks[slot*batch:][:batch]
rows := d.mtBatchRows(y, k)
n := 0
for ; n < rows && !m.stop.Load(); n++ {
if perr = d.parseTokenRow(y+n, blocks[n*d.mbW:][:d.mbW]); perr != nil {
break
}
}
if n == 0 {
break
}
// The rows parsed before an error are still emitted, as in
// decodeFrame. inFlight < mtSlots, so the send does not block.
j := mtJob{y: y, n: n, blocks: blocks}
if sendEmit {
j.emit = e
}
select {
case m.jobs <- j:
sendEmit = false
m.reconParked.handOff(m.procs)
case <-t.Done():
break parse
}
inFlight++
slot = (slot + 1) % mtSlots
y += n
}
join()
// The reconstruction helper converts the rows before those of the
// emit helper, so its error (or panic) comes first; either comes from
// an earlier row than perr.
if err := t.Wait(); err != nil {
return err
}
if e != nil {
if err := e.task.Wait(); err != nil {
return err
}
}
if perr != nil && d.rowsOut < d.sink.NeedRows() {
// decodeFrame would have stopped before parsing the broken row
// if the sink needed no more rows.
return perr
}
return nil
}
// init sizes and resets the pipeline state for a frame of mbW macroblock
// columns and batches of k rows.
func (m *mtState) init(mbW, k int) {
m.jobs = make(chan mtJob, mtSlots)
m.free = make(chan struct{}, mtSlots)
m.stop.Store(false)
if n := mtSlots * k * mbW; cap(m.blocks) < n {
m.blocks = make([]mbBlock, n)
} else {
m.blocks = m.blocks[:n]
}
// The token parser consumes about a batch of mode rows while the
// helpers work on the previous one; two batches let an idle helper
// keep ahead of it.
m.modeRows = 2*k + 2
if n := m.modeRows * mbW; cap(m.modes) < n {
m.modes = make([]mbModes, n)
} else {
m.modes = m.modes[:n]
}
if cap(m.eof) < m.modeRows {
m.eof = make([]bool, m.modeRows)
}
m.eof = m.eof[:m.modeRows]
m.modeNext = 0
m.modeReady.Store(0)
m.modeUsed.Store(0)
}
// parseModeRow parses the modes of macroblock row y into the mode ring.
// The caller holds modeMu.
func (d *decoder) parseModeRow(y int) {
m := d.mt
r := y % m.modeRows
modes := m.modes[r*d.mbW:][:d.mbW]
d.intraL = [4]uint8{}
for x := range modes {
d.parseIntraMode(x, &modes[x])
}
m.eof[r] = d.br.eof
m.modeNext = y + 1
m.modeReady.Store(int64(y + 1))
}
// parseModesAhead parses the modes of the next macroblock row, unless
// another goroutine is parsing modes, the ring is full or the frame is
// done; it reports whether it parsed a row. Idle helpers call it.
func (d *decoder) parseModesAhead() bool {
m := d.mt
if !m.modeMu.TryLock() {
return false
}
defer m.modeMu.Unlock()
y := m.modeNext
if y >= d.brMbY || y >= int(m.modeUsed.Load())+m.modeRows || m.stop.Load() {
return false
}
d.parseModeRow(y)
return true
}
// parseTokenRow parses the coefficients of macroblock row mbY into blocks,
// with the modes from the mode ring (parsing them first if no helper has).
func (d *decoder) parseTokenRow(mbY int, blocks []mbBlock) error {
m := d.mt
if testHookTokenRow != nil {
testHookTokenRow(d, mbY)
}
if int(m.modeReady.Load()) <= mbY {
m.modeMu.Lock()
for m.modeNext <= mbY {
d.parseModeRow(m.modeNext)
}
m.modeMu.Unlock()
}
r := mbY % m.modeRows
modes := m.modes[r*d.mbW:][:d.mbW]
tokenBR := &d.parts[mbY&d.numPartsMinusOne]
d.nzL, d.nzDCL = 0, 0
for mbX := range blocks {
blk := &blocks[mbX]
blk.mbModes = modes[mbX]
if err := d.parseTokens(mbX, blk, tokenBR); err != nil {
return err
}
}
eof := m.eof[r]
m.modeUsed.Store(int64(mbY + 1)) // the ring row may be reused
if eof {
return status.NotEnoughData("premature end-of-partition0 encountered")
}
return nil
}
// nextJob receives the next value from jobs. While none is ready, the
// caller (an idle helper, p) parses modes ahead for the token parser.
func nextJob[T any](d *decoder, jobs <-chan T, p *parked) (j T, ok bool) {
for {
select {
case j, ok = <-jobs:
return j, ok
default:
}
if !d.parseModesAhead() {
p.wait(func() { j, ok = <-jobs })
return j, ok
}
}
}
// reconBatches is the reconstruction helper of decodeFrameThreaded. It
// returns at the first error, or when the sink needs no more rows, without
// freeing the batch it was working on; stop tells the parser to stop early
// (and the helper, if the parser panicked).
func (d *decoder) reconBatches() error {
m := d.mt
var e *mtEmitter
cacheY, cacheU, cacheV := d.cacheY, d.cacheU, d.cacheV
done := false // all batches reconstructed: the emit helper finishes its own
defer func() {
if !done {
m.stop.Store(true)
}
if e != nil {
close(e.jobs)
d.cacheY, d.cacheU, d.cacheV = cacheY, cacheU, cacheV
}
}()
// carry holds the extraRows rows the next batch's filter still
// modifies (on top of the last row cache used).
carry := mtCache{cacheY, cacheU, cacheV}
for {
j, ok := nextJob(d, m.jobs, &m.reconParked)
if !ok {
done = true
return nil
}
if j.emit != nil {
e = j.emit
e.owned = true
}
if e == nil {
for i := 0; i < j.n; i++ {
if d.rowsOut >= d.sink.NeedRows() || m.stop.Load() {
return nil
}
d.reconRow(j.y+i, j.blocks[i*d.mbW:][:d.mbW])
if err := d.finishRow(j.y + i); err != nil {
return err
}
}
m.free <- struct{}{} // never blocks: at most mtSlots batches are in flight
m.parserParked.handOff(m.procs)
continue
}
s := -1
m.reconParked.wait(func() {
select {
case s = <-e.free:
case <-e.task.Done():
}
})
if s < 0 {
return nil // stopped early (stop is set) or panicked
}
c := &m.caches[s]
d.cacheY, d.cacheU, d.cacheV = c.y, c.u, c.v
extra := d.extraRows
copy(c.y[:extra*d.cacheYStride], carry.y)
copy(c.u[:extra/2*d.cacheUVStride], carry.u)
copy(c.v[:extra/2*d.cacheUVStride], carry.v)
for i := 0; i < j.n; i++ {
if m.stop.Load() {
return nil
}
d.cacheYOff = (extra + 16*i) * d.cacheYStride
d.cacheUVOff = (extra/2 + 8*i) * d.cacheUVStride
d.reconRow(j.y+i, j.blocks[i*d.mbW:][:d.mbW])
}
m.free <- struct{}{}
m.parserParked.handOff(m.procs)
carry = mtCache{c.y[16*j.n*d.cacheYStride:], c.u[8*j.n*d.cacheUVStride:], c.v[8*j.n*d.cacheUVStride:]}
e.jobs <- mtEmitJob{y: j.y, n: j.n, slot: s} // never blocks: the slot was free
e.parked.handOff(m.procs)
}
}
// startEmitter starts the emit helper, if the budget allows. It owns the
// output (sink, alpha, rowsOut, upsampling state) from the first batch it
// receives on.
func (d *decoder) startEmitter() *mtEmitter {
m := d.mt
k := len(m.blocks) / mtSlots / d.mbW
extra := d.extraRows
for i := range m.caches {
c := &m.caches[i]
c.y = grow(c.y, (extra+16*k)*d.cacheYStride)
c.u = grow(c.u, (extra/2+8*k)*d.cacheUVStride)
c.v = grow(c.v, (extra/2+8*k)*d.cacheUVStride)
}
e := &mtEmitter{jobs: make(chan mtEmitJob, mtSlots), free: make(chan int, mtSlots)}
for i := range mtSlots {
e.free <- i
}
if e.task = workers.Spawn(func() error { return d.emitBatches(e) }); e.task == nil {
return nil
}
return e
}
// emitBatches is the emit helper: it converts the rows of each batch as
// finishRow does.
func (d *decoder) emitBatches(e *mtEmitter) error {
m := d.mt
defer m.stop.Store(true)
for {
j, ok := nextJob(d, e.jobs, &e.parked)
if !ok {
return nil
}
c := &m.caches[j.slot]
for i := 0; i < j.n; i++ {
if d.rowsOut >= d.sink.NeedRows() || m.stop.Load() {
return nil
}
yo, uvo := 16*i*d.cacheYStride, 8*i*d.cacheUVStride
if err := d.emitRow(j.y+i, c.y[yo:], c.u[uvo:], c.v[uvo:]); err != nil {
return err
}
}
e.free <- j.slot // never blocks
m.reconParked.handOff(m.procs)
}
}
// parseRow parses the modes and coefficients of one macroblock row into
// blocks (benchmarks).
func (d *decoder) parseRow(mbY int, blocks []mbBlock) error {
tokenBR := &d.parts[mbY&d.numPartsMinusOne]
d.startParseRow()
for mbX := range blocks {
if err := d.parseMB(mbX, &blocks[mbX], tokenBR); err != nil {
return err
}
}
if d.br.eof {
return status.NotEnoughData("premature end-of-partition0 encountered")
}
return nil
}
// reconRow reconstructs, filters and dithers a parsed macroblock row into
// the row cache.
func (d *decoder) reconRow(mbY int, blocks []mbBlock) {
d.initRowEdges(mbY)
for mbX := range blocks {
d.reconMB(mbX, mbY, &blocks[mbX])
}
if d.dither {
d.ditherCurrentRow()
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8
import (
"encoding/binary"
"math/bits"
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
)
// Algorithm adapted from libwebp (BSD-3-Clause): dsp/yuv.h (14-bit fixed
// point YUV->RGB), dsp/upsampling.c (fancy upsampler) and dsp/yuv.c
// (point-sampling row converter).
// yuvLevel selects the x86 SIMD level of the row converters
// (yuv_amd64.go); tests lower it to cover every level. Other builds ignore
// it.
var yuvLevel = cpuinfo.Max
// yuvVBMI enables the AVX-512 fancy upsampler, which needs AVX512-VBMI
// (VPERMB, VPERMI2B), at yuvLevel AVX512; tests also run that level
// without it. Other builds ignore it.
var yuvVBMI = cpuinfo.X86.HasAVX512VBMI
// clipY is libwebp's VP8Clip8 for a 14-bit fixed point value v:
// clamp(v >> 6, 0, 255). Out-of-range values are rare, so the branch is
// cheaper than unconditional clamping.
func clipY(v int) uint32 {
v >>= 6
if uint(v) > 255 {
v = int(^uint(v>>(bits.UintSize-1)) & 255) // 0 if v < 0, else 255
}
return uint32(v)
}
// yuvTables holds libwebp's VP8YuvToRgb terms per sample value:
// y = MultHi(y,19077), vr = MultHi(v,26149)-14234,
// ub = MultHi(u,33050)-17685, ug = -MultHi(u,6419),
// vg = -MultHi(v,13320)+8708.
type yuvTables struct {
y, vr, ub, ug, vg [256]int32
}
// yuvTab is a pointer variable (not a constant address) so that hot loops
// keep it in a register instead of rematerializing table addresses.
var yuvTab = func() *yuvTables {
t := new(yuvTables)
for i := 0; i < 256; i++ {
t.y[i] = int32((i * 19077) >> 8)
t.vr[i] = int32((i*26149)>>8 - 14234)
t.ub[i] = int32((i*33050)>>8 - 17685)
t.ug[i] = int32(-((i * 6419) >> 8))
t.vg[i] = int32(-((i * 13320) >> 8) + 8708)
}
return t
}()
// yuvPix converts one pixel to packed little-endian R,G,B,A=0 using
// libwebp's 14-bit fixed point VP8YuvToRgb.
func yuvPix(t *yuvTables, y, u, v uint8) uint32 {
yy := int(t.y[y])
return clipY(yy+int(t.vr[v])) |
clipY(yy+int(t.ug[u]+t.vg[v]))<<8 |
clipY(yy+int(t.ub[u]))<<16
}
// opaque2 is the alpha bytes of two packed RGBA pixels. It is a variable
// on purpose: with a constant the compiler splits the 64-bit pixel store
// into byte stores.
var opaque2 uint64 = 0xff000000ff000000
// upsamplePairGo converts a pair of luma rows sharing the chroma rows
// topU/V (above) and curU/V (below) with libwebp's fancy upsampler
// (UpsampleRgbaLinePair). botY may be nil when only the top row is needed.
// uvT and uvB are scratch rows of at least w entries. topA and botA are the
// alpha rows of the two output rows, or nil for opaque output.
//
// This is the portable reference; upsamplePair (yuv_arm64.go,
// yuv_amd64.go, yuv_generic.go) is the entry point used by the decoder.
func upsamplePairGo(topY, botY, topU, topV, curU, curV, topDst, botDst, topA, botA []byte, uvT, uvB []uint32, w int) {
if botY == nil {
upsampleUV(topU, topV, curU, curV, uvT, nil, w)
convertRow(topY, uvT, topA, topDst, w)
return
}
upsampleUV(topU, topV, curU, curV, uvT, uvB, w)
convertRow(topY, uvT, topA, topDst, w)
convertRow(botY, uvB, botA, botDst, w)
}
// upsampleUV computes the full resolution chroma (packed u | v<<16) of the
// top and, if uvB is not nil, bottom luma rows lying between chroma rows
// top and cur. This is the chroma part of libwebp's UPSAMPLE_FUNC.
func upsampleUV(topU, topV, curU, curV []byte, uvT, uvB []uint32, w int) {
uvW := (w + 1) >> 1
topU, topV, curU, curV = topU[:uvW], topV[:uvW], curU[:uvW], curV[:uvW]
uvT = uvT[:w]
tl := uint32(topU[0]) | uint32(topV[0])<<16 // top-left sample
l := uint32(curU[0]) | uint32(curV[0])<<16 // left sample
last := (w - 1) >> 1
uvT[0] = (3*tl + l + 0x00020002) >> 2
if uvB != nil {
uvB = uvB[:w]
uvB[0] = (3*l + tl + 0x00020002) >> 2
for x := 1; x <= last; x++ {
t := uint32(topU[x]) | uint32(topV[x])<<16 // top sample
c := uint32(curU[x]) | uint32(curV[x])<<16 // sample
avg := tl + t + l + c + 0x00080008
diag12 := (avg + 2*(t+l)) >> 3
diag03 := (avg + 2*(tl+c)) >> 3
ut := (*[2]uint32)(uvT[2*x-1:])
ut[0] = (diag12 + tl) >> 1
ut[1] = (diag03 + t) >> 1
ub := (*[2]uint32)(uvB[2*x-1:])
ub[0] = (diag03 + l) >> 1
ub[1] = (diag12 + c) >> 1
tl, l = t, c
}
if w&1 == 0 {
uvT[w-1] = (3*tl + l + 0x00020002) >> 2
uvB[w-1] = (3*l + tl + 0x00020002) >> 2
}
return
}
for x := 1; x <= last; x++ {
t := uint32(topU[x]) | uint32(topV[x])<<16
c := uint32(curU[x]) | uint32(curV[x])<<16
avg := tl + t + l + c + 0x00080008
ut := (*[2]uint32)(uvT[2*x-1:])
ut[0] = (((avg + 2*(t+l)) >> 3) + tl) >> 1
ut[1] = (((avg + 2*(tl+c)) >> 3) + t) >> 1
tl, l = t, c
}
if w&1 == 0 {
uvT[w-1] = (3*tl + l + 0x00020002) >> 2
}
}
// convertRow converts a luma row and its packed full resolution chroma to
// RGBA. as is the alpha row, or nil for opaque output.
func convertRow(ys []byte, uv []uint32, as, dst []byte, w int) {
ys = ys[:w]
uv = uv[:w]
dst = dst[:4*w]
if as != nil {
as = as[:w]
}
a2 := opaque2
t := yuvTab
x := 0
for ; x+1 < w; x += 2 {
if as != nil {
a2 = uint64(as[x])<<24 | uint64(as[x+1])<<56
}
// Two pixels of yuvPix, written out so that it gets inlined.
y2 := (*[2]byte)(ys[x:])
c2 := (*[2]uint32)(uv[x:])
u0, v0 := uint8(c2[0]), uint8(c2[0]>>16)
u1, v1 := uint8(c2[1]), uint8(c2[1]>>16)
y0 := int(t.y[y2[0]])
y1 := int(t.y[y2[1]])
pa := clipY(y0+int(t.vr[v0])) | clipY(y0+int(t.ug[u0]+t.vg[v0]))<<8 | clipY(y0+int(t.ub[u0]))<<16
pb := clipY(y1+int(t.vr[v1])) | clipY(y1+int(t.ug[u1]+t.vg[v1]))<<8 | clipY(y1+int(t.ub[u1]))<<16
binary.LittleEndian.PutUint64(dst[4*x:], uint64(pa)|uint64(pb)<<32|a2)
}
if x < w {
c := uv[x]
a := uint32(0xff000000)
if as != nil {
a = uint32(as[x]) << 24
}
binary.LittleEndian.PutUint32(dst[4*x:], yuvPix(t, ys[x], uint8(c), uint8(c>>16))|a)
}
}
// edgePixel converts pixel x of a fancy-upsampled row whose chroma is
// (3*near + far + 2) >> 2 (upsampleUV's first and last pixels). The SIMD
// wrappers use it for the pixels their kernels leave out.
func edgePixel(dst []byte, x int, ys, as []byte, nu, nv, fu, fv byte) {
u := (3*uint32(nu) + uint32(fu) + 2) >> 2
v := (3*uint32(nv) + uint32(fv) + 2) >> 2
a := uint32(0xff000000)
if as != nil {
a = uint32(as[x]) << 24
}
binary.LittleEndian.PutUint32(dst[4*x:], yuvPix(yuvTab, ys[x], uint8(u), uint8(v))|a)
}
// sampleRowGo converts one luma row using nearest (point-sampled) chroma.
// as is the alpha row, or nil for opaque output. This is the portable
// reference; sampleRow is the entry point used by the decoder.
func sampleRowGo(ys, us, vs, as, dst []byte, w int) {
ys = ys[:w]
dst = dst[:4*w]
uvW := (w + 1) >> 1
us, vs = us[:uvW], vs[:uvW]
if as != nil {
as = as[:w]
}
a2 := opaque2
t := yuvTab
for x := 0; x+1 < w; x += 2 {
if as != nil {
a2 = uint64(as[x])<<24 | uint64(as[x+1])<<56
}
u, v := us[x>>1], vs[x>>1]
y2 := (*[2]byte)(ys[x:])
pa := yuvPix(t, y2[0], u, v)
pb := yuvPix(t, y2[1], u, v)
binary.LittleEndian.PutUint64(dst[4*x:], uint64(pa)|uint64(pb)<<32|a2)
}
if w&1 != 0 {
a := uint32(0xff000000)
if as != nil {
a = uint32(as[w-1]) << 24
}
binary.LittleEndian.PutUint32(dst[4*w-4:], yuvPix(t, ys[w-1], us[uvW-1], vs[uvW-1])|a)
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8
import (
"encoding/binary"
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
)
// SSE4.1, AVX2 and AVX-512 row converters (yuv_amd64.s), selected by
// yuvLevel (and yuvVBMI, for the AVX-512 fancy upsampler). The wrappers
// below check every bound and handle the pixels the kernels leave out; the
// kernels never access memory outside the slices they are given.
// upsampleRowsSSE41 and upsampleRowsAVX2 convert output pixels
// [1, 2*uvW-1) of the top row and, if botY is not nil, of the bottom row
// with the fancy upsampler. They read topY/botY/topA/botA[1 : 2*uvW-1] and
// topU/topV/curU/curV[:uvW], write topDst/botDst[4 : 4*(2*uvW-1)] and need
// uvW >= 17. topA and botA may be nil (opaque).
//
//go:noescape
func upsampleRowsSSE41(topY, botY, topU, topV, curU, curV, topDst, botDst, topA, botA *byte, uvW int)
//go:noescape
func upsampleRowsAVX2(topY, botY, topU, topV, curU, curV, topDst, botDst, topA, botA *byte, uvW int)
// upsampleRowsAVX512 is upsampleRowsAVX2 for uvW >= 33, at the AVX512
// level with AVX512-VBMI. It runs on every such CPU but has only been
// measured on Zen 5 (EPYC 4345P, full-width 512-bit units): 182 ns per pair
// of 1024-pixel rows against 358 ns for upsampleRowsAVX2 (-49%), and 6.3-7.0%
// off a lossy+alpha 3000x2000 DecodeInto. It has not been measured on Zen
// 4, which runs a 512-bit op as two 256-bit halves, nor on Intel CPUs.
//
//go:noescape
func upsampleRowsAVX512(topY, botY, topU, topV, curU, curV, topDst, botDst, topA, botA *byte, uvW int)
// sampleRowSSE41 converts pixels [0, w) with point-sampled chroma, w even
// and >= 16; sampleRowAVX2 needs w even and >= 32. They read y[:w], a[:w]
// (a may be nil: opaque), u/v[:w/2] and write dst[:4*w].
//
//go:noescape
func sampleRowSSE41(y, u, v, a, dst *byte, w int)
//go:noescape
func sampleRowAVX2(y, u, v, a, dst *byte, w int)
// upsamplePair converts a pair of luma rows with the fancy upsampler; see
// upsamplePairGo, which it matches bit for bit. uvT and uvB are only used
// by the Go code (narrow rows, no SIMD).
func upsamplePair(topY, botY, topU, topV, curU, curV, topDst, botDst, topA, botA []byte, uvT, uvB []uint32, w int) {
uvW := (w + 1) >> 1
if uvW < 17 || yuvLevel < cpuinfo.SSE41 {
upsamplePairGo(topY, botY, topU, topV, curU, curV, topDst, botDst, topA, botA, uvT, uvB, w)
return
}
topY = topY[:w]
topDst = topDst[:4*w]
topU, topV, curU, curV = topU[:uvW], topV[:uvW], curU[:uvW], curV[:uvW]
var pBotY, pBotDst, pTopA, pBotA *byte
if topA != nil {
topA = topA[:w]
pTopA = &topA[0]
}
if botY != nil {
botY = botY[:w]
botDst = botDst[:4*w]
pBotY, pBotDst = &botY[0], &botDst[0]
if botA != nil {
botA = botA[:w]
pBotA = &botA[0]
}
}
if uvW >= 33 && yuvLevel >= cpuinfo.AVX512 && yuvVBMI {
upsampleRowsAVX512(&topY[0], pBotY, &topU[0], &topV[0], &curU[0], &curV[0], &topDst[0], pBotDst, pTopA, pBotA, uvW)
} else if yuvLevel >= cpuinfo.AVX2 {
upsampleRowsAVX2(&topY[0], pBotY, &topU[0], &topV[0], &curU[0], &curV[0], &topDst[0], pBotDst, pTopA, pBotA, uvW)
} else {
upsampleRowsSSE41(&topY[0], pBotY, &topU[0], &topV[0], &curU[0], &curV[0], &topDst[0], pBotDst, pTopA, pBotA, uvW)
}
// The first pixel and, for even widths, the last one take their chroma
// from a single column: (3*near + far + 2) >> 2.
edgePixel(topDst, 0, topY, topA, topU[0], topV[0], curU[0], curV[0])
if w&1 == 0 {
edgePixel(topDst, w-1, topY, topA, topU[uvW-1], topV[uvW-1], curU[uvW-1], curV[uvW-1])
}
if botY != nil {
edgePixel(botDst, 0, botY, botA, curU[0], curV[0], topU[0], topV[0])
if w&1 == 0 {
edgePixel(botDst, w-1, botY, botA, curU[uvW-1], curV[uvW-1], topU[uvW-1], topV[uvW-1])
}
}
}
// sampleRow converts one luma row with point-sampled chroma; see
// sampleRowGo, which it matches bit for bit.
func sampleRow(ys, us, vs, as, dst []byte, w int) {
if w < 16 || yuvLevel < cpuinfo.SSE41 {
sampleRowGo(ys, us, vs, as, dst, w)
return
}
ys = ys[:w]
dst = dst[:4*w]
uvW := (w + 1) >> 1
us, vs = us[:uvW], vs[:uvW]
var pa *byte
if as != nil {
as = as[:w]
pa = &as[0]
}
if w >= 32 && yuvLevel >= cpuinfo.AVX2 {
sampleRowAVX2(&ys[0], &us[0], &vs[0], pa, &dst[0], w&^1)
} else {
sampleRowSSE41(&ys[0], &us[0], &vs[0], pa, &dst[0], w&^1)
}
if w&1 != 0 {
a := uint32(0xff000000)
if as != nil {
a = uint32(as[w-1]) << 24
}
binary.LittleEndian.PutUint32(dst[4*w-4:], yuvPix(yuvTab, ys[w-1], us[uvW-1], vs[uvW-1])|a)
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"sync"
"github.com/kolesa-team/go-webp/v2/internal/workers"
)
// Analysis pass: collects per-macroblock susceptibility ("alpha") and assigns
// segments with a simplified k-means.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
maxItersKMeans = 6
maxAlphaValue = 255 // 8b of precision for susceptibilities.
alphaScale = 2 * maxAlphaValue // scaling factor for alpha.
defaultAlpha = -1
)
func (e *encoder) smoothSegmentMap() {
w, h := e.mbW, e.mbH
const majorityCnt3x3 = 5
tmp := bytePool.Get(w * h) // only the inner macroblocks are written and read
defer bytePool.Put(tmp)
for y := 1; y < h-1; y++ {
for x := 1; x < w-1; x++ {
var cnt [numMBSegments]int
i := x + w*y
mb := e.mbInfo
majority := mb[i].segment
cnt[mb[i-w-1].segment&3]++
cnt[mb[i-w].segment&3]++
cnt[mb[i-w+1].segment&3]++
cnt[mb[i-1].segment&3]++
cnt[mb[i+1].segment&3]++
cnt[mb[i+w-1].segment&3]++
cnt[mb[i+w].segment&3]++
cnt[mb[i+w+1].segment&3]++
for n := 0; n < numMBSegments; n++ {
if cnt[n] >= majorityCnt3x3 {
majority = uint8(n)
break
}
}
tmp[i] = majority
}
}
for y := 1; y < h-1; y++ {
for x := 1; x < w-1; x++ {
e.mbInfo[x+w*y].segment = tmp[x+y*w]
}
}
}
func (e *encoder) setSegmentAlphas(centers *[numMBSegments]int, mid int) {
nb := e.numSegments
mn, mx := centers[0], centers[0]
if nb > 1 {
for n := 0; n < nb; n++ {
mn = min(mn, centers[n])
mx = max(mx, centers[n])
}
}
if mx == mn {
mx = mn + 1
}
for n := 0; n < nb; n++ {
alpha := 255 * (centers[n] - mid) / (mx - mn)
beta := 255 * (centers[n] - mn) / (mx - mn)
e.dqm[n].alpha = clipInt(alpha, -127, 127)
e.dqm[n].beta = clipInt(beta, 0, 255)
}
}
func (e *encoder) assignSegments(alphas *[maxAlphaValue + 1]int) {
nb := min(e.numSegments, numMBSegments)
var centers [numMBSegments]int
weightedAverage := 0
var segMap [maxAlphaValue + 1]int
var accum, distAccum [numMBSegments]int
n := 0
for n = 0; n <= maxAlphaValue && alphas[n] == 0; n++ {
}
minA := n
for n = maxAlphaValue; n > minA && alphas[n] == 0; n-- {
}
maxA := n
rangeA := maxA - minA
for k, n := 0, 1; k < nb; k, n = k+1, n+2 {
centers[k] = minA + (n*rangeA)/(2*nb)
}
for k := 0; k < maxItersKMeans; k++ {
for n := 0; n < nb; n++ {
accum[n] = 0
distAccum[n] = 0
}
n := 0
for a := minA; a <= maxA; a++ {
if alphas[a] != 0 {
for n+1 < nb && absInt(a-centers[n+1]) < absInt(a-centers[n]) {
n++
}
segMap[a] = n
distAccum[n] += a * alphas[a]
accum[n] += alphas[a]
}
}
displaced := 0
weightedAverage = 0
totalWeight := 0
for n := 0; n < nb; n++ {
if accum[n] != 0 {
newCenter := (distAccum[n] + accum[n]/2) / accum[n]
displaced += absInt(centers[n] - newCenter)
centers[n] = newCenter
weightedAverage += newCenter * accum[n]
totalWeight += accum[n]
}
}
weightedAverage = (weightedAverage + totalWeight/2) / totalWeight
if displaced < 5 {
break
}
}
for i := range e.mbInfo {
mb := &e.mbInfo[i]
a := int(mb.alpha)
mb.segment = uint8(segMap[a])
mb.alpha = uint8(centers[segMap[a]])
}
if nb > 1 && e.cfg.Preprocessing&1 != 0 {
e.smoothSegmentMap()
}
e.setSegmentAlphas(¢ers, weightedAverage)
}
func (it *iterator) mbAnalyzeBestIntra16Mode() int {
bestAlpha := defaultAlpha
bestMode := 0
it.makeLuma16Preds()
for mode := 0; mode < 2; mode++ {
maxValue, lastNonZero := collectHistogram(it.yuvIn[yOff:], it.yuvP[vp8I16ModeOffsets[mode]:], &tabY16)
alpha := 0
if maxValue > 1 {
alpha = alphaScale * lastNonZero / maxValue
}
if alpha > bestAlpha {
bestAlpha = alpha
bestMode = mode
}
}
it.setIntra16Mode(bestMode)
return bestAlpha
}
func (it *iterator) fastMBAnalyze() int {
q := 0 // a NaN quality converts to 0, as libwebp's (int) cast on arm64
if qf := it.enc.cfg.Quality; qf == qf {
q = int(qf)
}
threshold := uint32(8 + (17-8)*q/100)
var m, m2 uint32
for k := 0; k < 16; k += 4 {
ref := it.yuvIn[yOff+k*bps:]
for b := 0; b < 4; b++ {
var avg uint32
for y := 0; y < 4; y++ {
r := ref[y*bps+b*4 : y*bps+b*4+4]
avg += uint32(r[0]) + uint32(r[1]) + uint32(r[2]) + uint32(r[3])
}
m += avg
m2 += avg * avg
}
}
if threshold*m2 < m*m {
it.setIntra16Mode(0) // DC16
} else {
var modes [16]uint8 // DC4
it.setIntra4Mode(&modes)
}
return 0
}
func (it *iterator) mbAnalyzeBestUVMode() int {
bestAlpha := defaultAlpha
smallestAlpha := 0
bestMode := 0
it.makeChroma8Preds()
for mode := 0; mode < 2; mode++ {
maxValue, lastNonZero := collectHistogram(it.yuvIn[uOff:], it.yuvP[vp8UVModeOffsets[mode]:], &tabUV)
alpha := 0
if maxValue > 1 {
alpha = alphaScale * lastNonZero / maxValue
}
if alpha > bestAlpha {
bestAlpha = alpha
}
if mode == 0 || alpha < smallestAlpha {
smallestAlpha = alpha
bestMode = mode
}
}
it.mb().uvMode = uint8(bestMode)
return bestAlpha
}
// segmentJob holds the analysis results of a band of macroblock rows.
type segmentJob struct {
alphas [maxAlphaValue + 1]int
alpha, uvAlpha int
startRow, nRows int
}
// run analyzes the job's rows with it (an iterator in analysis mode). Every
// macroblock is analyzed from the source samples only, so bands are
// independent of each other and of the iterator used.
func (j *segmentJob) run(it *iterator) {
e := it.enc
j.alphas = [maxAlphaValue + 1]int{}
j.alpha, j.uvAlpha = 0, 0
it.setRow(j.startRow)
it.setCountDown(j.nRows * e.mbW)
if it.countDown <= 0 {
return
}
for {
if it.x == 0 && e.cfg.Interrupt != nil && e.pollInterrupt() {
return
}
it.importMB()
mb := it.mb()
it.setIntra16Mode(0)
mb.skip = false
mb.segment = 0
var bestAlpha int
if e.method <= 1 {
bestAlpha = it.fastMBAnalyze()
} else {
bestAlpha = it.mbAnalyzeBestIntra16Mode()
}
bestUVAlpha := it.mbAnalyzeBestUVMode()
bestAlpha = (3*bestAlpha + bestUVAlpha + 2) >> 2
bestAlpha = clipInt(maxAlphaValue-bestAlpha, 0, maxAlphaValue)
j.alphas[bestAlpha]++
mb.alpha = uint8(bestAlpha)
j.alpha += bestAlpha
j.uvAlpha += bestUVAlpha
if !it.next() {
break
}
}
}
const (
// maxAnalysisBands bounds the number of row bands the analysis pass is
// split into with ThreadLevel.
maxAnalysisBands = 8
// minBandMBs is the smallest band worth handing to a helper goroutine,
// about 0.5 ms of analysis: methods 0-1 analyze a macroblock in about
// 1 us, the others in about 2.7 us (Apple M5, source.jpg).
minBandMBs = 192
minBandMBsFast = 512
)
var sideIteratorPool = sync.Pool{New: func() any { return new(iterator) }}
// testHookAnalysisBand, if set (tests only), is called before a band is
// analyzed, on the goroutine that analyzes it.
var testHookAnalysisBand func(band int)
// analysisBands returns the number of row bands of the analysis pass.
func (e *encoder) analysisBands() int {
if !e.cfg.ThreadLevel {
return 1
}
minMBs := minBandMBs
if e.method <= 1 {
minMBs = minBandMBsFast
}
return max(1, min(maxAnalysisBands, e.mbH, e.mbW*e.mbH/minMBs))
}
// pollInterrupt polls Config.Interrupt (not nil) from an analysis band,
// about once per macroblock row. Once it has fired, every band stops
// without polling it again.
func (e *encoder) pollInterrupt() bool {
if e.stopped.Load() {
return true
}
if e.cfg.Interrupt() {
e.stopped.Store(true)
return true
}
return false
}
// analyze decides the segmentation and complexity, and assigns a first
// guess of the prediction modes. It reports whether Config.Interrupt fired
// (the analysis is then incomplete and the encode must stop).
func (e *encoder) analyze() bool {
doSegments := e.cfg.EmulateJPEGSize || e.numSegments > 1 || e.method <= 1
if !doSegments {
for i := range e.mbInfo {
e.mbInfo[i] = mbInfo{typ: 1}
}
e.dqm[0].alpha = 0
e.dqm[0].beta = 0
e.alpha = 0
e.uvAlpha = 0
return false
}
e.stopped.Store(false)
e.analyzeInBands(e.analysisBands())
return e.stopped.Load()
}
// analyzeInBands runs the analysis pass in nb (1..min(maxAnalysisBands,
// mbH)) row bands and merges their results.
func (e *encoder) analyzeInBands(nb int) {
totalMB := e.mbH * e.mbW
it := &e.it
it.init(e)
it.analysis = true
if nb == 1 {
job := &e.bands[0]
job.startRow, job.nRows = 0, e.mbH
if testHookAnalysisBand != nil {
testHookAnalysisBand(0)
}
job.run(it)
} else {
e.analyzeBands(nb)
}
it.analysis = false
if e.stopped.Load() {
return // interrupted: the bands are incomplete (and may be empty)
}
// Integer sums: the merge order does not matter.
var alphas [maxAlphaValue + 1]int
alpha, uvAlpha := 0, 0
for b := range e.bands[:nb] {
job := &e.bands[b]
for i, n := range job.alphas {
alphas[i] += n
}
alpha += job.alpha
uvAlpha += job.uvAlpha
}
e.alpha = alpha / totalMB
e.uvAlpha = uvAlpha / totalMB
e.assignSegments(&alphas)
}
// analyzeBands analyzes nb row bands on the calling goroutine and on up to
// nb-1 helper goroutines taken from the process-wide budget
// (internal/workers); with no helper available, the caller analyzes all
// bands itself. Workers claim bands in order through e.nextBand. Every band
// writes only its own macroblocks and its own segmentJob, so the result
// does not depend on how many helpers ran or which band each one took.
func (e *encoder) analyzeBands(nb int) {
for b := range e.bands[:nb] {
job := &e.bands[b]
job.startRow = e.mbH * b / nb
job.nRows = e.mbH*(b+1)/nb - job.startRow
}
e.nextBand.Store(0)
work := func(it *iterator) {
for {
b := int(e.nextBand.Add(1)) - 1
if b >= nb || e.stopped.Load() {
return
}
if testHookAnalysisBand != nil {
testHookAnalysisBand(b)
}
e.bands[b].run(it)
}
}
var (
its [maxAnalysisBands - 1]*iterator
tasks [maxAnalysisBands - 1]*workers.Task
n int
)
defer func() {
// If the caller panicked, let the helpers stop after their
// current band. Wait for all of them before recycling their
// iterators, then re-raise a helper panic, if any.
e.nextBand.Store(int32(nb))
for _, t := range tasks[:n] {
<-t.Done()
}
for _, sit := range its[:n] {
sit.enc = nil
sideIteratorPool.Put(sit)
}
for _, t := range tasks[:n] {
t.Wait()
}
}()
for n < nb-1 {
sit := sideIteratorPool.Get().(*iterator)
sit.reset(e)
sit.analysis = true
t := workers.Spawn(func() error {
work(sit)
return nil
})
if t == nil { // budget exhausted
sit.enc = nil
sideIteratorPool.Put(sit)
break
}
its[n], tasks[n] = sit, t
n++
}
work(&e.it)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
// Boolean (arithmetic) encoder of the VP8 bitstream.
// Algorithm adapted from libwebp (BSD-3-Clause).
// kNorm[r] is the renormalization shift for a range-1 value r < 127.
var kNorm = [128]uint8{
7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0,
}
// kNewRange[r] = ((r + 1) << kNorm[r]) - 1
var kNewRange = [128]uint8{
127, 127, 191, 127, 159, 191, 223, 127, 143, 159, 175, 191, 207, 223, 239,
127, 135, 143, 151, 159, 167, 175, 183, 191, 199, 207, 215, 223, 231, 239,
247, 127, 131, 135, 139, 143, 147, 151, 155, 159, 163, 167, 171, 175, 179,
183, 187, 191, 195, 199, 203, 207, 211, 215, 219, 223, 227, 231, 235, 239,
243, 247, 251, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149,
151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179,
181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209,
211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239,
241, 243, 245, 247, 249, 251, 253, 127,
}
type bitWriter struct {
rng int32 // range-1
value int32
run int // number of outstanding 0xff bytes
nbBits int // number of pending bits
buf []byte
}
func (bw *bitWriter) init(capHint int) {
bw.rng = 255 - 1
bw.value = 0
bw.run = 0
bw.nbBits = -8
if cap(bw.buf) < capHint {
bytePool.Put(bw.buf)
bw.buf = bytePool.Get(capHint)
}
bw.buf = bw.buf[:0]
}
// release returns the output buffer to its pool.
func (bw *bitWriter) release() {
bytePool.Put(bw.buf)
bw.buf = nil
}
// grow makes room for n more bytes when the output outgrows its estimate:
// the larger buffer comes from bytePool and the outgrown one goes back to
// it (append would leave it to the garbage collector).
func (bw *bitWriter) grow(n int) {
nb := bytePool.Get(max(2*cap(bw.buf), len(bw.buf)+n, 1024))
nb = append(nb[:0], bw.buf...)
bytePool.Put(bw.buf)
bw.buf = nb
}
func (bw *bitWriter) flush() {
s := uint(8 + bw.nbBits)
bits := bw.value >> s
bw.value -= bits << s
bw.nbBits -= 8
if bits&0xff != 0xff {
if len(bw.buf)+bw.run >= cap(bw.buf) {
bw.grow(bw.run + 1)
}
if bits&0x100 != 0 { // overflow -> propagate carry over pending 0xff's
if n := len(bw.buf); n > 0 {
bw.buf[n-1]++
}
}
if bw.run > 0 {
v := byte(0xff)
if bits&0x100 != 0 {
v = 0
}
for ; bw.run > 0; bw.run-- {
bw.buf = append(bw.buf, v)
}
}
bw.buf = append(bw.buf, byte(bits))
} else {
bw.run++ // delay writing of bytes 0xff, pending eventual carry.
}
}
// putBit codes 'bit' with probability 'prob' (of the bit being 0, /256).
func (bw *bitWriter) putBit(bit bool, prob int) bool {
split := (bw.rng * int32(prob)) >> 8
if bit {
bw.value += split + 1
bw.rng -= split + 1
} else {
bw.rng = split
}
if bw.rng < 127 {
shift := kNorm[bw.rng&127]
bw.rng = int32(kNewRange[bw.rng&127])
bw.value <<= shift
bw.nbBits += int(shift)
if bw.nbBits > 0 {
bw.flush()
}
}
return bit
}
func (bw *bitWriter) putBitUniform(bit bool) bool {
split := bw.rng >> 1
if bit {
bw.value += split + 1
bw.rng -= split + 1
} else {
bw.rng = split
}
if bw.rng < 127 {
bw.rng = int32(kNewRange[bw.rng&127])
bw.value <<= 1
bw.nbBits++
if bw.nbBits > 0 {
bw.flush()
}
}
return bit
}
func (bw *bitWriter) putBits(value uint32, nbBits int) {
for mask := uint32(1) << uint(nbBits-1); mask != 0; mask >>= 1 {
bw.putBitUniform(value&mask != 0)
}
}
func (bw *bitWriter) putSignedBits(value int, nbBits int) {
if !bw.putBitUniform(value != 0) {
return
}
if value < 0 {
bw.putBits(uint32((-value)<<1)|1, nbBits+1)
} else {
bw.putBits(uint32(value<<1), nbBits+1)
}
}
// finish flushes the pending bits and returns the coded bytes.
func (bw *bitWriter) finish() []byte {
bw.putBits(0, 9-bw.nbBits)
bw.nbBits = 0 // pad with zeroes
bw.flush()
return bw.buf
}
// pos returns the current bit position (approximate, for statistics).
func (bw *bitWriter) pos() uint64 {
return uint64(len(bw.buf)+bw.run)*8 + uint64(8+bw.nbBits)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package vp8enc implements a pure Go VP8 (lossy WebP) encoder.
//
// The encoder follows the architecture of libwebp's VP8 encoder: analysis
// pass with k-means segmentation on macroblock susceptibility, per-segment
// quantizers derived from the quality factor with libwebp's constants,
// rate-distortion optimised intra mode selection (i16/i4/UV), trellis
// quantization at methods 5-6, DC error diffusion for chroma, adaptive token
// probabilities, SSIM-based autofilter and multi-pass rate control towards a
// target size or PSNR. At equal settings, methods 4 and 6 produce files
// within -0.8%..+0.3% of cwebp 1.6.0's size at the same PSNR (+-0.01 dB) on
// the test photos (TestInteropVsCwebp); method 0 files are smaller.
//
// Encode returns the payload of a "VP8 " RIFF chunk; wrapping it into a
// WebP container (and coding the alpha plane) is left to the caller.
//
// Differences from libwebp 1.6.0, all of them producing valid bitstreams:
// - All methods code the frame from a token buffer (libwebp does so for
// methods >= 3 without LowMemory only). Methods 0-2 therefore get exact
// token probabilities, which makes their output smaller than cwebp's.
// The number of token partitions follows libwebp: Partitions is
// ignored (one partition) for methods >= 3 unless LowMemory is set.
// - The skip flag is used whenever enough macroblocks have no
// coefficients (libwebp only uses it for methods 0-2).
// - With a single segment, the autofilter result is applied (libwebp
// leaves the initial level in the frame header).
// - Methods 0-2 propagate the chroma DC diffusion error between
// macroblocks.
// - Config.Preprocessing bits 1 (dithering) and 2 (sharp YUV) act on the
// RGB->YUV conversion, which happens before Encode: use
// FromNRGBADithered with DitheringFor(cfg), and sharpYUV for bit 2.
// - Config.LowMemory only selects the number of partitions (see above);
// it does not change how the frame is coded.
//
// Algorithm adapted from libwebp (BSD-3-Clause).
package vp8enc
import (
"errors"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/utils"
)
// MaxDimension is the largest width or height the VP8 bitstream can carry.
const MaxDimension = 16383
// Config holds the lossy encoding parameters. The semantics follow libwebp's
// WebPConfig for the corresponding fields.
type Config struct {
Quality float32 // 0..100, between smallest size and best quality
Method int // 0..6 speed/quality trade-off (0=fast, 6=slowest)
// ImageHint is accepted for API compatibility; it does not influence
// lossy coding (as in libwebp).
ImageHint int
// TargetSize, when non-zero, is the desired output size in bytes. With
// Pass > 1 it overrides Quality through a multi-pass search; with a
// single pass it has no effect (as in libwebp's WebPEncode).
TargetSize int
// TargetPSNR, when non-zero, is the desired distortion in dB. Like
// TargetSize it needs Pass > 1 (TargetSize has precedence).
TargetPSNR float32
// Pass is the number of entropy-analysis passes (1..10). Values <= 0
// are treated as 1.
Pass int
Segments int // number of segments, 1..4
SNSStrength int // spatial noise shaping, 0..100
FilterStrength int // loop filter strength 0..100 (0 = off)
FilterSharpness int // 0..7, 0 = most sharp
FilterType int // 0 = simple, 1 = strong (complex)
Autofilter bool // auto-adjust the filter strengths per segment
// Preprocessing: bit 0 enables segment-map smoothing. Bits 1
// (dithered RGB->YUV conversion) and 2 (sharp YUV) concern the
// conversion done by FromNRGBADithered before Encode and are ignored
// here.
Preprocessing int
// Partitions is log2 of the number of token partitions, 0..3. As in
// libwebp it is ignored (one partition) for Method >= 3 unless
// LowMemory is set.
Partitions int
PartitionLimit int // 0..100: quality degradation allowed to fit the 512k limit on partition #0
EmulateJPEGSize bool
// ThreadLevel allows helper goroutines from the process-wide budget of
// internal/workers (the caller does the work itself when none is
// free): the analysis pass is split into up to 8 row bands, and the
// coding passes of large enough pictures code up to 8 macroblock rows
// at once as a wavefront (wavefront.go). The output does not depend on
// it.
ThreadLevel bool
// LowMemory is accepted for compatibility. The encoder always uses a
// compact token buffer; like libwebp's low_memory it only re-enables
// multiple partitions (Partitions) for Method >= 3.
LowMemory bool
// Interrupt, if not nil, is polled about once per macroblock row; when
// it returns true, Encode stops and returns ErrInterrupted. It must be
// safe for concurrent use and, once it has returned true, keep doing so.
Interrupt func() bool
// PassHelpers, if not nil, counts the helper goroutines the coding
// pass in progress holds (with ThreadLevel; 0 between the passes):
// work coded alongside the frame can then tell the slots the frame
// still needs (WavefrontHelpers) from those it already holds.
PassHelpers *atomic.Int32
}
// ErrInterrupted is returned by Encode when Config.Interrupt asked it to stop.
var ErrInterrupted = errors.New("vp8enc: interrupted")
// ErrTooManyTokens is returned by Encode when a coding pass records more
// coefficient tokens than the encoder can index (maxTokens). That takes a
// picture close to MaxDimension in both directions with noise-like content
// at a high quality, and about 4 GiB of tokens. libwebp reports running
// out of memory for its token buffer, so the status is OutOfMemory.
var ErrTooManyTokens = status.New(utils.Vp8StatusOutOfMemory, "vp8enc: too many coefficient tokens")
// interrupted polls c.Interrupt.
func (c *Config) interrupted() bool { return c.Interrupt != nil && c.Interrupt() }
// DefaultConfig returns libwebp's default lossy configuration (quality 75,
// method 4, the "default" preset).
func DefaultConfig() Config {
return Config{
Quality: 75,
Method: 4,
Pass: 1,
Segments: 4,
SNSStrength: 50,
FilterStrength: 60,
FilterSharpness: 0,
FilterType: 1,
}
}
func (c *Config) validate() error {
switch {
case c.Quality < 0 || c.Quality > 100: // NaN is accepted, as in libwebp
return status.InvalidParam("vp8enc: quality out of range [0,100]")
case c.Method < 0 || c.Method > 6:
return status.InvalidParam("vp8enc: method out of range [0,6]")
case c.TargetSize < 0:
return status.InvalidParam("vp8enc: negative target size")
case c.TargetPSNR < 0: // NaN is accepted (and ignored), as in libwebp
return status.InvalidParam("vp8enc: negative target PSNR")
case c.Pass > 10:
return status.InvalidParam("vp8enc: pass out of range [1,10]")
case c.Segments < 1 || c.Segments > 4:
return status.InvalidParam("vp8enc: segments out of range [1,4]")
case c.SNSStrength < 0 || c.SNSStrength > 100:
return status.InvalidParam("vp8enc: sns strength out of range [0,100]")
case c.FilterStrength < 0 || c.FilterStrength > 100:
return status.InvalidParam("vp8enc: filter strength out of range [0,100]")
case c.FilterSharpness < 0 || c.FilterSharpness > 7:
return status.InvalidParam("vp8enc: filter sharpness out of range [0,7]")
case c.FilterType < 0 || c.FilterType > 1:
return status.InvalidParam("vp8enc: filter type must be 0 or 1")
case c.Preprocessing < 0 || c.Preprocessing > 7:
return status.InvalidParam("vp8enc: preprocessing out of range [0,7]")
case c.Partitions < 0 || c.Partitions > 3:
return status.InvalidParam("vp8enc: partitions out of range [0,3]")
case c.PartitionLimit < 0 || c.PartitionLimit > 100:
return status.InvalidParam("vp8enc: partition limit out of range [0,100]")
case c.ImageHint < 0 || c.ImageHint > 3:
return status.InvalidParam("vp8enc: image hint out of range [0,3]")
}
return nil
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
// Token probabilities, statistics and bit-cost estimation.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
numTypes = 4
numBands = 8
numCtx = 3
numProbas = 11
numMBSegments = 4
maxVariableLevel = 67
)
// Coefficient types.
const (
typeI16AC = 0
typeI16DC = 1
typeChromaA = 2
typeI4AC = 3
)
var encBands = [16 + 1]uint8{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0}
var (
vp8Cat3 = []uint8{173, 148, 140}
vp8Cat4 = []uint8{176, 155, 140, 135}
vp8Cat5 = []uint8{180, 157, 141, 134, 130}
vp8Cat6 = []uint8{254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129}
)
// Mode costs: fixed probabilities in the coding trees turned into bit-cost.
var (
fixedCostsUV = [4]uint16{302, 984, 439, 642}
fixedCostsI16 = [4]uint16{663, 919, 872, 919} // includes VP8BitCost(1, 145)
)
// bitCost is the cost (in 1/256 bit) of coding 'bit' with probability 'p'.
func bitCost(bit int, p uint8) int {
if bit == 0 {
return int(entropyCost[p])
}
return int(entropyCost[255-p])
}
type levelCostTable [maxVariableLevel + 1]uint16
type encProba struct {
segments [3]uint8
skipProba uint8
useSkipProba bool
dirty bool
nbSkip int
coeffs [numTypes][numBands][numCtx][numProbas]uint8
stats [numTypes][numBands][numCtx][numProbas]uint32
// trellis holds the tables of trellisModesAVX2, derived from levelCost
// and coeffs (see calculateLevelCosts); empty in other builds, and not
// the last field, so that an empty one takes no room.
trellis trellisCostTables
levelCost [numTypes][numBands][numCtx]levelCostTable
}
func (p *encProba) reset() {
p.useSkipProba = false
p.skipProba = 255
p.segments = [3]uint8{255, 255, 255}
p.coeffs = coeffsProba0
p.stats = [numTypes]statsArray{}
p.dirty = true
p.nbSkip = 0
}
func variableLevelCost(level int, probas *[numProbas]uint8) int {
pattern := int(levelCodes[level-1][0])
bits := int(levelCodes[level-1][1])
cost := 0
for i := 2; pattern != 0; i++ {
if pattern&1 != 0 {
cost += bitCost(bits&1, probas[i])
}
bits >>= 1
pattern >>= 1
}
return cost
}
// calculateLevelCosts refreshes the level cost tables, and the tables of
// the vector trellis derived from them, from the current probabilities.
//
// trellisModesAVX2 reads the probabilities only through p.trellis, whose
// end-of-block costs are copied from p.coeffs here, while
// trellisQuantizeBlock, trellisModesAVX512 and trellisModesNEON read
// p.coeffs as it is. So p.coeffs must not change between
// calculateLevelCosts and a trellis call, or the AVX2 level would encode
// differently from the others: each finalizeTokenProbas that more
// macroblocks follow is followed by calculateLevelCosts.
// TestEncodeIdentity, which holds every level to the same hashes, covers
// the refreshes within a pass, in the wavefront and between passes.
func (p *encProba) calculateLevelCosts() {
if !p.dirty {
return
}
for ctype := 0; ctype < numTypes; ctype++ {
for band := 0; band < numBands; band++ {
for ctx := 0; ctx < numCtx; ctx++ {
pr := &p.coeffs[ctype][band][ctx]
table := &p.levelCost[ctype][band][ctx]
cost0 := 0
if ctx > 0 {
cost0 = bitCost(1, pr[0])
}
costBase := bitCost(1, pr[1]) + cost0
table[0] = uint16(bitCost(0, pr[1]) + cost0)
for v := 1; v <= maxVariableLevel; v++ {
table[v] = uint16(costBase + variableLevelCost(v, pr))
}
}
}
}
p.updateTrellisTables()
p.dirty = false
}
func levelCost(table *levelCostTable, level int) int {
if level > maxVariableLevel {
return int(levelFixedCosts[level&2047]) + int(table[maxVariableLevel])
}
return int(levelFixedCosts[level]) + int(table[level])
}
// residual describes one block of quantized levels (zigzag order).
type residual struct {
first int
last int
ctype int
coeffs *[16]int16
}
func (r *residual) setCoeffs(c *[16]int16) {
r.coeffs = c
r.last = lastNonZero(c)
}
// setCoeffsInfo is setCoeffs with the levelInfoOf summary of c known.
func (r *residual) setCoeffsInfo(c *[16]int16, info uint16) {
r.coeffs = c
r.last = infoLast(info)
}
// lastNonZero returns the index of the last non-zero coefficient, or -1.
func lastNonZero(c *[16]int16) int {
n := 15
for ; n >= 3; n -= 4 { // skip empty groups of 4 quickly
if c[n]|c[n-1]|c[n-2]|c[n-3] != 0 {
break
}
}
for ; n >= 0; n-- {
if c[n&15] != 0 {
return n
}
}
return -1
}
func abs16(v int16) int {
if v < 0 {
return -int(v)
}
return int(v)
}
// residualCostGo returns the bit-cost of coding the residual with context
// ctx0; residualCost (cost_amd64.go, cost_other.go) is bound to it or to
// an assembly kernel.
func (p *encProba) residualCostGo(ctx0 int, res *residual) int {
n := res.first
prob := &p.coeffs[res.ctype]
costs := &p.levelCost[res.ctype]
// should be prob[encBands[n]], but it's equivalent for n=0 or 1
p0 := prob[n][ctx0][0]
if res.last < 0 {
return bitCost(0, p0)
}
cost := 0
if ctx0 == 0 {
cost = bitCost(1, p0)
}
t := &costs[n][ctx0]
coeffs := res.coeffs
last := res.last
// Each level costs levelCost (the variable part clamped at
// maxVariableLevel) and picks the table of the next one by its context
// min(|level|, 2). The contexts follow the data, and a mispredicted
// branch costs more than the rest of an iteration, so they are summed
// from two comparisons (CSET or SETcc, no branch): with min() or an if
// the compiler branches, as it makes no conditional select for a value
// that goes into a load address (golang.org/issue/26306).
// min(v, maxVariableLevel) branches too, but levels above 67 are rare
// enough for it to be predicted.
for ; n < last; n++ {
v := absLevel(coeffs[n&15])
cost += int(levelFixedCosts[v&maxLevel]) + int(t[min(v, maxVariableLevel)])
t = &costs[encBands[(n+1)&15]&7][b2i(v != 0)+b2i(v > 1)]
}
// Last coefficient is always non-zero
v := absLevel(coeffs[n&15])
cost += int(levelFixedCosts[v&maxLevel]) + int(t[min(v, maxVariableLevel)])
if n < 15 {
ctx := 1 + b2i(v != 1) // 1 if v == 1, else 2
cost += bitCost(0, prob[encBands[n+1]&7][ctx][0])
}
return cost
}
// absLevel returns |v| (at most 32768) without a data-dependent branch.
// It works on int, which the load already sign-extends to, as int32 would
// cost two more sign extensions per level on 64-bit targets.
func absLevel(v int16) uint {
a := int(v)
m := a >> 15 // 0 or -1, the sign of v
return uint((a ^ m) - m)
}
// recordStats records a bit event in the 16b+16b stats counter.
func recordStats(bit int, s *uint32) int {
p := *s
if p >= 0xfffe0000 {
p = ((p + 1) >> 1) & 0x7fff7fff // divide the stats by 2.
}
p += 0x00010000 + uint32(bit)
*s = p
return bit
}
func calcTokenProba(nb, total int) int {
if nb == 0 {
return 255
}
return 255 - nb*255/total
}
func branchCost(nb, total, proba int) int {
return nb*bitCost(1, uint8(proba)) + (total-nb)*bitCost(0, uint8(proba))
}
// finalizeTokenProbas derives new probabilities from the statistics and
// returns the bit-cost of the probability updates.
func (p *encProba) finalizeTokenProbas() int {
hasChanged := false
size := 0
for t := 0; t < numTypes; t++ {
for b := 0; b < numBands; b++ {
for c := 0; c < numCtx; c++ {
for q := 0; q < numProbas; q++ {
stats := p.stats[t][b][c][q]
nb := int(stats & 0xffff)
total := int(stats >> 16)
updateProba := coeffsUpdateProba[t][b][c][q]
oldP := int(coeffsProba0[t][b][c][q])
newP := calcTokenProba(nb, total)
oldCost := branchCost(nb, total, oldP) + bitCost(0, updateProba)
newCost := branchCost(nb, total, newP) + bitCost(1, updateProba) + 8*256
finalP := oldP
if oldCost > newCost {
size += bitCost(1, updateProba) + 8*256
finalP = newP
} else {
size += bitCost(0, updateProba)
}
if int(p.coeffs[t][b][c][q]) != finalP {
hasChanged = true
p.coeffs[t][b][c][q] = uint8(finalP)
}
}
}
}
}
if hasChanged {
p.dirty = true
}
return size
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8enc
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
//go:noescape
func residualCostSSE41(costs *[numBands][numCtx]levelCostTable, prob *[numBands][numCtx][numProbas]uint8,
coeffs *[16]int16, first, last, ctx0 int) int
// residualCost returns the bit-cost of coding the residual with context
// ctx0: residualCostGo (cost.go) computed by residualCostSSE41
// (cost_amd64.s), which takes no data-dependent branch. Residuals the
// encoder never builds (first > 1, which the Go code reads as a band
// index, last > 15, ctx0 > 2) take the Go code.
func (p *encProba) residualCost(ctx0 int, res *residual) int {
if x86Level < cpuinfo.SSE41 || uint(res.first) > 1 || res.last > 15 || uint(ctx0) > 2 {
return p.residualCostGo(ctx0, res)
}
return residualCostSSE41(&p.levelCost[res.ctype], &p.coeffs[res.ctype], res.coeffs, res.first, res.last, ctx0)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"encoding/binary"
"math"
)
// DSP primitives: transforms, intra predictors, distortion metrics and
// quantization. All blocks live in 32-byte-stride work buffers.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
bps = 32 // stride of the work buffers
yOff = 0
uOff = 16
vOff = 16 + 8
yuvSize = bps * 16
predSize = 32*bps + 16*bps + 8*bps
// Layout of the prediction buffer.
i16DC16 = 0 * 16 * bps
i16TM16 = i16DC16 + 16
i16VE16 = 1 * 16 * bps
i16HE16 = i16VE16 + 16
c8DC8 = 2 * 16 * bps
c8TM8 = c8DC8 + 1*16
c8VE8 = 2*16*bps + 8*bps
c8HE8 = c8VE8 + 1*16
i4DC4 = 3*16*bps + 0
i4TM4 = i4DC4 + 4
i4VE4 = i4DC4 + 8
i4HE4 = i4DC4 + 12
i4RD4 = i4DC4 + 16
i4VR4 = i4DC4 + 20
i4LD4 = i4DC4 + 24
i4VL4 = i4DC4 + 28
i4HD4 = 3*16*bps + 4*bps
i4HU4 = i4HD4 + 4
i4TMP = i4HD4 + 8
)
// Intra16 / chroma modes (libwebp numbering).
const (
predDC = 0
predTM = 1
predVE = 2
predHE = 3
numPredModes = 4
numBModes = 10
)
var vp8I16ModeOffsets = [4]int{i16DC16, i16TM16, i16VE16, i16HE16}
var vp8UVModeOffsets = [4]int{c8DC8, c8TM8, c8VE8, c8HE8}
var vp8I4ModeOffsets = [numBModes]int{i4DC4, i4TM4, i4VE4, i4HE4, i4RD4, i4VR4, i4LD4, i4VL4, i4HD4, i4HU4}
var vp8Scan = [16]int{
0 + 0*bps, 4 + 0*bps, 8 + 0*bps, 12 + 0*bps,
0 + 4*bps, 4 + 4*bps, 8 + 4*bps, 12 + 4*bps,
0 + 8*bps, 4 + 8*bps, 8 + 8*bps, 12 + 8*bps,
0 + 12*bps, 4 + 12*bps, 8 + 12*bps, 12 + 12*bps,
}
var vp8ScanUV = [8]int{
0 + 0*bps, 4 + 0*bps, 0 + 4*bps, 4 + 4*bps, // U
8 + 0*bps, 12 + 0*bps, 8 + 4*bps, 12 + 4*bps, // V
}
var kZigzag = [16]uint8{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15}
func clip8(v int32) uint8 {
if uint32(v) <= 255 {
return uint8(v)
}
if v < 0 {
return 0
}
return 255
}
//------------------------------------------------------------------------------
// Transforms
// fTransform computes the forward DCT of src-ref (4x4, stride bps).
func fTransform(src, ref []byte, out *[16]int16) {
var t [4][4]int32
_ = src[3*bps+3]
_ = ref[3*bps+3]
for i := 0; i < 4; i++ {
s := src[i*bps : i*bps+4 : i*bps+4]
r := ref[i*bps : i*bps+4 : i*bps+4]
d0 := int32(s[0]) - int32(r[0])
d1 := int32(s[1]) - int32(r[1])
d2 := int32(s[2]) - int32(r[2])
d3 := int32(s[3]) - int32(r[3])
a0 := d0 + d3
a1 := d1 + d2
a2 := d1 - d2
a3 := d0 - d3
ti := &t[i]
ti[0] = (a0 + a1) * 8
ti[1] = (a2*2217 + a3*5352 + 1812) >> 9
ti[2] = (a0 - a1) * 8
ti[3] = (a3*2217 - a2*5352 + 937) >> 9
}
for i := 0; i < 4; i++ {
a0 := t[0][i] + t[3][i]
a1 := t[1][i] + t[2][i]
a2 := t[1][i] - t[2][i]
a3 := t[0][i] - t[3][i]
out[0+i] = int16((a0 + a1 + 7) >> 4)
v := (a2*2217 + a3*5352 + 12000) >> 16
if a3 != 0 {
v++
}
out[4+i] = int16(v)
out[8+i] = int16((a0 - a1 + 7) >> 4)
out[12+i] = int16((a3*2217 - a2*5352 + 51000) >> 16)
}
}
// fTransformWHT computes the Walsh-Hadamard transform of the 16 DC
// coefficients of blocks[0..15].
func fTransformWHT(blocks *[16][16]int16, out *[16]int16) {
var t [16]int32
for i := 0; i < 4; i++ {
b := blocks[i*4 : i*4+4 : i*4+4]
in0, in1, in2, in3 := int32(b[0][0]), int32(b[1][0]), int32(b[2][0]), int32(b[3][0])
a0 := in0 + in2
a1 := in1 + in3
a2 := in1 - in3
a3 := in0 - in2
t[0+i*4] = a0 + a1
t[1+i*4] = a3 + a2
t[2+i*4] = a3 - a2
t[3+i*4] = a0 - a1
}
for i := 0; i < 4; i++ {
a0 := t[0+i] + t[8+i]
a1 := t[4+i] + t[12+i]
a2 := t[4+i] - t[12+i]
a3 := t[0+i] - t[8+i]
b0 := a0 + a1
b1 := a3 + a2
b2 := a3 - a2
b3 := a0 - a1
out[0+i] = int16(b0 >> 1)
out[4+i] = int16(b1 >> 1)
out[8+i] = int16(b2 >> 1)
out[12+i] = int16(b3 >> 1)
}
}
// iTransformWHT is the inverse WHT; it writes the DC of blocks[0..15].
func iTransformWHT(in *[16]int16, blocks *[16][16]int16) {
var t [16]int32
for i := 0; i < 4; i++ {
a0 := int32(in[0+i]) + int32(in[12+i])
a1 := int32(in[4+i]) + int32(in[8+i])
a2 := int32(in[4+i]) - int32(in[8+i])
a3 := int32(in[0+i]) - int32(in[12+i])
t[0+i] = a0 + a1
t[8+i] = a0 - a1
t[4+i] = a3 + a2
t[12+i] = a3 - a2
}
for i := 0; i < 4; i++ {
dc := t[0+i*4] + 3
a0 := dc + t[3+i*4]
a1 := t[1+i*4] + t[2+i*4]
a2 := t[1+i*4] - t[2+i*4]
a3 := dc - t[3+i*4]
blocks[i*4+0][0] = int16((a0 + a1) >> 3)
blocks[i*4+1][0] = int16((a3 + a2) >> 3)
blocks[i*4+2][0] = int16((a0 - a1) >> 3)
blocks[i*4+3][0] = int16((a3 - a2) >> 3)
}
}
func mul1(a int32) int32 { return ((a * 20091) >> 16) + a }
func mul2(a int32) int32 { return (a * 35468) >> 16 }
// iTransform adds the inverse DCT of 'in' to ref and stores it into dst.
func iTransform(ref []byte, in *[16]int16, dst []byte) {
_ = ref[3*bps+3]
_ = dst[3*bps+3]
if in[1]|in[2]|in[3]|in[4]|in[5]|in[6]|in[7]|in[8]|in[9]|in[10]|in[11]|in[12]|in[13]|in[14]|in[15] == 0 {
// DC-only (or empty) block: same result as the full transform.
dc := (int32(in[0]) + 4) >> 3
for i := 0; i < 4; i++ {
r := ref[i*bps : i*bps+4 : i*bps+4]
o := dst[i*bps : i*bps+4 : i*bps+4]
if dc == 0 {
copy(o, r)
continue
}
o[0] = clip8(int32(r[0]) + dc)
o[1] = clip8(int32(r[1]) + dc)
o[2] = clip8(int32(r[2]) + dc)
o[3] = clip8(int32(r[3]) + dc)
}
return
}
var c [4][4]int32
for i := 0; i < 4; i++ { // vertical pass
i0, i4, i8, i12 := int32(in[i]), int32(in[4+i]), int32(in[8+i]), int32(in[12+i])
a := i0 + i8
b := i0 - i8
cc := mul2(i4) - mul1(i12)
d := mul1(i4) + mul2(i12)
ci := &c[i]
ci[0] = a + d
ci[1] = b + cc
ci[2] = b - cc
ci[3] = a - d
}
_ = ref[3*bps+3]
_ = dst[3*bps+3]
for i := 0; i < 4; i++ { // horizontal pass
dc := c[0][i] + 4
a := dc + c[2][i]
b := dc - c[2][i]
cc := mul2(c[1][i]) - mul1(c[3][i])
d := mul1(c[1][i]) + mul2(c[3][i])
r := ref[i*bps : i*bps+4 : i*bps+4]
o := dst[i*bps : i*bps+4 : i*bps+4]
o[0] = clip8(int32(r[0]) + ((a + d) >> 3))
o[1] = clip8(int32(r[1]) + ((b + cc) >> 3))
o[2] = clip8(int32(r[2]) + ((b - cc) >> 3))
o[3] = clip8(int32(r[3]) + ((a - d) >> 3))
}
}
//------------------------------------------------------------------------------
// Intra predictions
// splat8 returns v in each byte of a uint64.
func splat8(v byte) uint64 { return uint64(v) * 0x0101010101010101 }
// fill sets a size x size block (size 8 or 16) to v, 8 bytes per store.
func fill(dst []byte, v byte, size int) {
w := splat8(v)
for j := 0; j < size; j++ {
row := dst[j*bps : j*bps+size]
for i := 0; i < len(row); i += 8 {
binary.LittleEndian.PutUint64(row[i:], w)
}
}
}
func verticalPred(dst []byte, top []byte, size int) {
if top == nil {
fill(dst, 127, size)
return
}
for j := 0; j < size; j++ {
copy(dst[j*bps:j*bps+size], top[:size])
}
}
// left[0] is the top-left sample, left[1..size] the left column (size 8
// or 16).
func horizontalPred(dst []byte, left []byte, size int) {
if left == nil {
fill(dst, 129, size)
return
}
for j := 0; j < size; j++ {
row := dst[j*bps : j*bps+size]
w := splat8(left[1+j])
for i := 0; i < len(row); i += 8 {
binary.LittleEndian.PutUint64(row[i:], w)
}
}
}
func trueMotion(dst []byte, left, top []byte, size int) {
if left != nil {
if top != nil {
tl := int32(left[0])
top = top[:size]
for y := 0; y < size; y++ {
l := int32(left[1+y]) - tl
row := dst[y*bps : y*bps+size]
for x := range row {
row[x] = clip8(l + int32(top[x]))
}
}
} else {
horizontalPred(dst, left, size)
}
} else {
if top != nil {
verticalPred(dst, top, size)
} else {
fill(dst, 129, size)
}
}
}
func dcMode(dst []byte, left, top []byte, size int, round int, shift uint) {
dc := 0
if top != nil {
for j := 0; j < size; j++ {
dc += int(top[j])
}
if left != nil {
for j := 0; j < size; j++ {
dc += int(left[1+j])
}
} else {
dc += dc
}
dc = (dc + round) >> shift
} else if left != nil {
for j := 0; j < size; j++ {
dc += int(left[1+j])
}
dc += dc
dc = (dc + round) >> shift
} else {
dc = 0x80
}
fill(dst, byte(dc), size)
}
// predLuma16Ref computes the 4 intra16 predictions into p (nil left or top:
// not available).
func predLuma16Ref(p []byte, left, top []byte) {
dcMode(p[i16DC16:], left, top, 16, 16, 5)
verticalPred(p[i16VE16:], top, 16)
horizontalPred(p[i16HE16:], left, 16)
trueMotion(p[i16TM16:], left, top, 16)
}
// predChroma8Ref computes the 4 chroma predictions (U and V side by side).
// uvTop holds 8 U then 8 V samples.
func predChroma8Ref(p []byte, uLeft, vLeft, uvTop []byte) {
var top []byte
if uvTop != nil {
top = uvTop[0:8]
}
dcMode(p[c8DC8:], uLeft, top, 8, 8, 4)
verticalPred(p[c8VE8:], top, 8)
horizontalPred(p[c8HE8:], uLeft, 8)
trueMotion(p[c8TM8:], uLeft, top, 8)
if uvTop != nil {
top = uvTop[8:16]
}
dcMode(p[c8DC8+8:], vLeft, top, 8, 8, 4)
verticalPred(p[c8VE8+8:], top, 8)
horizontalPred(p[c8HE8+8:], vLeft, 8)
trueMotion(p[c8TM8+8:], vLeft, top, 8)
}
func avg3(a, b, c uint32) byte { return byte((a + 2*b + c + 2) >> 2) }
func avg2(a, b uint32) byte { return byte((a + b + 1) >> 1) }
func put4(dst []byte, a, b, c, d byte) {
_ = dst[3]
dst[0], dst[1], dst[2], dst[3] = a, b, c, d
}
// predLuma4Ref computes the 10 intra4 predictions. 'b' is the boundary array
// and 't' the index of the top sample: left samples are b[t-5..t-2]
// (bottom to top), top-left is b[t-1], top is b[t..t+3] and top-right is
// b[t+4..t+7].
func predLuma4Ref(p []byte, b []byte, t int) {
s := b[t-5 : t+8]
_ = s[12]
L := uint32(s[0])
K := uint32(s[1])
J := uint32(s[2])
I := uint32(s[3])
X := uint32(s[4])
A := uint32(s[5])
B := uint32(s[6])
C := uint32(s[7])
D := uint32(s[8])
E := uint32(s[9])
F := uint32(s[10])
G := uint32(s[11])
H := uint32(s[12])
// DC4
{
dc := byte((4 + A + B + C + D + L + K + J + I) >> 3)
d := p[i4DC4:]
for y := 0; y < 4; y++ {
put4(d[y*bps:], dc, dc, dc, dc)
}
}
// TM4
{
d := p[i4TM4:]
tl := int32(X)
lefts := [4]int32{int32(I), int32(J), int32(K), int32(L)}
for y := 0; y < 4; y++ {
l := lefts[y] - tl
put4(d[y*bps:], clip8(l+int32(A)), clip8(l+int32(B)), clip8(l+int32(C)), clip8(l+int32(D)))
}
}
// VE4
{
d := p[i4VE4:]
v0, v1, v2, v3 := avg3(X, A, B), avg3(A, B, C), avg3(B, C, D), avg3(C, D, E)
for y := 0; y < 4; y++ {
put4(d[y*bps:], v0, v1, v2, v3)
}
}
// HE4
{
d := p[i4HE4:]
a, bb, c, dd := avg3(X, I, J), avg3(I, J, K), avg3(J, K, L), avg3(K, L, L)
put4(d[0*bps:], a, a, a, a)
put4(d[1*bps:], bb, bb, bb, bb)
put4(d[2*bps:], c, c, c, c)
put4(d[3*bps:], dd, dd, dd, dd)
}
// RD4
{
d := p[i4RD4:]
jkl := avg3(J, K, L)
ijk := avg3(I, J, K)
xij := avg3(X, I, J)
axi := avg3(A, X, I)
bax := avg3(B, A, X)
cba := avg3(C, B, A)
dcb := avg3(D, C, B)
put4(d[0*bps:], axi, bax, cba, dcb)
put4(d[1*bps:], xij, axi, bax, cba)
put4(d[2*bps:], ijk, xij, axi, bax)
put4(d[3*bps:], jkl, ijk, xij, axi)
}
// VR4
{
d := p[i4VR4:]
xa := avg2(X, A)
ab := avg2(A, B)
bc := avg2(B, C)
cd := avg2(C, D)
kji := avg3(K, J, I)
jix := avg3(J, I, X)
ixa := avg3(I, X, A)
xab := avg3(X, A, B)
abc := avg3(A, B, C)
bcd := avg3(B, C, D)
put4(d[0*bps:], xa, ab, bc, cd)
put4(d[1*bps:], ixa, xab, abc, bcd)
put4(d[2*bps:], jix, xa, ab, bc)
put4(d[3*bps:], kji, ixa, xab, abc)
}
// LD4
{
d := p[i4LD4:]
abc := avg3(A, B, C)
bcd := avg3(B, C, D)
cde := avg3(C, D, E)
def := avg3(D, E, F)
efg := avg3(E, F, G)
fgh := avg3(F, G, H)
ghh := avg3(G, H, H)
put4(d[0*bps:], abc, bcd, cde, def)
put4(d[1*bps:], bcd, cde, def, efg)
put4(d[2*bps:], cde, def, efg, fgh)
put4(d[3*bps:], def, efg, fgh, ghh)
}
// VL4
{
d := p[i4VL4:]
ab := avg2(A, B)
bc := avg2(B, C)
cd := avg2(C, D)
de := avg2(D, E)
abc := avg3(A, B, C)
bcd := avg3(B, C, D)
cde := avg3(C, D, E)
def := avg3(D, E, F)
efg := avg3(E, F, G)
fgh := avg3(F, G, H)
put4(d[0*bps:], ab, bc, cd, de)
put4(d[1*bps:], abc, bcd, cde, def)
put4(d[2*bps:], bc, cd, de, efg)
put4(d[3*bps:], bcd, cde, def, fgh)
}
// HD4
{
d := p[i4HD4:]
ix := avg2(I, X)
ji := avg2(J, I)
kj := avg2(K, J)
lk := avg2(L, K)
abc := avg3(A, B, C)
xab := avg3(X, A, B)
ixa := avg3(I, X, A)
jix := avg3(J, I, X)
kji := avg3(K, J, I)
lkj := avg3(L, K, J)
put4(d[0*bps:], ix, ixa, xab, abc)
put4(d[1*bps:], ji, jix, ix, ixa)
put4(d[2*bps:], kj, kji, ji, jix)
put4(d[3*bps:], lk, lkj, kj, kji)
}
// HU4
{
d := p[i4HU4:]
ij := avg2(I, J)
jk := avg2(J, K)
kl := avg2(K, L)
ijk := avg3(I, J, K)
jkl := avg3(J, K, L)
kll := avg3(K, L, L)
l := byte(L)
put4(d[0*bps:], ij, ijk, jk, jkl)
put4(d[1*bps:], jk, jkl, kl, kll)
put4(d[2*bps:], kl, kll, l, l)
put4(d[3*bps:], l, l, l, l)
}
}
//------------------------------------------------------------------------------
// Metrics
func sseRow16(a, b []byte) int {
_ = a[15]
_ = b[15]
s := 0
for i := 0; i < 16; i++ {
d := int(a[i]) - int(b[i])
s += d * d
}
return s
}
func sseRow4(a, b []byte) int {
_ = a[3]
_ = b[3]
d0 := int(a[0]) - int(b[0])
d1 := int(a[1]) - int(b[1])
d2 := int(a[2]) - int(b[2])
d3 := int(a[3]) - int(b[3])
return d0*d0 + d1*d1 + d2*d2 + d3*d3
}
func sse16x16Ref(a, b []byte) int {
s := 0
for y := 0; y < 16; y++ {
s += sseRow16(a[y*bps:], b[y*bps:])
}
return s
}
func sse16x8Ref(a, b []byte) int {
s := 0
for y := 0; y < 8; y++ {
s += sseRow16(a[y*bps:], b[y*bps:])
}
return s
}
func sse4x4(a, b []byte) int {
return sseRow4(a, b) + sseRow4(a[bps:], b[bps:]) + sseRow4(a[2*bps:], b[2*bps:]) + sseRow4(a[3*bps:], b[3*bps:])
}
func iabs(v int32) int32 {
m := v >> 31
return (v ^ m) - m
}
func ttRow(in []byte) (int32, int32, int32, int32) {
_ = in[3]
a0 := int32(in[0]) + int32(in[2])
a1 := int32(in[1]) + int32(in[3])
a2 := int32(in[1]) - int32(in[3])
a3 := int32(in[0]) - int32(in[2])
return a0 + a1, a3 + a2, a3 - a2, a0 - a1
}
// tTransform returns the weighted sum of the absolute Hadamard coefficients.
func tTransform(in []byte, w *[16]uint16) int32 {
var t [16]int32
t[0], t[1], t[2], t[3] = ttRow(in[0:])
t[4], t[5], t[6], t[7] = ttRow(in[bps:])
t[8], t[9], t[10], t[11] = ttRow(in[2*bps:])
t[12], t[13], t[14], t[15] = ttRow(in[3*bps:])
var sum int32
for i := 0; i < 4; i++ {
a0 := t[0+i] + t[8+i]
a1 := t[4+i] + t[12+i]
a2 := t[4+i] - t[12+i]
a3 := t[0+i] - t[8+i]
b0 := a0 + a1
b1 := a3 + a2
b2 := a3 - a2
b3 := a0 - a1
sum += int32(w[0+i])*iabs(b0) + int32(w[4+i])*iabs(b1) + int32(w[8+i])*iabs(b2) + int32(w[12+i])*iabs(b3)
}
return sum
}
//------------------------------------------------------------------------------
// Quantization
const (
qfix = 17
maxLevel = 2047
)
func biasOf(b uint32) uint32 { return b << (qfix - 8) }
func quantDiv(n, iq, b uint32) int32 { return int32((n*iq + b) >> qfix) }
// matrix holds the quantization parameters of one coefficient type.
type matrix struct {
q [16]uint32 // quantizer steps
iq [16]uint32 // reciprocals, fixed point
bias [16]uint32 // rounding bias
zthresh [16]uint32 // value below which a coefficient is zeroed
sharpen [16]uint32 // frequency boosters for slight sharpening
// 16-bit copies of q, iq and sharpen for the vector quantizer, valid
// when vecOK is set (see prepareVec).
q16, iq16, sharpen16 [16]uint16
vecOK bool
// trellisOK is set when the vector trellis (trellisModes) computes
// the distortion terms of trellisQuantizeBlock exactly in 32 bits
// (see trellisVecOK); trellisTQ is then the largest |coefficient|
// that does not extend the trellis (isqrt(q[1]*q[1]/4)). trellis is
// what the trellis kernel of the architecture keeps of the matrix, if
// anything (see trellisMatrix.prepare; not the last field, so that an
// empty one takes no room).
trellis trellisMatrix
trellisOK bool
trellisTQ uint16
}
// prepareVec fills the 16-bit copies of the quantizer parameters. A vector
// quantizer working on 16-bit lanes (|coeff| <= 32768, then
// coeff+sharpen and (coeff+sharpen)*iq computed exactly in 16 and 32 bits)
// matches quantizeBlock bit for bit when iq < 2^16 and sharpen < 2^15; only
// the low 16 bits of q matter, since the dequantized value is truncated to
// int16. The encoder's quantizers (q >= 4, so iq <= 32768, and sharpen <=
// 12) always qualify; vecOK records it for any other matrix.
func (m *matrix) prepareVec() {
m.vecOK = true
for i := range m.q {
m.q16[i] = uint16(m.q[i])
m.iq16[i] = uint16(m.iq[i])
m.sharpen16[i] = uint16(m.sharpen[i])
if m.iq[i] > 0xffff || m.sharpen[i] > 0x7fff {
m.vecOK = false
}
}
m.trellisOK, m.trellisTQ = trellisVecOK(m)
m.trellis.prepare(m)
}
// trellisVecOK tells whether a vector trellis working on 32-bit lanes
// matches trellisQuantizeBlock bit for bit with the matrix m, and returns
// the threshold of the last-coefficient scan. With |coeff| <= 32768,
// sharpen <= 13000 (so coeff+sharpen <= 46340, whose square fits in 31
// bits), 2 <= q <= 30000 and iq = 2^17/q (the reciprocal expandMatrix
// sets, so that level*q <= coeff+sharpen+q/2 and every error term
// coeff+sharpen-level*q lies in [-1.5q, coeff+sharpen]), the squared
// errors and their differences fit in int32; quantDiv itself is uint32
// arithmetic in both. The encoder's matrices (q >= 4, sharpen <= 12)
// always qualify.
func trellisVecOK(m *matrix) (bool, uint16) {
for i := range m.q {
if m.q[i] < 2 || m.q[i] > 30000 || m.iq[i] != (1<<qfix)/m.q[i] || m.sharpen[i] > 13000 {
return false, 0
}
}
// v*v > t exactly when |v| > isqrt(t)
t := m.q[1] * m.q[1] / 4
r := uint32(math.Sqrt(float64(t)))
for r*r > t {
r--
}
for (r+1)*(r+1) <= t {
r++
}
return true, uint16(r)
}
// kInvZigzag maps a natural-order coefficient index to its zigzag position.
var kInvZigzag = [16]uint8{0, 1, 5, 6, 2, 4, 7, 12, 3, 8, 11, 13, 9, 10, 14, 15}
// quantizeBlock quantizes in[] (natural order) into out[] (zigzag order),
// replacing in[] with the dequantized values. Returns true if any level is
// non-zero. Branchless: QUANTDIV is zero exactly when coeff <= zthresh.
func quantizeBlock(in *[16]int16, out *[16]int16, m *matrix) bool {
var nz int32
for j := 0; j < 16; j++ {
v := int32(in[j])
s := v >> 31
coeff := uint32((v^s)-s) + m.sharpen[j]
level := min(int32((coeff*m.iq[j]+m.bias[j])>>qfix), maxLevel)
level = (level ^ s) - s
in[j] = int16(level * int32(m.q[j]))
out[kInvZigzag[j]&15] = int16(level)
nz |= level
}
return nz != 0
}
func isFlatSource16(src []byte) bool {
v := src[0]
for y := 0; y < 16; y++ {
row := src[y*bps : y*bps+16]
for _, s := range row {
if s != v {
return false
}
}
}
return true
}
func copy4x4(src, dst []byte) {
for y := 0; y < 4; y++ {
copy(dst[y*bps:y*bps+4], src[y*bps:y*bps+4])
}
}
func copy16x8(src, dst []byte) {
for y := 0; y < 8; y++ {
copy(dst[y*bps:y*bps+16], src[y*bps:y*bps+16])
}
}
//------------------------------------------------------------------------------
// Histogram (analysis)
const maxCoeffThresh = 31
// collectHistogram returns the (maxValue, lastNonZero) of the histogram of
// DCT coefficients of ref-pred over the blocks of t (tabY16 or tabUV).
func collectHistogram(ref, pred []byte, t *pairTable) (int, int) {
var coeffs [16][16]int16
n := 2 * t.n
fTransformPairs(ref, pred, t, coeffs[:n])
if vecKernels {
// When more than half of the coefficients fall in bin 0, no other
// bin can have more: the histogram reduces to two vector
// reductions (the common case).
count0, maxBin := zeroBinStats(coeffs[:n])
if 2*count0 > 16*n {
return count0, maxBin
}
}
return histogramStats(coeffs[:n])
}
// zeroBinStatsRef returns the number of coefficients in histogram bin 0
// and the largest bin (coeffBin).
func zeroBinStatsRef(coeffs [][16]int16) (int, int) {
count0, maxBin := 0, 0
for b := range coeffs {
for _, v := range coeffs[b] {
bin := coeffBin(v)
count0 += b2i(bin == 0)
maxBin = max(maxBin, bin)
}
}
return count0, maxBin
}
// coeffBin is the histogram bin of a DCT coefficient: min(|v| >> 3, 31).
func coeffBin(v int16) int {
a := int32(v)
s := a >> 31
return int(min((a^s-s)>>3, maxCoeffThresh)) & maxCoeffThresh
}
// histogramStats returns the largest bin count and the last non-empty bin
// of the histogram of coeffBin over the coefficients (at most 4096 of
// them). Most coefficients fall in bin 0, so the counting uses four
// interleaved sub-histograms: the increments do not form one serial chain
// through memory.
func histogramStats(coeffs [][16]int16) (int, int) {
var dist [4][maxCoeffThresh + 1]uint16
for b := range coeffs {
c := &coeffs[b]
for k := 0; k < 16; k += 4 {
dist[0][coeffBin(c[k])]++
dist[1][coeffBin(c[k+1])]++
dist[2][coeffBin(c[k+2])]++
dist[3][coeffBin(c[k+3])]++
}
}
maxValue, lastNonZero := 0, 1
for k := 0; k <= maxCoeffThresh; k++ {
value := int(dist[0][k]) + int(dist[1][k]) + int(dist[2][k]) + int(dist[3][k])
if value > 0 {
maxValue = max(maxValue, value)
lastNonZero = k
}
}
return maxValue, lastNonZero
}
// histogramStatsRef is the straightforward version of histogramStats.
func histogramStatsRef(coeffs [][16]int16) (int, int) {
var distribution [maxCoeffThresh + 1]int
for _, out := range coeffs {
for k := 0; k < 16; k++ {
v := int32(out[k])
s := v >> 31
distribution[min((v^s-s)>>3, maxCoeffThresh)&maxCoeffThresh]++
}
}
maxValue, lastNonZero := 0, 1
for k, value := range distribution {
if value > 0 {
if value > maxValue {
maxValue = value
}
lastNonZero = k
}
}
return maxValue, lastNonZero
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8enc
import (
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
"golang.org/x/sys/cpu"
)
// x86 implementations of the batched DSP entry points of dsp_batch.go:
// SSE4.1 kernels (128-bit, legacy encoding) in dsp_amd64.s and, where the
// 256-bit width pays off, AVX2 ones in dsp_avx2_amd64.s (the residual cost
// kernel is in cost_amd64.s). The wrappers below check every bound before
// calling the assembly, which then reads and writes exactly the bytes the
// reference implementation touches. All kernels are bit-exact with the Go
// reference code, so the encoder output does not depend on the build or
// on the CPU.
// x86MaxLevel is the highest kernel level this machine runs: cpuinfo.Max,
// except that the kernels also use POPCNT (present on every CPU with
// SSE4.2, but not part of the SSE41 level).
var x86MaxLevel = func() cpuinfo.Level {
if !cpu.X86.HasPOPCNT {
return cpuinfo.Go
}
return cpuinfo.Max
}()
// x86Level selects the kernels: below cpuinfo.SSE41 the Go reference, then
// the SSE4.1 kernels, and from cpuinfo.AVX2 the AVX2 kernels where there is
// one. Tests lower it to run every level against the Go reference.
//
// The trellis quantization of method 6 runs up to 16 blocks side by side
// (the 10 intra4 candidates of a sub-block, a diagonal of the 4 intra16
// candidates): 16 per register at the AVX512 level (trellis_amd64.s), 8
// at the AVX2 level (trellis_avx2_amd64.s). It is the only AVX-512
// kernel; the other kernels run their AVX2 versions on AVX-512 machines.
// The best other candidate, quantizeBlocks two blocks per register with
// VPERMW for the zigzag order and a mask register for the non-zero
// summary, was 8-12% faster than the AVX2 kernel but only 0.4% faster on
// a whole method 4 encode, both on an AMD EPYC 8024P (Zen 4) and an EPYC
// 4345P (Zen 5, full-width 512-bit units), and the other kernels are
// bound by their loads, not by the vector width.
var x86Level = x86MaxLevel
// vecKernels tells the mode search to call the batched entry points (one
// call per macroblock or per intra4 sub-block) rather than loop over the
// single-block Go functions; with the Go reference (x86Level lowered by a
// test) both give the same output.
var vecKernels = x86MaxLevel >= cpuinfo.SSE41
//go:noescape
func fTransformPairsSSE41(src, ref *byte, off *[8][2]uint16, n int, out *[16]int16)
//go:noescape
func iTransformPairsSSE41(ref *byte, in *[16]int16, dst *byte, off *[2]uint16, n int) int
//go:noescape
func quantizeBlocksSSE41(in, out *[16]int16, n int, m *matrix, info *uint16) uint32
//go:noescape
func tTransformPairsSSE41(a *byte, off *[8][2]uint16, n int, out *int32)
//go:noescape
func sse4x4PairsSSE41(a, b *byte, off *[8][2]uint16, n int, out *int32)
//go:noescape
func sse16xNSSE41(a, b *byte, rows int) int
//go:noescape
func predLuma16SSE41(p, left, top *byte)
//go:noescape
func predChroma8SSE41(p, uLeft, vLeft, uvTop *byte)
//go:noescape
func predLuma4SSE41(p, s *byte)
//go:noescape
func zeroBinStatsSSE41(c *[16]int16, n int) (count0, maxBin int)
//go:noescape
func fTransformPairsAVX2(src, ref *byte, off *[8][2]uint16, n int, out *[16]int16)
//go:noescape
func quantizeBlocksAVX2(in, out *[16]int16, n int, m *matrix, info *uint16) uint32
//go:noescape
func tTransformPairsAVX2(a *byte, off *[8][2]uint16, n int, out *int32)
//go:noescape
func iTransformPairsAVX2(ref *byte, in *[16]int16, dst *byte, off *[2]uint16, n int) int
//go:noescape
func sse16xNAVX2(a, b *byte, rows int) int
func zeroBinStats(coeffs [][16]int16) (int, int) {
if len(coeffs) > 16 {
panic("vp8enc: zeroBinStats: too many blocks")
}
if x86Level < cpuinfo.SSE41 || len(coeffs) == 0 {
return zeroBinStatsRef(coeffs)
}
return zeroBinStatsSSE41(&coeffs[0], len(coeffs))
}
// predLuma4 computes the 10 intra4 predictions into p from the boundary
// samples b[t-5..t+7] (see predLuma4Ref). The kernel loads 16 bytes from
// b[t-5]; the iterator's boundary array always has them.
func predLuma4(p []byte, b []byte, t int) {
if x86Level < cpuinfo.SSE41 || t < 5 || t+11 > len(b) {
predLuma4Ref(p, b, t)
return
}
if len(p) < i4DC4+7*bps+8 {
panic("vp8enc: predLuma4: buffer too small")
}
predLuma4SSE41(&p[i4DC4], &b[t-5])
}
// predLuma16 computes the 4 intra16 predictions into p; left (top-left
// then 16 samples) and top (16 samples) are nil when not available, which
// only happens on the picture edges and takes the Go code.
func predLuma16(p []byte, left, top []byte) {
if x86Level < cpuinfo.SSE41 || left == nil || top == nil {
predLuma16Ref(p, left, top)
return
}
if len(p) < i16HE16+15*bps+16 || len(left) < 17 || len(top) < 16 {
panic("vp8enc: predLuma16: buffer too small")
}
predLuma16SSE41(&p[0], &left[0], &top[0])
}
// predChroma8 computes the 4 chroma predictions into p (U and V side by
// side); uLeft, vLeft (top-left then 8 samples) and uvTop (8 U then 8 V
// samples) are nil when not available (picture edges: Go code).
func predChroma8(p []byte, uLeft, vLeft, uvTop []byte) {
if x86Level < cpuinfo.SSE41 || uLeft == nil || vLeft == nil || uvTop == nil {
predChroma8Ref(p, uLeft, vLeft, uvTop)
return
}
if len(p) < c8HE8+7*bps+16 || len(uLeft) < 9 || len(vLeft) < 9 || len(uvTop) < 16 {
panic("vp8enc: predChroma8: buffer too small")
}
predChroma8SSE41(&p[c8DC8], &uLeft[0], &vLeft[0], &uvTop[0])
}
func fTransformPairs(src, ref []byte, t *pairTable, out [][16]int16) {
if len(src) < t.need[0] || len(ref) < t.need[1] || len(out) < 2*t.n {
panic("vp8enc: fTransformPairs: buffer too small")
}
if x86Level < cpuinfo.SSE41 || t.n == 0 {
fTransformPairsRef(src, ref, t, out)
return
}
if x86Level >= cpuinfo.AVX2 {
fTransformPairsAVX2(&src[0], &ref[0], &t.off, t.n, &out[0])
return
}
fTransformPairsSSE41(&src[0], &ref[0], &t.off, t.n, &out[0])
}
// iTransformPairs runs the kernel, which stops before a pair holding a
// coefficient beyond its 16-bit range (|in| > 2047, see dsp_amd64.s);
// such a pair, rare in practice, takes the Go code, then the kernel
// resumes, so the pairs are still written in order. As in the reference,
// ref and dst must not overlap (the kernels read ahead of their stores).
func iTransformPairs(ref []byte, in [][16]int16, dst []byte, t *pairTable) {
if len(ref) < t.need[0] || len(dst) < t.need[1] || len(in) < 2*t.n {
panic("vp8enc: iTransformPairs: buffer too small")
}
if x86Level < cpuinfo.SSE41 || t.n == 0 {
iTransformPairsRef(ref, in, dst, t)
return
}
avx2 := x86Level >= cpuinfo.AVX2
for k := 0; k < t.n; k++ {
if avx2 {
k += iTransformPairsAVX2(&ref[0], &in[2*k], &dst[0], &t.off[k], t.n-k)
} else {
k += iTransformPairsSSE41(&ref[0], &in[2*k], &dst[0], &t.off[k], t.n-k)
}
if k < t.n {
r, d := int(t.off[k][0]), int(t.off[k][1])
iTransform(ref[r:], &in[2*k], dst[d:])
iTransform(ref[r+4:], &in[2*k+1], dst[d+4:])
}
}
}
func quantizeBlocks(in, out [][16]int16, m *matrix, info []uint16) uint32 {
n := len(in)
if len(out) < n || n > 32 || (info != nil && len(info) < n) {
panic("vp8enc: quantizeBlocks: bad block count")
}
if x86Level < cpuinfo.SSE41 || n == 0 || !m.vecOK {
return quantizeBlocksRef(in, out, m, info)
}
var pinfo *uint16
if info != nil {
pinfo = &info[0]
}
if x86Level >= cpuinfo.AVX2 {
return quantizeBlocksAVX2(&in[0], &out[0], n, m, pinfo)
}
return quantizeBlocksSSE41(&in[0], &out[0], n, m, pinfo)
}
func tTransformPairs(a []byte, t *pairTable, out []int32) {
if len(a) < t.need[0] || len(out) < 2*t.n {
panic("vp8enc: tTransformPairs: buffer too small")
}
if x86Level < cpuinfo.SSE41 || t.n == 0 {
tTransformPairsRef(a, t, out)
return
}
if x86Level >= cpuinfo.AVX2 {
tTransformPairsAVX2(&a[0], &t.off, t.n, &out[0])
return
}
tTransformPairsSSE41(&a[0], &t.off, t.n, &out[0])
}
// sse4x4Pairs has no AVX2 kernel: two pairs per 256-bit register measured
// slower than the SSE4.1 kernel (the row loads dominate).
func sse4x4Pairs(a, b []byte, t *pairTable, out []int32) {
if len(a) < t.need[0] || len(b) < t.need[1] || len(out) < 2*t.n {
panic("vp8enc: sse4x4Pairs: buffer too small")
}
if x86Level < cpuinfo.SSE41 || t.n == 0 {
sse4x4PairsRef(a, b, t, out)
return
}
sse4x4PairsSSE41(&a[0], &b[0], &t.off, t.n, &out[0])
}
func sse16x16(a, b []byte) int {
if len(a) < 15*bps+16 || len(b) < 15*bps+16 {
panic("vp8enc: sse16x16: buffer too small")
}
if x86Level < cpuinfo.SSE41 {
return sse16x16Ref(a, b)
}
if x86Level >= cpuinfo.AVX2 {
return sse16xNAVX2(&a[0], &b[0], 16)
}
return sse16xNSSE41(&a[0], &b[0], 16)
}
func sse16x8(a, b []byte) int {
if len(a) < 7*bps+16 || len(b) < 7*bps+16 {
panic("vp8enc: sse16x8: buffer too small")
}
if x86Level < cpuinfo.SSE41 {
return sse16x8Ref(a, b)
}
if x86Level >= cpuinfo.AVX2 {
return sse16xNAVX2(&a[0], &b[0], 8)
}
return sse16xNSSE41(&a[0], &b[0], 8)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import "math/bits"
// Batched DSP entry points. The mode search works on whole macroblocks
// (16 luma or 8 chroma 4x4 blocks per prediction mode) and on all 10
// intra4 modes of one sub-block at a time, so the kernels below take a
// list of block pairs instead of a single 4x4 block: an assembly
// implementation then pays the call overhead once per macroblock or
// sub-block, not once per 4x4 transform.
//
// The *Ref functions are the reference semantics, written on top of the
// single-block Go code of dsp.go; they are always compiled so that the
// tests can compare an assembly implementation against them. The entry
// points without the suffix (fTransformPairs, quantizeBlocks, ...) are
// bound to assembly in dsp_arm64.go and dsp_amd64.go (by kernel level) and
// to these references in dsp_generic.go.
// pairTable lists pairs of horizontally adjacent 4x4 blocks. Pair k is made
// of blocks 2k and 2k+1; off[k][0] and off[k][1] are the byte offsets of
// the left block of the pair from two base pointers (the right block is 4
// bytes further). Rows are bps bytes apart.
type pairTable struct {
off [8][2]uint16
n int // number of pairs
need [2]int // minimum length of the slices the offsets index
}
func newPairTable(offs ...[2]uint16) pairTable {
var t pairTable
t.n = len(offs)
for k, o := range offs {
t.off[k] = o
for i := 0; i < 2; i++ {
t.need[i] = max(t.need[i], int(o[i])+3*bps+8)
}
}
return t
}
// predOffI4 is the offset of the intra4 prediction of mode m from i4DC4 in
// the prediction buffer (modes 0-7 on the first 4 rows, 8-9 below).
func predOffI4(m int) uint16 { return uint16((m&7)*4 + (m>>3)*4*bps) }
var (
// tabY16: the 16 luma blocks in raster (vp8Scan) order; both offsets
// are the block position (source and prediction, or prediction and
// reconstruction, share the layout).
tabY16 = newPairTable(
[2]uint16{0, 0}, [2]uint16{8, 8},
[2]uint16{4 * bps, 4 * bps}, [2]uint16{4*bps + 8, 4*bps + 8},
[2]uint16{8 * bps, 8 * bps}, [2]uint16{8*bps + 8, 8*bps + 8},
[2]uint16{12 * bps, 12 * bps}, [2]uint16{12*bps + 8, 12*bps + 8})
// tabUV: the 8 chroma blocks in vp8ScanUV order (U then V).
tabUV = newPairTable(
[2]uint16{0, 0}, [2]uint16{4 * bps, 4 * bps},
[2]uint16{8, 8}, [2]uint16{4*bps + 8, 4*bps + 8})
// tabI4Src: the source sub-block (duplicated side by side, see
// iterator.i4Src) against the 10 intra4 predictions, which start at
// i4DC4.
tabI4Src = newPairTable(
[2]uint16{0, predOffI4(0)}, [2]uint16{0, predOffI4(2)}, [2]uint16{0, predOffI4(4)},
[2]uint16{0, predOffI4(6)}, [2]uint16{0, predOffI4(8)})
// tabI4Rec: the 10 intra4 predictions and their reconstructions, which
// use the same layout (iterator.i4Rec).
tabI4Rec = newPairTable(
[2]uint16{predOffI4(0), predOffI4(0)}, [2]uint16{predOffI4(2), predOffI4(2)},
[2]uint16{predOffI4(4), predOffI4(4)}, [2]uint16{predOffI4(6), predOffI4(6)},
[2]uint16{predOffI4(8), predOffI4(8)})
)
// fTransformPairsRef computes, for each pair k of t, out[2k+b] =
// fTransform(src[off[k][0]+4b:], ref[off[k][1]+4b:]), b = 0, 1.
func fTransformPairsRef(src, ref []byte, t *pairTable, out [][16]int16) {
for k := 0; k < t.n; k++ {
s, r := int(t.off[k][0]), int(t.off[k][1])
fTransform(src[s:], ref[r:], &out[2*k])
fTransform(src[s+4:], ref[r+4:], &out[2*k+1])
}
}
// iTransformPairsRef computes, for each pair k of t, the reconstruction
// iTransform(ref[off[k][0]+4b:], in[2k+b], dst[off[k][1]+4b:]), b = 0, 1.
func iTransformPairsRef(ref []byte, in [][16]int16, dst []byte, t *pairTable) {
for k := 0; k < t.n; k++ {
r, d := int(t.off[k][0]), int(t.off[k][1])
iTransform(ref[r:], &in[2*k], dst[d:])
iTransform(ref[r+4:], &in[2*k+1], dst[d+4:])
}
}
// levelInfoOf summarizes a block of quantized levels (zigzag order) for the
// rate and flatness estimates: bits 0-7 hold the index of the last
// non-zero level plus one (0 for an empty block), bits 8-15 the number of
// non-zero levels after the first (the AC levels).
//
// The Go mode search calls it for every quantized candidate block (the NEON
// quantizer computes the summary itself), so the non-zero mask is built
// four levels at a time instead of with a 16-step dependency chain.
func levelInfoOf(c *[16]int16) uint16 {
m := nonZero4(c[0], c[1], c[2], c[3]) | nonZero4(c[4], c[5], c[6], c[7])<<4 |
nonZero4(c[8], c[9], c[10], c[11])<<8 | nonZero4(c[12], c[13], c[14], c[15])<<12
return uint16(bits.Len32(m)) | uint16(bits.OnesCount32(m>>1))<<8
}
// nonZero4 returns a 4-bit mask with bit i set when the i-th argument is
// not zero. The levels are packed into 16-bit lanes: adding 0x7fff to the
// low 15 bits of a lane carries into its bit 15 when they are not all zero,
// and or-ing the lane itself adds its sign bit. The multiplication moves
// the four lane flags (bits 0, 16, 32 and 48) to bits 48-51; its other
// partial products land on distinct bits outside 48-51 or overflow, so
// there are no carries.
func nonZero4(a, b, c, d int16) uint32 {
const low15 = 0x7fff7fff7fff7fff
w := uint64(uint16(a)) | uint64(uint16(b))<<16 | uint64(uint16(c))<<32 | uint64(uint16(d))<<48
flags := ((w&low15 + low15) | w) >> 15 & 0x0001000100010001
return uint32(flags * 0x0001000200040008 >> 48)
}
// infoLast returns the index of the last non-zero level, or -1.
func infoLast(info uint16) int { return int(info&0xff) - 1 }
// infoNzAC returns the number of non-zero AC levels.
func infoNzAC(info uint16) int { return int(info >> 8) }
// quantizeBlocksRef quantizes each block of in into the matching block of
// out with quantizeBlock, and stores levelInfoOf of each block into info
// unless info is nil. Bit n of the result is set if block n has a non-zero
// level.
func quantizeBlocksRef(in, out [][16]int16, m *matrix, info []uint16) uint32 {
if len(out) < len(in) || len(in) > 32 || (info != nil && len(info) < len(in)) {
panic("vp8enc: quantizeBlocks: bad block count")
}
nz := uint32(0)
for n := range in {
if quantizeBlock(&in[n], &out[n], m) {
nz |= 1 << uint(n)
}
if info != nil {
info[n] = levelInfoOf(&out[n])
}
}
return nz
}
// sse4x4PairsRef computes out[2k+b] = sse4x4(a[off[k][0]+4b:],
// b[off[k][1]+4b:]).
func sse4x4PairsRef(a, b []byte, t *pairTable, out []int32) {
for k := 0; k < t.n; k++ {
x, y := int(t.off[k][0]), int(t.off[k][1])
out[2*k] = int32(sse4x4(a[x:], b[y:]))
out[2*k+1] = int32(sse4x4(a[x+4:], b[y+4:]))
}
}
// tTransformPairsRef computes out[2k+b] = tTransform(a[off[k][0]+4b:],
// &kWeightY); the second offset of the table is not used.
func tTransformPairsRef(a []byte, t *pairTable, out []int32) {
for k := 0; k < t.n; k++ {
x := int(t.off[k][0])
out[2*k] = tTransform(a[x:], &kWeightY)
out[2*k+1] = tTransform(a[x+4:], &kWeightY)
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"sync"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/bufpool"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// Algorithm adapted from libwebp (BSD-3-Clause).
const errorDiffusionQuality = 98 // quality below which error-diffusion is enabled
type encoder struct {
cfg Config
pic *Picture
mbW, mbH int
predsW int
numParts int
method int
rdOptLevel int
maxI4HeaderBits int
mbHeaderLimit int64
doSearch bool
profile int
// filter header
filterSimple bool
filterLevel int
filterSharpness int
// segment header
numSegments int
updateMap bool
segHdrSize int
dqm [numMBSegments]segmentInfo
baseQuant int
alpha int // global susceptibility
uvAlpha int // U/V quantization susceptibility
dqY1DC int
dqY2DC int
dqY2AC int
dqUVDC int
dqUVAC int
proba encProba
mbInfo []mbInfo
preds []uint8 // (4*mbW+1)*(4*mbH+1) intra modes, origin at predsW+1
nz []uint32 // mbW+1 non-zero contexts, nz[0] is the constant left border
yTop []byte // mbW*16 top luma samples
uvTop []byte // mbW*16 top chroma samples (8 U + 8 V per MB)
topDerr [][2][2]int8
lfStats *[numMBSegments][64]float64
lfStatsMem [numMBSegments][64]float64
tokens tokenBuffer
mbTokStart []int32 // start of each macroblock's tokens
parts [8]bitWriter
bw0 bitWriter
flat [numProbaSlots]uint8
it iterator
// analysis pass row bands (analysis.go)
bands [maxAnalysisBands]segmentJob
nextBand atomic.Int32
// stopped is set once Config.Interrupt fired during the analysis
// pass: the other bands then stop without polling it again.
stopped atomic.Bool
}
// encoderPool holds encoder structs (a few tens of KB, whatever the picture
// size): their buffers proportional to the picture area or to the output
// are detached by release and kept in the size-class pools instead.
var encoderPool = sync.Pool{New: func() any { return new(encoder) }}
func resize[T any](s []T, n int) []T {
if cap(s) < n {
return make([]T, n)
}
s = s[:n]
clear(s)
return s
}
// getCleared returns a zeroed buffer of length n from pool.
func getCleared[T any](pool *bufpool.Pool[T], n int) []T {
s := pool.Get(n)
clear(s)
return s
}
// release returns the buffers proportional to the picture area or to the
// output size to their pools.
func (e *encoder) release() {
e.pic = nil
e.cfg.Interrupt = nil // do not retain the caller's closure in the pool
e.tokens.release()
mbInfoPool.Put(e.mbInfo)
bytePool.Put(e.preds)
int32Pool.Put(e.mbTokStart)
e.mbInfo, e.preds, e.mbTokStart = nil, nil, nil
for i := range e.parts {
e.parts[i].release()
}
e.bw0.release()
}
// Encode encodes pic and returns the VP8 chunk payload (frame header,
// partition #0 and token partitions). The returned slice is owned by the
// caller.
func Encode(pic *Picture, cfg *Config) ([]byte, error) {
return EncodeWithHeadroom(pic, cfg, 0)
}
// EncodeWithHeadroom is Encode, with the payload written after headroom
// bytes reserved at the start of the returned slice: out[headroom:] is the
// VP8 chunk payload, and the caller can write the container headers into
// out[:headroom] instead of copying the payload. out is owned by the
// caller.
func EncodeWithHeadroom(pic *Picture, cfg *Config, headroom int) ([]byte, error) {
if pic == nil {
return nil, status.InvalidParam("vp8enc: nil picture")
}
if headroom < 0 {
return nil, status.InvalidParam("vp8enc: negative headroom")
}
c := DefaultConfig()
if cfg != nil {
c = *cfg
}
if c.Pass <= 1 {
// Like libwebp's WebPEncode (and unlike the cwebp tool, which
// raises the pass count), a size/PSNR target with a single pass
// does not search: the quality is used as is.
c.Pass = 1
}
if err := c.validate(); err != nil {
return nil, err
}
if err := pic.validate(); err != nil {
return nil, err
}
activeEncodes.Add(1)
defer activeEncodes.Add(-1)
e := encoderPool.Get().(*encoder)
defer func() {
e.release()
encoderPool.Put(e)
}()
e.setup(pic, &c)
if e.analyze() || c.interrupted() {
return nil, ErrInterrupted
}
if err := e.tokenLoop(); err != nil {
return nil, err
}
return e.write(headroom)
}
func (e *encoder) setup(pic *Picture, cfg *Config) {
e.cfg = *cfg
e.pic = pic
e.mbW = (pic.Width + 15) >> 4
e.mbH = (pic.Height + 15) >> 4
e.predsW = 4*e.mbW + 1
predsH := 4*e.mbH + 1
e.numParts = 1 << uint(cfg.Partitions)
e.mbInfo = getCleared(&mbInfoPool, e.mbW*e.mbH)
e.preds = getCleared(&bytePool, e.predsW*predsH)
e.nz = resize(e.nz, e.mbW+1)
e.yTop = resize(e.yTop, e.mbW*16)
e.uvTop = resize(e.uvTop, e.mbW*16)
if cfg.Quality <= errorDiffusionQuality || cfg.Pass > 1 {
e.topDerr = resize(e.topDerr, e.mbW)
} else {
e.topDerr = nil
}
e.lfStats = nil
if cfg.Autofilter {
e.lfStats = &e.lfStatsMem
}
useFilter := cfg.FilterStrength > 0 || cfg.Autofilter
switch {
case !useFilter:
e.profile = 2
case cfg.FilterType == 1:
e.profile = 0
default:
e.profile = 1
}
// MapConfigToTools
e.method = cfg.Method
switch {
case e.method >= 6:
e.rdOptLevel = rdOptTrellisAll
case e.method >= 5:
e.rdOptLevel = rdOptTrellis
case e.method >= 3:
e.rdOptLevel = rdOptBasic
default:
e.rdOptLevel = rdOptNone
}
// libwebp 1.6 codes methods >= 3 from its token buffer unless
// low_memory is set, and the token path supports a single partition
// only (MapConfigToTools: "doesn't work with multi-partition"): the
// Partitions setting is then ignored. Mirror that, so that the number
// of partitions in the output is the one cwebp writes.
if e.method >= 3 && !cfg.LowMemory {
e.numParts = 1
}
limit := 100 - cfg.PartitionLimit
e.maxI4HeaderBits = 256 * 16 * 16 * (limit * limit) / (100 * 100)
e.mbHeaderLimit = int64(256*510*8*1024) / int64(e.mbW*e.mbH)
e.doSearch = cfg.TargetSize > 0 || cfg.TargetPSNR > 0
e.proba.reset()
e.numSegments = cfg.Segments
e.updateMap = e.numSegments > 1
e.segHdrSize = 0
e.filterSimple = true
e.filterLevel = 0
e.filterSharpness = 0
e.dqm = [numMBSegments]segmentInfo{}
e.alpha, e.uvAlpha = 0, 0
e.tokens.reset()
e.mbTokStart = getCleared(&int32Pool, e.mbW*e.mbH+1)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
// Loop-filter strength selection (autofilter) based on SSIM of the filtered
// reconstruction.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
maxLFLevels = 64
ssimKernel = 3
ssimKernelLen = 2*ssimKernel + 1
)
func absInt(v int) int {
if v < 0 {
return -v
}
return v
}
func sclip1(v int) int { return clipInt(v, -128, 127) } // clips [-1020, 1020] to [-128, 127]
func sclip2(v int) int { return clipInt(v, -16, 15) } // clips [-112, 112] to [-16, 15]
func uclip(v int) byte { return byte(clipInt(v, 0, 255)) }
func doFilter2(p []byte, i, step int) {
p1, p0, q0, q1 := int(p[i-2*step]), int(p[i-step]), int(p[i]), int(p[i+step])
a := 3*(q0-p0) + sclip1(p1-q1)
a1 := sclip2((a + 4) >> 3)
a2 := sclip2((a + 3) >> 3)
p[i-step] = uclip(p0 + a2)
p[i] = uclip(q0 - a1)
}
func doFilter4(p []byte, i, step int) {
p1, p0, q0, q1 := int(p[i-2*step]), int(p[i-step]), int(p[i]), int(p[i+step])
a := 3 * (q0 - p0)
a1 := sclip2((a + 4) >> 3)
a2 := sclip2((a + 3) >> 3)
a3 := (a1 + 1) >> 1
p[i-2*step] = uclip(p1 + a3)
p[i-step] = uclip(p0 + a2)
p[i] = uclip(q0 - a1)
p[i+step] = uclip(q1 - a3)
}
func hev(p []byte, i, step, thresh int) bool {
p1, p0, q0, q1 := int(p[i-2*step]), int(p[i-step]), int(p[i]), int(p[i+step])
return absInt(p1-p0) > thresh || absInt(q1-q0) > thresh
}
func needsFilter(p []byte, i, step, t int) bool {
p1, p0, q0, q1 := int(p[i-2*step]), int(p[i-step]), int(p[i]), int(p[i+step])
return 4*absInt(p0-q0)+absInt(p1-q1) <= t
}
func needsFilter2(p []byte, i, step, t, it int) bool {
p3, p2, p1, p0 := int(p[i-4*step]), int(p[i-3*step]), int(p[i-2*step]), int(p[i-step])
q0, q1, q2, q3 := int(p[i]), int(p[i+step]), int(p[i+2*step]), int(p[i+3*step])
if 4*absInt(p0-q0)+absInt(p1-q1) > t {
return false
}
return absInt(p3-p2) <= it && absInt(p2-p1) <= it && absInt(p1-p0) <= it &&
absInt(q3-q2) <= it && absInt(q2-q1) <= it && absInt(q1-q0) <= it
}
// simpleFilter16i filters the 3 inner vertical (hstride=1) or horizontal
// edges of a 16x16 block starting at p[0].
func simpleFilter16i(p []byte, hstride, vstride, thresh int) {
thresh2 := 2*thresh + 1
for k := 1; k <= 3; k++ {
base := 4 * k * hstride
for i := 0; i < 16; i++ {
o := base + i*vstride
if needsFilter(p, o, hstride, thresh2) {
doFilter2(p, o, hstride)
}
}
}
}
func filterLoop24(p []byte, base, hstride, vstride, size, thresh, ithresh, hevThresh int) {
thresh2 := 2*thresh + 1
for i := 0; i < size; i++ {
o := base + i*vstride
if needsFilter2(p, o, hstride, thresh2, ithresh) {
if hev(p, o, hstride, hevThresh) {
doFilter2(p, o, hstride)
} else {
doFilter4(p, o, hstride)
}
}
}
}
// doFilter applies the inner-edge loop filter of the given level to a copy
// of the reconstruction (into yuvOut2).
func (it *iterator) doFilter(level int) {
e := it.enc
ilevel := getILevel(e.cfg.FilterSharpness, level)
limit := 2*level + ilevel
dst := it.yuvOut2
copy(dst[:yuvSize], it.yuvOut[:yuvSize])
y := dst[yOff:]
if e.filterSimple {
simpleFilter16i(y, 1, bps, limit) // horizontal filtering of vertical edges
simpleFilter16i(y, bps, 1, limit) // vertical filtering of horizontal edges
return
}
hevThresh := 0
if level >= 40 {
hevThresh = 2
} else if level >= 15 {
hevThresh = 1
}
for k := 1; k <= 3; k++ { // HFilter16i
filterLoop24(y, 4*k, 1, bps, 16, limit, ilevel, hevThresh)
}
filterLoop24(dst, uOff+4, 1, bps, 8, limit, ilevel, hevThresh) // HFilter8i
filterLoop24(dst, vOff+4, 1, bps, 8, limit, ilevel, hevThresh)
for k := 1; k <= 3; k++ { // VFilter16i
filterLoop24(y, 4*k*bps, bps, 1, 16, limit, ilevel, hevThresh)
}
filterLoop24(dst, uOff+4*bps, bps, 1, 8, limit, ilevel, hevThresh) // VFilter8i
filterLoop24(dst, vOff+4*bps, bps, 1, 8, limit, ilevel, hevThresh)
}
func getILevel(sharpness, level int) int {
if sharpness > 0 {
if sharpness > 4 {
level >>= 2
} else {
level >>= 1
}
if level > 9-sharpness {
level = 9 - sharpness
}
}
if level < 1 {
level = 1
}
return level
}
var kSSIMWeight = [ssimKernelLen]uint32{1, 2, 3, 4, 3, 2, 1}
func ssimGetClipped(src1, src2 []byte, xo, yo, W, H int) float64 {
var w, xm, ym, xxm, xym, yym uint32
ymin := max(yo-ssimKernel, 0)
ymax := min(yo+ssimKernel, H-1)
xmin := max(xo-ssimKernel, 0)
xmax := min(xo+ssimKernel, W-1)
for y := ymin; y <= ymax; y++ {
r1 := src1[y*bps:]
r2 := src2[y*bps:]
wy := kSSIMWeight[ssimKernel+y-yo]
for x := xmin; x <= xmax; x++ {
ww := kSSIMWeight[ssimKernel+x-xo] * wy
s1 := uint32(r1[x])
s2 := uint32(r2[x])
w += ww
xm += ww * s1
ym += ww * s2
xxm += ww * s1 * s1
xym += ww * s1 * s2
yym += ww * s2 * s2
}
}
return ssimCalculation(w, xm, ym, xxm, xym, yym)
}
func ssimCalculation(N, xm, ym, xxm, xym, yym uint32) float64 {
w2 := uint64(N) * uint64(N)
C1 := 20 * w2
C2 := 60 * w2
C3 := 8 * 8 * w2 // 'dark' limit ~= 6
xmxm := uint64(xm) * uint64(xm)
ymym := uint64(ym) * uint64(ym)
if xmxm+ymym >= C3 {
xmym := int64(xm) * int64(ym)
sxy := int64(xym)*int64(N) - xmym // can be negative
sxx := uint64(xxm)*uint64(N) - xmxm
syy := uint64(yym)*uint64(N) - ymym
if sxy < 0 {
sxy = 0
}
numS := (2*uint64(sxy) + C2) >> 8
denS := (sxx + syy + C2) >> 8
fnum := (2*uint64(xmym) + C1) * numS
fden := (xmxm + ymym + C1) * denS
return float64(fnum) / float64(fden)
}
return 1
}
func getMBSSIM(yuv1, yuv2 []byte) float64 {
sum := 0.
for y := ssimKernel; y < 16-ssimKernel; y++ {
for x := ssimKernel; x < 16-ssimKernel; x++ {
sum += ssimGetClipped(yuv1[yOff:], yuv2[yOff:], x, y, 16, 16)
}
}
for x := 1; x < 7; x++ {
for y := 1; y < 7; y++ {
sum += ssimGetClipped(yuv1[uOff:], yuv2[uOff:], x, y, 8, 8)
sum += ssimGetClipped(yuv1[vOff:], yuv2[vOff:], x, y, 8, 8)
}
}
return sum
}
func (e *encoder) initFilter() {
if e.lfStats != nil {
*e.lfStats = [numMBSegments][64]float64{}
}
}
func (e *encoder) storeFilterStats(it *iterator) {
if e.lfStats == nil {
return
}
mb := it.mb()
if mb.typ == 1 && mb.skip {
return
}
s := int(mb.segment & 3)
level0, deltaMin, deltaMax, stepSize := e.filterLevels(s)
e.lfStats[s][0] += getMBSSIM(it.yuvIn, it.yuvOut)
for d := deltaMin; d <= deltaMax; d += stepSize {
level := level0 + d
if level <= 0 || level >= maxLFLevels {
continue
}
it.doFilter(level)
e.lfStats[s][level] += getMBSSIM(it.yuvIn, it.yuvOut2)
}
}
// maxFilterSSIMs bounds the number of values appendFilterSSIMs appends for
// one macroblock: the unfiltered SSIM and one per level in (0, maxLFLevels).
const maxFilterSSIMs = maxLFLevels
// filterLevels returns the filter levels storeFilterStats tries for
// segment s: level0+d for d from deltaMin to deltaMax by step, skipping
// the levels outside (0, maxLFLevels).
func (e *encoder) filterLevels(s int) (level0, deltaMin, deltaMax, step int) {
level0 = e.dqm[s].fstrength
deltaMin = -e.dqm[s].quant
deltaMax = e.dqm[s].quant
step = 1
if deltaMax-deltaMin >= 4 {
step = 4
}
return
}
// appendFilterSSIMs is storeFilterStats for the wavefront pass: it appends
// the values storeFilterStats would add to lfStats for the current
// macroblock to dst, in the same order, and addFilterSSIMs adds them later
// in raster order (floating-point sums depend on the order).
func (it *iterator) appendFilterSSIMs(dst []float64) []float64 {
e := it.enc
mb := it.mb()
if mb.typ == 1 && mb.skip {
return dst
}
level0, deltaMin, deltaMax, step := e.filterLevels(int(mb.segment & 3))
dst = append(dst, getMBSSIM(it.yuvIn, it.yuvOut))
for d := deltaMin; d <= deltaMax; d += step {
level := level0 + d
if level <= 0 || level >= maxLFLevels {
continue
}
it.doFilter(level)
dst = append(dst, getMBSSIM(it.yuvIn, it.yuvOut2))
}
return dst
}
// addFilterSSIMs adds the values appendFilterSSIMs recorded for macroblock
// mb, starting at vals[pos], to lfStats and returns the position of the
// next macroblock's values.
func (e *encoder) addFilterSSIMs(mb *mbInfo, vals []float64, pos int) int {
if mb.typ == 1 && mb.skip {
return pos
}
s := int(mb.segment & 3)
level0, deltaMin, deltaMax, step := e.filterLevels(s)
e.lfStats[s][0] += vals[pos]
pos++
for d := deltaMin; d <= deltaMax; d += step {
level := level0 + d
if level <= 0 || level >= maxLFLevels {
continue
}
e.lfStats[s][level] += vals[pos]
pos++
}
return pos
}
func (e *encoder) adjustFilterStrength() {
if e.lfStats != nil {
for s := 0; s < numMBSegments; s++ {
bestLevel := 0
bestV := 1.00001 * e.lfStats[s][0]
for i := 1; i < maxLFLevels; i++ {
v := e.lfStats[s][i]
if v > bestV {
bestV = v
bestLevel = i
}
}
e.dqm[s].fstrength = bestLevel
}
// With a single segment the level is only carried by the filter
// header (libwebp leaves it unchanged, making autofilter a no-op).
if e.numSegments == 1 {
e.filterLevel = e.dqm[0].fstrength
}
return
}
if e.cfg.FilterStrength > 0 {
maxLevel := 0
for s := 0; s < numMBSegments; s++ {
dqm := &e.dqm[s]
delta := (dqm.maxEdge * int(dqm.y2.q[1])) >> 3
level := filterStrengthFromDelta(e.filterSharpness, delta)
if level > dqm.fstrength {
dqm.fstrength = level
}
if maxLevel < dqm.fstrength {
maxLevel = dqm.fstrength
}
}
e.filterLevel = maxLevel
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"math"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// Main coding loop, probabilities finalization and bitstream assembly.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
maxPartition0Size = 1 << 19
maxPartitionSize = 1 << 24
headerSizeEstimate = 12 + 8 + 10 // RIFF + chunk header + VP8 frame header
dqLimit = 0.4
minCount = 96
skipProbaThreshold = 250
)
// partition0SizeLimit is the header bit estimate (1/256 bits) above which a
// pass is redone with a stronger limit on the intra4 header bits. It is a
// variable so that tests can reach that path with small pictures.
var partition0SizeLimit = uint64(maxPartition0Size-2048) << 11
// maxTokens is the largest number of tokens a coding pass may record: the
// macroblocks' token offsets (mbTokStart) are int32. A pass that needs more
// fails with ErrTooManyTokens. It is a variable so that tests can reach that
// path with small pictures.
var maxTokens = math.MaxInt32
type passStats struct {
isFirst bool
dq float32
q, lastQ float32
qmin, qmax float32
value float64
lastValue float64
target float64
doSizeSearch bool
}
func clampF(v, lo, hi float32) float32 {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
func (e *encoder) initPassStats(s *passStats) {
s.isFirst = true
s.dq = 10
s.qmin = 0
s.qmax = 100
s.q = clampF(e.cfg.Quality, s.qmin, s.qmax)
s.lastQ = s.q
s.doSizeSearch = e.cfg.TargetSize != 0
switch {
case s.doSizeSearch:
s.target = float64(e.cfg.TargetSize)
case e.cfg.TargetPSNR > 0:
s.target = float64(e.cfg.TargetPSNR)
default:
s.target = 40
}
s.value, s.lastValue = 0, 0
}
func (s *passStats) computeNextQ() float32 {
var dq float32
if s.isFirst {
if s.value > s.target {
dq = -s.dq
} else {
dq = s.dq
}
s.isFirst = false
} else if s.value != s.lastValue {
slope := (s.target - s.value) / (s.lastValue - s.value)
dq = float32(slope * float64(s.lastQ-s.q))
} else {
dq = 0
}
s.dq = clampF(dq, -30, 30)
s.lastQ = s.q
s.lastValue = s.value
s.q = clampF(s.q+s.dq, s.qmin, s.qmax)
return s.q
}
func getProba(a, b int) uint8 {
total := a + b
if total == 0 {
return 255
}
return uint8((255*a + total/2) / total)
}
func (e *encoder) setSegmentProbas() {
var p [numMBSegments]int
for i := range e.mbInfo {
p[e.mbInfo[i].segment&3]++
}
if e.numSegments > 1 {
probas := &e.proba.segments
probas[0] = getProba(p[0]+p[1], p[2]+p[3])
probas[1] = getProba(p[0], p[1])
probas[2] = getProba(p[2], p[3])
e.updateMap = probas[0] != 255 || probas[1] != 255 || probas[2] != 255
if !e.updateMap {
for i := range e.mbInfo {
e.mbInfo[i].segment = 0
}
}
e.segHdrSize = p[0]*(bitCost(0, probas[0])+bitCost(0, probas[1])) +
p[1]*(bitCost(0, probas[0])+bitCost(1, probas[1])) +
p[2]*(bitCost(1, probas[0])+bitCost(0, probas[2])) +
p[3]*(bitCost(1, probas[0])+bitCost(1, probas[2]))
} else {
e.updateMap = false
e.segHdrSize = 0
}
}
func (e *encoder) setLoopParams(q float32) {
q = clampF(q, 0, 100)
e.setSegmentParams(float64(q))
e.setSegmentProbas()
e.proba.calculateLevelCosts()
e.proba.nbSkip = 0
}
func getPSNR(mse, size uint64) float64 {
if mse > 0 && size > 0 {
return 10 * math.Log10(255*255*float64(size)/float64(mse))
}
return 99
}
// recordTokens records the coefficient tokens of the current macroblock into
// tb and their statistics into stats.
func (it *iterator) recordTokens(rd *modeScore, tb *tokenBuffer, stats *[numTypes]statsArray) {
var res residual
it.nzToBytes()
if it.mb().typ == 1 { // i16x16
ctx := it.topNz[8] + it.leftNz[8]
res.first, res.ctype = 0, typeI16DC
res.setCoeffs(&rd.yDCLevels)
v := tb.recordCoeffTokens(ctx, &res, stats)
it.topNz[8] = v
it.leftNz[8] = v
res.first, res.ctype = 1, typeI16AC
} else {
res.first, res.ctype = 0, typeI4AC
}
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
ctx := it.topNz[x] + it.leftNz[y]
res.setCoeffs(&rd.yACLevels[x+y*4])
v := tb.recordCoeffTokens(ctx, &res, stats)
it.topNz[x] = v
it.leftNz[y] = v
}
}
res.first, res.ctype = 0, typeChromaA
for ch := 0; ch <= 2; ch += 2 {
for y := 0; y < 2; y++ {
for x := 0; x < 2; x++ {
ctx := it.topNz[4+ch+x] + it.leftNz[4+ch+y]
res.setCoeffs(&rd.uvLevels[ch*2+x+y*2])
v := tb.recordCoeffTokens(ctx, &res, stats)
it.topNz[4+ch+x] = v
it.leftNz[4+ch+y] = v
}
}
}
it.bytesToNz()
}
// tokenLoop runs the coding passes, recording all tokens.
func (e *encoder) tokenLoop() error {
nbMBs := e.mbW * e.mbH
maxCount := max(nbMBs>>3, minCount)
numPassLeft := e.cfg.Pass
pixelCount := uint64(nbMBs) * 384
it := &e.it
var stats passStats
e.initPassStats(&stats)
for numPassLeft > 0 {
numPassLeft--
isLastPass := math.Abs(float64(stats.dq)) <= dqLimit || numPassLeft == 0 || e.maxI4HeaderBits == 0
it.init(e)
e.setLoopParams(stats.q)
if isLastPass {
e.proba.stats = [numTypes]statsArray{}
e.initFilter()
}
e.tokens.reset()
sizeP0, distortion, err := e.codePass(isLastPass, maxCount)
if err != nil {
return err
}
e.mbTokStart[nbMBs] = int32(e.tokens.len()) // <= maxTokens: codePass checked it
sizeP0 += uint64(e.segHdrSize)
if stats.doSizeSearch {
size := uint64(e.proba.finalizeTokenProbas())
flattenProbas(&e.flat, &e.proba.coeffs)
size += e.tokens.estimateSize(&e.flat)
size = (size + sizeP0 + 1024) >> 11
size += headerSizeEstimate
stats.value = float64(size)
} else {
stats.value = getPSNR(distortion, pixelCount)
}
if e.maxI4HeaderBits > 0 && sizeP0 > partition0SizeLimit {
numPassLeft++
e.maxI4HeaderBits >>= 1 // strengthen header bit limitation...
continue // ...and start over
}
if isLastPass {
break
}
if e.doSearch {
stats.computeNextQ()
}
}
// Skip probability: only use it when it saves bits.
nbSkip := 0
for i := range e.mbInfo {
if e.mbInfo[i].skip {
nbSkip++
}
}
e.proba.nbSkip = nbSkip
skipProba := 255
if nbMBs > 0 {
skipProba = (nbMBs - nbSkip) * 255 / nbMBs
}
e.proba.skipProba = uint8(skipProba)
e.proba.useSkipProba = skipProba < skipProbaThreshold
if e.proba.useSkipProba {
// recompute the statistics without the skipped macroblocks
e.proba.stats = [numTypes]statsArray{}
for i := 0; i < nbMBs; i++ {
if !e.mbInfo[i].skip {
e.tokens.recordStatsRange(int(e.mbTokStart[i]), int(e.mbTokStart[i+1]), &e.proba.stats)
}
}
}
e.proba.finalizeTokenProbas()
e.adjustFilterStrength()
return nil
}
// codePass codes every macroblock once (one pass of tokenLoop): it picks
// the modes, records the tokens into e.tokens (e.mbTokStart) and their
// statistics, refreshing the cost tables every maxCount+1 macroblocks, and
// the autofilter statistics on the last pass. It returns the sum of the
// header bit estimates and of the distortions.
//
// With ThreadLevel the pass runs as a wavefront on helper goroutines when
// the picture is large enough and the budget has a free slot
// (codePassWavefront); the result is the same.
func (e *encoder) codePass(isLastPass bool, maxCount int) (sizeP0, distortion uint64, err error) {
if nw := e.wavefrontWorkers(); nw > 1 {
if sizeP0, distortion, ran, err := e.codePassWavefront(nw, isLastPass, maxCount); ran {
return sizeP0, distortion, err
}
}
it := &e.it
rd := &it.rd
rdOpt := e.rdOptLevel
cnt := maxCount
for {
if it.x == 0 && e.cfg.interrupted() {
return 0, 0, ErrInterrupted
}
it.importMB()
if rdOpt > rdOptNone {
cnt--
if cnt < 0 {
e.proba.finalizeTokenProbas()
e.proba.calculateLevelCosts()
cnt = maxCount
}
}
it.decimate(rd, rdOpt)
e.mbTokStart[it.mbIdx] = int32(e.tokens.len()) // <= maxTokens, checked below
it.recordTokens(rd, &e.tokens, &e.proba.stats)
if e.tokens.len() > maxTokens {
return 0, 0, ErrTooManyTokens
}
sizeP0 += uint64(rd.H)
distortion += uint64(rd.D)
if isLastPass {
e.storeFilterStats(it)
}
it.saveBoundary()
if !it.next() {
break
}
}
e.mergeMaxEdge(it)
return sizeP0, distortion, nil
}
//------------------------------------------------------------------------------
// Bitstream writing
func putI4Mode(bw *bitWriter, mode int, prob *[numBModes - 1]uint8) int {
if bw.putBit(mode != bDCPred, int(prob[0])) {
if bw.putBit(mode != bTMPred, int(prob[1])) {
if bw.putBit(mode != bVEPred, int(prob[2])) {
if !bw.putBit(mode >= bLDPred, int(prob[3])) {
if bw.putBit(mode != bHEPred, int(prob[4])) {
bw.putBit(mode != bRDPred, int(prob[5]))
}
} else {
if bw.putBit(mode != bLDPred, int(prob[6])) {
if bw.putBit(mode != bVLPred, int(prob[7])) {
bw.putBit(mode != bHDPred, int(prob[8]))
}
}
}
}
}
}
return mode
}
// Intra4 modes (libwebp numbering).
const (
bDCPred = iota
bTMPred
bVEPred
bHEPred
bRDPred
bVRPred
bLDPred
bVLPred
bHDPred
bHUPred
)
func putI16Mode(bw *bitWriter, mode int) {
if bw.putBit(mode == predTM || mode == predHE, 156) {
bw.putBit(mode == predTM, 128) // TM or HE
} else {
bw.putBit(mode == predVE, 163) // VE or DC
}
}
func putUVMode(bw *bitWriter, uvMode int) {
if bw.putBit(uvMode != predDC, 142) {
if bw.putBit(uvMode != predVE, 114) {
bw.putBit(uvMode != predHE, 183) // else: TM_PRED
}
}
}
func putSegment(bw *bitWriter, s int, p *[3]uint8) {
if bw.putBit(s >= 2, int(p[0])) {
bw.putBit(s&1 != 0, int(p[2]))
} else {
bw.putBit(s&1 != 0, int(p[1]))
}
}
func (e *encoder) codeIntraModes(bw *bitWriter) {
predsW := e.predsW
for my := 0; my < e.mbH; my++ {
for mx := 0; mx < e.mbW; mx++ {
mb := &e.mbInfo[my*e.mbW+mx]
p := predsW + 1 + my*4*predsW + mx*4
if e.updateMap {
putSegment(bw, int(mb.segment), &e.proba.segments)
}
if e.proba.useSkipProba {
bw.putBit(mb.skip, int(e.proba.skipProba))
}
if bw.putBit(mb.typ != 0, 145) { // i16x16
putI16Mode(bw, int(e.preds[p]))
} else {
topPred := p - predsW
for y := 0; y < 4; y++ {
left := int(e.preds[p-1])
for x := 0; x < 4; x++ {
probas := &bModesProba[e.preds[topPred+x]%numBModes][left%numBModes]
left = putI4Mode(bw, int(e.preds[p+x]%numBModes), probas)
}
topPred = p
p += predsW
}
}
putUVMode(bw, int(mb.uvMode))
}
}
}
func (e *encoder) writeProbas(bw *bitWriter) {
for t := 0; t < numTypes; t++ {
for b := 0; b < numBands; b++ {
for c := 0; c < numCtx; c++ {
for p := 0; p < numProbas; p++ {
p0 := e.proba.coeffs[t][b][c][p]
update := p0 != coeffsProba0[t][b][c][p]
if bw.putBit(update, int(coeffsUpdateProba[t][b][c][p])) {
bw.putBits(uint32(p0), 8)
}
}
}
}
}
if bw.putBitUniform(e.proba.useSkipProba) {
bw.putBits(uint32(e.proba.skipProba), 8)
}
}
func (e *encoder) putSegmentHeader(bw *bitWriter) {
if bw.putBitUniform(e.numSegments > 1) {
bw.putBitUniform(e.updateMap)
if bw.putBitUniform(true) { // update_data
bw.putBitUniform(true) // absolute values
for s := 0; s < numMBSegments; s++ {
bw.putSignedBits(e.dqm[s].quant, 7)
}
for s := 0; s < numMBSegments; s++ {
bw.putSignedBits(e.dqm[s].fstrength, 6)
}
}
if e.updateMap {
for s := 0; s < 3; s++ {
if bw.putBitUniform(e.proba.segments[s] != 255) {
bw.putBits(uint32(e.proba.segments[s]), 8)
}
}
}
}
}
func (e *encoder) putFilterHeader(bw *bitWriter) {
bw.putBitUniform(e.filterSimple)
bw.putBits(uint32(e.filterLevel), 6)
bw.putBits(uint32(e.filterSharpness), 3)
bw.putBitUniform(false) // no lf-delta
}
func (e *encoder) putQuant(bw *bitWriter) {
bw.putBits(uint32(e.baseQuant), 7)
bw.putSignedBits(e.dqY1DC, 4)
bw.putSignedBits(e.dqY2DC, 4)
bw.putSignedBits(e.dqY2AC, 4)
bw.putSignedBits(e.dqUVDC, 4)
bw.putSignedBits(e.dqUVAC, 4)
}
func (e *encoder) generatePartition0() []byte {
bw := &e.bw0
bw.init(e.mbW*e.mbH*7/8 + 1024)
bw.putBitUniform(false) // colorspace
bw.putBitUniform(false) // clamp type
e.putSegmentHeader(bw)
e.putFilterHeader(bw)
var np uint32
switch e.numParts {
case 8:
np = 3
case 4:
np = 2
case 2:
np = 1
}
bw.putBits(np, 2)
e.putQuant(bw)
bw.putBitUniform(false) // no proba update
e.writeProbas(bw)
e.codeIntraModes(bw)
return bw.finish()
}
// write assembles the frame after headroom bytes left for the caller.
func (e *encoder) write(headroom int) ([]byte, error) {
// token partitions
flattenProbas(&e.flat, &e.proba.coeffs)
nbMBs := e.mbW * e.mbH
estimate := e.tokens.len()/(6*e.numParts) + 1024
for p := 0; p < e.numParts; p++ {
e.parts[p].init(estimate)
}
mask := e.numParts - 1
for i := 0; i < nbMBs; i++ {
if e.proba.useSkipProba && e.mbInfo[i].skip {
continue
}
y := i / e.mbW
e.tokens.emitTokenRange(&e.parts[y&mask], int(e.mbTokStart[i]), int(e.mbTokStart[i+1]), &e.flat)
}
var parts [8][]byte
total := 0
for p := 0; p < e.numParts; p++ {
parts[p] = e.parts[p].finish()
if p < e.numParts-1 && len(parts[p]) >= maxPartitionSize {
return nil, status.InvalidParam("vp8enc: token partition overflow")
}
total += len(parts[p])
}
part0 := e.generatePartition0()
size0 := len(part0)
if size0 >= maxPartition0Size {
return nil, status.InvalidParam("vp8enc: partition #0 overflow (try a higher PartitionLimit)")
}
total += 10 + size0 + 3*(e.numParts-1)
// One spare byte for the RIFF padding byte that a writer framing the
// payload in place (out[:headroom]) appends to an odd-sized payload.
out := make([]byte, headroom, headroom+total+1)
bits := uint32(0) | uint32(e.profile)<<1 | 1<<4 | uint32(size0)<<5
out = append(out, byte(bits), byte(bits>>8), byte(bits>>16), 0x9d, 0x01, 0x2a,
byte(e.pic.Width), byte(e.pic.Width>>8), byte(e.pic.Height), byte(e.pic.Height>>8))
out = append(out, part0...)
for p := 0; p < e.numParts-1; p++ {
s := len(parts[p])
out = append(out, byte(s), byte(s>>8), byte(s>>16))
}
for p := 0; p < e.numParts; p++ {
out = append(out, parts[p]...)
}
return out, nil
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
// Macroblock iterator: walks the macroblocks, keeping the neighbouring
// samples, prediction modes and non-zero contexts up to date.
// Algorithm adapted from libwebp (BSD-3-Clause).
// mbInfo holds the coding decisions of one macroblock.
type mbInfo struct {
typ uint8 // 0=i4x4, 1=i16x16
uvMode uint8
segment uint8
alpha uint8 // quantization-susceptibility
skip bool
}
// vp8TopLeftI4 gives, for each 4x4 sub-block, the position of its top
// sample in the boundary array.
var vp8TopLeftI4 = [16]int{
17, 21, 25, 29,
13, 17, 21, 25,
9, 13, 17, 21,
5, 9, 13, 17,
}
type iterator struct {
enc *encoder
x, y int
yuvIn, yuvOut, yuvOut2, yuvP []byte
predsIdx int // index of the current macroblock's modes in enc.preds
mbIdx int // index of the current macroblock in enc.mbInfo
countDown int
i4 int // current intra4x4 sub-block
i4Top int // index of the top sample in i4Boundary
doTrellis bool // perform extra level optimisation
analysis bool // boundary samples come from the source (analysis pass)
topNz [9]int
leftNz [9]int // leftNz[8] is independent
leftDerr [2][2]int8
i4Boundary [40]byte
// maxEdge is the largest edge delta of each segment over the
// macroblocks this iterator coded in the current pass (merged into
// segmentInfo.maxEdge by mergeMaxEdge: every iterator of a wavefront
// pass keeps its own).
maxEdge [numMBSegments]int
// yLeft[0] is the top-left sample, yLeft[1..16] the left column.
yLeft [17]byte
uLeft, vLeft [9]byte
tmp32 [32]byte // source top samples (analysis pass)
// scratch
tmp16 [16][16]int16
tmpUV [8][16]int16
tmpLevels [1][16]int16
i4Levels [16][16]int16
srcTT [16]int32 // texture transform of the source luma blocks
tt16 [16]int32 // texture transform of a reconstructed macroblock
i4m i4Modes // the 10 intra4 candidates of the current sub-block
i16b i16Batch // the 4 intra16 candidates, quantized in one batch
rdTmp modeScore
rdUV modeScore
rd modeScore
yuvMem [3*yuvSize + predSize]byte
}
// init resets the iterator and the encoder's top context for a pass over
// the frame.
func (it *iterator) init(e *encoder) {
it.reset(e)
e.initTop()
}
// reset resets the iterator only (helper iterators of the analysis pass,
// which does not use the encoder's top context).
func (it *iterator) reset(e *encoder) {
it.enc = e
it.yuvIn = it.yuvMem[0:yuvSize:yuvSize]
it.yuvOut = it.yuvMem[yuvSize : 2*yuvSize : 2*yuvSize]
it.yuvOut2 = it.yuvMem[2*yuvSize : 3*yuvSize : 3*yuvSize]
it.yuvP = it.yuvMem[3*yuvSize:]
it.analysis = false
it.doTrellis = false
it.maxEdge = [numMBSegments]int{}
it.setRow(0)
it.countDown = e.mbW * e.mbH
}
// mergeMaxEdge raises the segments' maxEdge to the iterator's (the maximum
// does not depend on the order the macroblocks were coded in).
func (e *encoder) mergeMaxEdge(it *iterator) {
for s, v := range it.maxEdge {
e.dqm[s].maxEdge = max(e.dqm[s].maxEdge, v)
}
}
func (e *encoder) initTop() {
for i := range e.yTop {
e.yTop[i] = 127
}
for i := range e.uvTop {
e.uvTop[i] = 127
}
for i := range e.nz {
e.nz[i] = 0
}
for i := range e.topDerr {
e.topDerr[i] = [2][2]int8{}
}
}
func (it *iterator) initLeft() {
v := byte(127)
if it.y > 0 {
v = 129
}
it.yLeft[0], it.uLeft[0], it.vLeft[0] = v, v, v
for i := 1; i < 17; i++ {
it.yLeft[i] = 129
}
for i := 1; i < 9; i++ {
it.uLeft[i] = 129
it.vLeft[i] = 129
}
it.leftNz[8] = 0
it.leftDerr = [2][2]int8{}
}
func (it *iterator) setRow(y int) {
e := it.enc
it.x = 0
it.y = y
it.predsIdx = e.predsW + 1 + y*4*e.predsW
it.mbIdx = y * e.mbW
it.initLeft()
}
func (it *iterator) setCountDown(n int) { it.countDown = n }
func (it *iterator) mb() *mbInfo { return &it.enc.mbInfo[it.mbIdx] }
// next advances to the next macroblock; returns false when done.
func (it *iterator) next() bool {
it.x++
if it.x == it.enc.mbW {
it.setRow(it.y + 1)
} else {
it.predsIdx += 4
it.mbIdx++
}
it.countDown--
return it.countDown > 0
}
// nextInRow advances to the next macroblock of the row (wavefront pass,
// which walks one row at a time and moves to another row with setRow).
func (it *iterator) nextInRow() {
it.x++
it.predsIdx += 4
it.mbIdx++
}
func importBlock(src []byte, srcStride int, dst []byte, w, h, size int) {
for i := 0; i < h; i++ {
d := dst[i*bps : i*bps+size]
copy(d[:w], src[i*srcStride:i*srcStride+w])
if w < size {
v := d[w-1]
for k := w; k < size; k++ {
d[k] = v
}
}
}
for i := h; i < size; i++ {
copy(dst[i*bps:i*bps+size], dst[(i-1)*bps:(i-1)*bps+size])
}
}
func importLine(src []byte, srcStride int, dst []byte, l, total int) {
i := 0
for ; i < l; i++ {
dst[i] = src[i*srcStride]
}
for ; i < total; i++ {
dst[i] = dst[l-1]
}
}
// importMB loads the source samples of the current macroblock, replicating
// the picture boundary. In analysis mode the prediction boundary is also
// taken from the source.
func (it *iterator) importMB() {
e := it.enc
pic := e.pic
x, y := it.x, it.y
yo := y*16*pic.YStride + x*16
uvo := y*8*pic.UVStride + x*8
w := min(pic.Width-x*16, 16)
h := min(pic.Height-y*16, 16)
uvw := (w + 1) >> 1
uvh := (h + 1) >> 1
importBlock(pic.Y[yo:], pic.YStride, it.yuvIn[yOff:], w, h, 16)
importBlock(pic.U[uvo:], pic.UVStride, it.yuvIn[uOff:], uvw, uvh, 8)
importBlock(pic.V[uvo:], pic.UVStride, it.yuvIn[vOff:], uvw, uvh, 8)
if !it.analysis {
return
}
if x == 0 {
it.initLeft()
} else {
if y == 0 {
it.yLeft[0], it.uLeft[0], it.vLeft[0] = 127, 127, 127
} else {
it.yLeft[0] = pic.Y[yo-1-pic.YStride]
it.uLeft[0] = pic.U[uvo-1-pic.UVStride]
it.vLeft[0] = pic.V[uvo-1-pic.UVStride]
}
importLine(pic.Y[yo-1:], pic.YStride, it.yLeft[1:], h, 16)
importLine(pic.U[uvo-1:], pic.UVStride, it.uLeft[1:], uvh, 8)
importLine(pic.V[uvo-1:], pic.UVStride, it.vLeft[1:], uvh, 8)
}
if y == 0 {
for i := range it.tmp32 {
it.tmp32[i] = 127
}
} else {
importLine(pic.Y[yo-pic.YStride:], 1, it.tmp32[0:16], w, 16)
importLine(pic.U[uvo-pic.UVStride:], 1, it.tmp32[16:24], uvw, 8)
importLine(pic.V[uvo-pic.UVStride:], 1, it.tmp32[24:32], uvw, 8)
}
}
// top returns the luma and chroma top samples (nil when unavailable).
func (it *iterator) top() ([]byte, []byte) {
if it.y == 0 {
return nil, nil
}
if it.analysis {
return it.tmp32[0:16], it.tmp32[16:32]
}
o := it.x * 16
return it.enc.yTop[o:], it.enc.uvTop[o : o+16]
}
func (it *iterator) makeLuma16Preds() {
var left []byte
if it.x != 0 {
left = it.yLeft[:]
}
top, _ := it.top()
predLuma16(it.yuvP, left, top)
}
func (it *iterator) makeChroma8Preds() {
var uLeft, vLeft []byte
if it.x != 0 {
uLeft, vLeft = it.uLeft[:], it.vLeft[:]
}
_, uvTop := it.top()
predChroma8(it.yuvP, uLeft, vLeft, uvTop)
}
func (it *iterator) makeIntra4Preds() {
predLuma4(it.yuvP, it.i4Boundary[:], it.i4Top)
}
// saveBoundary saves the reconstructed samples as the prediction boundary
// of the next macroblocks.
func (it *iterator) saveBoundary() {
e := it.enc
x, y := it.x, it.y
ysrc := it.yuvOut[yOff:]
uvsrc := it.yuvOut[uOff:]
o := x * 16
if x < e.mbW-1 { // left
for i := 0; i < 16; i++ {
it.yLeft[1+i] = ysrc[15+i*bps]
}
for i := 0; i < 8; i++ {
it.uLeft[1+i] = uvsrc[7+i*bps]
it.vLeft[1+i] = uvsrc[15+i*bps]
}
// top-left (before 'top'!)
it.yLeft[0] = e.yTop[o+15]
it.uLeft[0] = e.uvTop[o+7]
it.vLeft[0] = e.uvTop[o+8+7]
}
if y < e.mbH-1 { // top
copy(e.yTop[o:o+16], ysrc[15*bps:15*bps+16])
copy(e.uvTop[o:o+16], uvsrc[7*bps:7*bps+16])
}
}
// Non-zero context bits:
//
// 0 1 2 3 Y
// 4 5 6 7
// 8 9 10 11
// 12 13 14 15
// 16 17 U
// 18 19
// 20 21 V
// 22 23
// 24 DC-intra16
func bit(nz uint32, n uint) int { return int((nz >> n) & 1) }
func (it *iterator) nzToBytes() {
nz := it.enc.nz
tnz := nz[it.x+1]
lnz := nz[it.x]
t := &it.topNz
l := &it.leftNz
t[0], t[1], t[2], t[3] = bit(tnz, 12), bit(tnz, 13), bit(tnz, 14), bit(tnz, 15)
t[4], t[5] = bit(tnz, 18), bit(tnz, 19)
t[6], t[7] = bit(tnz, 22), bit(tnz, 23)
t[8] = bit(tnz, 24)
l[0], l[1], l[2], l[3] = bit(lnz, 3), bit(lnz, 7), bit(lnz, 11), bit(lnz, 15)
l[4], l[5] = bit(lnz, 17), bit(lnz, 19)
l[6], l[7] = bit(lnz, 21), bit(lnz, 23)
// left-DC is special, iterated separately
}
func (it *iterator) bytesToNz() {
t := &it.topNz
l := &it.leftNz
nz := uint32(t[0]<<12 | t[1]<<13 | t[2]<<14 | t[3]<<15)
nz |= uint32(t[4]<<18 | t[5]<<19 | t[6]<<22 | t[7]<<23)
nz |= uint32(t[8] << 24) // we propagate the _top_ bit, esp. for intra4
nz |= uint32(l[0]<<3 | l[1]<<7 | l[2]<<11)
nz |= uint32(l[4]<<17 | l[6]<<21)
it.enc.nz[it.x+1] = nz
}
func (it *iterator) setIntra16Mode(mode int) {
e := it.enc
p := it.predsIdx
m := uint8(mode)
for y := 0; y < 4; y++ {
row := e.preds[p : p+4]
row[0], row[1], row[2], row[3] = m, m, m, m
p += e.predsW
}
it.mb().typ = 1
}
func (it *iterator) setIntra4Mode(modes *[16]uint8) {
e := it.enc
p := it.predsIdx
for y := 0; y < 4; y++ {
copy(e.preds[p:p+4], modes[y*4:y*4+4])
p += e.predsW
}
it.mb().typ = 0
}
// startI4 prepares the boundary samples for the intra4x4 iteration.
func (it *iterator) startI4() {
e := it.enc
it.i4 = 0
it.i4Top = vp8TopLeftI4[0]
b := &it.i4Boundary
for i := 0; i < 17; i++ { // left, bottom to top, then top-left
b[i] = it.yLeft[16-i]
}
top, _ := it.top()
if top == nil {
for i := 0; i < 20; i++ {
b[17+i] = 127
}
} else {
copy(b[17:33], top[:16])
if it.x < e.mbW-1 {
copy(b[33:37], top[16:20])
} else { // replicate the last valid pixel four times
v := b[17+15]
b[33], b[34], b[35], b[36] = v, v, v, v
}
}
it.nzToBytes()
}
// rotateI4 updates the boundary with the reconstructed sub-block and moves
// to the next one. Returns false when all 16 sub-blocks are done.
func (it *iterator) rotateI4(yuvOut []byte) bool {
blk := yuvOut[vp8Scan[it.i4]:]
t := it.i4Top
b := &it.i4Boundary
for i := 0; i <= 3; i++ {
b[t-4+i] = blk[i+3*bps] // store future top samples
}
if it.i4&3 != 3 { // if not on the right sub-blocks #3, #7, #11, #15
for i := 0; i <= 2; i++ { // store future left samples
b[t+i] = blk[3+(2-i)*bps]
}
} else { // else replicate top-right samples, as says the specs.
for i := 0; i <= 3; i++ {
b[t+i] = b[t+i+4]
}
}
it.i4++
if it.i4 == 16 {
return false
}
it.i4Top = vp8TopLeftI4[it.i4]
return true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"encoding/binary"
"image"
"math"
"math/bits"
"slices"
"sync"
"github.com/kolesa-team/go-webp/v2/internal/bufpool"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// Picture is a YUV 4:2:0 picture (BT.601 "studio" range as libwebp: Y in
// [16,235]). Y has YStride bytes per row; U and V have UVStride bytes per row
// and (Height+1)/2 rows of (Width+1)/2 samples.
type Picture struct {
Width, Height int
Y, U, V []byte
YStride, UVStride int
buf []byte // pooled backing storage, if any
}
// Reusable buffers of all sizes, under the process-wide retained-bytes
// budget of internal/bufpool.
var (
bytePool bufpool.Pool[byte] // pictures, prediction modes, bit writers
int32Pool bufpool.Pool[int32] // macroblock token offsets, RGB import
uint16Pool bufpool.Pool[uint16] // sharp YUV luma
int16Pool bufpool.Pool[int16] // sharp YUV chroma
mbInfoPool bufpool.Pool[mbInfo] // macroblock decisions
tokenPagePool bufpool.Pool[uint16] // token pages, all of tokenPageSize
)
func newPicture(w, h int) *Picture {
uvw, uvh := (w+1)>>1, (h+1)>>1
ySize := w * h
uvSize := uvw * uvh
n := ySize + 2*uvSize
buf := bytePool.Get(n) // every sample is written by the conversions
return &Picture{
Width: w, Height: h,
Y: buf[:ySize:ySize],
U: buf[ySize : ySize+uvSize : ySize+uvSize],
V: buf[ySize+uvSize : n : n],
YStride: w, UVStride: uvw,
buf: buf,
}
}
// unpooledPicture is newPicture with freshly allocated storage that Release
// does not return to the pool.
func unpooledPicture(w, h int) *Picture {
uvw, uvh := (w+1)>>1, (h+1)>>1
ySize := w * h
uvSize := uvw * uvh
n := ySize + 2*uvSize
buf := make([]byte, n)
return &Picture{
Width: w, Height: h,
Y: buf[:ySize:ySize],
U: buf[ySize : ySize+uvSize : ySize+uvSize],
V: buf[ySize+uvSize : n : n],
YStride: w, UVStride: uvw,
}
}
// Release returns the storage of a picture made by FromNRGBA,
// FromNRGBADithered or FromYCbCr to an internal pool (bounded by the
// retained-bytes budget of internal/bufpool, whatever the picture size).
// The picture must not be used afterwards. Calling it is optional: a
// picture that is never released is garbage collected like any other
// value. It does nothing on pictures not created by this package, on
// SnapshotYCbCr pictures, on nil and when called again.
func (p *Picture) Release() {
if p == nil || p.buf == nil {
return
}
b := p.buf
p.buf = nil
p.Y, p.U, p.V = nil, nil, nil
bytePool.Put(b)
}
func (p *Picture) validate() error {
w, h := p.Width, p.Height
if w < 1 || h < 1 || w > MaxDimension || h > MaxDimension {
return status.InvalidParam("vp8enc: bad picture dimensions")
}
uvw, uvh := (w+1)>>1, (h+1)>>1
if p.YStride < w || p.UVStride < uvw {
return status.InvalidParam("vp8enc: bad picture stride")
}
if len(p.Y) < (h-1)*p.YStride+w || len(p.U) < (uvh-1)*p.UVStride+uvw || len(p.V) < (uvh-1)*p.UVStride+uvw {
return status.InvalidParam("vp8enc: picture buffers too small")
}
return nil
}
//------------------------------------------------------------------------------
// RGB -> YUV conversion (libwebp's "fast" path with gamma-compressed chroma
// averaging). Algorithm adapted from libwebp (BSD-3-Clause).
const (
yuvFix = 16
yuvHalf = 1 << (yuvFix - 1)
gammaFix = 12
gammaTabFix = 7
gammaTabSize = 1 << (gammaFix - gammaTabFix)
kGammaF = 0.80
kGammaScale = (1 << gammaFix) - 1
kGammaTabScl = 1 << gammaTabFix
kGammaRounder = kGammaTabScl >> 1
kAlphaFix = 19
)
var (
csTablesOnce sync.Once
kGammaToLinearTab [256]uint32
kLinearToGammaTab [gammaTabSize + 1]int32
kInvAlpha [4*0xff + 1]uint32
)
func initCSTables() {
csTablesOnce.Do(func() {
scale := float64(1<<gammaTabFix) / kGammaScale
norm := 1. / 255.
for v := 0; v <= 255; v++ {
kGammaToLinearTab[v] = uint32(math.Pow(norm*float64(v), kGammaF)*kGammaScale + .5)
}
for v := 0; v <= gammaTabSize; v++ {
kLinearToGammaTab[v] = int32(255.*math.Pow(scale*float64(v), 1./kGammaF) + .5)
}
for a := 1; a < len(kInvAlpha); a++ {
kInvAlpha[a] = (1 << kAlphaFix) / uint32(a)
}
})
}
func linearToGamma(base uint32, shift uint) int32 {
v := int32(base << shift)
tabPos := (v >> (gammaTabFix + 2)) & 31
x := v & ((kGammaTabScl << 2) - 1)
v0 := kLinearToGammaTab[tabPos]
v1 := kLinearToGammaTab[tabPos+1]
y := v1*x + v0*((kGammaTabScl<<2)-x)
return (y + kGammaRounder) >> gammaTabFix
}
func rgbToY(r, g, b int32) uint8 { return rgbToYR(r, g, b, yuvHalf) }
// rgbToYR is VP8RGBToY with an explicit rounding term.
func rgbToYR(r, g, b, rounding int32) uint8 {
return uint8((16839*r + 33059*g + 6420*b + rounding + (16 << yuvFix)) >> yuvFix)
}
func clipUV(uv int32) uint8 { return clipUVR(uv, yuvHalf<<2) }
// clipUVR is VP8ClipUV with an explicit rounding term.
func clipUVR(uv, rounding int32) uint8 {
uv = (uv + rounding + (128 << (yuvFix + 2))) >> (yuvFix + 2)
if uint32(uv) <= 255 {
return uint8(uv)
}
if uv < 0 {
return 0
}
return 255
}
func rgbToU(r, g, b int32) uint8 { return clipUV(-9719*r - 19081*g + 28800*b) }
func rgbToV(r, g, b int32) uint8 { return clipUV(28800*r - 24116*g - 4684*b) }
// FromNRGBA converts img to a YUV 4:2:0 picture exactly like libwebp's
// RGBA import followed by WebPPictureARGBToYUVA (gamma-compressed, alpha
// weighted chroma averaging). If sharpYUV is true the iterative "sharp"
// conversion of libsharpyuv is used instead (for pictures of at least 4x4).
// If exact is false and the image has transparent pixels, the luma/chroma
// of fully transparent areas is flattened (WebPCleanupTransparentArea) to
// help compression. The returned picture may be pooled: call Release when
// done.
func FromNRGBA(img *image.NRGBA, sharpYUV bool, exact bool) *Picture {
return FromNRGBADithered(img, sharpYUV, exact, 0)
}
// FromNRGBADithered is FromNRGBA with libwebp's dithered conversion
// (WebPPictureARGBToYUVADithered): when dithering > 0 and sharpYUV is not
// used, the rounding term of every RGB->Y/U/V conversion is randomized
// with amplitude dithering (0..1, see DitheringFor), which only affects the
// sub-LSB rounding of the samples.
func FromNRGBADithered(img *image.NRGBA, sharpYUV bool, exact bool, dithering float32) *Picture {
initCSTables()
b := img.Rect
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 {
return &Picture{}
}
pic := newPicture(w, h)
pix := img.Pix[img.PixOffset(b.Min.X, b.Min.Y):]
stride := img.Stride
hasAlpha := false
for y := 0; y < h && !hasAlpha; y++ {
row := pix[y*stride : y*stride+4*w]
for x := 3; x < len(row); x += 4 {
if row[x] != 0xff {
hasAlpha = true
break
}
}
}
if sharpYUV && w >= 4 && h >= 4 {
sharpRGBToYUV(pix, stride, w, h, pic)
} else {
var rg *vp8Random
if dithering > 0 {
rg = newRandom(dithering)
}
importRGBA(pix, stride, w, h, hasAlpha, pic, rg)
}
if hasAlpha && !exact {
cleanupTransparentArea(pic, pix[3:], stride, 4)
}
return pic
}
func rowsOpaque(pix []byte, stride, w, n int) bool {
for y := 0; y < n; y++ {
row := pix[y*stride : y*stride+4*w]
for x := 3; x < len(row); x += 4 {
if row[x] != 0xff {
return false
}
}
}
return true
}
// importRGBA converts the RGB samples to Y'CbCr 4:2:0; rg, if not nil,
// randomizes the rounding (libwebp's ConvertRowToY/ConvertRowsToUV with a
// VP8Random, in the same draw order).
func importRGBA(pix []byte, stride, w, h int, hasAlpha bool, pic *Picture, rg *vp8Random) {
uvw := (w + 1) >> 1
tmp := int32Pool.Get(4 * uvw) // r,g,b accumulators, written before use
defer int32Pool.Put(tmp)
for y := 0; y < h; y += 2 {
rows := 2
rs := stride // stride to the second row
if y+1 >= h {
rows = 1
rs = 0
}
r0 := pix[y*stride:]
for k := 0; k < rows; k++ {
src := pix[(y+k)*stride : (y+k)*stride+4*w]
dst := pic.Y[(y+k)*pic.YStride : (y+k)*pic.YStride+w]
if rg != nil {
for x := range dst {
p := src[4*x : 4*x+3 : 4*x+3]
dst[x] = rgbToYR(int32(p[0]), int32(p[1]), int32(p[2]), rg.bits(yuvFix))
}
continue
}
for x := range dst {
p := src[4*x : 4*x+3 : 4*x+3]
dst[x] = rgbToY(int32(p[0]), int32(p[1]), int32(p[2]))
}
}
rowsHaveAlpha := hasAlpha && !rowsOpaque(r0, stride, w, rows)
accumulateRGBA(r0, rs, w, rowsHaveAlpha, tmp)
cy := y >> 1
du := pic.U[cy*pic.UVStride : cy*pic.UVStride+uvw]
dv := pic.V[cy*pic.UVStride : cy*pic.UVStride+uvw]
if rg != nil {
for i := range du {
t := tmp[4*i : 4*i+3 : 4*i+3]
r, g, b := t[0], t[1], t[2]
du[i] = clipUVR(-9719*r-19081*g+28800*b, rg.bits(yuvFix+2))
dv[i] = clipUVR(28800*r-24116*g-4684*b, rg.bits(yuvFix+2))
}
continue
}
for i := range du {
t := tmp[4*i : 4*i+3 : 4*i+3]
du[i] = rgbToU(t[0], t[1], t[2])
dv[i] = rgbToV(t[0], t[1], t[2])
}
}
}
func g2l(v byte) uint32 { return kGammaToLinearTab[v] }
func linearToGammaWeighted(src []byte, step, rs int, a0, a1, a2, a3 uint32, totalA uint32) int32 {
sum := a0*g2l(src[0]) + a1*g2l(src[step]) + a2*g2l(src[rs]) + a3*g2l(src[rs+step])
return linearToGamma((sum*kInvAlpha[totalA])>>(kAlphaFix-2), 0)
}
// accumulateRGBA averages 2x2 blocks (gamma-compressed, alpha-weighted if
// withAlpha) into tmp as 4x-scaled r,g,b values.
func accumulateRGBA(p []byte, rs, w int, withAlpha bool, tmp []int32) {
j := 0
i := 0
for ; i < w>>1; i, j = i+1, j+8 {
d := tmp[4*i : 4*i+3 : 4*i+3]
if withAlpha {
a0, a1, a2, a3 := uint32(p[j+3]), uint32(p[j+7]), uint32(p[j+rs+3]), uint32(p[j+rs+7])
a := a0 + a1 + a2 + a3
if a != 4*0xff && a != 0 {
for c := 0; c < 3; c++ {
d[c] = linearToGammaWeighted(p[j+c:], 4, rs, a0, a1, a2, a3, a)
}
continue
}
}
for c := 0; c < 3; c++ {
s := p[j+c:]
d[c] = linearToGamma(g2l(s[0])+g2l(s[4])+g2l(s[rs])+g2l(s[rs+4]), 0)
}
}
if w&1 != 0 {
d := tmp[4*i : 4*i+3 : 4*i+3]
if withAlpha {
a0, a2 := uint32(p[j+3]), uint32(p[j+rs+3])
a := 2 * (a0 + a2)
if a != 4*0xff && a != 0 {
for c := 0; c < 3; c++ {
d[c] = linearToGammaWeighted(p[j+c:], 0, rs, a0, a0, a2, a2, a)
}
return
}
}
for c := 0; c < 3; c++ {
s := p[j+c:]
d[c] = linearToGamma(g2l(s[0])+g2l(s[rs]), 1)
}
}
}
//------------------------------------------------------------------------------
// Transparent area cleanup (WebPCleanupTransparentArea on YUV).
// smoothenBlock replaces the luma of transparent pixels by the average of the
// non-transparent ones. Returns true if the whole block is transparent. The
// alpha of pixel (x, y) of the block is a[y*aStride+x*aStep]. The loops
// have no branch on alpha, which in blocks along the edges of a cutout
// is 0 or not in no order a branch predictor learns.
func smoothenBlock(a []byte, aStride, aStep int, yp []byte, yStride, w, h int) bool {
sum, count := 0, 0
for y := 0; y < h; y++ {
ar, yr := a[y*aStride:], yp[y*yStride:][:w]
for x, l := range yr {
m := (int(ar[aStep*x]) + 0xff) >> 8 // 1 if the pixel is not transparent, else 0
count += m
sum += int(l) & -m
}
}
if count > 0 && count < w*h {
avg := byte(sum / count)
for y := 0; y < h; y++ {
ar, yr := a[y*aStride:], yp[y*yStride:][:w]
for x, l := range yr {
if ar[aStep*x] == 0 {
l = avg
}
yr[x] = l
}
}
}
return count == 0
}
// smoothenBlock8 is smoothenBlock for an 8x8 block of an alpha plane (one
// byte per pixel) on 64-bit targets (see wide64). In most blocks either
// every alpha sample is 0 or none is, and smoothenBlock leaves them as
// they are: eight 8-byte loads tell them, instead of 64 tests of a sample.
func smoothenBlock8(a []byte, aStride int, yp []byte, yStride int) bool {
const ones, highs = 0x0101010101010101, 0x8080808080808080
var set, zero uint64
for y := 0; y < 8; y++ {
v := binary.LittleEndian.Uint64(a[y*aStride:])
set |= v
zero |= (v - ones) &^ v & highs // not 0 if a byte of v is 0
}
if set == 0 {
return true
}
if zero == 0 {
return false
}
return smoothenBlock(a, aStride, 1, yp, yStride, 8, 8)
}
func flatten(p []byte, v byte, stride, size int) {
for y := 0; y < size; y++ {
row := p[y*stride : y*stride+size]
for i := range row {
row[i] = v
}
}
}
// CleanupTransparentArea does to p what FromNRGBA does when exact is false
// and the picture has transparent pixels, for a picture whose alpha is the
// plane a (one byte per pixel, aStride bytes per row), as libwebp's
// WebPCleanupTransparentArea does to a YUVA picture: in every 8x8 block
// of pixels, the luma of the fully transparent pixels becomes the average
// luma of the others, and the blocks that are fully transparent are
// flattened (luma and chroma) to the samples of the first one of their
// run in the row of blocks, which compress better than whatever color
// they hide. The partial blocks of the right and bottom edges only get
// their luma averaged.
func (p *Picture) CleanupTransparentArea(a []byte, aStride int) {
cleanupTransparentArea(p, a, aStride, 1)
}
// cleanupTransparentArea flattens fully transparent 8x8 blocks (see
// CleanupTransparentArea). The alpha of pixel (x, y) is
// a[y*aStride+x*aStep]: aStep is 4 for the A bytes of RGBA pixels, 1 for
// an alpha plane.
func cleanupTransparentArea(pic *Picture, a []byte, aStride, aStep int) {
const size, size2 = 8, 4
width, height := pic.Width, pic.Height
var values [3]byte
y := 0
for ; y+size <= height; y += size {
needReset := true
ap := a[y*aStride:]
yp := pic.Y[y*pic.YStride:]
up := pic.U[(y>>1)*pic.UVStride:]
vp := pic.V[(y>>1)*pic.UVStride:]
x := 0
for ; x+size <= width; x += size {
var transparent bool
if aStep == 1 && wide64 {
transparent = smoothenBlock8(ap[x:], aStride, yp[x:], pic.YStride)
} else {
transparent = smoothenBlock(ap[aStep*x:], aStride, aStep, yp[x:], pic.YStride, size, size)
}
if transparent {
if needReset {
values[0] = yp[x]
values[1] = up[x>>1]
values[2] = vp[x>>1]
needReset = false
}
flatten(yp[x:], values[0], pic.YStride, size)
flatten(up[x>>1:], values[1], pic.UVStride, size2)
flatten(vp[x>>1:], values[2], pic.UVStride, size2)
} else {
needReset = true
}
}
if x < width {
smoothenBlock(ap[aStep*x:], aStride, aStep, yp[x:], pic.YStride, width-x, size)
}
}
if y < height {
sub := height - y
ap := a[y*aStride:]
yp := pic.Y[y*pic.YStride:]
x := 0
for ; x+size <= width; x += size {
smoothenBlock(ap[aStep*x:], aStride, aStep, yp[x:], pic.YStride, size, sub)
}
if x < width {
smoothenBlock(ap[aStep*x:], aStride, aStep, yp[x:], pic.YStride, width-x, sub)
}
}
}
//------------------------------------------------------------------------------
// YCbCr import
// FromYCbCr builds a Picture from an *image.YCbCr. Go's YCbCr is full-range
// (JFIF) while VP8 expects BT.601 studio range, so samples are rescaled with
// the same fixed-point coefficients as libwebp's RGB->YUV matrix
// (Y' = 16 + Y*219/255, C' = 128 + (C-128)*224/255). Chroma planes with a
// subsampling other than 4:2:0 are averaged down to 4:2:0.
//
// The returned picture may be pooled: call Release when done with it.
func FromYCbCr(img *image.YCbCr) *Picture {
return fromYCbCr(img, true, nil, 0)
}
// SnapshotYCbCr is FromYCbCr with storage that is never pooled: the picture
// can be kept indefinitely (and encoded several times) without a Release,
// which is then a no-op.
func SnapshotYCbCr(img *image.YCbCr) *Picture {
return fromYCbCr(img, false, nil, 0)
}
// FromYCbCrAlpha is FromYCbCr for the Y'CbCr samples of a picture with
// alpha (an *image.NYCbCrA): a holds the alpha of its pixels, one byte per
// pixel and aStride bytes per row, from img.Rect.Min. Where a 2x2 block's
// chroma is averaged from more than one sample (every ratio but 4:2:0, and
// 4:2:0 at an odd or a negative origin), the samples are weighted by the
// alpha of the pixels that take them, as libwebp's RGBA import weights
// the colors of a block's pixels (AccumulateRGBA), whose result FromNRGBA
// gives: the colors that transparent pixels hide, often a background that
// was keyed out, then do not tint the visible pixels next to them, and a
// block whose pixels are all transparent or all opaque keeps the plain
// average, as in libwebp. A 4:2:0 picture at an even origin that is not
// negative has one sample per block, which is taken as it is.
//
// The returned picture may be pooled: call Release when done with it.
func FromYCbCrAlpha(img *image.YCbCr, a []byte, aStride int) *Picture {
return fromYCbCr(img, true, a, aStride)
}
func fromYCbCr(img *image.YCbCr, pooled bool, a []byte, aStride int) *Picture {
b := img.Rect
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 {
return &Picture{}
}
var pic *Picture
if pooled {
pic = newPicture(w, h)
} else {
pic = unpooledPicture(w, h)
}
var lumaLUT, chromaLUT [256]uint8
for v := 0; v < 256; v++ {
lumaLUT[v] = uint8((56318*v + (16 << 16) + (1 << 15)) >> 16)
c := 128 + ((v-128)*57600+(1<<15))>>16
chromaLUT[v] = uint8(clipInt(c, 0, 255))
}
for y := 0; y < h; y++ {
src := img.Y[img.YOffset(b.Min.X, b.Min.Y+y):]
src = src[:w]
dst := pic.Y[y*pic.YStride : y*pic.YStride+w]
for x, v := range src {
dst[x] = lumaLUT[v]
}
}
uvw, uvh := (w+1)>>1, (h+1)>>1
// A 4:2:0 picture at an even origin has a chroma sample per 2x2 block,
// but left of x = 0 or above y = 0, where COffset's division rounds
// toward zero, a block's pixels take two: FromYCbCr takes the first
// one's, as it did up to v2.0.3, and FromYCbCrAlpha weights both.
if img.SubsampleRatio == image.YCbCrSubsampleRatio420 && b.Min.X&1 == 0 && b.Min.Y&1 == 0 &&
(a == nil || b.Min.X >= 0 && b.Min.Y >= 0) {
for y := 0; y < uvh; y++ {
co := img.COffset(b.Min.X, b.Min.Y+2*y)
cb := img.Cb[co : co+uvw]
cr := img.Cr[co : co+uvw]
du := pic.U[y*pic.UVStride : y*pic.UVStride+uvw]
dv := pic.V[y*pic.UVStride : y*pic.UVStride+uvw]
for x := range du {
du[x] = chromaLUT[cb[x]]
dv[x] = chromaLUT[cr[x]]
}
}
return pic
}
averageChroma(pic, img, &chromaLUT)
if a != nil {
weightChroma(pic, img, a, aStride, &chromaLUT)
}
return pic
}
// chromaShift returns log2 of the number of pixels of a row that share a
// chroma sample of the given ratio, as COffset divides x: 1 for 4:2:2 and
// 4:2:0, 2 for 4:1:1 and 4:1:0, 0 for the others (the image package takes
// unknown ratios for 4:4:4).
func chromaShift(r image.YCbCrSubsampleRatio) uint {
switch r {
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
return 1
case image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410:
return 2
}
return 0
}
// averageChroma writes to pic the chroma of an *image.YCbCr of any other
// ratio, or of a 4:2:0 one whose origin is odd: for each 2x2 block of
// pixels, lut of the rounded average of the samples that COffset finds
// for its four pixels (a block in the last column or row of an odd width
// or height counts that column's or row's pixels twice).
//
// COffset is not inlined, and its four calls per block took 3 ms of a
// 1920x1080 picture on Apple M5, four times the whole conversion of a
// 4:2:0 one. Here each row of blocks finds the samples of its two rows of
// pixels once, and averageChromaRow averages them. A sample spans 1<<hs
// pixels of a row: COffset divides x by 2 for 4:2:2 and 4:2:0, by 4 for
// 4:1:1 and 4:1:0 (and y by 2 for 4:2:0, 4:4:0 and 4:1:0, which COffset
// of each row's first pixel takes care of). For x >= 0 that is x>>hs, so
// pixel i of a row takes the row's sample (phase+i)>>hs, phase being
// b.Min.X's place in its sample. Left of x = 0 the division rounds toward
// zero and the shift down, and a sample spans other numbers of pixels:
// a picture that starts there with hs > 0 (decoders return pictures at
// the origin) calls COffset for each block, as before.
func averageChroma(pic *Picture, img *image.YCbCr, lut *[256]uint8) {
b := img.Rect
w := b.Dx()
uvw, uvh := (w+1)>>1, (b.Dy()+1)>>1
hs := chromaShift(img.SubsampleRatio)
if b.Min.X < 0 && hs > 0 {
for y := 0; y < uvh; y++ {
y0 := b.Min.Y + 2*y
y1 := min(y0+1, b.Max.Y-1)
for x := 0; x < uvw; x++ {
x0 := b.Min.X + 2*x
x1 := min(x0+1, b.Max.X-1)
o00, o01 := img.COffset(x0, y0), img.COffset(x1, y0)
o10, o11 := img.COffset(x0, y1), img.COffset(x1, y1)
sb := int(img.Cb[o00]) + int(img.Cb[o01]) + int(img.Cb[o10]) + int(img.Cb[o11])
sr := int(img.Cr[o00]) + int(img.Cr[o01]) + int(img.Cr[o10]) + int(img.Cr[o11])
pic.U[y*pic.UVStride+x] = lut[(sb+2)>>2]
pic.V[y*pic.UVStride+x] = lut[(sr+2)>>2]
}
}
return
}
phase := b.Min.X & (1<<hs - 1)
nc := (phase+w-1)>>hs + 1 // samples per row
// A malformed picture (a chroma plane shorter than its bounds need)
// panics exactly when it did when every sample was indexed, whatever
// the planes' capacity: a row's samples are all used, and the planes
// are clipped.
cb, cr := slices.Clip(img.Cb), slices.Clip(img.Cr)
for y := 0; y < uvh; y++ {
y0 := b.Min.Y + 2*y
y1 := min(y0+1, b.Max.Y-1)
o0, o1 := img.COffset(b.Min.X, y0), img.COffset(b.Min.X, y1)
du := pic.U[y*pic.UVStride:][:uvw]
dv := pic.V[y*pic.UVStride:][:uvw]
averageChromaRow(du, cb[o0:][:nc], cb[o1:][:nc], w, hs, phase, lut)
averageChromaRow(dv, cr[o0:][:nc], cr[o1:][:nc], w, hs, phase, lut)
}
}
// weightChroma rewrites the chroma that averageChroma wrote to pic for the
// 2x2 blocks whose pixels are neither all transparent nor all opaque under
// the alpha a (see FromYCbCrAlpha): lut of the average of the samples of
// the block's four pixels, weighted by their alpha and rounded. A block in
// the last column or row of an odd width or height counts that column's
// or row's pixels twice, as averageChroma does. Equal weights give
// averageChroma's value, so the blocks that are all transparent or all
// opaque, which libwebp tells apart too, keep it. The samples are found as
// averageChroma finds them, and are the ones it read, so that a malformed
// picture has already panicked there. At 1920x1080 on Apple M5 Pro it
// adds to the 0.8 ms of FromYCbCr 0.15 ms under opaque alpha, 0.3 ms
// under a cutout and 1 ms under alpha in runs of 8x8 blocks, a quarter of
// them with alpha in no order (BenchmarkFromYCbCrAlpha).
func weightChroma(pic *Picture, img *image.YCbCr, a []byte, aStride int, lut *[256]uint8) {
b := img.Rect
w, h := b.Dx(), b.Dy()
uvw, uvh := (w+1)>>1, (h+1)>>1
hs := chromaShift(img.SubsampleRatio)
perPixel := b.Min.X < 0 && hs > 0 // see averageChroma
phase := b.Min.X & (1<<hs - 1)
for y := 0; y < uvh; y++ {
r0 := 2 * y
r1 := min(r0+1, h-1)
a0, a1 := a[r0*aStride:][:w], a[r1*aStride:][:w]
o0, o1 := img.COffset(b.Min.X, b.Min.Y+r0), img.COffset(b.Min.X, b.Min.Y+r1)
du := pic.U[y*pic.UVStride:][:uvw]
dv := pic.V[y*pic.UVStride:][:uvw]
for x := 0; x < uvw; x++ {
c0 := 2 * x
// Most blocks of most pictures are all transparent or all
// opaque: tell four of them at a time on 64-bit targets (see
// wide64), from 8-byte words of their two rows of alpha.
if wide64 && x&3 == 0 && c0+8 <= w {
v0 := binary.LittleEndian.Uint64(a0[c0:])
if v0 == binary.LittleEndian.Uint64(a1[c0:]) && (v0 == 0 || v0 == math.MaxUint64) {
x += 3
continue
}
}
c1 := min(c0+1, w-1)
w00, w01, w10, w11 := int(a0[c0]), int(a0[c1]), int(a1[c0]), int(a1[c1])
t := w00 + w01 + w10 + w11
if t == 0 || t == 4*0xff {
continue
}
var i00, i01, i10, i11 int
if perPixel {
x0, x1, y0, y1 := b.Min.X+c0, b.Min.X+c1, b.Min.Y+r0, b.Min.Y+r1
i00, i01 = img.COffset(x0, y0), img.COffset(x1, y0)
i10, i11 = img.COffset(x0, y1), img.COffset(x1, y1)
} else {
j0, j1 := (phase+c0)>>hs, (phase+c1)>>hs
i00, i01, i10, i11 = o0+j0, o0+j1, o1+j0, o1+j1
}
sb := w00*int(img.Cb[i00]) + w01*int(img.Cb[i01]) + w10*int(img.Cb[i10]) + w11*int(img.Cb[i11])
sr := w00*int(img.Cr[i00]) + w01*int(img.Cr[i01]) + w10*int(img.Cr[i10]) + w11*int(img.Cr[i11])
du[x] = lut[(sb+t>>1)/t]
dv[x] = lut[(sr+t>>1)/t]
}
}
}
// averageChromaRow writes to d the chroma of the (w+1)/2 blocks of a row
// of w pixels, whose two rows of samples are s0 and s1, pixel i taking
// sample (phase+i)>>hs of each: lut of the rounded average of the four
// samples of a block, where the last block of an odd w counts its pixels
// twice.
func averageChromaRow(d, s0, s1 []byte, w int, hs uint, phase int, lut *[256]uint8) {
switch {
case hs == 0:
// a sample per pixel (4:4:4, 4:4:0)
n := w >> 1
average2x2(d[:n], s0[:2*n], s1[:2*n], lut)
if w&1 != 0 {
d[n] = lut[(int(s0[w-1])+int(s1[w-1])+1)>>1]
}
case hs == 1 && phase == 0:
// a sample per block (4:2:2, or 4:2:0 at an odd y)
average1x2(d, s0[:len(d)], s1[:len(d)], lut)
case hs == 1:
// a block across two samples (4:2:2 and 4:2:0 at an odd x)
n := w >> 1
averageNeighbors(d[:n], s0[:n+1], s1[:n+1], lut)
if w&1 != 0 {
d[n] = lut[(int(s0[n])+int(s1[n])+1)>>1]
}
case hs == 2 && phase&1 == 0:
// a sample per two blocks (4:1:1 and 4:1:0 at an even x): both
// pixels of a block share a sample, and a sample spans two blocks,
// or only the first block when phase is 2
if phase != 0 {
d[0] = lut[(int(s0[0])+int(s1[0])+1)>>1]
d, s0, s1 = d[1:], s0[1:], s1[1:]
}
n := len(d) >> 1
t0, t1 := s0[:n], s1[:n]
for k := range t0 {
v := lut[(int(t0[k])+int(t1[k])+1)>>1]
p := d[2*k : 2*k+2 : 2*k+2]
p[0], p[1] = v, v
}
if len(d)&1 != 0 {
d[2*n] = lut[(int(s0[n])+int(s1[n])+1)>>1]
}
default:
// 4:1:1 and 4:1:0 at an odd x (a sub-image), where every other
// block takes two samples
for x := range d {
i0 := 2 * x
i1 := min(i0+1, w-1)
j0, j1 := (phase+i0)>>hs, (phase+i1)>>hs
d[x] = lut[(int(s0[j0])+int(s0[j1])+int(s1[j0])+int(s1[j1])+2)>>2]
}
}
}
// average2x2 sets d[x] to lut of the rounded average of s0[2x], s0[2x+1],
// s1[2x] and s1[2x+1]; s0 and s1 hold 2*len(d) samples. On 64-bit targets
// (see wide64) it averages eight blocks at a time, whose sums it adds in
// the 16-bit lanes of two uint64, four in each (at most 4*255+2, so that
// no lane carries into the next; the bits that the shift brings into a
// lane from the next one are above its low byte). That averages a row of
// 1920 samples 2.2 times faster on Apple M5 than average2x2Bytes.
func average2x2(d, s0, s1 []byte, lut *[256]uint8) {
const m = 0x00ff00ff00ff00ff
for wide64 && len(d) >= 8 && len(s0) >= 16 && len(s1) >= 16 {
a0, a1 := binary.LittleEndian.Uint64(s0), binary.LittleEndian.Uint64(s1)
b0, b1 := binary.LittleEndian.Uint64(s0[8:]), binary.LittleEndian.Uint64(s1[8:])
a := (a0&m + a0>>8&m + a1&m + a1>>8&m + 0x0002000200020002) >> 2
b := (b0&m + b0>>8&m + b1&m + b1>>8&m + 0x0002000200020002) >> 2
d[0], d[1], d[2], d[3] = lut[uint8(a)], lut[uint8(a>>16)], lut[uint8(a>>32)], lut[uint8(a>>48)]
d[4], d[5], d[6], d[7] = lut[uint8(b)], lut[uint8(b>>16)], lut[uint8(b>>32)], lut[uint8(b>>48)]
d, s0, s1 = d[8:], s0[16:], s1[16:]
}
average2x2Bytes(d, s0, s1, lut)
}
// average2x2Bytes is average2x2 a block at a time, for 32-bit targets and
// for the last blocks of a row.
func average2x2Bytes(d, s0, s1 []byte, lut *[256]uint8) {
s0, s1 = s0[:2*len(d)], s1[:2*len(d)]
for x := range d {
p, q := s0[2*x:2*x+2:2*x+2], s1[2*x:2*x+2:2*x+2]
d[x] = lut[(int(p[0])+int(p[1])+int(q[0])+int(q[1])+2)>>2]
}
}
// average1x2 sets d[x] to lut of the rounded average of s0[x] and s1[x],
// each counted twice ((2s+2)>>2 is (s+1)>>1); s0 and s1 hold len(d)
// samples. On 64-bit targets (see wide64) it averages eight blocks at a
// time, in the 16-bit lanes of two uint64 (one for the even blocks, one
// for the odd ones), 1.3 times faster on Apple M5 than average1x2Bytes.
func average1x2(d, s0, s1 []byte, lut *[256]uint8) {
const m = 0x00ff00ff00ff00ff
for wide64 && len(d) >= 8 && len(s0) >= 8 && len(s1) >= 8 {
u0, u1 := binary.LittleEndian.Uint64(s0), binary.LittleEndian.Uint64(s1)
e := (u0&m + u1&m + 0x0001000100010001) >> 1
o := (u0>>8&m + u1>>8&m + 0x0001000100010001) >> 1
d[0], d[1], d[2], d[3] = lut[uint8(e)], lut[uint8(o)], lut[uint8(e>>16)], lut[uint8(o>>16)]
d[4], d[5], d[6], d[7] = lut[uint8(e>>32)], lut[uint8(o>>32)], lut[uint8(e>>48)], lut[uint8(o>>48)]
d, s0, s1 = d[8:], s0[8:], s1[8:]
}
average1x2Bytes(d, s0, s1, lut)
}
// average1x2Bytes is average1x2 a sample at a time, for 32-bit targets
// and for the last samples of a row.
func average1x2Bytes(d, s0, s1 []byte, lut *[256]uint8) {
s0, s1 = s0[:len(d)], s1[:len(d)]
for x := range d {
d[x] = lut[(int(s0[x])+int(s1[x])+1)>>1]
}
}
// averageNeighbors sets d[x] to lut of the rounded average of s0[x],
// s0[x+1], s1[x] and s1[x+1]; s0 and s1 hold len(d)+1 samples. On 64-bit
// targets (see wide64) it averages eight blocks at a time as average2x2
// does, the even ones from a word of eight samples of each row and the
// odd ones from the word one sample further, 2.3 times faster on Apple M5
// than averageNeighborsBytes.
func averageNeighbors(d, s0, s1 []byte, lut *[256]uint8) {
const m = 0x00ff00ff00ff00ff
for wide64 && len(d) >= 8 && len(s0) >= 9 && len(s1) >= 9 {
a0, a1 := binary.LittleEndian.Uint64(s0), binary.LittleEndian.Uint64(s1)
b0, b1 := binary.LittleEndian.Uint64(s0[1:]), binary.LittleEndian.Uint64(s1[1:])
a := (a0&m + a0>>8&m + a1&m + a1>>8&m + 0x0002000200020002) >> 2
b := (b0&m + b0>>8&m + b1&m + b1>>8&m + 0x0002000200020002) >> 2
d[0], d[1], d[2], d[3] = lut[uint8(a)], lut[uint8(b)], lut[uint8(a>>16)], lut[uint8(b>>16)]
d[4], d[5], d[6], d[7] = lut[uint8(a>>32)], lut[uint8(b>>32)], lut[uint8(a>>48)], lut[uint8(b>>48)]
d, s0, s1 = d[8:], s0[8:], s1[8:]
}
averageNeighborsBytes(d, s0, s1, lut)
}
// averageNeighborsBytes is averageNeighbors a block at a time, for 32-bit
// targets and for the last blocks of a row.
func averageNeighborsBytes(d, s0, s1 []byte, lut *[256]uint8) {
s0, s1 = s0[:len(d)+1], s1[:len(d)+1]
for x := range d {
p, q := s0[x:x+2:x+2], s1[x:x+2:x+2]
d[x] = lut[(int(p[0])+int(p[1])+int(q[0])+int(q[1])+2)>>2]
}
}
// wide64 is true where a uint64 fits in a register. There average2x2,
// average1x2 and averageNeighbors work on 8-byte words, which on a row of
// 960 blocks were 1.3 to 2.3 times faster than a block at a time on Apple
// M5, and 2.7 to 7.4 times on js/wasm (node). On 386 and arm a uint64 takes
// two registers, and the word loops of the encoder package were slower
// there than a pixel at a time. On riscv64 and mips64 the compiler builds
// each binary.LittleEndian.Uint64 from eight byte loads; the word loops
// have not been timed there.
const wide64 = bits.UintSize == 64
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import "math"
// Quantization setup, mode decision and reconstruction.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
midAlpha = 64 // neutral value for susceptibility
minAlpha = 30 // lowest usable value for susceptibility
maxAlpha = 100 // higher meaningful value for susceptibility
snsToDQ = 0.9 // scaling constant between the sns value and the QP power-law modulation
flatnessLimitI16 = 0
flatnessLimitI4 = 3
flatnessLimitUV = 2
flatnessPenalty = 140
rdDistoMult = 256
maxDQUV = 6
minDQUV = -4
fstrengthCutoff = 2
maxCost = int64(0x7fffffffffffff)
)
// Rate-distortion optimization levels.
const (
rdOptNone = 0
rdOptBasic = 1
rdOptTrellis = 2
rdOptTrellisAll = 3
)
var kDcTable = [128]uint8{
4, 5, 6, 7, 8, 9, 10, 10,
11, 12, 13, 14, 15, 16, 17, 17,
18, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 25, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36,
37, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 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, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89,
91, 93, 95, 96, 98, 100, 101, 102,
104, 106, 108, 110, 112, 114, 116, 118,
122, 124, 126, 128, 130, 132, 134, 136,
138, 140, 143, 145, 148, 151, 154, 157,
}
var kAcTable = [128]uint16{
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, 60,
62, 64, 66, 68, 70, 72, 74, 76,
78, 80, 82, 84, 86, 88, 90, 92,
94, 96, 98, 100, 102, 104, 106, 108,
110, 112, 114, 116, 119, 122, 125, 128,
131, 134, 137, 140, 143, 146, 149, 152,
155, 158, 161, 164, 167, 170, 173, 177,
181, 185, 189, 193, 197, 201, 205, 209,
213, 217, 221, 225, 229, 234, 239, 245,
249, 254, 259, 264, 269, 274, 279, 284,
}
var kAcTable2 = [128]uint16{
8, 8, 9, 10, 12, 13, 15, 17,
18, 20, 21, 23, 24, 26, 27, 29,
31, 32, 34, 35, 37, 38, 40, 41,
43, 44, 46, 48, 49, 51, 52, 54,
55, 57, 58, 60, 62, 63, 65, 66,
68, 69, 71, 72, 74, 75, 77, 79,
80, 82, 83, 85, 86, 88, 89, 93,
96, 99, 102, 105, 108, 111, 114, 117,
120, 124, 127, 130, 133, 136, 139, 142,
145, 148, 151, 155, 158, 161, 164, 167,
170, 173, 176, 179, 184, 189, 193, 198,
203, 207, 212, 217, 221, 226, 230, 235,
240, 244, 249, 254, 258, 263, 268, 274,
280, 286, 292, 299, 305, 311, 317, 323,
330, 336, 342, 348, 354, 362, 370, 379,
385, 393, 401, 409, 416, 424, 432, 440,
}
// [luma-ac,luma-dc,chroma][dc,ac]
var kBiasMatrices = [3][2]uint32{{96, 110}, {96, 108}, {110, 115}}
const sharpenBits = 11
var kFreqSharpening = [16]uint32{
0, 30, 60, 90,
30, 60, 90, 90,
60, 90, 90, 90,
90, 90, 90, 90,
}
var kWeightY = [16]uint16{38, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2}
var kWeightTrellis = [16]int32{
30, 27, 19, 11,
27, 24, 17, 10,
19, 17, 12, 8,
11, 10, 8, 6,
}
func clipInt(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
// segmentInfo holds the per-segment quantization parameters.
type segmentInfo struct {
y1, y2, uv matrix
alpha int // quant-susceptibility, range [-127,127]
beta int // filter-susceptibility, range [0,255]
quant int // final segment quantizer
fstrength int // final in-loop filtering strength
maxEdge int // max edge delta (for filtering strength)
minDisto int // minimum distortion required to trigger filtering record
lambdaI16, lambdaI4, lambdaUV int
lambdaMode, tlambda int
lambdaTrellisI16, lambdaTrellisI4, lambdaTrellisUV int
i4Penalty int64 // penalty for using Intra4
}
func expandMatrix(m *matrix, typ int) int {
for i := 0; i < 2; i++ {
isAC := 0
if i > 0 {
isAC = 1
}
bias := kBiasMatrices[typ][isAC]
m.iq[i] = (1 << qfix) / m.q[i]
m.bias[i] = biasOf(bias)
m.zthresh[i] = ((1 << qfix) - 1 - m.bias[i]) / m.iq[i]
}
for i := 2; i < 16; i++ {
m.q[i] = m.q[1]
m.iq[i] = m.iq[1]
m.bias[i] = m.bias[1]
m.zthresh[i] = m.zthresh[1]
}
sum := uint32(0)
for i := 0; i < 16; i++ {
if typ == 0 {
m.sharpen[i] = (kFreqSharpening[i] * m.q[i]) >> sharpenBits
} else {
m.sharpen[i] = 0
}
sum += m.q[i]
}
m.prepareVec()
return int((sum + 8) >> 4)
}
func atLeast1(v int) int {
if v < 1 {
return 1
}
return v
}
func (e *encoder) setupMatrices() {
tlambdaScale := 0
if e.method >= 4 {
tlambdaScale = e.cfg.SNSStrength
}
for i := 0; i < e.numSegments; i++ {
m := &e.dqm[i]
q := m.quant
m.y1.q[0] = uint32(kDcTable[clipInt(q+e.dqY1DC, 0, 127)])
m.y1.q[1] = uint32(kAcTable[clipInt(q, 0, 127)])
m.y2.q[0] = uint32(kDcTable[clipInt(q+e.dqY2DC, 0, 127)]) * 2
m.y2.q[1] = uint32(kAcTable2[clipInt(q+e.dqY2AC, 0, 127)])
m.uv.q[0] = uint32(kDcTable[clipInt(q+e.dqUVDC, 0, 117)])
m.uv.q[1] = uint32(kAcTable[clipInt(q+e.dqUVAC, 0, 127)])
qI4 := expandMatrix(&m.y1, 0)
qI16 := expandMatrix(&m.y2, 1)
qUV := expandMatrix(&m.uv, 2)
m.lambdaI4 = atLeast1((3 * qI4 * qI4) >> 7)
m.lambdaI16 = atLeast1(3 * qI16 * qI16)
m.lambdaUV = atLeast1((3 * qUV * qUV) >> 6)
m.lambdaMode = atLeast1((1 * qI4 * qI4) >> 7)
m.lambdaTrellisI4 = atLeast1((7 * qI4 * qI4) >> 3)
m.lambdaTrellisI16 = atLeast1((qI16 * qI16) >> 2)
m.lambdaTrellisUV = atLeast1((qUV * qUV) << 1)
m.tlambda = atLeast1((tlambdaScale * qI4) >> 5)
m.minDisto = 20 * int(m.y1.q[0])
m.maxEdge = 0
m.i4Penalty = 1000 * int64(qI4) * int64(qI4)
}
}
func filterStrengthFromDelta(sharpness, delta int) int {
pos := delta
if pos >= 64 {
pos = 63
}
if pos < 0 {
pos = 0
}
return int(levelsFromDelta[sharpness&7][pos])
}
func (e *encoder) setupFilterStrength() {
level0 := 5 * e.cfg.FilterStrength
for i := 0; i < numMBSegments; i++ {
m := &e.dqm[i]
qstep := int(kAcTable[clipInt(m.quant, 0, 127)]) >> 2
baseStrength := filterStrengthFromDelta(e.filterSharpness, qstep)
f := baseStrength * level0 / (256 + m.beta)
if f < fstrengthCutoff {
m.fstrength = 0
} else if f > 63 {
m.fstrength = 63
} else {
m.fstrength = f
}
}
e.filterLevel = e.dqm[0].fstrength
e.filterSimple = e.cfg.FilterType == 0
e.filterSharpness = e.cfg.FilterSharpness
}
func qualityToCompression(c float64) float64 {
linearC := 2*c - 1
if c < 0.75 {
linearC = c * (2. / 3.)
}
return math.Pow(linearC, 1/3.)
}
func qualityToJPEGCompression(c, alpha float64) float64 {
const (
amin = 0.30
amax = 0.85
expMin = 0.4
expMax = 0.9
slope = (expMin - expMax) / (amax - amin)
)
expn := expMax + slope*(alpha-amin)
if alpha > amax {
expn = expMin
} else if alpha < amin {
expn = expMax
}
return math.Pow(c, expn)
}
func (e *encoder) simplifySegments() {
segMap := [numMBSegments]uint8{0, 1, 2, 3}
numSegments := e.numSegments
numFinal := 1
for s1 := 1; s1 < numSegments; s1++ {
S1 := &e.dqm[s1]
found := false
s2 := 0
for ; s2 < numFinal; s2++ {
S2 := &e.dqm[s2]
if S1.quant == S2.quant && S1.fstrength == S2.fstrength {
found = true
break
}
}
segMap[s1] = uint8(s2)
if !found {
if numFinal != s1 {
e.dqm[numFinal] = e.dqm[s1]
}
numFinal++
}
}
if numFinal < numSegments {
for i := range e.mbInfo {
e.mbInfo[i].segment = segMap[e.mbInfo[i].segment&3]
}
e.numSegments = numFinal
for i := numFinal; i < numSegments; i++ {
e.dqm[i] = e.dqm[numFinal-1]
}
}
}
// setSegmentParams sets up the segments' quantization values, base_quant and
// filter strengths for the given quality.
func (e *encoder) setSegmentParams(quality float64) {
numSegments := e.numSegments
amp := snsToDQ * float64(e.cfg.SNSStrength) / 100. / 128.
Q := quality / 100.
var cBase float64
if e.cfg.EmulateJPEGSize {
cBase = qualityToJPEGCompression(Q, float64(e.alpha)/255.)
} else {
cBase = qualityToCompression(Q)
}
for i := 0; i < numSegments; i++ {
expn := 1. - amp*float64(e.dqm[i].alpha)
c := math.Pow(cBase, expn)
// A NaN quality yields NaN here; libwebp's (int) cast of it ends up
// as quantizer 0 after clipping (0 on arm64, INT_MIN on x86), so
// make that explicit instead of relying on Go's platform-dependent
// NaN conversion.
q := 0
if f := 127. * (1. - c); f == f {
q = int(f)
}
e.dqm[i].quant = clipInt(q, 0, 127)
}
e.baseQuant = e.dqm[0].quant
for i := numSegments; i < numMBSegments; i++ {
e.dqm[i].quant = e.baseQuant
}
dqUVAC := (e.uvAlpha - midAlpha) * (maxDQUV - minDQUV) / (maxAlpha - minAlpha)
dqUVAC = dqUVAC * e.cfg.SNSStrength / 100
dqUVAC = clipInt(dqUVAC, minDQUV, maxDQUV)
dqUVDC := -4 * e.cfg.SNSStrength / 100
dqUVDC = clipInt(dqUVDC, -15, 15)
e.dqY1DC = 0
e.dqY2DC = 0
e.dqY2AC = 0
e.dqUVDC = dqUVDC
e.dqUVAC = dqUVAC
e.setupFilterStrength()
if numSegments > 1 {
e.simplifySegments()
}
e.setupMatrices()
}
//------------------------------------------------------------------------------
// Mode scores
type modeScore struct {
D, SD, H, R, score int64
nz uint32
modeI16 int
modeUV int
modesI4 [16]uint8
derr [2][3]int8
yDCLevels [16]int16
yACLevels [16][16]int16
uvLevels [8][16]int16
// levelInfoOf summaries of the levels, for the rate and flatness
// estimates of the mode search (filled by reconstructIntra16 and
// reconstructUV when asked to).
yDCInfo [1]uint16
yACInfo [16]uint16
uvInfo [8]uint16
}
// flatInfo reports whether the blocks summarized by info have at most
// thresh non-zero AC levels in total (libwebp's IsFlat).
func flatInfo(info []uint16, thresh int) bool {
n := 0
for _, v := range info {
n += infoNzAC(v)
}
return n <= thresh
}
func (rd *modeScore) init() {
rd.D, rd.SD, rd.R, rd.H, rd.nz = 0, 0, 0, 0, 0
rd.score = maxCost
}
func (rd *modeScore) setRDScore(lambda int) {
rd.score = (rd.R+rd.H)*int64(lambda) + rdDistoMult*(rd.D+rd.SD)
}
// scoreT is the score-only part of a modeScore.
type scoreT struct {
D, SD, H, R, score int64
nz uint32
}
func (s *scoreT) setRDScore(lambda int) {
s.score = (s.R+s.H)*int64(lambda) + rdDistoMult*(s.D+s.SD)
}
func mult8b(a, b int) int64 { return int64((a*b + 128) >> 8) }
//------------------------------------------------------------------------------
// Trellis-optimized quantization
type trellisNode struct {
prev int8
sign bool
level int16
}
func rdScoreTrellis(lambda int, rate, distortion int64) int64 {
return rate*int64(lambda) + rdDistoMult*distortion
}
// trellisLevelCost is levelCost for 0 <= level <= maxLevel, without
// branches.
func trellisLevelCost(table *levelCostTable, level int) int64 {
return int64(levelFixedCosts[level&maxLevel]) + int64(table[min(uint(level), maxVariableLevel)])
}
// trellisQuantizeBlock is libwebp's TrellisQuantizeBlock. At each position
// it keeps two nodes, for levels level0 and level0+1; their state (best
// score so far and the level cost table of the context they leave) is held
// in scalars rather than arrays, so that it stays in registers.
//
// It returns the levelInfoOf summary of out (zero if no level is
// non-zero), out[0] counting as zero for typeI16AC: callers clear that DC
// position, which trellis quantization leaves untouched.
func (it *iterator) trellisQuantizeBlock(in *[16]int16, out *[16]int16, ctx0 int, coeffType int, mtx *matrix, lambda int) uint16 {
e := it.enc
probas := &e.proba.coeffs[coeffType]
costs := &e.proba.levelCost[coeffType]
first := 0
if coeffType == typeI16AC {
first = 1
}
lambda64 := int64(lambda)
var nodes [16][2]trellisNode
bestPath := [3]int{-1, -1, -1}
var bestScore int64
last := first - 1
// State of the two nodes of the previous position.
var score0, score1 int64
var costs0, costs1 *levelCostTable
{
thresh := int32(mtx.q[1] * mtx.q[1] / 4)
lastProba := probas[encBands[first]][ctx0][0]
for n := 15; n >= first; n-- {
j := kZigzag[n] & 15
err := int32(in[j]) * int32(in[j])
if err > thresh {
last = n
break
}
}
if last < 15 {
last++
}
cost := int64(bitCost(0, lastProba))
bestScore = rdScoreTrellis(lambda, cost, 0)
rate := int64(0)
if ctx0 == 0 {
rate = int64(bitCost(1, lastProba))
}
score0 = rdScoreTrellis(lambda, rate, 0)
score1 = score0
costs0 = &costs[encBands[first]][ctx0]
costs1 = costs0
}
for n := first; n <= last; n++ {
j := kZigzag[n&15] & 15
Q := int64(mtx.q[j])
iQ := mtx.iq[j]
v := int32(in[j])
sign := v < 0
neg := v >> 31
coeff0 := uint32((v^neg)-neg) + mtx.sharpen[j] // |v| + sharpen
// quantDiv results are >= 0
level0 := min(int(quantDiv(coeff0, iQ, biasOf(0x00))), maxLevel)
threshLevel := min(int(quantDiv(coeff0, iQ, biasOf(0x80))), maxLevel)
band := encBands[n+1]
bandCosts := &costs[band&7]
cur := &nodes[n]
if level0|threshLevel == 0 {
// Common case: only the level 0 node is possible. Its
// distortion delta is 0 and it cannot end the block.
bestCurScore := score0 + trellisLevelCost(costs0, 0)*lambda64
bestPrev := 0
if s := score1 + trellisLevelCost(costs1, 0)*lambda64; s < bestCurScore {
bestCurScore = s
bestPrev = 1
}
cur[0] = trellisNode{prev: int8(bestPrev), sign: sign}
score0, score1 = bestCurScore, maxCost
costs0, costs1 = &bandCosts[0], &bandCosts[1]
continue
}
bandProbas := &probas[band&7]
weight := int64(kWeightTrellis[j])
coeff0Sq := int64(coeff0) * int64(coeff0)
next0, next1 := maxCost, maxCost
if level := level0; level <= threshLevel {
newError := int64(coeff0) - int64(level)*Q
baseScore := rdDistoMult * (weight * (newError*newError - coeff0Sq))
bestCurScore := score0 + trellisLevelCost(costs0, level)*lambda64
bestPrev := 0
if s := score1 + trellisLevelCost(costs1, level)*lambda64; s < bestCurScore {
bestCurScore = s
bestPrev = 1
}
bestCurScore += baseScore
cur[0] = trellisNode{prev: int8(bestPrev), sign: sign, level: int16(level)}
next0 = bestCurScore
if level != 0 && bestCurScore < bestScore {
lastPosCost := int64(0)
if n < 15 {
lastPosCost = int64(bitCost(0, bandProbas[min(level, 2)][0]))
}
if score := bestCurScore + lastPosCost*lambda64; score < bestScore {
bestScore = score
bestPath = [3]int{n, 0, bestPrev}
}
}
}
if level := level0 + 1; level <= threshLevel {
newError := int64(coeff0) - int64(level)*Q
baseScore := rdDistoMult * (weight * (newError*newError - coeff0Sq))
bestCurScore := score0 + trellisLevelCost(costs0, level)*lambda64
bestPrev := 0
if s := score1 + trellisLevelCost(costs1, level)*lambda64; s < bestCurScore {
bestCurScore = s
bestPrev = 1
}
bestCurScore += baseScore
cur[1] = trellisNode{prev: int8(bestPrev), sign: sign, level: int16(level)}
next1 = bestCurScore
if bestCurScore < bestScore { // level != 0
lastPosCost := int64(0)
if n < 15 {
lastPosCost = int64(bitCost(0, bandProbas[min(level, 2)][0]))
}
if score := bestCurScore + lastPosCost*lambda64; score < bestScore {
bestScore = score
bestPath = [3]int{n, 1, bestPrev}
}
}
}
score0, score1 = next0, next1
costs0, costs1 = &bandCosts[min(level0, 2)], &bandCosts[min(level0+1, 2)]
}
if coeffType == typeI16AC {
for i := 1; i < 16; i++ {
in[i] = 0
out[i] = 0
}
} else {
*in = [16]int16{}
*out = [16]int16{}
}
if bestPath[0] == -1 {
return 0
}
// The block ends with a non-zero level (bestPath only records such
// nodes), at bestPath[0].
nzAC := 0
bestNode := bestPath[1]
n := bestPath[0]
nodes[n][bestNode].prev = int8(bestPath[2])
for ; n >= first; n-- {
node := &nodes[n][bestNode&1]
j := kZigzag[n] & 15
l := node.level
if node.sign {
l = -l
}
out[n] = l
nzAC += b2i(l != 0 && n > 0)
in[j] = int16(int32(l) * int32(mtx.q[j]))
bestNode = int(node.prev)
}
return uint16(bestPath[0]+1) | uint16(nzAC)<<8
}
//------------------------------------------------------------------------------
// Reconstruction
// reconstructIntra16 reconstructs the luma of the macroblock with the
// intra16 prediction mode into yuvOut, setting rd's luma levels (and their
// summaries if withInfo is set). Returns the non-zero bits.
func (it *iterator) reconstructIntra16(rd *modeScore, yuvOut []byte, mode int, withInfo bool) uint32 {
e := it.enc
ref := it.yuvP[vp8I16ModeOffsets[mode&3]:]
src := it.yuvIn[yOff:]
dqm := &e.dqm[it.mb().segment&3]
nz := uint32(0)
tmp := &it.tmp16
acLevels := &rd.yACLevels
var dcTmp, dcLev [1][16]int16
var dcInfo, acInfo []uint16
if withInfo {
dcInfo, acInfo = rd.yDCInfo[:], rd.yACInfo[:]
}
fTransformPairs(src, ref, &tabY16, tmp[:])
fTransformWHT(tmp, &dcTmp[0])
nz |= quantizeBlocks(dcTmp[:], dcLev[:], &dqm.y2, dcInfo) << 24
rd.yDCLevels = dcLev[0]
if it.doTrellis {
it.nzToBytes()
for y, n := 0, 0; y < 4; y++ {
for x := 0; x < 4; x, n = x+1, n+1 {
ctx := it.topNz[x] + it.leftNz[y]
info := it.trellisQuantizeBlock(&tmp[n], &acLevels[n], ctx, typeI16AC, &dqm.y1, dqm.lambdaTrellisI16)
v := b2i(info != 0)
it.topNz[x] = v
it.leftNz[y] = v
acLevels[n][0] = 0
nz |= uint32(v) << uint(n)
if withInfo {
acInfo[n] = info
}
}
}
} else {
for n := 0; n < 16; n++ {
tmp[n][0] = 0
}
nz |= quantizeBlocks(tmp[:], acLevels[:], &dqm.y1, acInfo)
}
iTransformWHT(&dcTmp[0], tmp)
iTransformPairs(ref, tmp[:], yuvOut, &tabY16)
return nz
}
// i4Modes holds the 10 intra4 candidates of one sub-block, reconstructed in
// one batch by reconstructI4Modes.
type i4Modes struct {
src [3*bps + 8]byte // the source sub-block, twice side by side (tabI4Src)
rec [8 * bps]byte // reconstructions, laid out as the predictions (tabI4Rec)
coeffs [numBModes][16]int16
levels [numBModes][16]int16 // quantized levels, zigzag order
info [numBModes]uint16 // levelInfoOf(levels)
d [numBModes]int32 // sse4x4(source, reconstruction)
tt [numBModes]int32 // tTransform(reconstruction), if requested
srcTT [2]int32 // tTransform(source), if requested
tw trellisScratch // workspace of the trellisModes kernel
}
// tabI4Self is the duplicated intra4 source block alone.
var tabI4Self = newPairTable([2]uint16{0, 0})
// setI4Source copies the source sub-block twice side by side into
// it.i4m.src, the layout the intra4 pair tables expect.
func (it *iterator) setI4Source(src []byte) {
s := &it.i4m.src
for y := 0; y < 4; y++ {
row := src[y*bps : y*bps+4]
copy(s[y*bps:y*bps+4], row)
copy(s[y*bps+4:y*bps+8], row)
}
}
// reconstructI4Modes does what reconstructIntra4 does for one mode for all
// 10 intra4 predictions (makeIntra4Preds) of the current sub-block src,
// then summarizes the levels and measures each reconstruction against the
// source (and the texture transforms when withTT is set) into it.i4m. Bit
// m of the result is set if mode m has a non-zero level.
//
// With vector kernels each step runs on the 10 modes in one call; the
// portable build keeps the mode-by-mode loop, which is faster in plain Go
// (the data stays in registers between the steps).
func (it *iterator) reconstructI4Modes(src []byte, withTT bool) uint32 {
s := &it.i4m
preds := it.yuvP[i4DC4:]
dqm := &it.enc.dqm[it.mb().segment&3]
x, y := it.i4&3, it.i4>>2
ctx := it.topNz[x] + it.leftNz[y]
var nz uint32
if !vecKernels {
for m := 0; m < numBModes; m++ {
ref := preds[predOffI4(m):]
rec := s.rec[predOffI4(m):]
c := &s.coeffs[m]
fTransform(src, ref, c)
if it.doTrellis {
s.info[m] = it.trellisQuantizeBlock(c, &s.levels[m], ctx, typeI4AC, &dqm.y1, dqm.lambdaTrellisI4)
} else {
quantizeBlock(c, &s.levels[m], &dqm.y1)
s.info[m] = levelInfoOf(&s.levels[m])
}
if s.info[m] != 0 {
nz |= 1 << uint(m)
}
iTransform(ref, c, rec)
s.d[m] = int32(sse4x4(src, rec))
if withTT {
s.tt[m] = tTransform(rec, &kWeightY)
}
}
if withTT {
s.srcTT[0] = tTransform(src, &kWeightY)
}
return nz
}
it.setI4Source(src)
fTransformPairs(s.src[:], preds, &tabI4Src, s.coeffs[:])
if it.doTrellis {
nz = it.trellisI4Modes(ctx, dqm)
} else {
nz = quantizeBlocks(s.coeffs[:], s.levels[:], &dqm.y1, s.info[:])
}
iTransformPairs(preds, s.coeffs[:], s.rec[:], &tabI4Rec)
sse4x4Pairs(s.src[:], s.rec[:], &tabI4Src, s.d[:])
if withTT {
tTransformPairs(s.rec[:], &tabI4Rec, s.tt[:])
tTransformPairs(s.src[:], &tabI4Self, s.srcTT[:])
}
return nz
}
// trellisI4Modes trellis-quantizes the 10 intra4 candidates it.i4m.coeffs
// of the current sub-block (context ctx) into it.i4m.levels and
// it.i4m.info, replacing the coefficients with their dequantized values,
// as trellisQuantizeBlock does for each of them. Bit m of the result is
// set if mode m has a non-zero level. A vector kernel (trellisModes)
// runs the 10 trellises side by side where there is one.
func (it *iterator) trellisI4Modes(ctx int, dqm *segmentInfo) uint32 {
s := &it.i4m
if nz, ok := it.trellisModes(ctx, dqm); ok {
return nz
}
var nz uint32
for m := 0; m < numBModes; m++ {
s.info[m] = it.trellisQuantizeBlock(&s.coeffs[m], &s.levels[m], ctx, typeI4AC, &dqm.y1, dqm.lambdaTrellisI4)
if s.info[m] != 0 {
nz |= 1 << uint(m)
}
}
return nz
}
// sseI4Modes computes the distortion of the 10 intra4 predictions of the
// current sub-block src into it.i4m.d.
func (it *iterator) sseI4Modes(src []byte) {
preds := it.yuvP[i4DC4:]
d := &it.i4m.d
if !vecKernels {
for m := 0; m < numBModes; m++ {
d[m] = int32(sse4x4(src, preds[predOffI4(m):]))
}
return
}
it.setI4Source(src)
sse4x4Pairs(it.i4m.src[:], preds, &tabI4Src, d[:])
}
func (it *iterator) reconstructIntra4(levels *[16]int16, src, yuvOut []byte, mode int) bool {
ref := it.yuvP[vp8I4ModeOffsets[mode]:]
dqm := &it.enc.dqm[it.mb().segment&3]
var tmp [16]int16
fTransform(src, ref, &tmp)
var nz bool
if it.doTrellis {
x, y := it.i4&3, it.i4>>2
ctx := it.topNz[x] + it.leftNz[y]
nz = it.trellisQuantizeBlock(&tmp, levels, ctx, typeI4AC, &dqm.y1, dqm.lambdaTrellisI4) != 0
} else {
nz = quantizeBlock(&tmp, levels, &dqm.y1)
}
iTransform(ref, &tmp, yuvOut)
return nz
}
// DC-error diffusion constants.
const (
derrC1 = 7 // fraction of error sent to the 4x4 block below
derrC2 = 8 // fraction of error sent to the 4x4 block on the right
derrDShift = 4
derrDScale = 1 // storage descaling, needed to make the error fit int8
)
func quantizeSingle(v *int16, mtx *matrix) int {
V := int(*v)
sign := V < 0
if sign {
V = -V
}
if V > int(mtx.zthresh[0]) {
qV := int(quantDiv(uint32(V), mtx.iq[0], mtx.bias[0])) * int(mtx.q[0])
err := V - qV
if sign {
*v = int16(-qV)
return (-err) >> derrDScale
}
*v = int16(qV)
return err >> derrDScale
}
*v = 0
if sign {
return (-V) >> derrDScale
}
return V >> derrDScale
}
func (it *iterator) correctDCValues(mtx *matrix, tmp *[8][16]int16, derr *[2][3]int8) {
for ch := 0; ch <= 1; ch++ {
top := &it.enc.topDerr[it.x][ch]
left := &it.leftDerr[ch]
c := tmp[ch*4 : ch*4+4 : ch*4+4]
c[0][0] += int16((derrC1*int(top[0]) + derrC2*int(left[0])) >> (derrDShift - derrDScale))
err0 := quantizeSingle(&c[0][0], mtx)
c[1][0] += int16((derrC1*int(top[1]) + derrC2*err0) >> (derrDShift - derrDScale))
err1 := quantizeSingle(&c[1][0], mtx)
c[2][0] += int16((derrC1*err0 + derrC2*int(left[1])) >> (derrDShift - derrDScale))
err2 := quantizeSingle(&c[2][0], mtx)
c[3][0] += int16((derrC1*err1 + derrC2*err2) >> (derrDShift - derrDScale))
err3 := quantizeSingle(&c[3][0], mtx)
derr[ch][0] = int8(err1)
derr[ch][1] = int8(err2)
derr[ch][2] = int8(err3)
}
}
func (it *iterator) storeDiffusionErrors(derr *[2][3]int8) {
for ch := 0; ch <= 1; ch++ {
top := &it.enc.topDerr[it.x][ch]
left := &it.leftDerr[ch]
left[0] = derr[ch][0]
left[1] = int8((3 * int(derr[ch][2])) >> 2)
top[0] = derr[ch][1]
top[1] = derr[ch][2] - left[1]
}
}
// reconstructUV reconstructs the chroma of the macroblock with the
// prediction mode into yuvOut, setting rd's chroma levels and diffusion
// errors (and the level summaries if withInfo is set). Returns the
// non-zero bits.
func (it *iterator) reconstructUV(rd *modeScore, yuvOut []byte, mode int, withInfo bool) uint32 {
e := it.enc
ref := it.yuvP[vp8UVModeOffsets[mode&3]:]
src := it.yuvIn[uOff:]
dqm := &e.dqm[it.mb().segment&3]
tmp := &it.tmpUV
fTransformPairs(src, ref, &tabUV, tmp[:])
if e.topDerr != nil {
it.correctDCValues(&dqm.uv, tmp, &rd.derr)
}
var info []uint16
if withInfo {
info = rd.uvInfo[:]
}
nz := quantizeBlocks(tmp[:], rd.uvLevels[:], &dqm.uv, info)
iTransformPairs(ref, tmp[:], yuvOut, &tabUV)
return nz << 16
}
//------------------------------------------------------------------------------
// RD-opt decision
func (it *iterator) swapOut() {
it.yuvOut, it.yuvOut2 = it.yuvOut2, it.yuvOut
}
// storeMaxDelta raises *maxEdge (the iterator's copy of a segment's
// segmentInfo.maxEdge, merged after the pass) to the largest edge delta of
// the DC levels.
func storeMaxDelta(maxEdge *int, dcs *[16]int16) {
v0 := abs16(dcs[1])
v1 := abs16(dcs[2])
v2 := abs16(dcs[4])
maxV := v0
if v1 > maxV {
maxV = v1
}
if v2 > maxV {
maxV = v2
}
if maxV > *maxEdge {
*maxEdge = maxV
}
}
func (it *iterator) pickBestIntra16(rd *modeScore) {
e := it.enc
dqm := &e.dqm[it.mb().segment&3]
lambda := dqm.lambdaI16
tlambda := dqm.tlambda
src := it.yuvIn[yOff:]
rdCur := &it.rdTmp
rdBest := rd
isFlatSrc := isFlatSource16(src)
if tlambda != 0 { // the source part of the texture distortion is constant
tTransformPairs(src, &tabY16, it.srcTT[:])
}
rd.modeI16 = -1
// With trellis quantization, the vector kernel quantizes the 4
// candidates in one batch.
batch := it.doTrellis && it.trellisI16Modes(dqm)
for mode := 0; mode < numPredModes; mode++ {
tmpDst := it.yuvOut2[yOff:]
rdCur.modeI16 = mode
if batch {
rdCur.nz = it.reconstructI16From(rdCur, tmpDst, mode)
} else {
rdCur.nz = it.reconstructIntra16(rdCur, tmpDst, mode, true)
}
rdCur.D = int64(sse16x16(src, tmpDst))
if tlambda != 0 {
tTransformPairs(tmpDst, &tabY16, it.tt16[:])
d := 0
for n := 0; n < 16; n++ {
d += int(iabs(it.tt16[n]-it.srcTT[n]) >> 5)
}
rdCur.SD = mult8b(tlambda, d)
} else {
rdCur.SD = 0
}
rdCur.H = int64(fixedCostsI16[mode])
rdCur.R = int64(it.getCostLuma16(rdCur))
if isFlatSrc {
isFlatSrc = flatInfo(rdCur.yACInfo[:], flatnessLimitI16)
if isFlatSrc {
rdCur.D *= 2
rdCur.SD *= 2
}
}
rdCur.setRDScore(lambda)
if mode == 0 || rdCur.score < rdBest.score {
rdCur, rdBest = rdBest, rdCur
it.swapOut()
}
}
if rdBest != rd {
*rd = *rdBest
}
rd.setRDScore(dqm.lambdaMode)
it.setIntra16Mode(rd.modeI16)
if rd.nz&0x100ffff == 0x1000000 && rd.D > int64(dqm.minDisto) {
storeMaxDelta(&it.maxEdge[it.mb().segment&3], &rd.yDCLevels)
}
}
func (it *iterator) getCostModeI4(modes *[16]uint8) *[numBModes]uint16 {
predsW := it.enc.predsW
x, y := it.i4&3, it.i4>>2
var left, top uint8
if x == 0 {
left = it.enc.preds[it.predsIdx+y*predsW-1]
} else {
left = modes[(it.i4-1)&15]
}
if y == 0 {
top = it.enc.preds[it.predsIdx-predsW+x]
} else {
top = modes[(it.i4-4)&15]
}
return &fixedCostsI4[top%numBModes][left%numBModes]
}
func (it *iterator) pickBestIntra4(rd *modeScore) bool {
e := it.enc
dqm := &e.dqm[it.mb().segment&3]
lambda := dqm.lambdaI4
tlambda := dqm.tlambda
src0 := it.yuvIn[yOff:]
bestBlocks := it.yuvOut2[yOff:]
totalHeaderBits := 0
var rdBest scoreT
bestLevels := &it.i4Levels
if e.maxI4HeaderBits == 0 {
return false
}
rdBest.score = maxCost
rdBest.H = 211 // '211' is the value of VP8BitCost(0, 145)
rdBest.setRDScore(dqm.lambdaMode)
it.startI4()
cand := &it.i4m
for {
var rdI4 scoreT
rdI4.score = maxCost
bestMode := -1
modeCosts := it.getCostModeI4(&rd.modesI4)
// Reconstruct and measure the 10 modes in one batch (each mode only
// depends on the source and its prediction), then score them in
// order as libwebp does.
it.makeIntra4Preds()
nzModes := it.reconstructI4Modes(src0[vp8Scan[it.i4]:], tlambda != 0)
for mode := 0; mode < numBModes; mode++ {
var rdTmp scoreT
nz := nzModes>>uint(mode)&1 != 0
if nz {
rdTmp.nz = 1 << uint(it.i4)
}
rdTmp.D = int64(cand.d[mode])
if tlambda != 0 {
rdTmp.SD = mult8b(tlambda, int(iabs(cand.tt[mode]-cand.srcTT[0])>>5))
}
rdTmp.H = int64(modeCosts[mode])
if mode > 0 && (!nz || infoNzAC(cand.info[mode]) <= flatnessLimitI4) {
rdTmp.R = flatnessPenalty
} else {
rdTmp.R = 0
}
// early-out check
rdTmp.setRDScore(lambda)
if bestMode >= 0 && rdTmp.score >= rdI4.score {
continue
}
rdTmp.R += int64(it.getCostLuma4(&cand.levels[mode], cand.info[mode]))
rdTmp.setRDScore(lambda)
if bestMode < 0 || rdTmp.score < rdI4.score {
rdI4 = rdTmp
bestMode = mode
}
}
bestLevels[it.i4] = cand.levels[bestMode]
rdI4.setRDScore(dqm.lambdaMode)
rdBest.D += rdI4.D
rdBest.SD += rdI4.SD
rdBest.R += rdI4.R
rdBest.H += rdI4.H
rdBest.nz |= rdI4.nz
rdBest.score += rdI4.score
if rdBest.score >= rd.score {
return false
}
totalHeaderBits += int(rdI4.H)
if totalHeaderBits > e.maxI4HeaderBits {
return false
}
copy4x4(cand.rec[predOffI4(bestMode):], bestBlocks[vp8Scan[it.i4]:])
rd.modesI4[it.i4] = uint8(bestMode)
v := 0
if rdI4.nz != 0 {
v = 1
}
it.topNz[it.i4&3] = v
it.leftNz[it.i4>>2] = v
if !it.rotateI4(bestBlocks) {
break
}
}
rd.D, rd.SD, rd.R, rd.H, rd.nz, rd.score = rdBest.D, rdBest.SD, rdBest.R, rdBest.H, rdBest.nz, rdBest.score
it.setIntra4Mode(&rd.modesI4)
it.swapOut()
rd.yACLevels = *bestLevels
return true
}
func (it *iterator) pickBestUV(rd *modeScore) {
const kNumBlocks = 8
e := it.enc
dqm := &e.dqm[it.mb().segment&3]
lambda := dqm.lambdaUV
src := it.yuvIn[uOff:]
tmpDst := it.yuvOut2[uOff:]
dst0 := it.yuvOut[uOff:]
dst := dst0
dstIsDst0 := true
var rdBest scoreT
rdUV := &it.rdUV
rd.modeUV = -1
rdBest.score = maxCost
for mode := 0; mode < numPredModes; mode++ {
var s scoreT
s.nz = it.reconstructUV(rdUV, tmpDst, mode, true)
s.D = int64(sse16x8(src, tmpDst))
s.SD = 0
s.H = int64(fixedCostsUV[mode])
s.R = int64(it.getCostUV(rdUV))
if mode > 0 && flatInfo(rdUV.uvInfo[:], flatnessLimitUV) {
s.R += flatnessPenalty * kNumBlocks
}
s.setRDScore(lambda)
if mode == 0 || s.score < rdBest.score {
rdBest = s
rd.modeUV = mode
rd.uvLevels = rdUV.uvLevels
if e.topDerr != nil {
rd.derr = rdUV.derr
}
dst, tmpDst = tmpDst, dst
dstIsDst0 = !dstIsDst0
}
}
it.mb().uvMode = uint8(rd.modeUV)
rd.D += rdBest.D
rd.SD += rdBest.SD
rd.R += rdBest.R
rd.H += rdBest.H
rd.nz |= rdBest.nz
rd.score += rdBest.score
if !dstIsDst0 {
copy16x8(dst, dst0)
}
if e.topDerr != nil {
it.storeDiffusionErrors(&rd.derr)
}
}
//------------------------------------------------------------------------------
// Final reconstruction and quantization.
// simpleQuantize redoes the final quantization of the chosen modes (used
// with trellis). The chroma part, which is never trellis-quantized, is kept
// from pickBestUV when uvDone is true.
func (it *iterator) simpleQuantize(rd *modeScore, uvDone bool) {
e := it.enc
mb := it.mb()
nz := uint32(0)
if mb.typ == 1 {
nz = it.reconstructIntra16(rd, it.yuvOut[yOff:], int(e.preds[it.predsIdx]), false)
} else {
it.startI4()
for {
mode := int(e.preds[it.predsIdx+(it.i4&3)+(it.i4>>2)*e.predsW])
src := it.yuvIn[yOff+vp8Scan[it.i4]:]
dst := it.yuvOut[yOff+vp8Scan[it.i4]:]
it.makeIntra4Preds()
if it.reconstructIntra4(&rd.yACLevels[it.i4], src, dst, mode%numBModes) {
nz |= 1 << uint(it.i4)
}
if !it.rotateI4(it.yuvOut[yOff:]) {
break
}
}
}
if uvDone {
nz |= rd.nz & 0xff0000
} else {
nz |= it.reconstructUV(rd, it.yuvOut[uOff:], int(mb.uvMode), false)
}
rd.nz = nz
}
const (
lambdaDI16 = 106
lambdaDI4 = 11
lambdaDUV = 120
)
// pickI16BySSE selects the intra16 mode with the lowest distortion-based
// score. It returns the score and whether i16 must be kept (flat border
// macroblock).
func (it *iterator) pickI16BySSE(bitLimit int64) (int64, bool) {
bestScore := maxCost
bestMode := -1
stick := false
src := it.yuvIn[yOff:]
for mode := 0; mode < numPredModes; mode++ {
ref := it.yuvP[vp8I16ModeOffsets[mode]:]
score := int64(sse16x16(src, ref))*rdDistoMult + int64(fixedCostsI16[mode])*lambdaDI16
if mode > 0 && int64(fixedCostsI16[mode]) > bitLimit {
continue
}
if score < bestScore {
bestMode = mode
bestScore = score
}
}
if it.x == 0 || it.y == 0 {
// avoid starting a checkerboard resonance from the border.
if isFlatSource16(src) {
if it.x == 0 {
bestMode = 0
} else {
bestMode = 2
}
stick = true
}
}
it.setIntra16Mode(bestMode)
return bestScore, stick
}
// refineUsingDistortion refines intra16/intra4 sub-modes based on
// distortion only (not rate).
func (it *iterator) refineUsingDistortion(tryBothModes, refineUVMode bool, rd *modeScore) {
e := it.enc
bestScore := maxCost
nz := uint32(0)
isI16 := tryBothModes || it.mb().typ == 1
evaluatedI16 := false
dqm := &e.dqm[it.mb().segment&3]
scoreI4 := dqm.i4Penalty
i4BitSum := int64(0)
bitLimit := maxCost
if tryBothModes {
bitLimit = e.mbHeaderLimit
}
// Also honour the intra4 header budget (partition #0 size control).
i4Limit := min(bitLimit, int64(e.maxI4HeaderBits))
if isI16 {
var stick bool
bestScore, stick = it.pickI16BySSE(bitLimit)
evaluatedI16 = true
if stick {
tryBothModes = false
}
}
if tryBothModes || !isI16 {
isI16 = false
it.startI4()
for {
bestI4Mode := -1
bestI4Score := maxCost
src := it.yuvIn[yOff+vp8Scan[it.i4]:]
modeCosts := it.getCostModeI4(&rd.modesI4)
it.makeIntra4Preds()
it.sseI4Modes(src)
dist := &it.i4m.d
for mode := 0; mode < numBModes; mode++ {
score := int64(dist[mode])*rdDistoMult + int64(modeCosts[mode])*lambdaDI4
if score < bestI4Score {
bestI4Mode = mode
bestI4Score = score
}
}
i4BitSum += int64(modeCosts[bestI4Mode])
rd.modesI4[it.i4] = uint8(bestI4Mode)
scoreI4 += bestI4Score
if scoreI4 >= bestScore || i4BitSum > i4Limit {
isI16 = true
break
}
tmpDst := it.yuvOut2[yOff+vp8Scan[it.i4]:]
if it.reconstructIntra4(&rd.yACLevels[it.i4], src, tmpDst, bestI4Mode) {
nz |= 1 << uint(it.i4)
}
if !it.rotateI4(it.yuvOut2[yOff:]) {
break
}
}
if isI16 && !evaluatedI16 {
it.pickI16BySSE(bitLimit)
}
}
// Header bits and distortion are not used for the decision, but feed
// the partition #0 size control and the target size/PSNR search.
if !isI16 {
it.setIntra4Mode(&rd.modesI4)
it.swapOut()
bestScore = scoreI4
rd.H = 211 + i4BitSum // 211 is VP8BitCost(0, 145)
} else {
mode := int(e.preds[it.predsIdx])
nz = it.reconstructIntra16(rd, it.yuvOut[yOff:], mode, false)
rd.H = int64(fixedCostsI16[mode&3])
}
if refineUVMode {
bestMode := -1
bestUVScore := maxCost
src := it.yuvIn[uOff:]
for mode := 0; mode < numPredModes; mode++ {
ref := it.yuvP[vp8UVModeOffsets[mode]:]
score := int64(sse16x8(src, ref))*rdDistoMult + int64(fixedCostsUV[mode])*lambdaDUV
if score < bestUVScore {
bestMode = mode
bestUVScore = score
}
}
it.mb().uvMode = uint8(bestMode)
}
uvMode := int(it.mb().uvMode)
nz |= it.reconstructUV(rd, it.yuvOut[uOff:], uvMode, false)
if e.topDerr != nil {
it.storeDiffusionErrors(&rd.derr)
}
rd.H += int64(fixedCostsUV[uvMode&3])
rd.D = int64(sse16x16(it.yuvIn[yOff:], it.yuvOut[yOff:]) + sse16x8(it.yuvIn[uOff:], it.yuvOut[uOff:]))
rd.nz = nz
rd.score = bestScore
}
// decimate picks the best modes and fills the levels. Returns true if the
// macroblock has no non-zero coefficient.
func (it *iterator) decimate(rd *modeScore, rdOpt int) bool {
method := it.enc.method
rd.init()
it.makeLuma16Preds()
it.makeChroma8Preds()
if rdOpt > rdOptNone {
it.doTrellis = rdOpt >= rdOptTrellisAll
it.pickBestIntra16(rd)
if method >= 2 {
it.pickBestIntra4(rd)
}
it.pickBestUV(rd)
if rdOpt == rdOptTrellis {
it.doTrellis = true
it.simpleQuantize(rd, true)
}
} else {
it.refineUsingDistortion(method >= 2, method >= 1, rd)
}
skipped := rd.nz == 0
it.mb().skip = skipped
return skipped
}
//------------------------------------------------------------------------------
// Rate calculation
// getCostLuma16 returns the rate of rd's intra16 levels (rd.yDCInfo and
// rd.yACInfo must be set).
func (it *iterator) getCostLuma16(rd *modeScore) int {
p := &it.enc.proba
var res residual
r := 0
it.nzToBytes()
// DC
res.first, res.ctype = 0, typeI16DC
res.setCoeffsInfo(&rd.yDCLevels, rd.yDCInfo[0])
r += p.residualCost(it.topNz[8]+it.leftNz[8], &res)
// AC
res.first, res.ctype = 1, typeI16AC
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
ctx := it.topNz[x] + it.leftNz[y]
res.setCoeffsInfo(&rd.yACLevels[x+y*4], rd.yACInfo[x+y*4])
r += p.residualCost(ctx, &res)
v := b2i(res.last >= 0)
it.topNz[x] = v
it.leftNz[y] = v
}
}
return r
}
// getCostLuma4 returns the rate of the levels of the current intra4
// sub-block; info is their levelInfoOf summary.
func (it *iterator) getCostLuma4(levels *[16]int16, info uint16) int {
x, y := it.i4&3, it.i4>>2
ctx := it.topNz[x] + it.leftNz[y]
if infoLast(info) < 0 { // empty block: only the EOB is coded
return bitCost(0, it.enc.proba.coeffs[typeI4AC][0][ctx%numCtx][0])
}
var res residual
res.first, res.ctype = 0, typeI4AC
res.setCoeffsInfo(levels, info)
return it.enc.proba.residualCost(it.topNz[x]+it.leftNz[y], &res)
}
// getCostUV returns the rate of rd's chroma levels (rd.uvInfo must be
// set).
func (it *iterator) getCostUV(rd *modeScore) int {
p := &it.enc.proba
var res residual
r := 0
it.nzToBytes()
res.first, res.ctype = 0, typeChromaA
for ch := 0; ch <= 2; ch += 2 {
for y := 0; y < 2; y++ {
for x := 0; x < 2; x++ {
ctx := it.topNz[4+ch+x] + it.leftNz[4+ch+y]
res.setCoeffsInfo(&rd.uvLevels[ch*2+x+y*2], rd.uvInfo[ch*2+x+y*2])
r += p.residualCost(ctx, &res)
v := b2i(res.last >= 0)
it.topNz[4+ch+x] = v
it.leftNz[4+ch+y] = v
}
}
}
return r
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
// Algorithm adapted from libwebp (BSD-3-Clause): utils/random_utils.[ch]
// (VP8Random) and the dithered RGB->YUV conversion of
// enc/picture_csp_enc.c.
const (
randomTableSize = 55
randomDitherFix = 8
)
// kRandomTable is libwebp's 31-bit subtractive generator seed table.
var kRandomTable = [randomTableSize]uint32{
0x0de15230, 0x03b31886, 0x775faccb, 0x1c88626a, 0x68385c55, 0x14b3b828,
0x4a85fef8, 0x49ddb84b, 0x64fcf397, 0x5c550289, 0x4a290000, 0x0d7ec1da,
0x5940b7ab, 0x5492577d, 0x4e19ca72, 0x38d38c69, 0x0c01ee65, 0x32a1755f,
0x5437f652, 0x5abb2c32, 0x0faa57b1, 0x73f533e7, 0x685feeda, 0x7563cce2,
0x6e990e83, 0x4730a7ed, 0x4fc0d9c6, 0x496b153c, 0x4f1403fa, 0x541afb0c,
0x73990b32, 0x26d7cb1c, 0x6fcc3706, 0x2cbb77d8, 0x75762f2a, 0x6425ccdd,
0x24b35461, 0x0a7d8715, 0x220414a8, 0x141ebf67, 0x56b41583, 0x73e502e3,
0x44cab16f, 0x28264d42, 0x73baaefb, 0x0a50ebed, 0x1d6ab6fb, 0x0d3ad40b,
0x35db3b68, 0x2b081e83, 0x77ce6b95, 0x5181e5f0, 0x78853bbc, 0x009f9494,
0x27e5ed3c,
}
// vp8Random is libwebp's VP8Random.
type vp8Random struct {
index1, index2 int
amp int
tab [randomTableSize]uint32
}
// newRandom mirrors VP8InitRandom(rg, dithering).
func newRandom(dithering float32) *vp8Random {
rg := &vp8Random{index1: 0, index2: 31, tab: kRandomTable}
switch {
case dithering < 0:
rg.amp = 0
case dithering > 1:
rg.amp = 1 << randomDitherFix
default:
rg.amp = int(uint32(float32(1<<randomDitherFix) * dithering))
}
return rg
}
// bits mirrors VP8RandomBits: a random rounding term of numBits bits,
// centered on 1<<(numBits-1).
func (rg *vp8Random) bits(numBits uint) int32 {
diff := int64(rg.tab[rg.index1]) - int64(rg.tab[rg.index2])
if diff < 0 {
diff += 1 << 31
}
rg.tab[rg.index1] = uint32(diff)
if rg.index1++; rg.index1 == randomTableSize {
rg.index1 = 0
}
if rg.index2++; rg.index2 == randomTableSize {
rg.index2 = 0
}
v := int(int32(uint32(diff)<<1) >> (32 - numBits)) // sign-extend, 0-center
v = (v * rg.amp) >> randomDitherFix // restrict range
v += 1 << (numBits - 1) // back to 0.5-center
return int32(v)
}
// DitheringFor returns the RGB->YUV conversion dithering strength libwebp's
// WebPEncode uses for a lossy config: 0 unless Preprocessing bit 1 is set,
// otherwise an amplitude decreasing from 1 to 0.5 as quality grows.
func DitheringFor(cfg *Config) float32 {
if cfg == nil || cfg.Preprocessing&2 == 0 {
return 0
}
x := cfg.Quality / 100
x2 := x * x
return 1 + (0.5-1)*x2*x2
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"math"
"sync"
)
// Iterative "sharp" RGB -> YUV 4:2:0 conversion (libsharpyuv), for 8-bit
// input with the sRGB transfer function and libwebp's conversion matrix.
// Algorithm adapted from libwebp's sharpyuv (BSD-3-Clause).
const (
sharpIterations = 4
sharpYBits = 10 // 8-bit input + 2 bits of precision
gammaToLinearBits = 16
g2lTabBits = 10
l2gTabBits = 9
)
var (
sharpOnce sync.Once
sharpG2LTab [1<<g2lTabBits + 2]uint32
sharpL2GTab [1<<l2gTabBits + 2]uint32
)
func initSharpTables() {
sharpOnce.Do(func() {
const a = 0.09929682680944
const thresh = 0.018053968510807
const finalScale = 1 << gammaToLinearBits
const kGamma = 1. / 0.45
{
norm := 1. / (1 << g2lTabBits)
aRec := 1. / (1. + a)
for v := 0; v <= 1<<g2lTabBits; v++ {
g := norm * float64(v)
var value float64
if g <= thresh*4.5 {
value = g / 4.5
} else {
value = math.Pow(aRec*(g+a), kGamma)
}
sharpG2LTab[v] = uint32(value*finalScale + .5)
}
sharpG2LTab[1<<g2lTabBits+1] = sharpG2LTab[1<<g2lTabBits]
}
{
scale := 1. / (1 << l2gTabBits)
for v := 0; v <= 1<<l2gTabBits; v++ {
g := scale * float64(v)
var value float64
if g <= thresh {
value = 4.5 * g
} else {
value = (1.+a)*math.Pow(g, 1./kGamma) - a
}
sharpL2GTab[v] = uint32(finalScale*value + 0.5)
}
sharpL2GTab[1<<l2gTabBits+1] = sharpL2GTab[1<<l2gTabBits]
}
})
}
// sharpToLinear converts a 10-bit gamma value to 16-bit linear.
func sharpToLinear(v uint16) uint32 {
if v > 1<<g2lTabBits {
v = 1 << g2lTabBits
}
return sharpG2LTab[v]
}
// sharpFromLinear converts a 16-bit linear value to 10-bit gamma.
func sharpFromLinear(value uint32) uint16 {
const shiftR = gammaToLinearBits - l2gTabBits // 7
tabPos := value >> shiftR
if tabPos > 1<<l2gTabBits {
tabPos = 1 << l2gTabBits
}
x := value - (tabPos << shiftR)
v0 := sharpL2GTab[tabPos] >> (gammaToLinearBits - sharpYBits)
v1 := sharpL2GTab[tabPos+1] >> (gammaToLinearBits - sharpYBits)
v2 := (v1 - v0) * x
return uint16(v0 + ((v2 + (1 << (shiftR - 1))) >> shiftR))
}
func rgbToGray(r, g, b int64) int {
return int((13933*r + 46871*g + 4732*b + yuvHalf) >> yuvFix)
}
func scaleDown(a, b, c, d uint16) int {
A := sharpToLinear(a)
B := sharpToLinear(b)
C := sharpToLinear(c)
D := sharpToLinear(d)
return int(sharpFromLinear((A + B + C + D + 2) >> 2))
}
func sharpUpdateW(src []uint16, dst []uint16, w int) {
for i := 0; i < w; i++ {
R := sharpToLinear(src[0*w+i])
G := sharpToLinear(src[1*w+i])
B := sharpToLinear(src[2*w+i])
Y := rgbToGray(int64(R), int64(G), int64(B))
dst[i] = sharpFromLinear(uint32(Y))
}
}
func sharpUpdateChroma(src1, src2 []uint16, dst []int16, uvw int) {
for i := 0; i < uvw; i++ {
r := scaleDown(src1[0*uvw*2+2*i], src1[0*uvw*2+2*i+1], src2[0*uvw*2+2*i], src2[0*uvw*2+2*i+1])
g := scaleDown(src1[1*uvw*2+2*i], src1[1*uvw*2+2*i+1], src2[1*uvw*2+2*i], src2[1*uvw*2+2*i+1])
b := scaleDown(src1[2*uvw*2+2*i], src1[2*uvw*2+2*i+1], src2[2*uvw*2+2*i], src2[2*uvw*2+2*i+1])
W := rgbToGray(int64(r), int64(g), int64(b))
dst[0*uvw+i] = int16(r - W)
dst[1*uvw+i] = int16(g - W)
dst[2*uvw+i] = int16(b - W)
}
}
func sharpStoreGray(rgb []uint16, y []uint16, w int) {
for i := 0; i < w; i++ {
y[i] = uint16(rgbToGray(int64(rgb[0*w+i]), int64(rgb[1*w+i]), int64(rgb[2*w+i])))
}
}
func clipY10(v int) uint16 {
const mx = 1<<sharpYBits - 1
if v < 0 {
return 0
}
if v > mx {
return mx
}
return uint16(v)
}
func sharpFilter2(A, B, W0 int) uint16 {
v0 := (A*3 + B + 2) >> 2
return clipY10(v0 + W0)
}
func sharpImportRow(src []byte, picWidth int, dst []uint16) {
w := (picWidth + 1) &^ 1
for i := 0; i < picWidth; i++ {
p := src[4*i : 4*i+3 : 4*i+3]
dst[i+0*w] = uint16(p[0]) << 2
dst[i+1*w] = uint16(p[1]) << 2
dst[i+2*w] = uint16(p[2]) << 2
}
if picWidth&1 != 0 {
dst[picWidth+0*w] = dst[picWidth+0*w-1]
dst[picWidth+1*w] = dst[picWidth+1*w-1]
dst[picWidth+2*w] = dst[picWidth+2*w-1]
}
}
func sharpFilterRow(A, B []int16, n int, bestY []uint16, out []uint16) {
for i := 0; i < n; i++ {
a0, a1, b0, b1 := int(A[i]), int(A[i+1]), int(B[i]), int(B[i+1])
v0 := (a0*9 + a1*3 + b0*3 + b1 + 8) >> 4
v1 := (a1*9 + a0*3 + b1*3 + b0 + 8) >> 4
out[2*i+0] = clipY10(int(bestY[2*i+0]) + v0)
out[2*i+1] = clipY10(int(bestY[2*i+1]) + v1)
}
}
func sharpInterpolateTwoRows(bestY []uint16, prevUV, curUV, nextUV []int16, w int, out1, out2 []uint16) {
uvw := w >> 1
n := (w - 1) >> 1
for k := 0; k < 3; k++ {
cu := curUV[k*uvw:]
pu := prevUV[k*uvw:]
nu := nextUV[k*uvw:]
o1 := out1[k*w:]
o2 := out2[k*w:]
o1[0] = sharpFilter2(int(cu[0]), int(pu[0]), int(bestY[0]))
o2[0] = sharpFilter2(int(cu[0]), int(nu[0]), int(bestY[w]))
sharpFilterRow(cu, pu, n, bestY[1:], o1[1:])
sharpFilterRow(cu, nu, n, bestY[w+1:], o2[1:])
if w&1 == 0 {
o1[w-1] = sharpFilter2(int(cu[uvw-1]), int(pu[uvw-1]), int(bestY[w-1]))
o2[w-1] = sharpFilter2(int(cu[uvw-1]), int(nu[uvw-1]), int(bestY[w-1+w]))
}
}
}
func rgbToYUVComponent(r, g, b int, c0, c1, c2, c3 int) int {
const sfix = 2
const srounder = 1 << (yuvFix + sfix - 1)
return (c0*r + c1*g + c2*b + c3 + srounder) >> (yuvFix + sfix)
}
func clip8i(v int) uint8 {
if v < 0 {
return 0
}
if v > 255 {
return 255
}
return uint8(v)
}
func sharpRGBToYUV(pix []byte, stride, width, height int, pic *Picture) {
initSharpTables()
w := (width + 1) &^ 1
h := (height + 1) &^ 1
uvw := w >> 1
uvh := h >> 1
// Scratch from the pools, not cleared: every element is written before
// it is read (the setup loop below covers all w*h luma and uvw*3*uvh
// chroma samples, the per-row buffers are filled before use). The
// planes are separate buffers so that each stays within the
// per-buffer share of the pool budget for large pictures.
rows := uint16Pool.Get(w*3*2 + w*2)
defer uint16Pool.Put(rows)
tmp, bestRGBY := rows[:w*3*2:w*3*2], rows[w*3*2:]
bestYBase := uint16Pool.Get(w * h)
defer uint16Pool.Put(bestYBase)
targetYBase := uint16Pool.Get(w * h)
defer uint16Pool.Put(targetYBase)
bestUVBase := int16Pool.Get(uvw * 3 * uvh)
defer int16Pool.Put(bestUVBase)
targetUVBase := int16Pool.Get(uvw * 3 * uvh)
defer int16Pool.Put(targetUVBase)
bestRGBUV := int16Pool.Get(uvw * 3)
defer int16Pool.Put(bestRGBUV)
diffYThreshold := uint64(3.0 * float64(w) * float64(h))
src1 := tmp[0 : 3*w]
src2 := tmp[3*w : 6*w]
for j := 0; j < height; j += 2 {
isLastRow := j == height-1
sharpImportRow(pix[j*stride:], width, src1)
if !isLastRow {
sharpImportRow(pix[(j+1)*stride:], width, src2)
} else {
copy(src2, src1)
}
bestY := bestYBase[j*w:]
targetY := targetYBase[j*w:]
sharpStoreGray(src1, bestY[0:], w)
sharpStoreGray(src2, bestY[w:], w)
sharpUpdateW(src1, targetY, w)
sharpUpdateW(src2, targetY[w:], w)
uvo := (j >> 1) * 3 * uvw
sharpUpdateChroma(src1, src2, targetUVBase[uvo:], uvw)
copy(bestUVBase[uvo:uvo+3*uvw], targetUVBase[uvo:uvo+3*uvw])
}
prevDiffYSum := ^uint64(0)
for iter := 0; iter < sharpIterations; iter++ {
curUV := bestUVBase
prevUV := bestUVBase
diffYSum := uint64(0)
for j := 0; j < h; j += 2 {
uvo := (j >> 1) * 3 * uvw
nextUV := curUV
if j < h-2 {
nextUV = curUV[3*uvw:]
}
bestY := bestYBase[j*w:]
sharpInterpolateTwoRows(bestY, prevUV, curUV, nextUV, w, src1, src2)
prevUV = curUV
curUV = nextUV
sharpUpdateW(src1, bestRGBY[0:], w)
sharpUpdateW(src2, bestRGBY[w:], w)
sharpUpdateChroma(src1, src2, bestRGBUV, uvw)
targetY := targetYBase[j*w:]
for i := 0; i < 2*w; i++ {
diffY := int(targetY[i]) - int(bestRGBY[i])
bestY[i] = clipY10(int(bestY[i]) + diffY)
if diffY < 0 {
diffYSum += uint64(-diffY)
} else {
diffYSum += uint64(diffY)
}
}
targetUV := targetUVBase[uvo:]
bestUV := bestUVBase[uvo:]
for i := 0; i < 3*uvw; i++ {
bestUV[i] += targetUV[i] - bestRGBUV[i]
}
}
if iter > 0 {
if diffYSum < diffYThreshold {
break
}
if diffYSum > prevDiffYSum {
break
}
}
prevDiffYSum = diffYSum
}
// Convert to final YUV.
const c3Y = (16 << 16) << 2
const c3UV = (128 << 16) << 2
for j := 0; j < height; j++ {
bestY := bestYBase[j*w:]
bestUV := bestUVBase[(j>>1)*3*uvw:]
dst := pic.Y[j*pic.YStride : j*pic.YStride+width]
for i := range dst {
off := i >> 1
W := int(bestY[i])
r := int(bestUV[off+0*uvw]) + W
g := int(bestUV[off+1*uvw]) + W
b := int(bestUV[off+2*uvw]) + W
dst[i] = clip8i(rgbToYUVComponent(r, g, b, 16839, 33059, 6420, c3Y))
}
}
cw := (width + 1) >> 1
for j := 0; j < (height+1)>>1; j++ {
bestUV := bestUVBase[j*3*uvw:]
du := pic.U[j*pic.UVStride : j*pic.UVStride+cw]
dv := pic.V[j*pic.UVStride : j*pic.UVStride+cw]
for i := range du {
r := int(bestUV[i+0*uvw])
g := int(bestUV[i+1*uvw])
b := int(bestUV[i+2*uvw])
du[i] = clip8i(rgbToYUVComponent(r, g, b, -9719, -19081, 28800, c3UV))
dv[i] = clip8i(rgbToYUVComponent(r, g, b, 28800, -24116, -4684, c3UV))
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
// Token buffer: records the coefficient coding events before the final
// probabilities are known, then emits them.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
tokenFixedProba = 1 << 14 // token uses a constant probability
tokenBit = 1 << 15 // bit value
numProbaSlots = numTypes * numBands * numCtx * numProbas
)
type statsArray = [numBands][numCtx][numProbas]uint32
func tokenID(t, b, ctx int) int {
return numProbas * (ctx + numCtx*(b+numBands*t))
}
// Tokens are stored in fixed-size pages, like libwebp's VP8TBuffer: the
// buffer grows one page at a time without ever copying, its footprint
// follows the actual number of tokens, and pages are recycled through
// tokenPagePool across encodes (1.5-2.5 B/px of pages for photos).
const (
tokenPageShift = 13
tokenPageSize = 1 << tokenPageShift
tokenPageMask = tokenPageSize - 1
)
type tokenPage = [tokenPageSize]uint16
// tokenBuffer is a paged list of tokens. Tokens are addressed by a global
// index; index i lives in pages[i>>tokenPageShift][i&tokenPageMask].
type tokenBuffer struct {
pages []*tokenPage
cur []uint16 // pages[n][:k], the page being filled (nil before the first token)
n int // index of the current page
}
// reset empties the buffer, keeping its pages for reuse.
func (tb *tokenBuffer) reset() {
tb.n = 0
tb.cur = nil
if len(tb.pages) > 0 {
tb.cur = tb.pages[0][:0]
}
}
// release returns all pages to the pool.
func (tb *tokenBuffer) release() {
for i, pg := range tb.pages {
tokenPagePool.Put(pg[:])
tb.pages[i] = nil
}
tb.pages = tb.pages[:0]
tb.cur = nil
tb.n = 0
}
// len returns the number of tokens recorded.
func (tb *tokenBuffer) len() int { return tb.n<<tokenPageShift + len(tb.cur) }
// nextPage moves to the next page once the current one is full.
func (tb *tokenBuffer) nextPage() {
if cap(tb.cur) != 0 {
tb.n++
}
if tb.n == len(tb.pages) {
// Pages are written before they are read: no clearing needed.
tb.pages = append(tb.pages, (*tokenPage)(tokenPagePool.Get(tokenPageSize)))
}
tb.cur = tb.pages[tb.n][:0]
}
// chunk returns the tokens from index start up to end or the end of start's
// page, whichever comes first.
func (tb *tokenBuffer) chunk(start, end int) []uint16 {
off := start & tokenPageMask
return tb.pages[start>>tokenPageShift][off : off+min(end-start, tokenPageSize-off)]
}
// appendTokens appends already recorded tokens (the wavefront pass moves
// each row's tokens into the frame's buffer this way, in raster order).
func (tb *tokenBuffer) appendTokens(src []uint16) {
for len(src) > 0 {
if len(tb.cur) == cap(tb.cur) {
tb.nextPage()
}
n := copy(tb.cur[len(tb.cur):cap(tb.cur)], src)
tb.cur = tb.cur[:len(tb.cur)+n]
src = src[n:]
}
}
func (tb *tokenBuffer) add(bit int, idx int, s *uint32) int {
if len(tb.cur) == cap(tb.cur) {
tb.nextPage()
}
tb.cur = append(tb.cur, uint16(bit<<15|idx))
return recordStats(bit, s)
}
func (tb *tokenBuffer) addConstant(bit int, proba int) {
if len(tb.cur) == cap(tb.cur) {
tb.nextPage()
}
tb.cur = append(tb.cur, uint16(bit<<15|tokenFixedProba|proba))
}
func b2i(b bool) int {
if b {
return 1
}
return 0
}
// recordCoeffTokens records the tokens for one residual and returns whether
// it had non-zero coefficients.
func (tb *tokenBuffer) recordCoeffTokens(ctx int, res *residual, allStats *[numTypes]statsArray) int {
coeffs := res.coeffs
ctype := res.ctype
last := res.last
n := res.first
stats := &allStats[ctype]
baseID := tokenID(ctype, n, ctx)
// should be stats[encBands[n]], but it's equivalent for n=0 or 1
s := &stats[n][ctx]
if tb.add(b2i(last >= 0), baseID+0, &s[0]) == 0 {
return 0
}
for n < 16 {
c := int(coeffs[n])
n++
sign := 0
v := c
if c < 0 {
sign = 1
v = -c
}
if tb.add(b2i(v != 0), baseID+1, &s[1]) == 0 {
b := int(encBands[n])
baseID = tokenID(ctype, b, 0)
s = &stats[b][0]
continue
}
if tb.add(b2i(v > 1), baseID+2, &s[2]) == 0 {
b := int(encBands[n])
baseID = tokenID(ctype, b, 1)
s = &stats[b][1]
} else {
if tb.add(b2i(v > 4), baseID+3, &s[3]) == 0 {
if tb.add(b2i(v != 2), baseID+4, &s[4]) != 0 {
tb.add(b2i(v == 4), baseID+5, &s[5])
}
} else if tb.add(b2i(v > 10), baseID+6, &s[6]) == 0 {
if tb.add(b2i(v > 6), baseID+7, &s[7]) == 0 {
tb.addConstant(b2i(v == 6), 159)
} else {
tb.addConstant(b2i(v >= 9), 165)
tb.addConstant(b2i(v&1 == 0), 145)
}
} else {
var mask int
var tab []uint8
residue := v - 3
if residue < (8 << 1) { // Cat3 (3b)
tb.add(0, baseID+8, &s[8])
tb.add(0, baseID+9, &s[9])
residue -= 8 << 0
mask = 1 << 2
tab = vp8Cat3
} else if residue < (8 << 2) { // Cat4 (4b)
tb.add(0, baseID+8, &s[8])
tb.add(1, baseID+9, &s[9])
residue -= 8 << 1
mask = 1 << 3
tab = vp8Cat4
} else if residue < (8 << 3) { // Cat5 (5b)
tb.add(1, baseID+8, &s[8])
tb.add(0, baseID+10, &s[10])
residue -= 8 << 2
mask = 1 << 4
tab = vp8Cat5
} else { // Cat6 (11b)
tb.add(1, baseID+8, &s[8])
tb.add(1, baseID+10, &s[10])
residue -= 8 << 3
mask = 1 << 10
tab = vp8Cat6
}
for i := 0; mask != 0; i++ {
tb.addConstant(b2i(residue&mask != 0), int(tab[i]))
mask >>= 1
}
}
b := int(encBands[n])
baseID = tokenID(ctype, b, 2)
s = &stats[b][2]
}
tb.addConstant(sign, 128)
if n == 16 || tb.add(b2i(n <= last), baseID+0, &s[0]) == 0 {
return 1 // EOB
}
}
return 1
}
// emitTokenRange codes tokens [start, end) with the final probabilities.
func (tb *tokenBuffer) emitTokenRange(bw *bitWriter, start, end int, probas *[numProbaSlots]uint8) {
for start < end {
c := tb.chunk(start, end)
emitTokens(bw, c, probas)
start += len(c)
}
}
// estimateSize returns the cost (1/256 bits) of all recorded tokens.
func (tb *tokenBuffer) estimateSize(probas *[numProbaSlots]uint8) uint64 {
var size uint64
for i, end := 0, tb.len(); i < end; {
c := tb.chunk(i, end)
size += estimateTokenSize(c, probas)
i += len(c)
}
return size
}
// recordStatsRange accumulates the statistics of tokens [start, end).
func (tb *tokenBuffer) recordStatsRange(start, end int, stats *[numTypes]statsArray) {
for start < end {
c := tb.chunk(start, end)
recordTokenStats(c, stats)
start += len(c)
}
}
// tokenProba returns the probability a token is coded with: its constant
// probability, or its slot in probas. For a constant token t&0x3fff is the
// probability itself (< 256), so the table load is always in range, and
// the two are selected with a mask rather than a branch (constant and slot
// tokens alternate unpredictably).
func tokenProba(t uint16, probas *[numProbaSlots]uint8) uint8 {
p := probas[int(t&0x3fff)%numProbaSlots]
m := -uint8(t >> 14 & 1) // 0xff for a constant-probability token
return p&^m | uint8(t)&m
}
// kNorm256 and kNewRange256 extend kNorm and kNewRange to every value of
// range-1: values >= 127 need no renormalization (shift 0, same range).
var kNorm256, kNewRange256 = func() (norm, newRange [256]uint8) {
for r := range 256 {
if r < 127 {
norm[r], newRange[r] = kNorm[r], kNewRange[r]
} else {
newRange[r] = uint8(r)
}
}
return
}()
// emitTokens codes the tokens with the final probabilities. It is libwebp's
// VP8PutBit for every token, with the coder state kept in locals and the
// bit update and renormalization done without branches; only the byte
// output (flush) goes through the bitWriter. TestEmitTokensExact checks it
// against the straightforward coder.
func emitTokens(bw *bitWriter, toks []uint16, probas *[numProbaSlots]uint8) {
rng, value, nbBits := bw.rng, bw.value, bw.nbBits
for _, t := range toks {
split := (rng * int32(tokenProba(t, probas))) >> 8
mask := -int32(t >> 15) // bit ? -1 : 0
value += (split + 1) & mask
// bit ? rng - (split + 1) : split; rng stays in [0, 254].
rng = split ^ ((split ^ (rng - split - 1)) & mask)
shift := kNorm256[uint8(rng)]
rng = int32(kNewRange256[uint8(rng)])
value <<= shift & 7
nbBits += int(shift)
if nbBits > 0 {
bw.rng, bw.value, bw.nbBits = rng, value, nbBits
bw.flush()
value, nbBits = bw.value, bw.nbBits
}
}
bw.rng, bw.value, bw.nbBits = rng, value, nbBits
}
// estimateTokenSize returns the cost (1/256 bits) of the tokens.
func estimateTokenSize(toks []uint16, probas *[numProbaSlots]uint8) uint64 {
var size uint64
for _, t := range toks {
// bitCost(bit, p) is entropyCost[p] for a 0 and entropyCost[255-p]
// (= p^0xff) for a 1.
size += uint64(entropyCost[tokenProba(t, probas)^uint8(-(t>>15))])
}
return size
}
// recordTokenStats accumulates the statistics of already recorded tokens.
func recordTokenStats(toks []uint16, stats *[numTypes]statsArray) {
for _, t := range toks {
if t&tokenFixedProba == 0 {
idx := int(t & 0x3fff)
p := idx % numProbas
idx /= numProbas
c := idx % numCtx
idx /= numCtx
b := idx % numBands
ty := (idx / numBands) & 3
recordStats(int(t>>15), &stats[ty][b][c][p])
}
}
}
func flattenProbas(dst *[numProbaSlots]uint8, src *[numTypes][numBands][numCtx][numProbas]uint8) {
i := 0
for t := range src {
for b := range src[t] {
for c := range src[t][b] {
i += copy(dst[i:], src[t][b][c][:])
}
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8enc
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// trellisMatrix is empty: the amd64 kernels read the matrix themselves.
type trellisMatrix struct{}
func (*trellisMatrix) prepare(*matrix) {}
// trellisPos is what trellisModesAVX512 keeps of one position (zigzag
// index n) of its trellises; lane m is block m except in v.
type trellisPos struct {
v [16]int32 // in[m][kZigzag[n]], block m in lane 2m (m < 8) or 2(m-8)+1
l0 [16]uint16 // level0 (the level of node 0; node 1 has level0+1)
e [4]uint32 // bitCost(0, probas[encBands[n+1]][ctx][0]) for ctx 0..2; 0 at n = 15
p0 uint16 // bit m: the best predecessor of node 0 is node 1
p1 uint16 // the same for node 1
s uint16 // bit m: in[m][kZigzag[n]] < 0
_ [5]uint16
}
// trellisScratch is the workspace of the trellis kernels: the fields below
// are trellisModesAVX512's, y is trellisModesAVX2's.
type trellisScratch struct {
pos [16]trellisPos
stage [16][16]int16 // the blocks, then their levels
deq [16][16]int16 // the dequantized blocks
last [16]int64 // last position of each trellis (-1 beyond lanes)
bn [16]int32 // position of the best end of block, -1 if none
maxLast int64
first int64
lanes int64
kvalid int64 // the lanes in use, dword order
y trellisScratchY
}
// trellisW256 is rdDistoMult*kWeightTrellis, the factors of the distortion
// terms, as int64 for the broadcasts of trellisModesAVX512 (VPMULDQ takes
// their low 32 bits).
var trellisW256 = func() (t [16]int64) {
for j, w := range kWeightTrellis {
t[j] = rdDistoMult * int64(w)
}
return
}()
// trellisModesAVX512 runs trellisQuantizeBlock on the a.lanes blocks of
// a at once (a.lanes in 1..16, see trellis_amd64.s), sets a.info and
// returns the blocks with a non-zero summary as a bit mask.
//
//go:noescape
func trellisModesAVX512(a *trellisArgs, w *trellisScratch) uint32
// trellisKernelOn tells whether trellisKernel may run: from the AVX2
// level on.
func trellisKernelOn() bool { return x86Level >= cpuinfo.AVX2 }
// trellisKernel runs the trellis kernel of the level: trellisModesAVX512
// at the AVX512 level, trellisModesAVX2 (on its part of w) at the AVX2
// level.
func trellisKernel(a *trellisArgs, w *trellisScratch) uint32 {
if x86Level >= cpuinfo.AVX512 {
return trellisModesAVX512(a, w)
}
return trellisModesAVX2(a, &w.y)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8enc
import "unsafe"
// Tables and workspace of trellisModesAVX2 (trellis_avx2_amd64.s), the
// AVX2 version of trellisModesAVX512: the same trellises side by side, 8
// blocks per 256-bit register, two registers of 64-bit scores.
// trellisBandY holds the level costs of one band that trellisModesAVX2
// looks up in registers (VPERMD), for the levels 0..4 of the two nodes of
// a position whose level0 is at most 3: entry l of lo0 is
// trellisLevelCost(&costs[band][0], l), entry l of hi0 the same for level
// l+1, and entry 4*(ctx-1)+l of lo12 and hi12 the same with the tables of
// the contexts 1 and 2. The context left by node 1 is never 0, so the
// lookups after node 1 take one register; those after node 0 take two
// (lo0 when the context is 0).
type trellisBandY struct {
lo0, hi0, lo12, hi12 [8]uint32
}
// trellisTablesY are the tables of trellisModesAVX2 for one coefficient
// type: the level costs of each band and, for each position n, the cost
// of ending the block there (bitCost(0, probas[encBands[n+1]][ctx][0]),
// 0 at n = 15) at index (ctx+7)&7, the index the kernel derives from the
// level that sets the context.
type trellisTablesY struct {
band [numBands]trellisBandY
e [16][8]uint32
}
// trellisCostTables are the trellisTablesY of typeI16AC and typeI4AC,
// refreshed with the level costs (updateTrellisTables), so that the
// kernel does not rebuild them on every call.
type trellisCostTables [2]trellisTablesY
// of returns the tables of the coefficient type ctype (typeI16AC or
// typeI4AC).
func (t *trellisCostTables) of(ctype int) *trellisTablesY {
if ctype == typeI4AC {
return &t[1]
}
return &t[0]
}
// updateTrellisTables fills p.trellis from p.levelCost and p.coeffs.
func (p *encProba) updateTrellisTables() {
for _, ctype := range [2]int{typeI16AC, typeI4AC} {
t := p.trellis.of(ctype)
costs := &p.levelCost[ctype]
for b := range t.band {
bt := &t.band[b]
*bt = trellisBandY{}
for l := 0; l < 4; l++ {
bt.lo0[l] = uint32(trellisLevelCost(&costs[b][0], l))
bt.hi0[l] = uint32(trellisLevelCost(&costs[b][0], l+1))
for ctx := 1; ctx < numCtx; ctx++ {
bt.lo12[4*(ctx-1)+l] = uint32(trellisLevelCost(&costs[b][ctx], l))
bt.hi12[4*(ctx-1)+l] = uint32(trellisLevelCost(&costs[b][ctx], l+1))
}
}
}
for n := range t.e {
t.e[n] = [8]uint32{}
if n < 15 {
for ctx := 0; ctx < numCtx; ctx++ {
t.e[n][(ctx+7)&7] = uint32(bitCost(0, p.coeffs[ctype][encBands[n+1]][ctx][0]))
}
}
}
}
}
// trellisPosY is what trellisModesAVX2 keeps of one position n of the 8
// trellises of a group for the backtracking, in slot order (see the
// kernel); the masks are -1 (true) or 0.
type trellisPosY struct {
l0 [8]int32 // level0 (node 0; node 1 has level0+1)
p0, p1 [8]int32 // the best predecessor of node 0 (node 1) is node 1
u0, u1 [8]int32 // node 0 (node 1) improved the best end of block
}
// trellisScratchY is the workspace of trellisModesAVX2.
type trellisScratchY struct {
pos [16]trellisPosY
tv [16][16]int16 // coefficient j of the block in slot s of group g at tv[j][8g+s]
wv [16][8]int16 // the levels of position n of a group (slot order)
gtab [6][8]uint32 // the costs of a position found by gathers, as trellisBandY (see the kernel)
lastd [8]int32 // last position of each slot of the group
ce0, ce1, nx [8]int32 // the masks of the current position
lam [4]int64 // lambda
lastw [16]uint16 // last position of each slot (both groups)
ctx [16]uint8 // the contexts, at most 2
first int64
lanes int64
maxLast int64 // the largest last position of the group
g int64 // 8 * the group
nz int64 // the blocks with a non-zero summary
}
// trellisPosConstY are the constants of position n (zigzag order) for
// trellisModesAVX2.
type trellisPosConstY struct {
w [4]int64 // rdDistoMult*kWeightTrellis[kZigzag[n]] (VPMULDQ takes the low 32 bits)
nm1 [8]int32 // n-1
j uint32 // kZigzag[n]
band uint32 // byte offset of the tables of band encBands[n] in trellisTablesY
costs uint32 // byte offset of the level costs of that band in trellisArgs.costs
e uint32 // byte offset of the end-of-block costs of n in trellisTablesY
}
var trellisConstY = func() (t [16]trellisPosConstY) {
for n := range t {
c := &t[n]
j := kZigzag[n]
for i := range c.w {
c.w[i] = rdDistoMult * int64(kWeightTrellis[j])
}
for i := range c.nm1 {
c.nm1[i] = int32(n - 1)
}
c.j = uint32(j)
c.band = uint32(unsafe.Offsetof(trellisTablesY{}.band)) + uint32(encBands[n])*uint32(unsafe.Sizeof(trellisBandY{}))
c.costs = uint32(encBands[n]) * uint32(unsafe.Sizeof([numCtx]levelCostTable{}))
c.e = uint32(unsafe.Offsetof(trellisTablesY{}.e)) + uint32(n)*uint32(unsafe.Sizeof([8]uint32{}))
}
return
}()
// trellisModesAVX2 is trellisModesAVX512 for the AVX2 level: it runs
// trellisQuantizeBlock on the a.lanes blocks of a (a.lanes in 1..16, 8 at
// a time), sets a.info and returns the blocks with a non-zero summary as a
// bit mask. a.ytab must hold the tables of the coefficient type.
//
//go:noescape
func trellisModesAVX2(a *trellisArgs, w *trellisScratchY) uint32
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build (amd64 || arm64) && !purego
package vp8enc
import "math"
// The driver of the vector trellis quantization (method 6), shared by the
// AVX-512 and AVX2 kernels (trellis_amd64.s, trellis_avx2_amd64.s) and the
// NEON one (trellis_arm64.s): each runs trellisQuantizeBlock on up to 16
// blocks per call, 16, 8 or 4 of them side by side (one block per lane),
// through trellisKernel, and each needs trellisKernelOn and its own part
// of trellisScratch.
// trellisArgs are the parameters of the trellis kernel: the blocks, which
// share the coefficient type, quantizer, lambda and probabilities of
// trellisQuantizeBlock, each with its own context.
type trellisArgs struct {
costs *[numBands][numCtx]levelCostTable // levelCost of the coefficient type
probas *[numBands][numCtx][numProbas]uint8
mtx *matrix
lambda int64
first int64 // first position: 0, or 1 for typeI16AC (position 0 is left alone)
lanes int64 // number of blocks, 1..16
tq int64 // matrix.trellisTQ
score0 [8]int64 // initial score of both nodes by context: lambda * (ctx == 0 ? bitCost(1, p0) : 0)
best0 [8]int64 // initial best score by context: lambda * bitCost(0, p0)
in [16]*[16]int16 // the blocks (natural order), dequantized on return
out [16]*[16]int16 // their levels (zigzag order)
ctx [16]uint8 // the context of each block, 0..2
info [16]uint16 // returned: the trellisQuantizeBlock summary of each block
ytab *trellisTablesY // the cost tables of trellisModesAVX2 for the coefficient type (nil on arm64)
}
// trellisSetup fills the parameters of a that its blocks of type ctype
// (typeI4AC or typeI16AC) share. It reports false (the blocks take
// trellisQuantizeBlock) when there is no trellis kernel at the current
// level or when the kernel would not be exact: matrices outside
// trellisVecOK and lambdas >= 2^31 (the 64-bit products of the kernels
// take 32-bit factors).
func (it *iterator) trellisSetup(a *trellisArgs, ctype int, mtx *matrix, lambda int) bool {
if !trellisKernelOn() || !mtx.trellisOK || lambda < 0 || lambda > math.MaxInt32 {
return false
}
p := &it.enc.proba
first := 0
if ctype == typeI16AC {
first = 1
}
a.costs, a.probas, a.mtx = &p.levelCost[ctype], &p.coeffs[ctype], mtx
a.ytab = p.trellis.of(ctype)
a.lambda, a.first, a.tq = int64(lambda), int64(first), int64(mtx.trellisTQ)
for ctx := 0; ctx < numCtx; ctx++ {
p0 := p.coeffs[ctype][encBands[first]][ctx][0]
rate := 0
if ctx == 0 {
rate = bitCost(1, p0)
}
a.score0[ctx] = rdScoreTrellis(lambda, int64(rate), 0)
a.best0[ctx] = rdScoreTrellis(lambda, int64(bitCost(0, p0)), 0)
}
return true
}
// trellisModes runs the trellis kernel on the 10 intra4 candidates of
// it.i4m when trellisSetup allows it.
func (it *iterator) trellisModes(ctx int, dqm *segmentInfo) (uint32, bool) {
if !trellisKernelOn() || uint(ctx) > 2 { // before a is cleared
return 0, false
}
var a trellisArgs
if !it.trellisSetup(&a, typeI4AC, &dqm.y1, dqm.lambdaTrellisI4) {
return 0, false
}
s := &it.i4m
a.lanes = numBModes
for m := 0; m < numBModes; m++ {
a.in[m], a.out[m], a.ctx[m] = &s.coeffs[m], &s.levels[m], uint8(ctx)
}
nz := trellisKernel(&a, &s.tw)
copy(s.info[:], a.info[:numBModes])
return nz, true
}
// i16Batch holds the luma of the 4 intra16 candidates of a macroblock,
// transformed and quantized by trellisI16Modes for reconstructI16From.
type i16Batch struct {
tmp [numPredModes][16][16]int16 // dequantized coefficients
dcTmp [numPredModes][1][16]int16
dcLev [numPredModes][1][16]int16
dcInfo [numPredModes][1]uint16
acLevels [numPredModes][16][16]int16
acInfo [numPredModes][16]uint16
nz [numPredModes]uint32
}
// trellisI16Modes does the transform and quantization part of
// reconstructIntra16 (with trellis) for the 4 intra16 candidates at once,
// into it.i16b, and reports whether it did. The AC blocks of all
// candidates go through the trellis kernel one diagonal of the macroblock
// at a time (blocks x+y = d, up to 16 per call): the context of a block
// depends on its top and left neighbours, which belong to the previous
// diagonal, as in the raster order of reconstructIntra16.
func (it *iterator) trellisI16Modes(dqm *segmentInfo) bool {
if !trellisKernelOn() { // before a is cleared
return false
}
var a trellisArgs
if !it.trellisSetup(&a, typeI16AC, &dqm.y1, dqm.lambdaTrellisI16) {
return false
}
b := &it.i16b
src := it.yuvIn[yOff:]
for mode := 0; mode < numPredModes; mode++ {
fTransformPairs(src, it.yuvP[vp8I16ModeOffsets[mode]:], &tabY16, b.tmp[mode][:])
fTransformWHT(&b.tmp[mode], &b.dcTmp[mode][0])
b.nz[mode] = quantizeBlocks(b.dcTmp[mode][:], b.dcLev[mode][:], &dqm.y2, b.dcInfo[mode][:]) << 24
}
it.nzToBytes()
var top, left [numPredModes][4]uint8
for mode := range top {
for i := 0; i < 4; i++ {
top[mode][i], left[mode][i] = uint8(it.topNz[i]), uint8(it.leftNz[i])
}
}
for d := 0; d < 7; d++ {
x0, x1 := max(0, d-3), min(d, 3)
l := 0
for mode := 0; mode < numPredModes; mode++ {
for x := x0; x <= x1; x++ {
y := d - x
n := x + 4*y
a.in[l], a.out[l] = &b.tmp[mode][n], &b.acLevels[mode][n]
a.ctx[l] = top[mode][x] + left[mode][y]
l++
}
}
a.lanes = int64(l)
trellisKernel(&a, &it.i4m.tw)
l = 0
for mode := 0; mode < numPredModes; mode++ {
for x := x0; x <= x1; x++ {
y := d - x
n := x + 4*y
info := a.info[l]
v := uint8(b2i(info != 0))
top[mode][x], left[mode][y] = v, v
b.acLevels[mode][n][0] = 0
b.nz[mode] |= uint32(v) << uint(n)
b.acInfo[mode][n] = info
l++
}
}
}
return true
}
// reconstructI16From finishes reconstructIntra16 (withInfo set) for mode
// from what trellisI16Modes left in it.i16b.
func (it *iterator) reconstructI16From(rd *modeScore, yuvOut []byte, mode int) uint32 {
b := &it.i16b
mode &= 3
rd.yDCLevels = b.dcLev[mode][0]
rd.yDCInfo = b.dcInfo[mode]
rd.yACLevels = b.acLevels[mode]
rd.yACInfo = b.acInfo[mode]
iTransformWHT(&b.dcTmp[mode][0], &b.tmp[mode])
iTransformPairs(it.yuvP[vp8I16ModeOffsets[mode]:], b.tmp[mode][:], yuvOut, &tabY16)
return b.nz[mode]
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8enc
import (
"math"
"runtime"
"sync"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/bufpool"
"github.com/kolesa-team/go-webp/v2/internal/workers"
)
// Wavefront-parallel coding pass (Config.ThreadLevel).
//
// The calling goroutine and helpers from the process-wide budget of
// internal/workers code the macroblock rows, each worker taking the next
// row when it finishes one. Macroblock (x, r) reads the top context
// (samples, non-zero bits, intra modes and chroma diffusion errors) of
// macroblocks x-1..x+1 of row r-1, so row r codes macroblock x once row r-1
// has finished macroblock x+1. The shared top context arrays (yTop, uvTop,
// nz, topDerr, preds) are then safe: the entries row r-1 still writes are
// beyond those row r reads, row r overwrites an entry only after reading
// it, and row r+1 reads the entries of row r only once row r is past them.
//
// The output is the sequential pass's, byte for byte, whatever the number
// of workers:
// - The cost tables are refreshed before the same macroblocks. Every
// period-th macroblock is a refresh point; the worker that reaches one
// waits until all earlier macroblocks are coded and committed (the
// rows above), then refreshes the tables and starts a new epoch. A
// macroblock is coded only in its epoch, so the rows below a refresh
// point wait for it.
// - The token statistics and the autofilter SSIM sums are accumulated
// when a row is committed, in raster order. Workers record each row's
// tokens into a row buffer, with statistics counted from zero, and the
// SSIM values into a list. The statistics counters halve when they
// saturate, so the row's counts are added to the frame's only if no
// counter reaches that point (mergeStats, almost always); otherwise the
// row's tokens are replayed one by one. The SSIM values are floating
// point and are added one by one, in order.
// - Committing a row appends its tokens to e.tokens and sets its
// e.mbTokStart entries, so the frame's token buffer and everything that
// reads it after the pass are unchanged.
// - The header bit and distortion sums, and the maxEdge maxima, are
// merged after the pass.
//
// Rows are committed in order by whichever worker finishes the row that
// unblocks them, so committing never makes a worker wait. Row buffers live
// in a ring of a few more slots than workers; a worker starting a row waits
// until the row that used its slot is committed, which bounds the memory
// to a few rows of tokens on top of the frame's.
//
// Every wait blocks on a sync.Cond (one per worker) and is woken only when
// its condition holds: a row's progress is published with an atomic store,
// and the worker of the row below, if it sleeps, is signalled only once the
// row is a full gap (see minWavefrontGap) ahead. Hand-offs are expensive:
// the Go scheduler leaves a goroutine woken by a running one on the
// waker's processor, and another thread steals it only after sleeping
// 3 us, which takes about 50 us on Linux (timer slack) and about 1 ms in
// some virtual machines. So the rows are kept far enough apart that
// workers rarely have to sleep, and only pictures with enough work per
// row and per worker are coded as a wavefront.
const (
// maxWavefrontWorkers bounds the number of rows coded at once (the
// refresh points limit the gain beyond).
maxWavefrontWorkers = 8
// minWavefrontGap is the smallest distance (in macroblocks) between
// two rows coded at once: a worker that has to sleep until the row
// above is far enough ahead is woken only once that row is
// max(minWavefrontGap, mbW/workers) macroblocks ahead, the spacing
// rows naturally take, so that each wake-up is followed by a run of
// work rather than another wait.
minWavefrontGap = 8
noWant = math.MaxInt32
// The wavefront is used only when the pass is long enough to pay for
// its hand-offs (each worker sleeps and is woken a few times per
// refresh point): at least minWavefrontWork of estimated work in all,
// minWavefrontRowWork per row and wavefrontWorkPerWorker per worker
// (nanoseconds).
minWavefrontWork = 8_000_000
minWavefrontRowWork = 250_000
wavefrontWorkPerWorker = 4_000_000
)
// wavefrontMBCost estimates the coding pass time per macroblock (ns) of
// each method, measured on a photo (Apple M5) with the vector kernels and
// with the Go reference ones.
var wavefrontMBCost = func() [7]int64 {
if vecKernels {
return [7]int64{1500, 1500, 2400, 7400, 7800, 9400, 24000}
}
return [7]int64{3200, 3500, 4800, 24600, 23600, 24800, 35200}
}()
var (
// wavefrontPool holds the wfState structs (about 1 KB); their buffers
// come from the bufpool pools below, which outlive garbage collections
// (sync.Pool drops its content at every other one).
wavefrontPool = sync.Pool{New: func() any { return new(wfState) }}
// lfValuePool holds the autofilter SSIM lists of the row slots.
lfValuePool bufpool.Pool[float64]
// wfStatsPool holds the slots' token statistics (4 KB each).
wfStatsPool bufpool.Pool[[numTypes]statsArray]
// wfRowPool holds the rows' progress counters.
wfRowPool bufpool.Pool[wfRow]
// activeEncodes counts the Encode calls in progress. A wavefront pass
// takes at most GOMAXPROCS/activeEncodes workers: a server that
// already codes about one picture per processor gains nothing from
// helpers, whose rows would then wait on each other's descheduled
// workers.
activeEncodes atomic.Int32
// forceWavefront (tests only) codes every picture of two rows or more
// as a wavefront, whatever its size.
forceWavefront bool
// testHookWavefrontRow, if set (tests only), is called on the worker
// goroutine before it codes a row of a wavefront pass.
testHookWavefrontRow func(row int)
)
// wavefrontWorkers returns how many rows the coding pass may code at once
// (1: sequential).
func (e *encoder) wavefrontWorkers() int {
if !e.cfg.ThreadLevel {
return 1
}
return wavefrontWorkersFor(e.mbW, e.mbH, e.method, int(activeEncodes.Load()))
}
// wavefrontWorkersFor is wavefrontWorkers for a picture of mbW x mbH
// macroblocks coded at method (0..6) with ThreadLevel, while active
// encodes are in progress.
func wavefrontWorkersFor(mbW, mbH, method, active int) int {
if forceWavefront {
return max(1, min(maxWavefrontWorkers, mbH, mbW/2))
}
// int64: the estimate of a 16383x16383 picture overflows 32 bits.
cost := wavefrontMBCost[method]
work := int64(mbW) * int64(mbH) * cost
if work < minWavefrontWork || int64(mbW)*cost < minWavefrontRowWork {
return 1
}
nw := min(maxWavefrontWorkers, mbH, mbW/minWavefrontGap, int(min(work/wavefrontWorkPerWorker, maxWavefrontWorkers)))
return max(1, min(nw, runtime.GOMAXPROCS(0)/max(1, active)))
}
// WavefrontHelpers returns the number of helper goroutines the coding
// passes of Encode take at most for a width x height picture with cfg, if
// the budget has them free when each pass starts: 0 without ThreadLevel or
// when the passes are coded on one goroutine. It counts the encode about
// to start among those in progress. A lossy encode with alpha leaves that
// many slots of the budget to its VP8 frame while its alpha plane is coded
// alongside (the passes take their helpers once per pass, so a slot taken
// just before a pass starts is lost to it for the whole pass).
func WavefrontHelpers(width, height int, cfg *Config) int {
if !cfg.ThreadLevel || width < 1 || height < 1 {
return 0
}
method := min(max(cfg.Method, 0), 6)
return wavefrontWorkersFor((width+15)>>4, (height+15)>>4, method, int(activeEncodes.Load())+1) - 1
}
// wfWorker is one goroutine of a wavefront pass.
type wfWorker struct {
it *iterator
cond sync.Cond // L is the wfState's mu
// Under mu: whether the worker sleeps in await, and the condition it
// waits for (see wfState.ready).
sleeping bool
above int // row whose progress it waits for, or -1
need, epochNeed, commitNeed int32
sizeP0, dist uint64
}
// wfSeen holds the last values of the row above's progress and of the
// epoch a worker saw: it reads the shared counters again only when it
// needs more, rather than for every macroblock.
type wfSeen struct{ above, epoch int32 }
// wfRow is the progress of a row, alone in its cache line (128 bytes on
// Apple CPUs): the worker of the row writes prog after every macroblock,
// and only the worker of the row below reads it.
type wfRow struct {
prog atomic.Int32 // macroblocks coded
want atomic.Int32 // progress the worker of the row below sleeps for
_ [120]byte
}
// wfSlot holds the coded but not yet committed part of a row.
type wfSlot struct {
tokens tokenBuffer
stats *[numTypes]statsArray // statistics of the tokens not committed yet
mbEnd []int32 // mbEnd[x+1]: end of macroblock x's tokens; mbEnd[0] = 0
lf []float64 // autofilter SSIM values (appendFilterSSIMs)
lfPos int // values already committed
commitX int // macroblocks already committed
finished bool // under mu: the row is coded
}
// wfState is the shared state of a wavefront pass.
type wfState struct {
e *encoder
mbW, mbH int
rdOpt int
period int // cost tables refresh period, 0: none
lf bool // record the autofilter statistics
gap int32 // see minWavefrontGap
nextRow atomic.Int32 // next row to take
epoch atomic.Int32 // cost table refreshes done
committed atomic.Int32 // rows committed
stopped atomic.Bool // interrupted, too many tokens, or a worker panicked
interrupted atomic.Bool
tooMany atomic.Bool // a commit would have exceeded maxTokens
rows []wfRow
slots []wfSlot
stats [][numTypes]statsArray // the slots' statistics
mu sync.Mutex
nw int // registered workers (under mu)
workers [maxWavefrontWorkers]wfWorker
}
// codePassWavefront is codePass on nw workers: the calling goroutine and
// up to nw-1 helpers. It reports ran == false, without coding anything,
// when the budget has no free slot; the caller then codes the pass itself.
func (e *encoder) codePassWavefront(nw int, isLastPass bool, maxCount int) (sizeP0, distortion uint64, ran bool, err error) {
if workers.InUse() >= workers.Limit() {
return 0, 0, false, nil
}
wf := wavefrontPool.Get().(*wfState)
wf.init(e, nw, isLastPass, maxCount)
w0 := wf.addWorker(&e.it)
var (
its [maxWavefrontWorkers - 1]*iterator
tasks [maxWavefrontWorkers - 1]*workers.Task
n int
)
for n+1 < nw {
sit := sideIteratorPool.Get().(*iterator)
sit.reset(e)
w := wf.addWorker(sit)
t := workers.Spawn(func() error {
done := false
defer func() {
if !done { // panic or Goexit: let the others stop
wf.stop()
}
}()
wf.run(w)
done = true
return nil
})
if t == nil { // budget exhausted
wf.removeWorker()
sit.enc = nil
sideIteratorPool.Put(sit)
break
}
its[n], tasks[n] = sit, t
n++
}
if e.cfg.PassHelpers != nil {
e.cfg.PassHelpers.Add(int32(n))
}
joined, interrupted, tooMany := false, false, false
join := func() {
// Wait for every helper before recycling anything, then re-raise
// a helper panic, if any.
for _, t := range tasks[:n] {
<-t.Done()
}
joined = true
if e.cfg.PassHelpers != nil {
e.cfg.PassHelpers.Add(-int32(n))
}
// Read only now: a helper may still poll Interrupt for the last
// rows after the calling goroutine ran out of rows, and commit
// them.
interrupted = wf.interrupted.Load()
tooMany = wf.tooMany.Load()
for k := range wf.nw {
e.mergeMaxEdge(wf.workers[k].it)
sizeP0 += wf.workers[k].sizeP0
distortion += wf.workers[k].dist
}
for _, sit := range its[:n] {
sit.enc = nil
sideIteratorPool.Put(sit)
}
wf.release()
wavefrontPool.Put(wf)
for _, t := range tasks[:n] {
t.Wait()
}
}
defer func() {
if !joined { // the calling goroutine panicked
wf.stop()
join()
}
}()
if n == 0 {
// No helper: code the pass sequentially instead (the state is
// recycled by join).
join()
return 0, 0, false, nil
}
wf.run(w0)
join()
if interrupted {
return 0, 0, true, ErrInterrupted
}
if tooMany {
return 0, 0, true, ErrTooManyTokens
}
return sizeP0, distortion, true, nil
}
func (wf *wfState) init(e *encoder, nw int, isLastPass bool, maxCount int) {
wf.e = e
wf.mbW, wf.mbH = e.mbW, e.mbH
wf.rdOpt = e.rdOptLevel
wf.period = 0
if wf.rdOpt > rdOptNone {
wf.period = maxCount + 1
}
wf.lf = isLastPass && e.lfStats != nil
wf.gap = int32(max(minWavefrontGap, wf.mbW/nw))
wf.nextRow.Store(0)
wf.epoch.Store(0)
wf.committed.Store(0)
wf.stopped.Store(false)
wf.interrupted.Store(false)
wf.tooMany.Store(false)
wf.rows = wfRowPool.Get(wf.mbH)
for r := range wf.rows {
wf.rows[r].prog.Store(0)
wf.rows[r].want.Store(noWant)
}
nslots := min(nw+2, wf.mbH)
if cap(wf.slots) < nslots {
wf.slots = make([]wfSlot, nslots)
}
wf.slots = wf.slots[:nslots]
wf.stats = wfStatsPool.Get(nslots)
for i := range wf.slots {
s := &wf.slots[i]
s.stats = &wf.stats[i]
s.mbEnd = int32Pool.Get(wf.mbW + 1)
if wf.lf {
s.lf = lfValuePool.Get(wf.mbW * maxFilterSSIMs)
}
s.finished = false
}
wf.nw = 0
}
// release returns the slots' buffers to their pools.
func (wf *wfState) release() {
for i := range wf.slots {
s := &wf.slots[i]
s.tokens.release()
int32Pool.Put(s.mbEnd)
lfValuePool.Put(s.lf)
s.mbEnd, s.lf, s.stats = nil, nil, nil
}
wfStatsPool.Put(wf.stats)
wfRowPool.Put(wf.rows)
wf.stats, wf.rows = nil, nil
for k := range wf.workers {
wf.workers[k].it = nil
}
wf.e = nil
}
// addWorker registers a worker coding with it.
func (wf *wfState) addWorker(it *iterator) *wfWorker {
wf.mu.Lock()
defer wf.mu.Unlock()
w := &wf.workers[wf.nw]
w.it = it
w.cond.L = &wf.mu
w.sleeping = false
w.sizeP0, w.dist = 0, 0
wf.nw++
return w
}
// removeWorker unregisters the last worker (its helper could not start).
func (wf *wfState) removeWorker() {
wf.mu.Lock()
wf.nw--
wf.workers[wf.nw].it = nil
wf.mu.Unlock()
}
// run codes rows until there are none left or the pass stopped.
func (wf *wfState) run(w *wfWorker) {
e := wf.e
it := w.it
rd := &it.rd
nslots := len(wf.slots)
// The sums stay in registers rather than in w, next to the other
// workers' fields.
var sizeP0, dist uint64
defer func() { w.sizeP0, w.dist = sizeP0, dist }()
var seen wfSeen
for {
r := int(wf.nextRow.Add(1)) - 1
if r >= wf.mbH || wf.stopped.Load() {
return
}
// Row r reuses the slot of row r-nslots: wait until that row is
// committed.
if r >= nslots && !wf.await(w, -1, 0, 0, 0, int32(r-nslots+1)) {
return
}
if e.cfg.Interrupt != nil && e.cfg.Interrupt() {
wf.interrupted.Store(true)
wf.stop()
return
}
if testHookWavefrontRow != nil {
testHookWavefrontRow(r)
}
s := &wf.slots[r%nslots]
s.tokens.reset()
*s.stats = [numTypes]statsArray{}
s.mbEnd[0] = 0
s.lf = s.lf[:0]
s.lfPos, s.commitX = 0, 0
seen.above = 0
it.setRow(r)
for x := range wf.mbW {
if !wf.awaitMB(w, r, x, &seen) {
return
}
it.importMB()
it.decimate(rd, wf.rdOpt)
it.recordTokens(rd, &s.tokens, s.stats)
s.mbEnd[x+1] = int32(s.tokens.len())
sizeP0 += uint64(rd.H)
dist += uint64(rd.D)
if wf.lf {
s.lf = it.appendFilterSSIMs(s.lf)
}
it.saveBoundary()
it.nextInRow()
wf.publish(r, int32(x+1))
}
wf.finishRow(r)
}
}
// awaitMB waits until macroblock x of row r may be coded: row r-1 has
// coded macroblock x+1 and the cost tables are those of the macroblock's
// epoch. At a refresh point it refreshes them. It returns false if the
// pass stopped.
func (wf *wfState) awaitMB(w *wfWorker, r, x int, seen *wfSeen) bool {
epoch := int32(0)
if wf.period > 0 {
i := r*wf.mbW + x
epoch = int32((i + 1) / wf.period)
if (i+1)%wf.period == 0 {
return wf.refresh(w, r, x, epoch)
}
}
need := int32(min(x+2, wf.mbW))
if r > 0 && seen.above < need {
seen.above = wf.rows[r-1].prog.Load()
}
if seen.epoch < epoch {
seen.epoch = wf.epoch.Load()
}
if (r == 0 || seen.above >= need) && seen.epoch >= epoch && !wf.stopped.Load() {
return true
}
if !wf.await(w, r-1, need, min(int32(x)+wf.gap, int32(wf.mbW)), epoch, 0) {
return false
}
if r > 0 {
seen.above = wf.rows[r-1].prog.Load()
}
seen.epoch = wf.epoch.Load()
return true
}
// refresh refreshes the cost tables before macroblock x of row r, a
// refresh point, as the sequential pass does: from the statistics of all
// earlier macroblocks, which it first waits for (the rows above) and
// commits (this row's).
func (wf *wfState) refresh(w *wfWorker, r, x int, epoch int32) bool {
if !wf.await(w, -1, 0, 0, epoch-1, int32(r)) || !wf.commit(r, x) {
return false
}
p := &wf.e.proba
p.finalizeTokenProbas()
p.calculateLevelCosts()
wf.mu.Lock()
wf.epoch.Store(epoch)
wf.wakeReadyLocked()
wf.mu.Unlock()
return true
}
// publish records that row r has coded n macroblocks, waking the worker of
// row r+1 if it sleeps until then.
func (wf *wfState) publish(r int, n int32) {
row := &wf.rows[r]
row.prog.Store(n)
if n >= row.want.Load() {
wf.mu.Lock()
row.want.Store(noWant)
wf.wakeReadyLocked()
wf.mu.Unlock()
}
}
// finishRow marks row r coded and commits it, with the coded rows below
// it, if the rows above are committed; otherwise the worker committing
// the row above will.
func (wf *wfState) finishRow(r int) {
nslots := len(wf.slots)
wf.mu.Lock()
wf.slots[r%nslots].finished = true
mine := int(wf.committed.Load()) == r
wf.mu.Unlock()
for mine && !wf.stopped.Load() {
if !wf.commit(r, wf.mbW) {
return
}
wf.mu.Lock()
wf.slots[r%nslots].finished = false
r++
wf.committed.Store(int32(r))
wf.wakeReadyLocked()
mine = r < wf.mbH && wf.slots[r%nslots].finished
wf.mu.Unlock()
}
}
// commit commits macroblocks [commitX, x1) of row r: it appends their
// tokens to e.tokens, accumulates their token statistics and autofilter
// values. Rows are committed in raster order, as the sequential pass
// records them. If the tokens would take e.tokens past maxTokens, it
// commits nothing, stops the pass and returns false.
//
// A slot holds one row's tokens, at most a few million (mbW <= 1024), so
// the slot's int32 offsets (mbEnd) cannot overflow.
func (wf *wfState) commit(r, x1 int) bool {
e := wf.e
s := &wf.slots[r%len(wf.slots)]
x0 := s.commitX
if x0 >= x1 {
return true
}
start, end := int(s.mbEnd[x0]), int(s.mbEnd[x1])
if e.tokens.len()+(end-start) > maxTokens {
wf.tooMany.Store(true)
wf.stop()
return false
}
base := r * wf.mbW
off := int32(e.tokens.len()) - s.mbEnd[x0]
for x := x0; x < x1; x++ {
e.mbTokStart[base+x] = s.mbEnd[x] + off
}
for i := start; i < end; {
c := s.tokens.chunk(i, end)
e.tokens.appendTokens(c)
i += len(c)
}
if !mergeStats(&e.proba.stats, s.stats) {
s.tokens.recordStatsRange(start, end, &e.proba.stats)
}
if x1 < wf.mbW {
// Count the rest of the row from zero.
*s.stats = [numTypes]statsArray{}
}
if wf.lf {
for x := x0; x < x1; x++ {
s.lfPos = e.addFilterSSIMs(&e.mbInfo[base+x], s.lf, s.lfPos)
}
}
s.commitX = x1
return true
}
// ready reports whether w's wait is over (under mu).
func (wf *wfState) ready(w *wfWorker) bool {
if wf.stopped.Load() {
return true
}
return (w.above < 0 || wf.rows[w.above].prog.Load() >= w.need) &&
wf.epoch.Load() >= w.epochNeed && wf.committed.Load() >= w.commitNeed
}
// await blocks until row above (if >= 0) has coded need macroblocks, epoch
// epochNeed has begun and commitNeed rows are committed, or the pass
// stopped (it then returns false). Waiting for a row's progress, it sleeps
// until the row has coded target (>= need) macroblocks.
func (wf *wfState) await(w *wfWorker, above int, need, target, epochNeed, commitNeed int32) bool {
wf.mu.Lock()
w.above, w.need, w.epochNeed, w.commitNeed = above, need, epochNeed, commitNeed
if above >= 0 {
// Stored before ready loads the progress, which publish stores
// before loading want: either this wait sees the progress or
// publish sees want.
wf.rows[above].want.Store(target)
}
for !wf.ready(w) {
w.sleeping = true
w.cond.Wait()
}
w.sleeping = false
if above >= 0 {
wf.rows[above].want.Store(noWant)
}
wf.mu.Unlock()
return !wf.stopped.Load()
}
// wakeReadyLocked wakes the sleeping workers whose wait is over (under mu).
func (wf *wfState) wakeReadyLocked() {
for k := range wf.nw {
w := &wf.workers[k]
if w.sleeping && wf.ready(w) {
w.sleeping = false
w.cond.Signal()
}
}
}
// stop makes every worker return as soon as possible.
func (wf *wfState) stop() {
wf.stopped.Store(true)
wf.mu.Lock()
wf.wakeReadyLocked()
wf.mu.Unlock()
}
// mergeStats adds the statistics local, counted from zero, to global if
// recording the same events into global one by one gives the same result:
// when none of global's counters reaches the point where recordStats
// halves it (and local's never did). Otherwise it leaves global unchanged
// and returns false.
func mergeStats(global, local *[numTypes]statsArray) bool {
ok := true
for t := range local {
for b := range local[t] {
for c := range local[t][b] {
g, l := &global[t][b][c], &local[t][b][c]
for p := range l {
// recordStats halves a counter before an event when its
// total is 0xfffe; a local total of 0x7fff or more may
// have been halved already.
n := l[p] >> 16
ok = ok && n < 0x7fff && g[p]>>16+n <= 0xfffe
}
}
}
}
if !ok {
return false
}
for t := range local {
for b := range local[t] {
for c := range local[t][b] {
g, l := &global[t][b][c], &local[t][b][c]
for p := range l {
// Totals and counts of ones add separately: the counts
// never exceed the totals, which stay below 0x10000.
g[p] += l[p]
}
}
}
}
return true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
import (
"errors"
"sync"
"sync/atomic"
"time"
"github.com/kolesa-team/go-webp/v2/internal/workers"
)
// Two-stage decoding (Options.UseThreads).
//
// The calling goroutine entropy-decodes the level-0 pixels (decodePixels)
// while a helper goroutine runs the inverse transforms and the output
// conversion (emitRows) on the rows decoded so far, and writes them into the
// sink. Rows are handed over in jobs of about jobPixels image pixels,
// zero-copy: a job is a slice of the level-0 buffer, which the producer does
// not overwrite until the helper has acknowledged the job (see beforeSlide).
//
// The helper processes the jobs in order, in the same row batches as the
// sequential path, so the output does not depend on whether, or when, the
// helper runs. Errors keep their sequential order: a sink error of the
// helper is reported before a later bitstream error of the producer, whose
// pending rows are handed over before stopping (finishAsync).
//
// libwebp ignores use_threads for lossless images; the helper only starts
// when it can pay for itself and the process-wide helper budget
// (internal/workers) has a free slot.
//
// A hand-off costs the producer a channel send and, the helper being idle
// between jobs, a wake-up: on Linux (EPYC 8024P) the helper starts a job
// about 60 microseconds after the send, on darwin (Apple M) 15-25. The
// pipeline saves at most the helper's share of the work, which with the
// assembly kernels is small: about 0.15 ns per pixel for palette images
// (the 3000x2000 logo: 0.8 ms of 3.7, -12% with the helper on one L3 of
// the EPYC, -26% on darwin), 1 ns for photos (-6..-9%, -7..-14% on
// darwin), and almost nothing for pictures made of long LZ77 copies of
// one color (+7..+18% with the helper for such 0.25-1 MP pictures, on
// both systems). So the producer first emits asyncProbePixels pixels
// itself, timing the emission, and starts the helper only if the rest of
// the picture projects to at least asyncMinWork of emission work
// (probeDone): those pictures project to 25-140 us, the smallest gain
// measured (a 2048x1024 part of the logo, -5% on Linux) to 220 us.
//
// And on Linux the helper must share the last-level cache with the
// producer (asyncSharedLLC): the rows it reads and writes were last
// touched by the producer (the level-0 window, the output zeroed by its
// allocation), and with the whole EPYC, two 16 MB L3 of 4 cores each, the
// 3000x2000 logo decoded 10% slower with the helper, with 42% more CPU
// time (while on one L3 it decodes 12-24% faster).
var (
// asyncMinPixels is the smallest image (in needed pixels) decoded in
// two stages. A variable for tests.
asyncMinPixels = 256 * 1024
// asyncProbePixels is the number of pixels the producer emits, timed,
// before the helper may start; 0 starts it at once. A variable for
// tests.
asyncProbePixels = 32 * 1024
// asyncMinWork is the least emission work, projected from the probe
// for the rest of the picture, for which the helper starts. A
// variable for tests.
asyncMinWork = 200 * time.Microsecond
// asyncSharedLLC reports whether the CPUs this process may run on
// share one last-level cache (sharedLLC, evaluated once). A variable
// for tests.
asyncSharedLLC = sync.OnceValue(sharedLLC)
// asyncJobPixels, when > 0, overrides the job size (jobPixels). A
// variable for tests.
asyncJobPixels = 0
// asyncTestHook, if set, runs on the producer before each job is
// handed over (tests: producer panics).
asyncTestHook func(y0, y1 int)
// asyncProbeHook, if set, receives the projection of each probe
// (tests).
asyncProbeHook func(projected time.Duration)
)
// jobPixels returns the number of level-0 pixels per job for an image of
// total needed pixels coded in dataLen bytes. A hand-over costs a channel
// operation and, when the helper waits, a wake-up (tens of microseconds on
// some systems), so a job should be about half a millisecond of work. The
// work per pixel grows with the coded bits per pixel: about 1 ns per pixel
// plus 2 ns per bit (logos and palette images are near 1 ns, photos above
// 10 ns). At least 16 jobs keep the pipeline fill and drain short.
func jobPixels(total, dataLen int) int {
if asyncJobPixels > 0 {
return asyncJobPixels
}
const targetNs = 500_000
bits1024 := int(min(int64(dataLen)*8*1024/int64(max(total, 1)), 1<<20)) // bits per 1024 px
j := targetNs * 1024 / (1024 + 2*bits1024)
return max(min(j, total/16), 1)
}
// asyncProbe times the emission of the first rows of a picture that may be
// decoded in two stages (see probeDone).
type asyncProbe struct {
active bool
pixels int // pixels emitted while probing
time time.Duration // time spent emitting them
}
// asyncWanted reports whether a two-stage decode may be started: the
// option, an RGBA output, a big enough picture, and a helper sharing the
// producer's last-level cache.
func (d *decoder) asyncWanted() bool {
return d.useThreads && d.out == outRGBA && d.width*d.needRows >= asyncMinPixels && asyncSharedLLC()
}
// probeStart returns the time at which the producer starts emitting rows
// while probing, or the zero time.
func (d *decoder) probeStart() time.Time {
if !d.probe.active {
return time.Time{}
}
return time.Now()
}
// probeDone ends the timing begun at t0 (probeStart) of the emission of
// the rows up to d.lastRow, from y0. Once asyncProbePixels pixels are
// timed, it starts the helper if the emission of the rest projects to at
// least asyncMinWork.
func (d *decoder) probeDone(t0 time.Time, y0 int) {
if t0.IsZero() {
return
}
p := &d.probe
p.pixels += (d.lastRow - y0) * d.width
p.time += time.Since(t0)
if p.pixels < asyncProbePixels {
return
}
p.active = false
rest := (d.needRows - d.lastRow) * d.width
projected := time.Duration(int64(p.time) * int64(rest) / int64(max(p.pixels, 1)))
if asyncProbeHook != nil {
asyncProbeHook(projected)
}
if rest > 0 && projected >= asyncMinWork {
d.startAsync()
}
}
// maxAsyncJobs bounds the jobs handed to the helper and not yet
// acknowledged.
const maxAsyncJobs = 4
// rowJob is rows [y0, y1) of level-0 pixels, starting at argb[0], or at
// idx[0] for index bytes (idx8.go).
type rowJob struct {
argb []uint32
idx []byte
y0, y1 int
}
// asyncEmit is the producer side of a two-stage decode.
type asyncEmit struct {
task *workers.Task
jobs chan rowJob
acks chan struct{}
// stop asks the helper to return without processing further jobs
// (abort after a producer panic).
stop atomic.Bool
// starts holds the level-0 buffer index of the first pixel of each job
// in flight, oldest first (a ring of inFlight entries from head).
starts [maxAsyncJobs]int
head int
inFlight int
// pendingRow is the last row boundary passed to processRows: rows
// [d.lastRow, pendingRow) are decoded but not yet handed over.
pendingRow int
// guard, when > 0, is a buffer index the producer must not write at or
// past until the guardJobs oldest jobs (handed over before the last
// window slide, and still reading the buffer from guard on) are done.
guard, guardJobs int
jobPixels int
}
// startAsync starts the helper goroutine of a two-stage decode, if the
// image is big enough and the worker budget allows. It returns false when
// the decode must run sequentially.
func (d *decoder) startAsync() bool {
if !d.asyncWanted() {
return false
}
a := &asyncEmit{
jobs: make(chan rowJob, maxAsyncJobs),
acks: make(chan struct{}, maxAsyncJobs),
jobPixels: jobPixels(d.width*d.needRows, len(d.br.data)),
}
if d.sliding {
// Pending rows stay in the window: keep them well below the room
// a slide leaves (see initBuffer32). The window counts level-0
// pixels, at most as many as image pixels.
a.jobPixels = min(a.jobPixels, d.window/4)
}
a.task = workers.Spawn(func() error { return d.consume(a) })
if a.task == nil {
return false
}
d.async = a
return true
}
// consume is the helper goroutine: it emits the rows of each job in
// numCacheRows batches and acknowledges the job.
func (d *decoder) consume(a *asyncEmit) error {
w := d.xsize
for j := range a.jobs {
if a.stop.Load() {
return nil
}
for y := j.y0; y < j.y1; y += numCacheRows {
y1 := min(y+numCacheRows, j.y1)
var err error
if j.idx != nil {
err = d.emitIdx8(j.idx[(y-j.y0)*w:(y1-j.y0)*w], y, y1)
} else {
err = d.emitRows(j.argb[(y-j.y0)*w:(y1-j.y0)*w], y, y1)
}
if err != nil {
return err
}
}
// Never blocks: at most maxAsyncJobs jobs are unacknowledged.
a.acks <- struct{}{}
}
return nil
}
// sendRows hands rows [d.lastRow, row) of the level-0 buffer (d.buf, or
// d.ib with d.idx8), which starts at pixel base, over to the helper once
// they make a big enough job (or always with flush, or at the last needed
// row).
func (d *decoder) sendRows(base, row int, flush bool) error {
a := d.async
y0 := d.lastRow
if row <= y0 {
return nil
}
w := d.xsize
if !flush && row < d.needRows && (row-y0)*d.width < a.jobPixels {
a.pendingRow = row
return nil
}
if a.inFlight == maxAsyncJobs {
if err := a.waitOne(); err != nil {
return err
}
}
if asyncTestHook != nil {
asyncTestHook(y0, row)
}
start := y0*w - base
j := rowJob{y0: y0, y1: row}
if d.idx8 {
j.idx = d.ib[start : row*w-base]
} else {
j.argb = d.buf[start : row*w-base]
}
// Never blocks: there is room for maxAsyncJobs jobs.
a.jobs <- j
a.starts[(a.head+a.inFlight)%maxAsyncJobs] = start
a.inFlight++
a.pendingRow = row
d.lastRow = row
return nil
}
// waitOne waits for the oldest job in flight to be acknowledged. If the
// helper has stopped (it failed), it returns the helper's error.
func (a *asyncEmit) waitOne() error {
select {
case <-a.acks:
a.ack()
return nil
case <-a.task.Done():
return a.helperError()
}
}
// poll accounts for the jobs acknowledged so far, without blocking.
func (a *asyncEmit) poll() {
for {
select {
case <-a.acks:
a.ack()
default:
return
}
}
}
func (a *asyncEmit) ack() {
a.head = (a.head + 1) % maxAsyncJobs
a.inFlight--
if a.guardJobs > 0 {
if a.guardJobs--; a.guardJobs == 0 {
a.guard = 0
}
}
}
// helperError returns the error the stopped helper returned. A helper that
// stops before its jobs channel is closed has failed; Wait re-raises its
// panic, if any, on this goroutine.
func (a *asyncEmit) helperError() error {
if err := a.task.Wait(); err != nil {
return err
}
// Unreachable: the helper only returns early with an error or panic.
return errHelperStopped
}
var errHelperStopped = errors.New("vp8l: helper goroutine stopped")
// waitGuard waits until the producer may write past a.guard.
func (a *asyncEmit) waitGuard() error {
for a.guardJobs > 0 {
if err := a.waitOne(); err != nil {
return err
}
}
return nil
}
// beforeSlide is called before the window slide copies the kept pixels to
// buf[:destEnd]: the copy must not overwrite pixels the helper still reads.
// If the oldest job in flight starts at or past destEnd, the slide can go
// ahead, and the producer must then stop before that start (a.guard) until
// those jobs are done; otherwise beforeSlide waits for them.
func (a *asyncEmit) beforeSlide(destEnd int) error {
a.poll()
if a.inFlight == 0 {
return nil
}
if oldest := a.starts[a.head]; destEnd <= oldest {
a.guard, a.guardJobs = oldest, a.inFlight
return nil
}
for a.inFlight > 0 {
if err := a.waitOne(); err != nil {
return err
}
}
return nil
}
// finishAsync ends a two-stage decode whose producer returned err: on error,
// the rows the sequential decoder would have emitted are handed over first;
// then the helper is stopped and waited for. A helper error comes first in
// the sequential order, so it takes precedence over err.
func (d *decoder) finishAsync(err error) error {
a := d.async
if err != nil && a.pendingRow > d.lastRow {
// The rows up to the last batch boundary the producer passed.
if e := d.sendRows(d.px.base, a.pendingRow, true); e != nil {
err = e
}
}
d.async = nil
close(a.jobs)
if herr := a.task.Wait(); herr != nil {
return herr
}
return err
}
// abortAsync stops the helper after the producer panicked (deferred; a
// no-op once finishAsync ran). It waits for the helper without re-raising
// a helper panic, so that the producer's panic propagates.
func (d *decoder) abortAsync() {
a := d.async
if a == nil {
return
}
d.async = nil
a.stop.Store(true)
close(a.jobs)
<-a.task.Done()
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
// Algorithm adapted from libwebp (BSD-3-Clause): src/utils/bit_reader_utils.c (VP8LBitReader,
// including its end-of-stream rules).
import "encoding/binary"
// bitReader is an LSB-first bit reader over an in-memory buffer.
//
// val holds the not yet consumed bits, the next bit in bit 0. nbits is the
// number of valid bits in val; bits above nbits are either zero or already
// equal to the upcoming stream bits, which lets refill OR a whole 64-bit word
// in without masking. Reading past the end of data yields zero bits; pos then
// runs past len(data) and eos reports the overrun.
//
// The hot decoding loops copy val/nbits/pos into locals and inline the refill
// logic; the methods here are used for headers and Huffman code reading.
type bitReader struct {
data []byte
pos int
val uint64
nbits uint
}
func (b *bitReader) init(data []byte) {
b.data = data
b.pos = 0
b.val = 0
b.nbits = 0
b.refill()
}
// refill guarantees at least 56 valid bits in val (zero padded at the end of
// data).
func (b *bitReader) refill() {
if b.pos+8 <= len(b.data) {
b.val |= binary.LittleEndian.Uint64(b.data[b.pos:]) << b.nbits
b.pos += int((63 - b.nbits) >> 3)
b.nbits |= 56
return
}
b.val, b.nbits, b.pos = refillSlow(b.data, b.val, b.nbits, b.pos)
}
// refillSlow loads the stream byte by byte near the end of data.
func refillSlow(data []byte, val uint64, nbits uint, pos int) (uint64, uint, int) {
for nbits <= 56 {
if pos < len(data) {
val |= uint64(data[pos]) << nbits
}
pos++
nbits += 8
}
return val, nbits, pos
}
// read returns the next n (n <= 32) bits.
func (b *bitReader) read(n uint) uint32 {
if b.nbits < n {
b.refill()
}
v := uint32(b.val & (uint64(1)<<n - 1))
b.val >>= n
b.nbits -= n
return v
}
// eos reports whether more bits were consumed than the stream contains.
func (b *bitReader) eos() bool {
return isEOS(len(b.data), b.pos, b.nbits)
}
// eosLimit returns the number of bits that may be consumed from n bytes
// before the end of stream is reached. Like libwebp, whose 64-bit window
// is zero-filled for streams shorter than 8 bytes, at least 64 bits are
// allowed.
func eosLimit(n int) int {
return max(n, 8) * 8
}
func isEOS(n, pos int, nbits uint) bool {
return pos*8-int(nbits) > eosLimit(n)
}
// tailReader emulates libwebp's VP8LBitReader once its 64-bit window holds
// the last bytes of the stream, including its end-of-stream quirks: a
// prefetch at bit position 64 wraps around to the window start, and
// detecting the end of stream resets the position to 0. Only the 8-bit
// alpha path, which tolerates running out of data on the very last pixel,
// can observe these quirks.
type tailReader struct {
val uint64 // window: the last 8 bytes (or the whole stream if shorter)
bitPos int
eos bool
}
func newTailReader(data []byte, consumed int) tailReader {
var t tailReader
start := max(len(data)-8, 0)
for i, c := range data[start:] {
t.val |= uint64(c) << (8 * uint(i))
}
t.bitPos = consumed - start*8
return t
}
func (t *tailReader) prefetch() uint64 { return uint64(uint32(t.val >> (uint(t.bitPos) & 63))) }
func (t *tailReader) setEOS() {
t.eos = true
t.bitPos = 0
}
// shift mirrors ShiftBytes with no bytes left to load.
func (t *tailReader) shift() {
if t.bitPos > 64 {
t.setEOS()
}
}
func (t *tailReader) fill() {
if t.bitPos >= 32 {
t.shift()
}
}
func (t *tailReader) readBits(n uint) int {
if t.eos {
t.setEOS()
return 0
}
v := int(t.prefetch() & (uint64(1)<<n - 1))
t.bitPos += int(n)
t.shift()
return v
}
func (t *tailReader) readSym(table []huffCode) int {
v := t.prefetch()
idx := int(v & 0xff)
e := table[idx]
if e.bits > rootBits {
t.bitPos += rootBits
v = t.prefetch()
idx += int(e.value) + int(v&(uint64(1)<<(e.bits-rootBits)-1))
e = table[idx]
}
t.bitPos += int(e.bits)
return int(e.value)
}
func (t *tailReader) copyValue(sym int) int {
if sym < 4 {
return sym + 1
}
eb := uint(sym-2) >> 1
return (2+sym&1)<<eb + t.readBits(eb) + 1
}
func (t *tailReader) atEnd() bool { return t.eos || t.bitPos > 64 }
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package vp8l implements a pure Go decoder for the WebP lossless (VP8L)
// bitstream, including the ALPH chunk payload variant used for alpha planes.
//
// Algorithm adapted from libwebp (BSD-3-Clause): src/dec/vp8l_dec.c.
package vp8l
import (
"encoding/binary"
"errors"
"sync"
"github.com/kolesa-team/go-webp/v2/internal/pipeline"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/utils"
)
const (
headerSize = 5
signature = 0x2f
maxDimension = 1 << 14 // 14-bit sizes: 1..16384
numCacheRows = 16 // rows per inverse-transform batch
maxCopyLength = 4096 // longest LZ77 copy
maxPlaneDist = 1048576 - 120
colorCacheMult = 0x1e35a7bd
)
// metadata is the entropy coding state of one (sub-)image.
type metadata struct {
cacheBits int
huffBits int
huffMask int // (1<<huffBits)-1, or -1 without meta Huffman codes
huffXSize int
huffImage []uint32
groups []htreeGroup
}
func (md *metadata) group(groups []htreeGroup, col, row int) *htreeGroup {
if md.huffImage == nil {
return &groups[0]
}
return &groups[md.huffImage[(row>>md.huffBits)*md.huffXSize+col>>md.huffBits]]
}
// output selects what processRows emits.
const (
outRGBA = iota // RGBA rows into a pipeline.Sink
outGreen // green channel into an alpha plane
)
// decoder holds all state of one decode. Instances are pooled.
type decoder struct {
br bitReader
transforms [4]transform
nTransforms int
seen uint8
// Huffman scratch and storage, reused for each (sub-)image.
tables []huffCode
packed []packedCode
groups []htreeGroup
treeOffs [][5]int
codeLengths [maxAlphabetSize]uint8
sorted [maxAlphabetSize]uint16
lenTable [1 << lengthsBits]huffCode
single [maxAlphabetSize]int32 // offset+1 of the shared table per single symbol
singleSet []uint16 // symbols with a non-zero single entry
arena []uint32 // sub-images (transform data, entropy image)
argb []uint32 // level-0 decoded pixels (whole image or sliding window)
rows []uint32 // inverse transform output: 1 top row + numCacheRows rows
colorCache *[1 << maxCacheBits]uint32
pal [256]uint32 // RGBA palette for fused color-index output
palReady bool
premulPal bool // pal is alpha-premultiplied (pipeline.PremultipliedSink)
bundle []uint64 // RGBA pixels of each bundled index byte (bundleTable)
bundleReady bool
alphaTab *alphaTables // 8-bit alpha path tables (built once per decode)
// Level-0 output state.
out int
sink pipeline.Sink
alpha []byte
alphaRow int // the frame row alpha[0] holds (AlphaDecoder.DecodeRowsAt)
width int // final image width
height int
xsize int // level-0 coded width (after color-index bundling)
lastRow int // rows [0, lastRow) were emitted
needRows int
// inPixels is set once the level-0 header (transforms, color cache,
// Huffman codes) has been read and pixel decoding starts.
inPixels bool
// Resumable level-0 pixel decoding state (incremental alpha decoding).
md0 metadata
px pixState
buf []uint32 // level-0 pixel buffer (d.argb[:bufLen])
sliding bool // buf (or ib) is a sliding window, not the whole image
window int // LZ77 window kept when sliding
use8b bool // 8-bit alpha path (decodeAlpha8Rows)
ib []byte // 8-bit index buffer (whole image or sliding window)
inTail bool // the 8-bit path switched to the tail bit reader
tr tailReader
// Palette images decoded as bytes (idx8.go).
idx8 bool // the level-0 pixels are the index bytes in d.ib
idxARB uint32 // alpha, red and blue of every level-0 pixel
cache8 *[1 << maxCacheBits]uint16
hash8 [256]uint16 // color cache slot of each index
useThreads bool // Options.UseThreads
async *asyncEmit // two-stage decode in progress (async.go)
probe asyncProbe // timing of the first rows before a two-stage decode
}
// pixState is the position of a (resumable) pixel decoding loop. base is
// the absolute pixel index of the start of the window buffer and p the
// position in it.
type pixState struct {
base, p, col, row, lastCached int
started bool
}
var decoderPool = sync.Pool{New: func() any { return new(decoder) }}
func getDecoder() *decoder {
d := decoderPool.Get().(*decoder)
d.nTransforms = 0
d.seen = 0
d.tables = d.tables[:0]
d.packed = d.packed[:0]
d.arena = d.arena[:0]
d.lastRow = 0
d.inPixels = false
d.px = pixState{}
d.md0 = metadata{}
d.buf = nil
d.use8b = false
d.idx8 = false
d.inTail = false
d.palReady = false
d.premulPal = false
d.bundleReady = false
d.useThreads = false
d.async = nil
d.probe = asyncProbe{}
return d
}
const maxPooledPixels = 4 << 20
func putDecoder(d *decoder) {
d.sink = nil
d.alpha = nil
d.br.data = nil
for i := range d.transforms {
d.transforms[i].data = nil
}
if cap(d.argb) > maxPooledPixels {
d.argb = nil
}
if cap(d.arena) > maxPooledPixels {
d.arena = nil
}
if cap(d.rows) > maxPooledPixels {
d.rows = nil
}
if cap(d.ib) > 4*maxPooledPixels {
d.ib = nil
}
d.buf = nil
d.md0 = metadata{}
for i := range d.groups {
d.groups[i] = htreeGroup{}
}
if cap(d.groups) > 1<<12 {
d.groups = nil
d.treeOffs = nil
}
if cap(d.tables) > 1<<20 {
d.tables = nil
d.packed = nil
}
decoderPool.Put(d)
}
// DecodeHeader parses the VP8L chunk payload header (signature byte 0x2f,
// 14-bit w-1, 14-bit h-1, alpha_is_used bit, 3-bit version which must be 0).
func DecodeHeader(data []byte) (width, height int, hasAlpha bool, err error) {
if len(data) < headerSize {
return 0, 0, false, status.NotEnoughData("vp8l: header too short")
}
if data[0] != signature {
return 0, 0, false, status.Bitstream("vp8l: invalid signature")
}
v := binary.LittleEndian.Uint32(data[1:])
if v>>29 != 0 {
return 0, 0, false, status.Bitstream("vp8l: invalid version")
}
width = int(v&0x3fff) + 1
height = int(v>>14&0x3fff) + 1
hasAlpha = v>>28&1 == 1
return width, height, hasAlpha, nil
}
// Options configures DecodeWithOptions.
type Options struct {
// UseThreads decodes big images (at least 256K needed pixels) in two
// stages when the process-wide helper budget allows (see package
// internal/workers): the calling goroutine decodes the entropy-coded
// pixels while a helper goroutine applies the inverse transforms and
// writes the rows into the sink. The output is the same either way.
// libwebp ignores use_threads for lossless images.
UseThreads bool
}
// Decode decodes a VP8L chunk payload and writes non-premultiplied RGBA rows
// into sink, top to bottom (respecting sink.NeedRows() to stop early).
//
// data may extend past the end of the chunk. libwebp hands the lossless
// decoder everything from the chunk start to the end of the input (padding
// byte and trailing chunks included), so a malformed stream that overruns
// its chunk by a few bits still decodes there; passing the same extended
// slice reproduces that behavior exactly. Bits beyond len(data) read as
// zero.
func Decode(data []byte, sink pipeline.Sink) error {
return DecodeWithOptions(data, sink, nil)
}
// DecodeWithOptions is Decode with options (nil for the defaults). With
// UseThreads the sink may be called from a helper goroutine, never
// concurrently and always before DecodeWithOptions returns.
func DecodeWithOptions(data []byte, sink pipeline.Sink, opts *Options) error {
w, h, _, err := DecodeHeader(data)
if err != nil {
return err
}
if sink == nil {
return status.InvalidParam("vp8l: nil sink")
}
need := min(sink.NeedRows(), h)
d := getDecoder()
defer putDecoder(d)
// The bit reader spans the header too: libwebp's end-of-stream limit
// depends on the total payload size.
d.br.init(data)
d.br.read(8)
d.br.read(32)
d.out = outRGBA
d.sink = sink
d.needRows = max(need, 0)
d.useThreads = opts != nil && opts.UseThreads
err = d.decodeLevel0(w, h)
if status.CodeOf(err) == utils.Vp8StatusNotEnoughData {
// The whole file is available (no incremental decoding): like
// libwebp's DecodeImageData ("if not incremental, and we are past
// the end of buffer (eos_=1), then this is a real bitstream
// error"), running out of data is a bitstream error.
var se *status.Error
msg := err.Error()
if errors.As(err, &se) {
msg = se.Msg
}
return status.Bitstream(msg)
}
return err
}
// DecodeAlpha decodes an ALPH chunk compressed with method 1: data is a VP8L
// image stream WITHOUT the 5-byte header (no signature/size), of the given
// width/height; the green channel of each pixel is written into dst
// (len >= width*height, stride=width).
//
// Errors in the stream header (transforms, color cache, Huffman codes) have
// the code utils.Vp8StatusOutOfMemory: libwebp's alpha decoder
// (VP8DecompressAlphaRows) reports that code when ALPHInit fails, because
// the failed lossless decoder, and its status, are already gone. Errors in
// the pixel data are bitstream errors.
func DecodeAlpha(data []byte, width, height int, dst []byte) error {
if len(dst) < width*height {
return status.InvalidParam("vp8l: alpha buffer too small")
}
var a AlphaDecoder
if err := a.init(data, width, height); err != nil {
return err
}
defer a.Close()
return a.DecodeRows(dst, height)
}
// AlphaDecoder decodes an ALPH chunk payload (method 1) incrementally, a
// batch of rows at a time, like libwebp's VP8LDecodeAlphaImageStream: a
// caller that only needs the first rows (because the VP8 frame turns out
// to be truncated, for example) never pays for decoding the whole plane.
type AlphaDecoder struct {
d *decoder
rows int
err error
}
// NewAlphaDecoder reads the header of the alpha stream data (transforms,
// color cache, Huffman codes; see DecodeAlpha for the format and the error
// codes) of a width x height plane. The decoder must be released with
// Close.
func NewAlphaDecoder(data []byte, width, height int) (*AlphaDecoder, error) {
a := new(AlphaDecoder)
if err := a.init(data, width, height); err != nil {
return nil, err
}
return a, nil
}
func (a *AlphaDecoder) init(data []byte, width, height int) error {
if width <= 0 || height <= 0 || width > maxDimension || height > maxDimension {
return status.InvalidParam("vp8l: invalid alpha dimensions")
}
d := getDecoder()
d.br.init(data)
d.out = outGreen
if err := d.readLevel0Header(width, height); err != nil {
putDecoder(d)
var se *status.Error
msg := err.Error()
if errors.As(err, &se) {
msg = se.Msg
}
return status.New(utils.Vp8StatusOutOfMemory, "alpha decoder initialization failed: "+msg)
}
d.inPixels = true
d.use8b = d.nTransforms == 1 && d.transforms[0].kind == colorIndexingTransform && is8bOptimizable(&d.md0)
if d.use8b {
d.initBuffer8()
if d.alphaTab == nil {
d.alphaTab = new(alphaTables)
}
d.alphaTab.init(&d.transforms[0])
} else {
d.initBuffer32()
}
*a = AlphaDecoder{d: d}
return nil
}
// Rows returns the number of rows decoded so far.
func (a *AlphaDecoder) Rows() int { return a.rows }
// DecodeRows decodes the plane up to row upTo (exclusive, clamped to the
// height) into dst, the width x upTo top part of the plane (stride width;
// len(dst) >= width*upTo). Rows written by earlier calls are not written
// again, so dst must hold the same top rows on every call (it may be a
// longer copy of the previous buffer). After an error every call returns
// that error.
func (a *AlphaDecoder) DecodeRows(dst []byte, upTo int) error {
return a.DecodeRowsAt(dst, 0, upTo)
}
// DecodeRowsAt is DecodeRows into a window of the plane: dst holds the rows
// [first, upTo) (stride width), first <= Rows(), and only the rows
// [Rows(), upTo) are written. The rows before first are not needed, so a
// caller may keep a few rows of the plane at a time.
func (a *AlphaDecoder) DecodeRowsAt(dst []byte, first, upTo int) error {
if a.err != nil {
return a.err
}
d := a.d
if d == nil {
return status.InvalidParam("vp8l: alpha decoder closed")
}
upTo = min(upTo, d.height)
if upTo <= a.rows {
return nil
}
if first < 0 || first > a.rows || len(dst) < (upTo-first)*d.width {
return status.InvalidParam("vp8l: alpha buffer too small")
}
d.alpha = dst
d.alphaRow = first
d.needRows = upTo
var err error
if d.use8b {
err = d.decodeAlpha8Rows(upTo)
} else {
err = d.decodePixels(&d.md0, d.buf, d.xsize, d.height, true, d.sliding, d.window, &d.px)
}
d.alpha = nil
if err != nil {
a.err = err
return err
}
a.rows = upTo
return nil
}
// Close releases the decoder's buffers.
func (a *AlphaDecoder) Close() {
if a.d != nil {
putDecoder(a.d)
a.d = nil
}
}
// readLevel0Header reads the main image stream header: transforms, color
// cache and Huffman codes (into d.md0).
func (d *decoder) readLevel0Header(w, h int) error {
br := &d.br
d.width, d.height = w, h
xsize := w
for br.read(1) == 1 {
if err := d.readTransform(&xsize, h); err != nil {
return err
}
}
if err := d.readImageCodes(&d.md0, xsize, h, true); err != nil {
return err
}
d.xsize = xsize
if br.eos() {
return status.NotEnoughData("vp8l: truncated header")
}
return nil
}
// initBuffer32 allocates the inverse transform rows and the level-0 pixel
// buffer: the whole image, or a sliding window big enough for any LZ77
// distance plus the rows not yet emitted.
func (d *decoder) initBuffer32() {
w, h, xsize := d.width, d.height, d.xsize
if d.nTransforms > 0 {
n := w * (numCacheRows + 1)
if cap(d.rows) < n {
d.rows = make([]uint32, n)
}
d.rows = d.rows[:n]
}
total := xsize * h
d.window = max(maxPlaneDist, 7*xsize+8)
bufLen := d.window + d.window/2 + (numCacheRows+2)*xsize + 2*maxCopyLength
d.sliding = bufLen < total
if !d.sliding {
bufLen = total
}
if cap(d.argb) < bufLen {
d.argb = make([]uint32, bufLen)
}
d.buf = d.argb[:bufLen]
}
// initBuffer8 allocates the index buffer of the 8-bit alpha path, with the
// same window logic as initBuffer32.
func (d *decoder) initBuffer8() {
total := d.xsize * d.height
d.window = max(maxPlaneDist, 7*d.xsize+8)
bufLen := d.window + d.window/2 + (numCacheRows+2)*d.xsize + 2*maxCopyLength
d.sliding = bufLen < total
if !d.sliding {
bufLen = total
}
if cap(d.ib) < bufLen {
d.ib = make([]byte, bufLen)
}
d.ib = d.ib[:bufLen]
}
// decodeLevel0 decodes the main image stream: transforms, codes, pixels.
func (d *decoder) decodeLevel0(w, h int) error {
if err := d.readLevel0Header(w, h); err != nil {
return err
}
if d.needRows == 0 {
return nil
}
d.inPixels = true
// When the palette lookup is the last step, a sink that premultiplies
// its rows (scaling) can be fed premultiplied palette colors instead:
// premultiplying 256 palette entries once gives the same pixels as
// premultiplying every pixel.
if d.nTransforms > 0 && d.transforms[0].kind == colorIndexingTransform {
if ps, ok := d.sink.(pipeline.PremultipliedSink); ok && ps.AcceptPremultiplied() {
d.premulPal = true
}
}
if arb, ok := d.idx8ARB(); ok {
d.initIdx8(arb)
} else {
d.initBuffer32()
}
if d.asyncWanted() {
// Stop the helper on every path; after a normal return finishAsync
// already did, and this is a no-op.
defer d.abortAsync()
if asyncProbePixels > 0 {
// The helper starts, or not, after the first rows (probeDone).
d.probe.active = true
} else {
d.startAsync()
}
err := d.decodeLevel0Pixels(h)
if d.async != nil {
return d.finishAsync(err)
}
return err
}
return d.decodeLevel0Pixels(h)
}
// decodeLevel0Pixels decodes the level-0 pixels of an image of height h,
// as index bytes when d.idx8 is set (switching to 32 bits if the stream
// requires it, see idx8.go).
func (d *decoder) decodeLevel0Pixels(h int) error {
if d.idx8 {
err := d.decodeIdx8(&d.md0, d.ib, d.xsize, h, d.sliding, d.window, &d.px)
if err != errWiden {
return err
}
if err := d.widenIdx8(); err != nil {
return err
}
}
return d.decodePixels(&d.md0, d.buf, d.xsize, h, true, d.sliding, d.window, &d.px)
}
func is8bOptimizable(md *metadata) bool {
if md.cacheBits > 0 {
return false
}
for i := range md.groups {
t := &md.groups[i].trees
if t[treeRed][0].bits > 0 || t[treeBlue][0].bits > 0 || t[treeAlpha][0].bits > 0 {
return false
}
}
return true
}
// readImageCodes reads the color cache info and Huffman codes of an image.
func (d *decoder) readImageCodes(md *metadata, xsize, ysize int, level0 bool) error {
br := &d.br
md.cacheBits = 0
if br.read(1) == 1 {
bits := int(br.read(4))
if bits < 1 || bits > maxCacheBits {
return status.Bitstream("vp8l: invalid color cache bits")
}
md.cacheBits = bits
}
return d.readHuffmanCodes(md, xsize, ysize, md.cacheBits, level0)
}
// readTransform reads one transform; xsize is updated for color indexing.
func (d *decoder) readTransform(xsize *int, ysize int) error {
br := &d.br
kind := int(br.read(2))
if d.seen&(1<<kind) != 0 {
return status.Bitstream("vp8l: repeated transform")
}
d.seen |= 1 << kind
t := &d.transforms[d.nTransforms]
d.nTransforms++
*t = transform{kind: kind, xsize: *xsize, ysize: ysize}
switch kind {
case predictorTransform, crossColorTransform:
t.bits = int(br.read(3)) + 2
data, err := d.decodeSubImage(subSampleSize(*xsize, t.bits), subSampleSize(ysize, t.bits))
if err != nil {
return err
}
t.data = data
case colorIndexingTransform:
numColors := int(br.read(8)) + 1
bits := 0
switch {
case numColors > 16:
case numColors > 4:
bits = 1
case numColors > 2:
bits = 2
default:
bits = 3
}
t.bits = bits
*xsize = subSampleSize(*xsize, bits)
data, err := d.decodeSubImage(numColors, 1)
if err != nil {
return err
}
// Expand the delta-coded palette to its full size; unused
// entries are transparent black.
pal := d.allocArena(1 << (8 >> bits))
clear(pal)
pal[0] = data[0]
for i := 1; i < numColors && i < len(pal); i++ {
pal[i] = addPixels(data[i], pal[i-1])
}
t.data = pal
}
return nil
}
// allocArena returns n (not zeroed) pixels for a sub-image. Earlier
// sub-images stay valid if the arena grows.
func (d *decoder) allocArena(n int) []uint32 {
off := len(d.arena)
if cap(d.arena)-off < n {
na := make([]uint32, 0, max(2*cap(d.arena), off+n, 1024))
d.arena = na
off = 0
}
d.arena = d.arena[:off+n]
return d.arena[off : off+n : off+n]
}
// decodeSubImage decodes an entropy-coded sub-image (no transforms, no meta
// Huffman codes).
func (d *decoder) decodeSubImage(xsize, ysize int) ([]uint32, error) {
var md metadata
if err := d.readImageCodes(&md, xsize, ysize, false); err != nil {
return nil, err
}
buf := d.allocArena(xsize * ysize)
var st pixState
if err := d.decodePixels(&md, buf, xsize, ysize, false, false, 0, &st); err != nil {
return nil, err
}
return buf, nil
}
// planeCodeToDistance maps a distance code to a linear pixel distance.
func planeCodeToDistance(xsize, code int) int {
if code > len(distanceMap) {
return code - len(distanceMap)
}
dc := int(distanceMap[(code-1)&127])
d := (dc>>4)*xsize + 8 - dc&0xf
if d < 1 {
return 1
}
return d
}
// distanceMap maps the 120 short distance codes to (dy<<4 | (8-dx)).
var distanceMap = [120]uint8{
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a,
0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a,
0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b,
0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03,
0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c,
0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e,
0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b,
0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f,
0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b,
0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41,
0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f,
0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
}
// copyBlock32 copies length pixels from p-dist to p, with LZ77 semantics
// for overlapping ranges (the pattern of period dist repeats).
func copyBlock32(buf []uint32, p, dist, length int) {
src := p - dist
if dist >= length {
copy(buf[p:p+length], buf[src:src+length])
return
}
if dist == 1 {
v := buf[src]
s := buf[p : p+length]
for i := range s {
s[i] = v
}
return
}
n := copy(buf[p:p+dist], buf[src:p])
for n < length {
n += copy(buf[p+n:p+length], buf[p:p+n])
}
}
func copyBlock8(buf []byte, p, dist, length int) {
src := p - dist
if dist >= length {
copy(buf[p:p+length], buf[src:src+length])
return
}
if dist == 1 {
v := buf[src]
s := buf[p : p+length]
for i := range s {
s[i] = v
}
return
}
n := copy(buf[p:p+dist], buf[src:p])
for n < length {
n += copy(buf[p+n:p+length], buf[p:p+n])
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8l
import "github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
// SSE4.1, AVX2 and AVX-512 kernels of the inverse transforms and the output
// conversion (emit_amd64.s, predict_amd64.s, bundled_amd64.s,
// lookup_amd64.s, palette_amd64.s), selected by x86Level (and x86VBMI).
// The wrappers below check every length and pass the assembly exact pixel
// counts: it reads and writes only inside the slices, tails included. The
// pure-Go references (the ...Go functions) are the specification;
// dsp_test.go compares them with every level.
//
// Levels without a kernel of their own use the next lower one: AVX-512
// adds only the VBMI palette lookups (the other kernels are bound by
// loads and stores, or by serial dependencies, at 256 bits already).
const haveAsm = true
//go:noescape
func emitRGBASSE41(src *uint32, dst *byte, n int)
//go:noescape
func emitRGBAAVX2(src *uint32, dst *byte, n int)
//go:noescape
func emitAddGreenSSE41(src *uint32, dst *byte, n int)
//go:noescape
func emitAddGreenAVX2(src *uint32, dst *byte, n int)
//go:noescape
func addGreenSSE41(in, out *uint32, n int)
//go:noescape
func addGreenAVX2(in, out *uint32, n int)
//go:noescape
func crossColorRowSSE41(mults, src, dst *uint32, width, bits int)
//go:noescape
func crossColorRowAVX2(mults, src, dst *uint32, width, bits int)
//go:noescape
func predictRowSSE41(in, out, up, modes *uint32, x, width, bits int) int
//go:noescape
func lookupRGBAVBMI(pal *[256]uint32, src, dst *byte, n int)
//go:noescape
func lookupRGBAAVX2(pal *[256]uint32, src, dst *byte, n int)
//go:noescape
func lookupBytesVBMI(pal *[256]byte, in, out *byte, n int)
//go:noescape
func lookupBytesSSE41(pal *[256]byte, in, out *byte, n int)
//go:noescape
func lookupBytesAVX2(pal *[256]byte, in, out *byte, n int)
//go:noescape
func expandBundled8SSE41(pal *[256]byte, src, dst *byte, n, bits int)
//go:noescape
func expandBundled8AVX2(pal *[256]byte, src, dst *byte, n, bits int)
//go:noescape
func expandBundledRGBAAVX2(pal *[256]uint32, src, dst *byte, n, bits int)
// emitRGBA converts the ARGB pixels src to RGBA bytes in dst (as many
// pixels as fit).
func emitRGBA(src []uint32, dst []byte) {
n := min(len(src), len(dst)/4)
switch {
case n == 0 || x86Level < cpuinfo.SSE41:
emitRGBAGo(src, dst)
case x86Level >= cpuinfo.AVX2:
emitRGBAAVX2(&src[0], &dst[0], n)
default:
emitRGBASSE41(&src[0], &dst[0], n)
}
}
// emitAddGreen fuses the inverse subtract-green transform with emitRGBA.
func emitAddGreen(src []uint32, dst []byte) {
n := min(len(src), len(dst)/4)
switch {
case n == 0 || x86Level < cpuinfo.SSE41:
emitAddGreenGo(src, dst)
case x86Level >= cpuinfo.AVX2:
emitAddGreenAVX2(&src[0], &dst[0], n)
default:
emitAddGreenSSE41(&src[0], &dst[0], n)
}
}
// addGreen undoes the subtract-green transform. in may alias out.
func addGreen(in, out []uint32) {
out = out[:len(in)]
switch {
case len(in) == 0 || x86Level < cpuinfo.SSE41:
addGreenGo(in, out)
case x86Level >= cpuinfo.AVX2:
addGreenAVX2(&in[0], &out[0], len(in))
default:
addGreenSSE41(&in[0], &out[0], len(in))
}
}
// lookupBytes sets out[i] = pal[in[i]] (len(out) >= len(in)).
func lookupBytes(pal *[256]byte, in, out []byte) {
out = out[:len(in)]
n := len(in) &^ 15
switch {
case len(in) == 0:
return
case x86Level >= cpuinfo.AVX512 && x86VBMI:
lookupBytesVBMI(pal, &in[0], &out[0], len(in))
return
case n == 0:
case x86Level >= cpuinfo.AVX2:
lookupBytesAVX2(pal, &in[0], &out[0], n)
case x86Level >= cpuinfo.SSE41:
lookupBytesSSE41(pal, &in[0], &out[0], n)
default:
n = 0
}
lookupBytesGo(pal, in[n:], out[n:])
}
// lookupRGBAMinVBMI is the shortest row for lookupRGBAVBMI, which first
// transposes the palette (about as long as 40 pixels of the Go loop).
const lookupRGBAMinVBMI = 64
// lookupRGBA writes the RGBA words pal[src[i]] to dst (as many pixels as
// fit). The AVX2 gather does groups of 8 pixels, the Go reference the
// rest.
func lookupRGBA(pal *[256]uint32, src, dst []byte) {
n := min(len(src), len(dst)/4)
switch {
case n >= lookupRGBAMinVBMI && x86Level >= cpuinfo.AVX512 && x86VBMI:
lookupRGBAVBMI(pal, &src[0], &dst[0], n)
return
case n >= 8 && x86Level >= cpuinfo.AVX2:
m := n &^ 7
lookupRGBAAVX2(pal, &src[0], &dst[0], m)
src, dst = src[m:n], dst[4*m:]
}
lookupRGBAGo(pal, src, dst)
}
// crossColorRow undoes the cross-color transform on one row src into dst,
// with the multipliers of each tile of 1<<bits pixels in mults. src may
// alias dst.
func crossColorRow(mults, src, dst []uint32, bits int) {
width := len(src)
if width == 0 || x86Level < cpuinfo.SSE41 {
crossColorRowGo(mults, src, dst, bits)
return
}
dst = dst[:width]
if bits < 0 || bits > 30 {
panic("vp8l: invalid cross-color tile bits")
}
mults = mults[:subSampleSize(width, bits)]
if x86Level >= cpuinfo.AVX2 {
crossColorRowAVX2(&mults[0], &src[0], &dst[0], width, bits)
} else {
crossColorRowSSE41(&mults[0], &src[0], &dst[0], width, bits)
}
}
// predictRow undoes the predictor transform for the pixels 1 to
// len(out)-1 of a row whose pixel 0 is already done, with the mode of each
// tile of 1<<bits pixels in modes. up is the previous output row extended
// by out[0] (see predictRun). in may alias out.
//
// The assembly handles every mode but 13 (rare, and serial per pixel): it
// returns at the first tile of mode 13, which predictRun then does before
// the assembly goes on.
func predictRow(modes, in, out, up []uint32, bits int) {
width := len(out)
if width < 2 || x86Level < cpuinfo.SSE41 {
predictRowGo(modes, in, out, up, bits)
return
}
if bits < 0 || bits > 30 {
panic("vp8l: invalid predictor tile bits")
}
in = in[:width]
up = up[:width+1]
modes = modes[:subSampleSize(width, bits)]
x := 1
for {
x = predictRowSSE41(&in[0], &out[0], &up[0], &modes[0], x, width, bits)
if x >= width {
return
}
xEnd := min((x>>bits+1)<<bits, width)
predictRun(modes[x>>bits]>>8&0xf, in, out, up, x, xEnd)
x = xEnd
}
}
// expandBundledRow expands one row of bundled indices (each byte of src
// holds 1<<bits of them, bits 1 to 3) into the output bytes dst, from the
// palette a.pal8 (at most 16 entries). The assembly does whole blocks of
// 16 packed bytes, the Go reference the rest of the row.
func expandBundledRow(a *alphaTables, bits int, src, dst []byte) {
n := min(len(dst)>>bits, len(src)) &^ 15
if n > 0 && bits >= 1 && bits <= 3 && x86Level >= cpuinfo.SSE41 {
if x86Level >= cpuinfo.AVX2 {
expandBundled8AVX2(&a.pal8, &src[0], &dst[0], n, bits)
} else {
expandBundled8SSE41(&a.pal8, &src[0], &dst[0], n, bits)
}
src, dst = src[n:], dst[n<<bits:]
}
expandBundledRowGo(a, bits, src, dst)
}
// expandBundledRGBA expands one row of bundled palette indices (each byte
// of src holds 1<<bits of them, bits 1 to 3) into the RGBA bytes dst (as
// many pixels as fit), from the RGBA palette pal (at most 16 entries).
// The assembly does whole groups of 8 pixels, the Go reference (with tab,
// see bundleTable) the rest of the row.
func expandBundledRGBA(pal *[256]uint32, tab []uint64, bits int, src, dst []byte) {
if x86Level >= cpuinfo.AVX2 && bits >= 1 && bits <= 3 {
group := 8 >> bits // packed bytes of 8 pixels
n := min(len(dst)/(4<<bits), len(src)) &^ (group - 1)
if n > 0 {
expandBundledRGBAAVX2(pal, &src[0], &dst[0], n, bits)
src, dst = src[n:], dst[n*(4<<bits):]
}
}
expandBundledRGBAGo(tab, bits, src, dst)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
// Algorithm adapted from libwebp (BSD-3-Clause): two-level Huffman lookup
// tables (src/utils/huffman_utils.c) and the HTreeGroup fast paths
// (src/dec/vp8l_dec.c).
import "github.com/kolesa-team/go-webp/v2/internal/status"
const (
numLiteralCodes = 256
numLengthCodes = 24
numDistanceCodes = 40
maxCacheBits = 11
maxAlphabetSize = numLiteralCodes + numLengthCodes + 1<<maxCacheBits
rootBits = 8 // root table bits of the main Huffman tables
lengthsBits = 7 // root table bits of the code-length code table
maxCodeLength = 15
packedBits = 6 // HUFFMAN_PACKED_BITS
packedSize = 1 << packedBits
specialMarker = 0x100 // packedCode.bits marker for non-literal green codes
)
// Indices of the five Huffman trees of a group.
const (
treeGreen = iota
treeRed
treeBlue
treeAlpha
treeDist
)
// huffCode is one Huffman lookup table entry. In a root table, an entry with
// bits > rootBits links to a second-level table: value is the offset of that
// table relative to the root entry index and bits-rootBits its index width.
type huffCode struct {
bits uint8
value uint16
}
// packedCode is a packed-table entry: either a full ARGB literal decoded with
// one lookup (bits < specialMarker), or a non-literal green code
// (bits = specialMarker + code length, value = green symbol).
type packedCode struct {
bits uint32
value uint32
}
// htreeGroup is the set of five Huffman codes used for one entropy tile.
type htreeGroup struct {
trees [5][]huffCode
// literalARB holds the constant alpha/red/blue of a trivial literal (and
// green too when isTrivialCode).
literalARB uint32
isTrivialLiteral bool // red, blue and alpha trees have a single symbol
isTrivialCode bool // every pixel of the tile is literalARB
usePacked bool // packed holds a 6-bit one-lookup table
packed []packedCode
}
// readSym decodes one symbol from table t using the prefetched bits val.
// It returns the symbol and the number of bits used.
func readSym(t []huffCode, val uint64) (int, uint) {
idx := int(val & 0xff)
e := t[idx]
if e.bits <= rootBits {
return int(e.value), uint(e.bits)
}
idx += int(e.value) + int((val>>rootBits)&(uint64(1)<<(e.bits-rootBits)-1))
e2 := t[idx]
return int(e2.value), uint(e2.bits) + rootBits
}
// maxTableSize returns an upper bound of the table size (root bits 8) of a
// complete code over alphabetSize symbols (values from zlib's "enough").
func maxTableSize(alphabetSize int) int {
switch {
case alphabetSize <= numDistanceCodes:
return 410
case alphabetSize <= 256:
return 630
}
// Green alphabet: 280 + color cache size.
switch alphabetSize - numLiteralCodes - numLengthCodes {
case 0:
return 654
case 1 << 1:
return 656
case 1 << 2:
return 658
case 1 << 3:
return 662
case 1 << 4:
return 670
case 1 << 5:
return 686
case 1 << 6:
return 718
case 1 << 7:
return 782
case 1 << 8:
return 910
case 1 << 9:
return 1166
case 1 << 10:
return 1678
}
return 2702
}
// buildTable builds a two-level lookup table for the given code lengths
// into table. It returns the table size, 0 if the code is invalid, or -1 if
// table is too small (the caller then retries with a bigger one).
// sorted is scratch space of at least len(lengths) entries.
func buildTable(table []huffCode, root int, lengths []uint8, sorted []uint16) int {
var count [maxCodeLength + 1]int
for _, l := range lengths {
count[l&15]++ // lengths are always <= 15
}
numSymbols := len(lengths) - count[0]
if numSymbols == 0 {
return 0
}
var offset [maxCodeLength + 1]int
for l := 1; l < maxCodeLength; l++ {
if count[l] > 1<<l {
return 0
}
offset[l+1] = offset[l] + count[l]
}
for s, l := range lengths {
if l != 0 {
sorted[offset[l]] = uint16(s)
offset[l]++
}
}
tableSize := 1 << root
if len(table) < tableSize {
return -1
}
// Special case: a code with only one symbol uses zero bits.
if numSymbols == 1 {
c := huffCode{bits: 0, value: sorted[0]}
t := table[:tableSize]
for i := range t {
t[i] = c
}
return tableSize
}
totalSize := tableSize
mask := totalSize - 1
key := 0
numNodes := 1
numOpen := 1
sym := 0
tbl := 0
low := -1
// Fill the root table.
for l, step := 1, 2; l <= root; l, step = l+1, step<<1 {
numOpen <<= 1
numNodes += numOpen
numOpen -= count[l]
if numOpen < 0 {
return 0
}
for ; count[l] > 0; count[l]-- {
replicate(table[key:], step, tableSize, huffCode{bits: uint8(l), value: sorted[sym]})
sym++
key = nextKey(key, l)
}
}
// Fill second-level tables and link them from the root table.
for l, step := root+1, 2; l <= maxCodeLength; l, step = l+1, step<<1 {
numOpen <<= 1
numNodes += numOpen
numOpen -= count[l]
if numOpen < 0 {
return 0
}
for ; count[l] > 0; count[l]-- {
if key&mask != low {
tbl += tableSize
tableBits := nextTableBits(&count, l, root)
tableSize = 1 << tableBits
totalSize += tableSize
if totalSize > len(table) {
return -1
}
low = key & mask
table[low] = huffCode{bits: uint8(tableBits + root), value: uint16(tbl - low)}
}
replicate(table[tbl+key>>root:], step, tableSize, huffCode{bits: uint8(l - root), value: sorted[sym]})
sym++
key = nextKey(key, l)
}
}
// The tree must be complete.
if numNodes != 2*numSymbols-1 {
return 0
}
return totalSize
}
// replicate stores c at t[0], t[step], ... below end.
func replicate(t []huffCode, step, end int, c huffCode) {
for end > 0 {
end -= step
t[end] = c
}
}
// nextKey returns the bit-reversed increment of key, for a code of length l.
func nextKey(key, l int) int {
step := 1 << (l - 1)
for key&step != 0 {
step >>= 1
}
if step == 0 {
return key
}
return key&(step-1) + step
}
// nextTableBits returns the width of the next second-level table.
func nextTableBits(count *[maxCodeLength + 1]int, l, root int) int {
left := 1 << (l - root)
for l < maxCodeLength {
left -= count[l]
if left <= 0 {
break
}
l++
left <<= 1
}
return l - root
}
var codeLengthCodeOrder = [19]uint8{17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
// readHuffmanCode reads one Huffman code over alphabetSize symbols and
// appends its lookup table to d.tables (single-symbol tables are shared).
// It returns the table offset; every table spans at least 1<<rootBits
// entries from there. The code lengths stay in d.codeLengths[:alphabetSize].
func (d *decoder) readHuffmanCode(alphabetSize int) (int, error) {
br := &d.br
lengths := d.codeLengths[:alphabetSize]
clear(lengths)
if br.read(1) == 1 {
// Simple code: one or two symbols.
numSymbols := br.read(1) + 1
firstBits := br.read(1)
s := int(br.read(1 + 7*uint(firstBits)))
if s < alphabetSize {
lengths[s] = 1
}
if numSymbols == 2 {
s = int(br.read(8))
if s < alphabetSize {
lengths[s] = 1
}
}
} else {
var clc [len(codeLengthCodeOrder)]uint8
n := int(br.read(4)) + 4
for i := 0; i < n; i++ {
clc[codeLengthCodeOrder[i]] = uint8(br.read(3))
}
if err := d.readCodeLengths(&clc, lengths); err != nil {
return 0, err
}
}
if br.eos() {
return 0, status.NotEnoughData("vp8l: truncated huffman code")
}
off := len(d.tables)
need := maxTableSize(alphabetSize)
for {
if cap(d.tables)-off < need {
nt := make([]huffCode, off, 2*cap(d.tables)+need)
copy(nt, d.tables)
d.tables = nt
}
size := buildTable(d.tables[off:off+need], rootBits, lengths, d.sorted[:])
if size == 0 {
return 0, status.Bitstream("vp8l: invalid huffman code")
}
if size > 0 {
if first := d.tables[off : off+1][0]; first.bits == 0 {
// Single-symbol code: share one table per symbol.
sym := first.value
if o := d.single[sym]; o > 0 {
d.tables = d.tables[:off]
return int(o - 1), nil
}
d.single[sym] = int32(off + 1)
d.singleSet = append(d.singleSet, sym)
}
d.tables = d.tables[:off+size]
return off, nil
}
// Table bound too small (only possible for incomplete codes).
need *= 2
if need > 1<<20 {
return 0, status.Bitstream("vp8l: invalid huffman code")
}
}
}
// readCodeLengths reads the code lengths of a normal Huffman code.
func (d *decoder) readCodeLengths(clc *[19]uint8, lengths []uint8) error {
table := d.lenTable[:]
if buildTable(table, lengthsBits, clc[:], d.sorted[:]) <= 0 {
return status.Bitstream("vp8l: invalid code length code")
}
br := &d.br
numSymbols := len(lengths)
maxSymbol := numSymbols
if br.read(1) == 1 {
n := 2 + 2*uint(br.read(3))
maxSymbol = 2 + int(br.read(n))
if maxSymbol > numSymbols {
return status.Bitstream("vp8l: invalid max symbol")
}
}
prev := uint8(8)
for sym := 0; sym < numSymbols; {
if maxSymbol == 0 {
break
}
maxSymbol--
if br.nbits < 32 {
br.refill()
}
e := table[br.val&(1<<lengthsBits-1)]
br.val >>= e.bits
br.nbits -= uint(e.bits)
cl := e.value
if cl < 16 {
lengths[sym] = uint8(cl)
sym++
if cl != 0 {
prev = uint8(cl)
}
continue
}
var repeat int
var v uint8
switch cl {
case 16:
repeat = int(br.read(2)) + 3
v = prev
case 17:
repeat = int(br.read(3)) + 3
default:
repeat = int(br.read(7)) + 11
}
if sym+repeat > numSymbols {
return status.Bitstream("vp8l: invalid code length repeat")
}
for end := sym + repeat; sym < end; sym++ {
lengths[sym] = v
}
}
return nil
}
// readHuffmanCodes reads the meta Huffman codes of an image of the given
// size into md.
func (d *decoder) readHuffmanCodes(md *metadata, xsize, ysize, cacheBits int, allowRecursion bool) error {
br := &d.br
numGroups := 1
var mapping []int32
md.huffBits = 0
md.huffMask = -1
md.huffXSize = 0
md.huffImage = nil
if allowRecursion && br.read(1) == 1 {
bits := int(br.read(3)) + 2
hx, hy := subSampleSize(xsize, bits), subSampleSize(ysize, bits)
img, err := d.decodeSubImage(hx, hy)
if err != nil {
return err
}
maxGroup := 0
for i, p := range img {
g := (p >> 8) & 0xffff
img[i] = g
if int(g) >= maxGroup {
maxGroup = int(g) + 1
}
}
numGroups = maxGroup
if maxGroup > 1000 || maxGroup > len(img) {
// Remap the used group indices to [0, n) so that bogus huge
// indices do not cause huge allocations.
mapping = make([]int32, maxGroup)
for i := range mapping {
mapping[i] = -1
}
n := int32(0)
for i, g := range img {
m := &mapping[g]
if *m == -1 {
*m = n
n++
}
img[i] = uint32(*m)
}
numGroups = int(n)
}
md.huffBits = bits
md.huffMask = 1<<bits - 1
md.huffXSize = hx
md.huffImage = img
}
// Tables of the previous (sub-)image are no longer needed.
d.tables = d.tables[:0]
d.packed = d.packed[:0]
d.resetSingle(0)
if cap(d.groups) < numGroups {
d.groups = make([]htreeGroup, numGroups)
}
groups := d.groups[:numGroups]
offs := d.treeOffs[:0]
cacheSize := 0
if cacheBits > 0 {
cacheSize = 1 << cacheBits
}
alphabet := [5]int{numLiteralCodes + numLengthCodes + cacheSize, 256, 256, 256, numDistanceCodes}
numStored := numGroups
if mapping != nil {
numStored = len(mapping)
}
for i := 0; i < numStored; i++ {
gi := i
if mapping != nil {
gi = int(mapping[i])
}
mark := len(d.tables)
isTrivialLiteral := true
totalBits := 0
maxBits := 0
var o [5]int
for j := 0; j < 5; j++ {
off, err := d.readHuffmanCode(alphabet[j])
if err != nil {
return err
}
o[j] = off
rb := int(d.tables[off].bits)
if j >= treeRed && j <= treeAlpha && isTrivialLiteral {
isTrivialLiteral = rb == 0
}
totalBits += rb
if j <= treeAlpha {
m := uint8(0)
for _, l := range d.codeLengths[:alphabet[j]] {
m = max(m, l)
}
maxBits += int(m)
}
}
if gi < 0 {
// Unused group: validated, then dropped.
d.tables = d.tables[:mark]
d.resetSingle(mark)
continue
}
offs = append(offs, o)
g := &groups[gi]
*g = htreeGroup{isTrivialLiteral: isTrivialLiteral}
if isTrivialLiteral {
red := uint32(d.tables[o[treeRed]].value)
blue := uint32(d.tables[o[treeBlue]].value)
alpha := uint32(d.tables[o[treeAlpha]].value)
g.literalARB = alpha<<24 | red<<16 | blue
if green := uint32(d.tables[o[treeGreen]].value); totalBits == 0 && green < numLiteralCodes {
g.isTrivialCode = true
g.literalARB |= green << 8
}
}
g.usePacked = !g.isTrivialCode && maxBits < packedBits
}
d.treeOffs = offs
// d.tables is final now: slice the trees out of it.
numPacked := 0
for i := range groups {
if groups[i].usePacked {
numPacked++
}
}
if cap(d.packed) < numPacked*packedSize {
d.packed = make([]packedCode, numPacked*packedSize)
}
d.packed = d.packed[:numPacked*packedSize]
k, kp := 0, 0
for i := 0; i < numStored; i++ {
gi := i
if mapping != nil {
gi = int(mapping[i])
if gi < 0 {
continue
}
}
o := offs[k]
k++
g := &groups[gi]
for j := 0; j < 5; j++ {
g.trees[j] = d.tables[o[j]:]
}
if g.usePacked {
g.packed = d.packed[kp : kp+packedSize : kp+packedSize]
kp += packedSize
buildPacked(g)
}
}
md.groups = groups
return nil
}
// resetSingle forgets shared single-symbol tables at offsets >= from.
func (d *decoder) resetSingle(from int) {
keep := d.singleSet[:0]
for _, sym := range d.singleSet {
if int(d.single[sym]-1) >= from {
d.single[sym] = 0
} else {
keep = append(keep, sym)
}
}
d.singleSet = keep
}
// buildPacked fills g.packed: for every 6-bit input, either the complete
// ARGB literal or the green non-literal code.
func buildPacked(g *htreeGroup) {
for code := 0; code < packedSize; code++ {
bits := code
h := g.trees[treeGreen][bits&0xff]
p := &g.packed[code]
if int(h.value) >= numLiteralCodes {
p.bits = uint32(h.bits) + specialMarker
p.value = uint32(h.value)
continue
}
p.bits = uint32(h.bits)
p.value = uint32(h.value) << 8
bits >>= h.bits
h = g.trees[treeRed][bits&0xff]
p.bits += uint32(h.bits)
p.value |= uint32(h.value) << 16
bits >>= h.bits
h = g.trees[treeBlue][bits&0xff]
p.bits += uint32(h.bits)
p.value |= uint32(h.value)
bits >>= h.bits
h = g.trees[treeAlpha][bits&0xff]
p.bits += uint32(h.bits)
p.value |= uint32(h.value) << 24
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
import (
"encoding/binary"
"errors"
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// Palette images decoded as bytes.
//
// When color indexing is the only transform and every Huffman group codes
// the same constant alpha, red and blue (libwebp's encoder writes the
// palette indices as 0xff000000 | index<<8), every level-0 pixel is
// arb | index<<8 and only its index byte varies. decodeIdx8 then decodes the
// index bytes into a byte window (d.ib) instead of a 32-bit one: a quarter
// of the memory (1.6 MB instead of 6.5 MB for a 3000-pixel-wide image), and
// of the bytes moved by LZ77 copies and window slides. The rows are
// expanded straight from the bytes into RGBA by emitIdx8.
//
// The color cache (cache8) holds the index of each slot, flagged with 0x100
// once the slot is set; d.hash8 maps an index to the slot of its pixel. A
// lookup of a slot that was never set yields the pixel 0, which has no index
// form unless arb is 0: valid streams never do that, but when one does,
// widenIdx8 converts the window and the cache to 32 bits and decodePixels
// goes on from the same position, so the output is always the one of the
// 32-bit path.
var (
// idx8Enabled enables the byte path. A variable so that tests can
// compare it with the 32-bit path.
idx8Enabled = true
// idx8TestWidenAt, when > 0, makes decodeIdx8 switch to 32 bits at the
// first pixel boundary at or after this pixel index (tests).
idx8TestWidenAt = 0
// idx8Widens counts the switches to 32 bits (tests).
idx8Widens atomic.Int64
)
// errWiden is returned by decodeIdx8 when the 32-bit path must take over.
var errWiden = errors.New("vp8l: switch to 32-bit pixels")
// cacheSet flags a set slot of cache8.
const cacheSet = 0x100
// idx8ARB reports whether the level-0 pixels can be decoded as index bytes
// (see above) and returns their constant alpha, red and blue.
func (d *decoder) idx8ARB() (uint32, bool) {
if !idx8Enabled || d.out != outRGBA || d.nTransforms != 1 || d.transforms[0].kind != colorIndexingTransform {
return 0, false
}
groups := d.md0.groups
if len(groups) == 0 {
return 0, false
}
// A trivial code also holds the green of its only literal.
arb := groups[0].literalARB &^ 0xff00
for i := range groups {
g := &groups[i]
if !g.isTrivialLiteral || g.literalARB&^0xff00 != arb {
return 0, false
}
}
return arb, true
}
// initIdx8 sets up the byte path for pixels arb | index<<8: the index
// window and the color cache.
func (d *decoder) initIdx8(arb uint32) {
d.idx8, d.idxARB = true, arb
d.initBuffer8()
bits := d.md0.cacheBits
if bits == 0 {
return
}
if d.cache8 == nil {
d.cache8 = new([1 << maxCacheBits]uint16)
}
shift := uint(32 - bits)
for i := range d.hash8 {
d.hash8[i] = uint16((arb | uint32(i)<<8) * colorCacheMult >> shift)
}
// The cache starts with the pixel 0 in every slot, index 0 when arb
// is 0, and not representable otherwise.
unset := uint16(0)
if arb == 0 {
unset = cacheSet
}
s := d.cache8[:1<<bits]
for i := range s {
s[i] = unset
}
}
// insertCache8 inserts the index bytes px into the color cache in order.
func insertCache8(cache *[1 << maxCacheBits]uint16, hash *[256]uint16, px []byte) {
for _, b := range px {
cache[hash[b]&(1<<maxCacheBits-1)] = cacheSet | uint16(b)
}
}
// settleCache8 is settleCache for index bytes, for a cache of full (a mask
// of one bit per slot, at most 64 slots). A run of equal bytes changes
// nothing after its last byte, so runs are skipped 8 bytes at a time.
func settleCache8(cache *[1 << maxCacheBits]uint16, hash *[256]uint16, px []byte, full uint64) {
var seen uint64
for i := len(px) - 1; i >= 0 && seen != full; i-- {
b := px[i]
if h := hash[b] & 63; seen>>h&1 == 0 {
seen |= 1 << h
cache[h] = cacheSet | uint16(b)
}
if i > 0 && px[i-1] == b {
rep := uint64(b) * 0x0101010101010101
for i >= 8 && binary.LittleEndian.Uint64(px[i-8:i]) == rep {
i -= 8
}
}
}
}
// widenIdx8 switches a level-0 decode from index bytes to 32-bit pixels at
// the current position: the window and the color cache are converted, and
// decodePixels takes over.
func (d *decoder) widenIdx8() error {
idx8Widens.Add(1)
if a := d.async; a != nil {
// The jobs in flight read d.ib.
for a.inFlight > 0 {
if err := a.waitOne(); err != nil {
return err
}
}
}
d.initBuffer32()
arb := d.idxARB
src := d.ib[:d.px.p]
dst := d.buf[:len(src)]
for i, b := range src {
dst[i] = arb | uint32(b)<<8
}
if bits := d.md0.cacheBits; bits > 0 {
if d.colorCache == nil {
d.colorCache = new([1 << maxCacheBits]uint32)
}
for i, v := range d.cache8[:1<<bits] {
c := uint32(0)
if v&cacheSet != 0 {
c = arb | uint32(v&0xff)<<8
}
d.colorCache[i] = c
}
}
d.idx8 = false
return nil
}
// decodeIdx8 is decodePixels (level 0) for index bytes: it decodes the
// w*h image into the byte window buf, with the same end-of-stream behavior
// and the same row batches. It returns errWiden when the 32-bit path must
// take over, with the position in st and the bit reader at the start of the
// pixel to decode next.
func (d *decoder) decodeIdx8(md *metadata, buf []byte, w, h int, sliding bool, window int, st *pixState) error {
groups := md.groups
total := w * h
lastPixel := w * d.needRows
cache := d.cache8
hash := &d.hash8
cacheBits := md.cacheBits
cacheSize := 0
eager := false
settleFull := uint64(0) // one bit per slot
minRun := max(lazyCacheMinRun, 1)
if cacheBits > 0 {
cacheSize = 1 << cacheBits
eager = cacheBits > min(lazyCacheMaxBits, 6)
settleFull = ^uint64(0) >> ((64 - 1<<(min(cacheBits, 6))) & 63)
}
const lenCodeLimit = numLiteralCodes + numLengthCodes
cacheLimit := lenCodeLimit + cacheSize
mask := md.huffMask
data := d.br.data
bpos, val, nbits := d.br.pos, d.br.val, d.br.nbits
st.started = true
base, p, col, row, lastCached := st.base, st.p, st.col, st.row, st.lastCached
var g *htreeGroup
if base+p < lastPixel {
g = md.group(groups, col, row)
}
var err error
settle := false // a lookup needs the pending pixels settled first
outer:
for {
stop := lastPixel - base
if sliding {
stop = min(stop, len(buf)-maxCopyLength)
}
if a := d.async; a != nil && a.guard > 0 {
// Do not overwrite the rows the helper still reads.
stop = min(stop, a.guard-maxCopyLength)
}
if idx8TestWidenAt > 0 {
stop = min(stop, idx8TestWidenAt-base)
}
inner:
for p < stop {
if col&mask == 0 {
g = md.group(groups, col, row)
}
if g.isTrivialCode {
buf[p] = byte(g.literalARB >> 8)
} else {
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
// The green symbol is consumed in each case below, so that
// errWiden leaves the bit reader before it.
var code int
var n uint
if g.usePacked {
pc := g.packed[val&(packedSize-1)]
if pc.bits < specialMarker {
// A literal: red, blue and alpha take no bits.
code, n = int(pc.value>>8&0xff), uint(pc.bits)
} else {
code, n = int(pc.value), uint(pc.bits-specialMarker)
}
} else {
code, n = readSym(g.trees[treeGreen], val)
}
switch {
case code < numLiteralCodes:
val >>= n
nbits -= n
buf[p] = byte(code)
case code < lenCodeLimit:
val >>= n
nbits -= n
length, n := prefixValue(code-numLiteralCodes, val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
distSym, n := readSym(g.trees[treeDist], val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
distCode, n := prefixValue(distSym, val)
val >>= n
nbits -= n
dist := planeCodeToDistance(w, distCode)
if isEOS(len(data), bpos, nbits) {
err = errTruncated()
break outer
}
abs := base + p
if dist > p || length > total-abs {
err = status.Bitstream("vp8l: invalid backward reference")
break outer
}
copyBlock8(buf, p, dist, length)
p += length
col += length
for col >= w {
col -= w
row++
if row%numCacheRows == 0 {
if err = d.processIdx8(base, row); err != nil {
break outer
}
}
}
if col&mask != 0 {
g = md.group(groups, col, row)
}
if eager {
insertCache8(cache, hash, buf[lastCached:p])
lastCached = p
}
continue
case code < cacheLimit:
if !eager && p-lastCached >= minRun {
// Settle outside this loop, where the call does not
// slow down the loop, then decode the symbol again.
settle = true
break inner
}
insertCache8(cache, hash, buf[lastCached:p])
lastCached = p
v := cache[(code-lenCodeLimit)&(1<<maxCacheBits-1)]
if v&cacheSet == 0 {
// The pixel 0 of a slot never set.
err = errWiden
break outer
}
val >>= n
nbits -= n
buf[p] = byte(v)
default:
err = status.Bitstream("vp8l: invalid green symbol")
break outer
}
}
p++
col++
if col >= w {
col = 0
row++
if row%numCacheRows == 0 {
if err = d.processIdx8(base, row); err != nil {
break outer
}
}
if eager {
insertCache8(cache, hash, buf[lastCached:p])
lastCached = p
}
if bpos > len(data) && isEOS(len(data), bpos, nbits) {
err = errTruncated()
break outer
}
}
}
if settle {
settle = false
settleCache8(cache, hash, buf[lastCached:p], settleFull)
lastCached = p
continue
}
if base+p >= lastPixel {
break
}
if idx8TestWidenAt > 0 && base+p >= idx8TestWidenAt {
err = errWiden
break
}
if a := d.async; a != nil && a.guard > 0 && p < len(buf)-maxCopyLength {
// Stopped at the guard: wait for the helper, then go on.
if err = a.waitGuard(); err != nil {
break
}
continue
}
// Slide the window (see decodePixels).
if cacheBits > 0 {
if !eager && p-lastCached >= minRun {
settleCache8(cache, hash, buf[lastCached:p], settleFull)
} else {
insertCache8(cache, hash, buf[lastCached:p])
}
}
keep := min(base+p-window, d.lastRow*w)
if a := d.async; a != nil {
if err = a.beforeSlide(p - (keep - base)); err != nil {
break
}
}
n := copy(buf, buf[keep-base:p])
base = keep
p = n
lastCached = p
}
d.br.pos, d.br.val, d.br.nbits = bpos, val, nbits
*st = pixState{base: base, p: p, col: col, row: row, lastCached: lastCached, started: true}
if err != nil {
return err
}
if d.br.eos() {
return errTruncated()
}
return d.processIdx8(base, row)
}
// processIdx8 is processRows for index bytes.
func (d *decoder) processIdx8(base, row int) error {
row = min(row, d.needRows)
if d.async != nil {
return d.sendRows(base, row, false)
}
y0 := d.lastRow
if row <= y0 {
return nil
}
w := d.xsize
idx := d.ib[y0*w-base : row*w-base]
d.lastRow = row
t0 := d.probeStart()
if err := d.emitIdx8(idx, y0, row); err != nil {
return err
}
d.probeDone(t0, y0)
return nil
}
// emitIdx8 is emitRows for index bytes: it expands the (possibly bundled)
// indices of rows [y0, row) into RGBA rows of the sink.
func (d *decoder) emitIdx8(idx []byte, y0, row int) error {
n := row - y0
fw := d.width
b := d.sink.Buffer(y0, n)
stride := d.sink.Stride()
if stride < 4*fw || len(b) < (n-1)*stride+4*fw {
return status.InvalidParam("vp8l: sink buffer too small")
}
t := &d.transforms[0]
pw := d.xsize
for y := 0; y < n; y++ {
d.emitPaletteIdx8(t, idx[y*pw:(y+1)*pw], b[y*stride:y*stride+4*fw])
}
return d.sink.Commit(y0, n)
}
// emitPaletteIdx8 is emitPalette for one row of index bytes.
func (d *decoder) emitPaletteIdx8(t *transform, src, dst []byte) {
if t.bits == 0 {
lookupRGBA(d.paletteRGBA(t), src, dst)
return
}
expandBundledRGBA(d.paletteRGBA(t), d.bundleTable(t), t.bits, src, dst)
}
// lookupRGBAGo is the reference of lookupRGBA (dsp_*.go): it writes the
// RGBA words pal[src[i]] to dst (as many pixels as fit), 8 pixels per step.
// (A 256-color palette does not fit NEON tables, and scalar arm64 assembly
// measured only 1.08x faster than this loop.)
func lookupRGBAGo(pal *[256]uint32, src, dst []byte) {
n := min(len(src), len(dst)/4)
src, dst = src[:n], dst[:4*n]
i := 0
for ; i+8 <= n; i += 8 {
v := binary.LittleEndian.Uint64(src[i : i+8])
o := dst[4*i : 4*i+32]
binary.LittleEndian.PutUint64(o[0:], uint64(pal[byte(v)])|uint64(pal[byte(v>>8)])<<32)
binary.LittleEndian.PutUint64(o[8:], uint64(pal[byte(v>>16)])|uint64(pal[byte(v>>24)])<<32)
binary.LittleEndian.PutUint64(o[16:], uint64(pal[byte(v>>32)])|uint64(pal[byte(v>>40)])<<32)
binary.LittleEndian.PutUint64(o[24:], uint64(pal[byte(v>>48)])|uint64(pal[byte(v>>56)])<<32)
}
for ; i < n; i++ {
binary.LittleEndian.PutUint32(dst[4*i:], pal[src[i]])
}
}
// expandBundledRGBAGo is the reference of expandBundledRGBA (dsp_*.go): it
// expands one row of bundled palette indices (each byte of src holds
// 1<<bits of them, bits 1 to 3) into the RGBA bytes dst (as many pixels as
// fit), from tab, the pixels of each packed byte two per word (see
// bundleTable).
func expandBundledRGBAGo(tab []uint64, bits int, src, dst []byte) {
n := 4 << bits // bytes per packed byte
full := min(len(dst)/n, len(src))
switch bits {
case 1:
t := tab[:256]
d := dst[:8*full]
for k, b := range src[:full] {
binary.LittleEndian.PutUint64(d[8*k:], t[b])
}
case 2:
t := tab[:512]
d := dst[:16*full]
for k, b := range src[:full] {
e := t[2*int(b) : 2*int(b)+2]
o := d[16*k : 16*k+16]
binary.LittleEndian.PutUint64(o[0:], e[0])
binary.LittleEndian.PutUint64(o[8:], e[1])
}
default:
t := tab[:1024]
d := dst[:32*full]
for k, b := range src[:full] {
e := t[4*int(b) : 4*int(b)+4]
o := d[32*k : 32*k+32]
binary.LittleEndian.PutUint64(o[0:], e[0])
binary.LittleEndian.PutUint64(o[8:], e[1])
binary.LittleEndian.PutUint64(o[16:], e[2])
binary.LittleEndian.PutUint64(o[24:], e[3])
}
}
if x := full * n; x < len(dst) && full < len(src) {
// The last packed byte of the row holds fewer pixels.
e := tab[int(src[full])<<bits>>1:]
for j := 0; x+4 <= len(dst); j++ {
binary.LittleEndian.PutUint32(dst[x:], uint32(e[j>>1]>>(32*(j&1))))
x += 4
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
import (
"fmt"
"os"
"runtime"
"strconv"
"strings"
)
// sharedLLC reports whether the CPUs this process may run on share one
// last-level cache (see asyncSharedLLC). It answers true off Linux, and
// when the system does not say otherwise.
func sharedLLC() bool {
if runtime.GOOS != "linux" {
return true
}
return sharedLLCFrom(os.ReadFile)
}
// sharedLLCFrom is sharedLLC on Linux, reading the files with read: the
// online CPUs of Cpus_allowed_list (/proc/self/status) must all be in the
// shared_cpu_list of the deepest cache (level 3 or more) of the first of
// them (sysfs). Without that information (no L3 listed, as on some arm64
// servers whose system cache sysfs does not show, or files missing) it
// reports true.
func sharedLLCFrom(read func(string) ([]byte, error)) bool {
status, err := read("/proc/self/status")
if err != nil {
return true
}
var list string
for line := range strings.SplitSeq(string(status), "\n") {
if v, ok := strings.CutPrefix(line, "Cpus_allowed_list:"); ok {
list = v
break
}
}
allowed, ok := parseCPUList(list)
if !ok || len(allowed) == 0 {
return true
}
if b, err := read("/sys/devices/system/cpu/online"); err == nil {
if online, ok := parseCPUList(string(b)); ok {
for c := range allowed {
if !online[c] {
delete(allowed, c)
}
}
}
}
first := -1
for c := range allowed {
if first < 0 || c < first {
first = c
}
}
if first < 0 {
return true
}
level, shared := 0, ""
for i := 0; i < 16; i++ {
dir := fmt.Sprintf("/sys/devices/system/cpu/cpu%d/cache/index%d/", first, i)
b, err := read(dir + "level")
if err != nil {
break
}
l, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil || l < 3 || l <= level {
continue
}
if s, err := read(dir + "shared_cpu_list"); err == nil {
level, shared = l, string(s)
}
}
if level == 0 {
return true
}
llc, ok := parseCPUList(shared)
if !ok {
return true
}
for c := range allowed {
if !llc[c] {
return false
}
}
return true
}
// parseCPUList parses a Linux CPU list such as "0-3,8,10-11\n".
func parseCPUList(s string) (map[int]bool, bool) {
set := map[int]bool{}
s = strings.TrimSpace(s)
if s == "" {
return set, true
}
for part := range strings.SplitSeq(s, ",") {
lo, hi, isRange := strings.Cut(strings.TrimSpace(part), "-")
a, err := strconv.Atoi(lo)
if err != nil || a < 0 {
return nil, false
}
b := a
if isRange {
if b, err = strconv.Atoi(hi); err != nil || b < a {
return nil, false
}
}
if b-a > 1<<16 {
return nil, false
}
for c := a; c <= b; c++ {
set[c] = true
}
}
return set, true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
// Algorithm adapted from libwebp (BSD-3-Clause): DecodeImageData,
// DecodeAlphaData and ProcessRows from src/dec/vp8l_dec.c.
import (
"encoding/binary"
"github.com/kolesa-team/go-webp/v2/internal/resample"
"github.com/kolesa-team/go-webp/v2/internal/status"
)
// prefixValue decodes an LZ77 length/distance prefix symbol, taking its
// extra bits from val. It returns the value and the number of bits used.
func prefixValue(sym int, val uint64) (int, uint) {
if sym < 4 {
return sym + 1, 0
}
eb := uint(sym-2) >> 1
off := (2 + sym&1) << eb
return off + int(val&(uint64(1)<<eb-1)) + 1, eb
}
func errTruncated() error { return status.NotEnoughData("vp8l: truncated pixel data") }
// Color cache maintenance.
//
// libwebp inserts every decoded pixel into the color cache: at the end of
// each row, after each backward reference and before each cache lookup.
// Only lookups read the cache, so decodePixels defers the insertions: the
// pixels buf[lastCached:p] are pending, and they are inserted in order (a
// forward loop) before the next lookup, before the window slides (which
// moves them) or, for caches of more than lazyCacheMaxBits bits, at the
// same points as libwebp.
//
// Small caches (palette images use 2 to 4 bits) are settled backwards
// instead when many pixels are pending: the last pending pixel hashing to a
// slot is the value that slot ends up with, so the scan can stop as soon as
// every slot has been seen, usually after a handful of pixels instead of
// the whole range. Both orders leave the cache in the same state.
var (
// lazyCacheMaxBits is the largest cache (in bits) maintained lazily; at
// most 6 (settleCache tracks the slots in a uint64). A variable so that
// tests can compare against eager maintenance (0).
lazyCacheMaxBits = 4
// lazyCacheMinRun is the smallest pending range settled backwards;
// shorter ranges are inserted forwards. A variable for tests.
lazyCacheMinRun = 256
)
// insertCache inserts px into the color cache in order. shift is
// 32-cacheBits.
func insertCache(cache *[1 << maxCacheBits]uint32, px []uint32, shift uint) {
for _, c := range px {
cache[(c*colorCacheMult)>>(shift&31)&(1<<maxCacheBits-1)] = c
}
}
// settleCache leaves a color cache of at most 64 slots (shift >= 26) in
// the state inserting px in order would: scanning backwards, the first
// pixel seen for a slot is its final value, and the scan stops once every
// slot is settled.
//
// It is small enough to be inlined: a call on the cache lookup path of
// decodePixels makes the register allocator spill around it even when the
// branch is not taken, which costs more than 10% on photos.
func settleCache(cache *[1 << maxCacheBits]uint32, px []uint32, shift uint) {
full := ^uint64(0) >> (64 - 1<<(32-shift&31)) // one bit per slot
var seen uint64
for i := len(px) - 1; i >= 0 && seen != full; i-- {
c := px[i]
h := (c * colorCacheMult) >> (shift & 31) & 63
if seen>>h&1 == 0 {
seen |= 1 << h
cache[h] = c
}
}
}
// decodePixels entropy-decodes a w*h image into buf.
//
// For level0, rows are passed through the inverse transforms to the output
// every numCacheRows rows and decoding stops after d.needRows rows. With
// sliding, buf is smaller than the image and acts as an LZ77 window of at
// least window pixels (plus the rows not yet emitted). The loop position is
// kept in st, so that a level-0 decode can be resumed with a larger
// d.needRows (incremental alpha decoding).
func (d *decoder) decodePixels(md *metadata, buf []uint32, w, h int, level0, sliding bool, window int, st *pixState) error {
groups := md.groups
total := w * h
lastPixel := total
if level0 {
lastPixel = w * d.needRows
}
var cache *[1 << maxCacheBits]uint32
var cacheShift uint
var cacheSize int
// eager: insert the pending pixels at the same points as libwebp,
// otherwise only before lookups and window slides (see above).
eager := false
if md.cacheBits > 0 {
if d.colorCache == nil {
d.colorCache = new([1 << maxCacheBits]uint32)
}
cache = d.colorCache
cacheSize = 1 << md.cacheBits
if !st.started {
clear(cache[:cacheSize])
}
cacheShift = 32 - uint(md.cacheBits)
eager = md.cacheBits > min(lazyCacheMaxBits, 6)
}
const lenCodeLimit = numLiteralCodes + numLengthCodes
cacheLimit := lenCodeLimit + cacheSize
mask := md.huffMask
data := d.br.data
bpos, val, nbits := d.br.pos, d.br.val, d.br.nbits
st.started = true
base, p, col, row, lastCached := st.base, st.p, st.col, st.row, st.lastCached
var g *htreeGroup
if base+p < lastPixel {
g = md.group(groups, col, row)
}
var err error
outer:
for {
stop := lastPixel - base
if sliding {
stop = min(stop, len(buf)-maxCopyLength)
}
if a := d.async; a != nil && level0 && a.guard > 0 {
// Do not overwrite the rows the helper still reads (copies
// write up to maxCopyLength pixels past stop).
stop = min(stop, a.guard-maxCopyLength)
}
for p < stop {
if col&mask == 0 {
g = md.group(groups, col, row)
}
if g.isTrivialCode {
buf[p] = g.literalARB
} else {
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
var code int
if g.usePacked {
pc := g.packed[val&(packedSize-1)]
if pc.bits < specialMarker {
val >>= pc.bits
nbits -= uint(pc.bits)
buf[p] = pc.value
code = -1
} else {
n := pc.bits - specialMarker
val >>= n
nbits -= uint(n)
code = int(pc.value)
}
} else {
c, n := readSym(g.trees[treeGreen], val)
val >>= n
nbits -= n
code = c
}
switch {
case code < 0:
// Literal fully decoded from the packed table.
case code < numLiteralCodes:
if g.isTrivialLiteral {
buf[p] = g.literalARB | uint32(code)<<8
break
}
red, n := readSym(g.trees[treeRed], val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
blue, n := readSym(g.trees[treeBlue], val)
val >>= n
nbits -= n
alpha, n := readSym(g.trees[treeAlpha], val)
val >>= n
nbits -= n
buf[p] = uint32(alpha)<<24 | uint32(red)<<16 | uint32(code)<<8 | uint32(blue)
case code < lenCodeLimit:
length, n := prefixValue(code-numLiteralCodes, val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
distSym, n := readSym(g.trees[treeDist], val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
distCode, n := prefixValue(distSym, val)
val >>= n
nbits -= n
dist := planeCodeToDistance(w, distCode)
// Like libwebp, stop as soon as the data is exhausted:
// zero bits past the end decode as valid copies and would
// otherwise fill the rest of a (possibly huge) frame.
if isEOS(len(data), bpos, nbits) {
err = errTruncated()
break outer
}
abs := base + p
if dist > p || length > total-abs {
err = status.Bitstream("vp8l: invalid backward reference")
break outer
}
copyBlock32(buf, p, dist, length)
p += length
col += length
for col >= w {
col -= w
row++
if level0 && row%numCacheRows == 0 {
if err = d.processRows(buf, base, row); err != nil {
break outer
}
}
}
if col&mask != 0 {
g = md.group(groups, col, row)
}
if eager {
insertCache(cache, buf[lastCached:p], cacheShift)
lastCached = p
}
continue
case code < cacheLimit:
if !eager && p-lastCached >= lazyCacheMinRun {
settleCache(cache, buf[lastCached:p], cacheShift)
} else {
insertCache(cache, buf[lastCached:p], cacheShift)
}
lastCached = p
buf[p] = cache[(code-lenCodeLimit)&(1<<maxCacheBits-1)]
default:
err = status.Bitstream("vp8l: invalid green symbol")
break outer
}
}
p++
col++
if col >= w {
col = 0
row++
if level0 && row%numCacheRows == 0 {
if err = d.processRows(buf, base, row); err != nil {
break outer
}
}
if eager {
insertCache(cache, buf[lastCached:p], cacheShift)
lastCached = p
}
if bpos > len(data) && isEOS(len(data), bpos, nbits) {
err = errTruncated()
break outer
}
}
}
if base+p >= lastPixel {
break
}
if a := d.async; a != nil && level0 && a.guard > 0 && p < len(buf)-maxCopyLength {
// Stopped at the guard: wait for the helper, then go on.
if err = a.waitGuard(); err != nil {
break
}
continue
}
// Slide the window: keep the LZ77 window and the rows not yet
// emitted. The pending cache pixels move, so settle them first.
if cache != nil && !eager && p-lastCached >= lazyCacheMinRun {
settleCache(cache, buf[lastCached:p], cacheShift)
} else if cache != nil {
insertCache(cache, buf[lastCached:p], cacheShift)
}
keep := min(base+p-window, d.lastRow*w)
if a := d.async; a != nil && level0 {
if err = a.beforeSlide(p - (keep - base)); err != nil {
break
}
}
n := copy(buf, buf[keep-base:p])
base = keep
p = n
lastCached = p
}
d.br.pos, d.br.val, d.br.nbits = bpos, val, nbits
*st = pixState{base: base, p: p, col: col, row: row, lastCached: lastCached, started: true}
if err != nil {
return err
}
if d.br.eos() {
return errTruncated()
}
if level0 {
return d.processRows(buf, base, row)
}
return nil
}
// processRows runs the inverse transforms over the decoded rows
// [d.lastRow, row) and emits them. The last inverse transform is fused with
// the output conversion when it is subtract-green or color indexing.
func (d *decoder) processRows(buf []uint32, base, row int) error {
row = min(row, d.needRows)
if d.async != nil {
return d.sendRows(base, row, false)
}
y0, t0 := d.lastRow, d.probeStart()
// A resumed decode (AlphaDecoder) may have more than numCacheRows
// decoded rows pending: emit them in batches that fit d.rows.
for row-d.lastRow > numCacheRows {
if err := d.processBatch(buf, base, d.lastRow+numCacheRows); err != nil {
return err
}
}
if err := d.processBatch(buf, base, row); err != nil {
return err
}
d.probeDone(t0, y0)
return nil
}
// processBatch is processRows for at most numCacheRows rows.
func (d *decoder) processBatch(buf []uint32, base, row int) error {
y0 := d.lastRow
n := row - y0
if n <= 0 {
return nil
}
w := d.xsize
argb := buf[y0*w-base : row*w-base]
d.lastRow = row
return d.emitRows(argb, y0, row)
}
// emitRows runs the inverse transforms over rows [y0, row) (at most
// numCacheRows rows, the level-0 pixels argb) and emits them. Rows must
// arrive in order. In a two-stage decode it runs on the helper goroutine,
// so it must only use the decoder state reserved to it: d.rows, the fused
// palette tables and the output.
func (d *decoder) emitRows(argb []uint32, y0, row int) error {
n := row - y0
fw := d.width
// Pick the transform fused into the output step, if any.
var final *transform
last := 0
if d.nTransforms > 0 {
t := &d.transforms[0]
switch {
case t.kind == subtractGreenTransform:
last = 1
if d.out == outRGBA {
final = t
}
case t.kind == colorIndexingTransform && d.out == outRGBA:
last = 1
final = t
}
}
if d.nTransforms > last {
out := d.rows[fw : fw+fw*n]
src := argb
inCache := false
for i := d.nTransforms - 1; i >= last; i-- {
t := &d.transforms[i]
switch t.kind {
case predictorTransform:
inversePredictor(t, y0, row, src, d.rows, fw)
if row != t.ysize {
// Keep the last row as the top row of the next batch.
copy(d.rows[fw-t.xsize:fw], d.rows[fw+(n-1)*t.xsize:fw+n*t.xsize])
}
case crossColorTransform:
inverseCrossColor(t, y0, row, src, out)
case subtractGreenTransform:
addGreen(src[:n*t.xsize], out)
case colorIndexingTransform:
if inCache && t.bits > 0 {
// Move the bundled indices to the end of the rows so
// they can be expanded in place.
outLen := n * t.xsize
inLen := n * subSampleSize(t.xsize, t.bits)
s := out[outLen-inLen : outLen]
copy(s, out[:inLen])
inverseColorIndex(t, y0, row, s, out)
} else {
inverseColorIndex(t, y0, row, src, out)
}
}
src = out
inCache = true
}
argb = out
}
if d.out == outGreen {
dst := d.alpha[(y0-d.alphaRow)*fw : (row-d.alphaRow)*fw]
argb = argb[:len(dst)]
for i, c := range argb {
dst[i] = byte(c >> 8)
}
return nil
}
b := d.sink.Buffer(y0, n)
stride := d.sink.Stride()
if stride < 4*fw || len(b) < (n-1)*stride+4*fw {
return status.InvalidParam("vp8l: sink buffer too small")
}
switch {
case final == nil:
for y := 0; y < n; y++ {
emitRGBA(argb[y*fw:(y+1)*fw], b[y*stride:y*stride+4*fw])
}
case final.kind == subtractGreenTransform:
for y := 0; y < n; y++ {
emitAddGreen(argb[y*fw:(y+1)*fw], b[y*stride:y*stride+4*fw])
}
default:
pw := subSampleSize(fw, final.bits)
for y := 0; y < n; y++ {
d.emitPalette(final, argb[y*pw:(y+1)*pw], b[y*stride:y*stride+4*fw])
}
}
return d.sink.Commit(y0, n)
}
// toRGBA converts an ARGB pixel to the little-endian word of its R,G,B,A
// bytes.
func toRGBA(c uint32) uint32 {
return c&0xff00ff00 | c>>16&0xff | (c&0xff)<<16
}
// emitRGBAGo is the reference of emitRGBA (dsp_*.go): it converts the ARGB
// pixels src to RGBA bytes in dst (as many pixels as fit), two pixels per
// 64-bit word.
func emitRGBAGo(src []uint32, dst []byte) {
for len(src) >= 2 && len(dst) >= 8 {
c := uint64(src[0]) | uint64(src[1])<<32
binary.LittleEndian.PutUint64(dst, swapRB2(c))
src, dst = src[2:], dst[8:]
}
if len(src) > 0 && len(dst) >= 4 {
binary.LittleEndian.PutUint32(dst, toRGBA(src[0]))
}
}
// swapRB2 swaps the red and blue bytes of the two ARGB pixels in c.
func swapRB2(c uint64) uint64 {
return c&0xff00ff00ff00ff00 | c>>16&0x000000ff000000ff | c&0x000000ff000000ff<<16
}
// emitAddGreenGo is the reference of emitAddGreen (dsp_*.go), which fuses
// the inverse subtract-green transform with emitRGBA.
func emitAddGreenGo(src []uint32, dst []byte) {
for len(src) >= 2 && len(dst) >= 8 {
c := uint64(src[0]) | uint64(src[1])<<32
g := c & 0x0000ff000000ff00
rb := (c&0x00ff00ff00ff00ff + (g>>8 | g<<8)) & 0x00ff00ff00ff00ff
binary.LittleEndian.PutUint64(dst, swapRB2(c&0xff00ff00ff00ff00|rb))
src, dst = src[2:], dst[8:]
}
if len(src) > 0 && len(dst) >= 4 {
c := src[0]
g := c >> 8 & 0xff
rb := (c&0x00ff00ff + (g<<16 | g)) & 0x00ff00ff
binary.LittleEndian.PutUint32(dst, toRGBA(c&0xff00ff00|rb))
}
}
// emitPalette fuses the inverse color-indexing transform with emitRGBA.
// src is one row of (possibly bundled) indices, dst one RGBA row.
func (d *decoder) emitPalette(t *transform, src []uint32, dst []byte) {
pal := d.paletteRGBA(t)
if t.bits == 0 {
for _, c := range src {
if len(dst) < 4 {
return
}
binary.LittleEndian.PutUint32(dst, pal[c>>8&0xff])
dst = dst[4:]
}
return
}
// Bundled indices: expand a whole packed byte at once from a table of
// the 256 possible byte values.
tab := d.bundleTable(t)
wpb := 1 << t.bits >> 1 // words per packed byte
for _, c := range src {
k := int(c>>8&0xff) * wpb
for _, v := range tab[k : k+wpb] {
if len(dst) < 8 {
if len(dst) >= 4 {
binary.LittleEndian.PutUint32(dst, uint32(v))
}
return
}
binary.LittleEndian.PutUint64(dst, v)
dst = dst[8:]
}
}
}
// paletteRGBA returns the palette of t converted to RGBA words,
// alpha-premultiplied with d.premulPal.
func (d *decoder) paletteRGBA(t *transform) *[256]uint32 {
if !d.palReady {
for i, c := range t.data {
d.pal[i] = toRGBA(c)
}
if d.premulPal {
var b [4 * 256]byte
n := len(t.data)
for i, c := range d.pal[:n] {
binary.LittleEndian.PutUint32(b[4*i:], c)
}
resample.PremultiplyRGBA(b[:4*n])
for i := range d.pal[:n] {
d.pal[i] = binary.LittleEndian.Uint32(b[4*i:])
}
}
d.palReady = true
}
return &d.pal
}
// bundleTable returns, for each packed index byte, the RGBA words of the
// 1<<t.bits pixels it holds, two pixels per little-endian 64-bit word
// (1<<t.bits/2 words per byte).
func (d *decoder) bundleTable(t *transform) []uint64 {
if d.bundleReady {
return d.bundle
}
pal := d.paletteRGBA(t)
ppb := 1 << t.bits
bpp := uint(8 >> t.bits)
mask := 1<<bpp - 1
wpb := ppb / 2
n := 256 * wpb
if cap(d.bundle) < n {
d.bundle = make([]uint64, 256*4)
}
tab := d.bundle[:n]
for v := 0; v < 256; v++ {
e := tab[v*wpb : (v+1)*wpb]
for k := range e {
lo := pal[v>>(uint(2*k)*bpp)&mask]
hi := pal[v>>(uint(2*k+1)*bpp)&mask]
e[k] = uint64(lo) | uint64(hi)<<32
}
}
d.bundle = tab
d.bundleReady = true
return tab
}
// decodeAlpha8Rows continues the 8-bit alpha path (only transform: color
// indexing; red, blue and alpha codes trivial; no color cache) up to row
// upTo: the indices are decoded as bytes into d.ib (the whole image or a
// sliding window) and expanded into d.alpha in row batches, like libwebp's
// DecodeAlphaData + ExtractPalettedAlphaRows.
func (d *decoder) decodeAlpha8Rows(upTo int) error {
md := &d.md0
w := d.xsize
st := &d.px
limit := w * upTo
for st.base+st.p < limit {
stop := limit - st.base
if d.sliding {
stop = min(stop, len(d.ib)-maxCopyLength)
}
var err error
if d.inTail {
err = d.decodeTail8(md, stop)
} else {
err = d.decodePixels8(md, stop)
}
if err != nil {
return err
}
if st.base+st.p >= limit || (d.inTail && d.tr.eos) {
break
}
// Slide the window: emit the complete rows, then keep the LZ77
// window and the rows not yet emitted.
d.extractAlpha8(st.row)
keep := min(st.base+st.p-d.window, d.lastRow*w)
n := copy(d.ib, d.ib[keep-st.base:st.p])
st.base = keep
st.p = n
}
d.extractAlpha8(min(st.row, upTo))
if d.inTail {
// libwebp's DecodeAlphaData: running out of data is an error only
// before the last pixel of the image is decoded.
d.tr.eos = d.tr.atEnd()
if d.tr.eos && st.base+st.p < w*d.height {
return errTruncated()
}
}
return nil
}
// extractAlpha8 expands the indices of rows [d.lastRow, row) into d.alpha.
func (d *decoder) extractAlpha8(row int) {
y0 := d.lastRow
if row <= y0 {
return
}
w, fw, base := d.xsize, d.width, d.px.base
inverseColorIndexAlpha(&d.transforms[0], d.alphaTab, row-y0, d.ib[y0*w-base:row*w-base], d.alpha[(y0-d.alphaRow)*fw:(row-d.alphaRow)*fw])
d.lastRow = row
}
// decodeTail8 continues decodePixels8 up to window position stop with
// libwebp's exact end-of-stream behavior (DecodeAlphaData): the bits read
// past the end are the ones libwebp's reader produces, and decoding stops
// (d.tr.eos) when the end of the stream is reached.
func (d *decoder) decodeTail8(md *metadata, stop int) error {
groups := md.groups
mask := md.huffMask
st := &d.px
buf := d.ib
w := d.xsize
total := w*d.height - st.base // pixels left from the window start
p, col, row := st.p, st.col, st.row
tr := &d.tr
g := md.group(groups, col, row)
var err error
for !tr.eos && p < stop {
if col&mask == 0 {
g = md.group(groups, col, row)
}
if g.isTrivialCode {
buf[p] = byte(g.literalARB >> 8)
p++
col++
if col >= w {
col = 0
row++
}
continue // libwebp does not re-check the end of stream here
}
tr.fill()
code := tr.readSym(g.trees[treeGreen])
switch {
case code < numLiteralCodes:
buf[p] = byte(code)
p++
col++
if col >= w {
col = 0
row++
}
case code < numLiteralCodes+numLengthCodes:
length := tr.copyValue(code - numLiteralCodes)
distSym := tr.readSym(g.trees[treeDist])
tr.fill()
dist := planeCodeToDistance(w, tr.copyValue(distSym))
if dist > p || length > total-p {
if tr.atEnd() {
err = errTruncated()
} else {
err = status.Bitstream("vp8l: invalid backward reference")
}
break
}
copyBlock8(buf, p, dist, length)
p += length
col += length
for col >= w {
col -= w
row++
}
if p < total && col&mask != 0 {
g = md.group(groups, col, row)
}
default:
if tr.atEnd() {
err = errTruncated()
} else {
err = status.Bitstream("vp8l: invalid green symbol")
}
}
if err != nil {
break
}
tr.eos = tr.atEnd()
}
st.p, st.col, st.row = p, col, row
return err
}
// decodePixels8 is decodePixels for 8-bit index data (no color cache, no
// transforms, trivial red/blue/alpha codes), up to window position stop.
// Close to the end of the data it hands over to decodeTail8.
func (d *decoder) decodePixels8(md *metadata, stop int) error {
groups := md.groups
mask := md.huffMask
st := &d.px
buf := d.ib
w := d.xsize
total := w*d.height - st.base // pixels left from the window start
data := d.br.data
bpos, val, nbits := d.br.pos, d.br.val, d.br.nbits
p, col, row := st.p, st.col, st.row
g := md.group(groups, col, row)
limit := eosLimit(len(data))
tailPos := len(data) - 8
var err error
loop:
for p < stop {
if bpos >= tailPos && bpos*8-int(nbits)+64 > limit {
// Close to the end of data: finish with an exact emulation of
// libwebp's bit reader.
d.br.pos, d.br.val, d.br.nbits = bpos, val, nbits
st.p, st.col, st.row = p, col, row
consumed := bpos*8 - int(nbits)
if consumed > eosLimit(len(data)) {
return errTruncated()
}
d.inTail = true
d.tr = newTailReader(data, consumed)
return d.decodeTail8(md, stop)
}
if col&mask == 0 {
g = md.group(groups, col, row)
}
if g.isTrivialCode {
buf[p] = byte(g.literalARB >> 8)
} else {
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
code, n := readSym(g.trees[treeGreen], val)
val >>= n
nbits -= n
if code < numLiteralCodes {
buf[p] = byte(code)
} else if code < numLiteralCodes+numLengthCodes {
length, n := prefixValue(code-numLiteralCodes, val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
distSym, n := readSym(g.trees[treeDist], val)
val >>= n
nbits -= n
if nbits < 32 {
if bpos+8 <= len(data) {
val |= binary.LittleEndian.Uint64(data[bpos:]) << nbits
bpos += int((63 - nbits) >> 3)
nbits |= 56
} else {
val, nbits, bpos = refillSlow(data, val, nbits, bpos)
}
}
distCode, n := prefixValue(distSym, val)
val >>= n
nbits -= n
dist := planeCodeToDistance(w, distCode)
if dist > p || length > total-p {
if isEOS(len(data), bpos, nbits) {
err = errTruncated()
} else {
err = status.Bitstream("vp8l: invalid backward reference")
}
break loop
}
copyBlock8(buf, p, dist, length)
p += length
col += length
for col >= w {
col -= w
row++
}
if col&mask != 0 {
g = md.group(groups, col, row)
}
continue
} else {
err = status.Bitstream("vp8l: invalid green symbol")
break loop
}
}
p++
col++
if col >= w {
col = 0
row++
}
}
d.br.pos, d.br.val, d.br.nbits = bpos, val, nbits
st.p, st.col, st.row = p, col, row
return err
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8l
// Algorithm adapted from libwebp (BSD-3-Clause): inverse transforms
// (src/dsp/lossless.c).
import "encoding/binary"
const (
predictorTransform = 0
crossColorTransform = 1
subtractGreenTransform = 2
colorIndexingTransform = 3
)
// transform is one decoded image transform.
type transform struct {
kind int
bits int
xsize int // width of the image the transform applies to
ysize int
data []uint32 // sub-image (predictor, cross color) or palette
}
func subSampleSize(size, bits int) int {
return (size + 1<<bits - 1) >> bits
}
// addPixels adds two ARGB pixels per channel, modulo 256.
func addPixels(a, b uint32) uint32 {
ag := (a & 0xff00ff00) + (b & 0xff00ff00)
rb := (a & 0x00ff00ff) + (b & 0x00ff00ff)
return ag&0xff00ff00 | rb&0x00ff00ff
}
func average2(a, b uint32) uint32 {
return ((a^b)&0xfefefefe)>>1 + a&b
}
// Two pixels per 64-bit word (SWAR): the predictors that do not depend on
// the left pixel process the row two pixels at a time.
// load2 returns the pixels s[x] and s[x+1] as one word.
func load2(s []uint32, x int) uint64 {
p := s[x : x+2 : x+2]
return uint64(p[0]) | uint64(p[1])<<32
}
// store2 stores the two pixels of v at s[x] and s[x+1].
func store2(s []uint32, x int, v uint64) {
p := s[x : x+2 : x+2]
p[0], p[1] = uint32(v), uint32(v>>32)
}
// addPixels2 is addPixels for two pixels per word.
func addPixels2(a, b uint64) uint64 {
ag := (a & 0xff00ff00ff00ff00) + (b & 0xff00ff00ff00ff00)
rb := (a & 0x00ff00ff00ff00ff) + (b & 0x00ff00ff00ff00ff)
return ag&0xff00ff00ff00ff00 | rb&0x00ff00ff00ff00ff
}
// average2x2 is average2 for two pixels per word.
func average2x2(a, b uint64) uint64 {
return ((a^b)&0xfefefefefefefefe)>>1 + a&b
}
// absDiff returns |a-b| for channel values a, b.
func absDiff(a, b uint32) int32 {
d := int32(a) - int32(b)
m := d >> 31
return (d ^ m) - m
}
// predictLeft is predictor mode 1 (L) over in[x0:x1]: a running sum of the
// residuals. Per-channel addition modulo 256 is associative, so 4 pixels at
// a time are summed among themselves first, off the critical path, and the
// serial dependency on the left pixel costs one addPixels per 4 pixels
// instead of one per pixel. in may alias out (each group of 4 is read before
// it is written).
func predictLeft(in, out []uint32, x0, x1 int) {
in = in[:x1]
out = out[:x1]
l := out[x0-1]
x := x0
for ; x+4 <= x1; x += 4 {
s := in[x : x+4 : x+4]
a := s[0]
s2 := addPixels(a, s[1])
s3 := addPixels(s2, s[2])
s4 := addPixels(s3, s[3])
o := out[x : x+4 : x+4]
o[0] = addPixels(a, l)
o[1] = addPixels(s2, l)
o[2] = addPixels(s3, l)
l = addPixels(s4, l)
o[3] = l
}
for ; x < x1; x++ {
l = addPixels(in[x], l)
out[x] = l
}
}
// clampByte clamps a to [0, 255] without branches.
func clampByte(a int32) int32 { return min(max(a, 0), 255) }
// predictAddSubFull is predictor mode 12 (ClampedAddSubtractFull) over
// in[x0:x1]. The left pixel is kept as four channel values, so that the
// serial dependency per pixel is one add, clamp, add and mask per channel,
// with the channels in parallel; everything from the top row is computed
// off that path. in may alias out.
func predictAddSubFull(in, out, up []uint32, x0, x1 int) {
in, out, up = in[:x1], out[:x1], up[:x1]
l := out[x0-1]
la, lr, lg, lb := int32(l>>24), int32(l>>16&0xff), int32(l>>8&0xff), int32(l&0xff)
for x := x0; x < x1; x++ {
t, tl, c := up[x], up[x-1], in[x]
la = (clampByte(la+int32(t>>24)-int32(tl>>24)) + int32(c>>24)) & 0xff
lr = (clampByte(lr+int32(t>>16&0xff)-int32(tl>>16&0xff)) + int32(c>>16&0xff)) & 0xff
lg = (clampByte(lg+int32(t>>8&0xff)-int32(tl>>8&0xff)) + int32(c>>8&0xff)) & 0xff
lb = (clampByte(lb+int32(t&0xff)-int32(tl&0xff)) + int32(c&0xff)) & 0xff
out[x] = uint32(la)<<24 | uint32(lr)<<16 | uint32(lg)<<8 | uint32(lb)
}
}
// predictAddSubHalf is predictor mode 13 (ClampedAddSubtractHalf) over
// in[x0:x1]: per channel clip(avg + (avg - tl) / 2) with avg the floor
// average of the left and top pixels, the division truncating toward zero
// as in C. Channel-parallel like predictAddSubFull. in may alias out.
func predictAddSubHalf(in, out, up []uint32, x0, x1 int) {
in, out, up = in[:x1], out[:x1], up[:x1]
l := out[x0-1]
la, lr, lg, lb := int32(l>>24), int32(l>>16&0xff), int32(l>>8&0xff), int32(l&0xff)
for x := x0; x < x1; x++ {
t, tl, c := up[x], up[x-1], in[x]
a := (la + int32(t>>24)) >> 1
la = (clampByte(a+(a-int32(tl>>24))/2) + int32(c>>24)) & 0xff
a = (lr + int32(t>>16&0xff)) >> 1
lr = (clampByte(a+(a-int32(tl>>16&0xff))/2) + int32(c>>16&0xff)) & 0xff
a = (lg + int32(t>>8&0xff)) >> 1
lg = (clampByte(a+(a-int32(tl>>8&0xff))/2) + int32(c>>8&0xff)) & 0xff
a = (lb + int32(t&0xff)) >> 1
lb = (clampByte(a+(a-int32(tl&0xff))/2) + int32(c&0xff)) & 0xff
out[x] = uint32(la)<<24 | uint32(lr)<<16 | uint32(lg)<<8 | uint32(lb)
}
}
// predictRun adds predictor mode to the residuals in[x0:x1] and stores the
// result in out. up is the previous output row, extended by one pixel (the
// first pixel of out) so that the top-right of the last column is valid.
// in may alias out.
func predictRun(mode uint32, in, out, up []uint32, x0, x1 int) {
in = in[:x1]
out = out[:x1]
up = up[:x1+1]
switch mode {
case 1: // L
predictLeft(in, out, x0, x1)
case 2: // T
x := x0
for ; x+2 <= x1; x += 2 {
store2(out, x, addPixels2(load2(in, x), load2(up, x)))
}
if x < x1 {
out[x] = addPixels(in[x], up[x])
}
case 3: // TR
x := x0
for ; x+2 <= x1; x += 2 {
store2(out, x, addPixels2(load2(in, x), load2(up, x+1)))
}
if x < x1 {
out[x] = addPixels(in[x], up[x+1])
}
case 4: // TL
x := x0
for ; x+2 <= x1; x += 2 {
store2(out, x, addPixels2(load2(in, x), load2(up, x-1)))
}
if x < x1 {
out[x] = addPixels(in[x], up[x-1])
}
case 5:
l := out[x0-1]
for x := x0; x < x1; x++ {
l = addPixels(in[x], average2(average2(l, up[x+1]), up[x]))
out[x] = l
}
case 6:
l := out[x0-1]
for x := x0; x < x1; x++ {
l = addPixels(in[x], average2(l, up[x-1]))
out[x] = l
}
case 7:
l := out[x0-1]
for x := x0; x < x1; x++ {
l = addPixels(in[x], average2(l, up[x]))
out[x] = l
}
case 8:
x := x0
for ; x+2 <= x1; x += 2 {
store2(out, x, addPixels2(load2(in, x), average2x2(load2(up, x-1), load2(up, x))))
}
if x < x1 {
out[x] = addPixels(in[x], average2(up[x-1], up[x]))
}
case 9:
x := x0
for ; x+2 <= x1; x += 2 {
store2(out, x, addPixels2(load2(in, x), average2x2(load2(up, x), load2(up, x+1))))
}
if x < x1 {
out[x] = addPixels(in[x], average2(up[x], up[x+1]))
}
case 10:
l := out[x0-1]
for x := x0; x < x1; x++ {
l = addPixels(in[x], average2(average2(l, up[x-1]), average2(up[x], up[x+1])))
out[x] = l
}
case 11:
// libwebp Select: T if the sum over the channels of |l-tl| is at
// most that of |t-tl|, else L. Both sums are added to the residual
// before the choice, which shortens the dependency on l.
l := out[x0-1]
for x := x0; x < x1; x++ {
t, tl := up[x], up[x-1]
pt := absDiff(t>>24, tl>>24) + absDiff(t>>16&0xff, tl>>16&0xff) +
absDiff(t>>8&0xff, tl>>8&0xff) + absDiff(t&0xff, tl&0xff)
pl := absDiff(l>>24, tl>>24) + absDiff(l>>16&0xff, tl>>16&0xff) +
absDiff(l>>8&0xff, tl>>8&0xff) + absDiff(l&0xff, tl&0xff)
c := in[x]
withT, withL := addPixels(c, t), addPixels(c, l)
l = withL
if pl <= pt {
l = withT
}
out[x] = l
}
case 12:
predictAddSubFull(in, out, up, x0, x1)
case 13:
predictAddSubHalf(in, out, up, x0, x1)
default: // 0, and 14/15 which libwebp treats as black too
x := x0
for ; x+2 <= x1; x += 2 {
store2(out, x, addPixels2(load2(in, x), 0xff000000ff000000))
}
if x < x1 {
out[x] = addPixels(in[x], 0xff000000)
}
}
}
// inversePredictor undoes the predictor transform for rows [y0, y1). in
// holds the residual rows; the output rows start at c[o], and c[o-width:o]
// must hold the previous output row (when y0 > 0).
func inversePredictor(t *transform, y0, y1 int, in, c []uint32, o int) {
width := t.xsize
i := 0
if y0 == 0 {
out := c[o : o+width]
inr := in[:width]
out[0] = addPixels(inr[0], 0xff000000)
predictLeft(inr, out, 1, width)
o += width
i += width
y0++
}
bits := t.bits
tilesPerRow := subSampleSize(width, bits)
for y := y0; y < y1; y++ {
modes := t.data[(y>>bits)*tilesPerRow : (y>>bits+1)*tilesPerRow]
out := c[o : o+width]
up := c[o-width : o+1]
inr := in[i : i+width]
out[0] = addPixels(inr[0], up[0])
predictRow(modes, inr, out, up, bits)
o += width
i += width
}
}
// predictRowGo is the reference of predictRow (dsp_*.go): it undoes the
// predictor transform for the pixels 1 to len(out)-1 of a row whose pixel
// 0 is already done, with the mode of each tile of 1<<bits pixels in
// modes. up is the previous output row extended by out[0] (see
// predictRun). in may alias out.
func predictRowGo(modes, in, out, up []uint32, bits int) {
width := len(out)
tileW := 1 << bits
x := 1
for tx := 0; x < width; tx++ {
xEnd := min(x&^(tileW-1)+tileW, width)
predictRun(modes[tx]>>8&0xf, in, out, up, x, xEnd)
x = xEnd
}
}
func colorTransformDelta(pred, color int8) int32 {
return (int32(pred) * int32(color)) >> 5
}
// inverseCrossColor undoes the cross-color transform for rows [y0, y1).
// in may alias out.
func inverseCrossColor(t *transform, y0, y1 int, in, out []uint32) {
width := t.xsize
bits := t.bits
tilesPerRow := subSampleSize(width, bits)
i := 0
for y := y0; y < y1; y++ {
mults := t.data[(y>>bits)*tilesPerRow : (y>>bits+1)*tilesPerRow]
crossColorRow(mults, in[i:i+width], out[i:i+width], bits)
i += width
}
}
// crossColorRowGo is the reference of crossColorRow (dsp_*.go): it undoes
// the cross-color transform on one row src into dst, with the multipliers
// of each tile of 1<<bits pixels in mults. src may alias dst.
func crossColorRowGo(mults, src, dst []uint32, bits int) {
width := len(src)
dst = dst[:width]
tileW := 1 << bits
for tx, m := range mults {
g2r := int8(m)
g2b := int8(m >> 8)
r2b := int8(m >> 16)
x0 := tx << bits
if x0 >= width {
break
}
x1 := min(x0+tileW, width)
s := src[x0:x1]
d := dst[x0:x1]
d = d[:len(s)]
for k, argb := range s {
green := int8(argb >> 8)
r := int32(argb>>16) + colorTransformDelta(g2r, green)
r &= 0xff
b := int32(argb) + colorTransformDelta(g2b, green) + colorTransformDelta(r2b, int8(r))
b &= 0xff
d[k] = argb&0xff00ff00 | uint32(r)<<16 | uint32(b)
}
}
}
// addGreenGo is the reference of addGreen (dsp_*.go): it undoes the
// subtract-green transform. in may alias out.
func addGreenGo(in, out []uint32) {
out = out[:len(in)]
for i, argb := range in {
g := argb >> 8 & 0xff
rb := (argb&0x00ff00ff + (g<<16 | g)) & 0x00ff00ff
out[i] = argb&0xff00ff00 | rb
}
}
// inverseColorIndex maps palette indices (possibly bundled) of rows
// [y0, y1) to colors. in must not overlap the part of out written before it
// is read (see processRows).
func inverseColorIndex(t *transform, y0, y1 int, in, out []uint32) {
width := t.xsize
pal := t.data
if t.bits == 0 {
n := (y1 - y0) * width
in = in[:n]
out = out[:n]
pal = pal[:256]
for i, p := range in {
out[i] = pal[p>>8&0xff]
}
return
}
bpp := uint(8 >> t.bits)
ppb := 1 << t.bits
mask := uint32(1)<<bpp - 1
pal = pal[:mask+1]
pw := subSampleSize(width, t.bits)
i, o := 0, 0
for y := y0; y < y1; y++ {
src := in[i : i+pw]
dst := out[o : o+width]
x := 0
for _, p := range src {
packed := p >> 8 & 0xff
n := min(ppb, width-x)
for k := 0; k < n; k++ {
dst[x] = pal[packed&mask]
packed >>= bpp
x++
}
}
i += pw
o += width
}
}
// alphaTables holds the lookup tables of the 8-bit alpha path: the green
// channel of each palette color, and, for bundled indices, the output bytes
// of each packed index byte.
type alphaTables struct {
pal8 [256]byte
bundle [256]uint64 // byte k: pal8 of the k-th index of the packed byte
}
// init builds the tables of the color-indexing transform t.
func (a *alphaTables) init(t *transform) {
clear(a.pal8[:])
for i, c := range t.data {
a.pal8[i] = byte(c >> 8)
}
if t.bits == 0 {
return
}
bpp := uint(8 >> t.bits)
ppb := 1 << t.bits
mask := 1<<bpp - 1
for v := range a.bundle {
var e uint64
for k := 0; k < ppb; k++ {
e |= uint64(a.pal8[v>>(uint(k)*bpp)&mask]) << (8 * k)
}
a.bundle[v] = e
}
}
// inverseColorIndexAlpha is the 8-bit variant of inverseColorIndex used for
// alpha planes: in holds the green (index) bytes of height rows (possibly
// bundled), out receives the green channel of their palette colors. in and
// out must not overlap.
func inverseColorIndexAlpha(t *transform, tab *alphaTables, height int, in, out []byte) {
width := t.xsize
if t.bits == 0 {
n := width * height
lookupBytes(&tab.pal8, in[:n], out[:n])
return
}
pw := subSampleSize(width, t.bits)
in = in[:pw*height]
out = out[:width*height]
for y := 0; y < height; y++ {
expandBundledRow(tab, t.bits, in[y*pw:(y+1)*pw], out[y*width:(y+1)*width])
}
}
// lookupBytesGo is the reference of lookupBytes (dsp_*.go): it sets
// out[i] = pal[in[i]] (len(out) >= len(in)), 8 bytes per step.
func lookupBytesGo(pal *[256]byte, in, out []byte) {
out = out[:len(in)]
i := 0
for ; i+8 <= len(in); i += 8 {
v := binary.LittleEndian.Uint64(in[i:])
r := uint64(pal[byte(v)]) | uint64(pal[byte(v>>8)])<<8 |
uint64(pal[byte(v>>16)])<<16 | uint64(pal[byte(v>>24)])<<24 |
uint64(pal[byte(v>>32)])<<32 | uint64(pal[byte(v>>40)])<<40 |
uint64(pal[byte(v>>48)])<<48 | uint64(pal[v>>56])<<56
binary.LittleEndian.PutUint64(out[i:], r)
}
for ; i < len(in); i++ {
out[i] = pal[in[i]]
}
}
// expandBundledRowGo is the reference of expandBundledRow (dsp_*.go): it
// expands one row of bundled indices (each byte of src holds 1<<bits of
// them, bits 1 to 3) into the output bytes dst, with one 2-, 4- or 8-byte
// store per packed byte from a.bundle.
func expandBundledRowGo(a *alphaTables, bits int, src, dst []byte) {
tab := &a.bundle
ppb := 1 << bits
full := min(len(dst)>>bits, len(src)) // packed bytes expanded whole
switch bits {
case 1:
d := dst[:2*full]
for k, b := range src[:full] {
binary.LittleEndian.PutUint16(d[2*k:], uint16(tab[b]))
}
case 2:
d := dst[:4*full]
for k, b := range src[:full] {
binary.LittleEndian.PutUint32(d[4*k:], uint32(tab[b]))
}
default:
d := dst[:8*full]
for k, b := range src[:full] {
binary.LittleEndian.PutUint64(d[8*k:], tab[b])
}
}
if x := full * ppb; x < len(dst) && full < len(src) {
// The last packed byte of the row holds fewer pixels.
e := tab[src[full]]
for ; x < len(dst); x++ {
dst[x] = byte(e)
e >>= 8
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import "math"
// Backward reference (LZ77) computation.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
modeLiteral = 0
modeCache = 1
modeCopy = 2
)
// pixOrCopy is a literal pixel, a color cache index or a (distance, length)
// copy. Distances are linear pixel distances (converted to plane codes when
// the stream is written).
type pixOrCopy struct {
val uint32 // argb, cache index or distance
lm uint32 // len<<2 | mode
}
func (p pixOrCopy) mode() uint32 { return p.lm & 3 }
func (p pixOrCopy) length() int { return int(p.lm >> 2) }
func mkLiteral(argb uint32) pixOrCopy { return pixOrCopy{argb, 1<<2 | modeLiteral} }
func mkCache(idx uint32) pixOrCopy { return pixOrCopy{idx, 1<<2 | modeCache} }
func mkCopy(dist uint32, l int) pixOrCopy { return pixOrCopy{dist, uint32(l)<<2 | modeCopy} }
// initRefsCap returns the initial capacity of a reference buffer for the
// w x h image argb. A parse has at most one entry per pixel, but graphics
// and alpha planes typically need 100-1000 times fewer, so the buffer is
// sized from a cheap estimate: the number of pixels that differ from both
// their left and top neighbors (each such pixel starts a literal or a
// copy), with 50% headroom. Photos thus get one allocation of about n
// entries, flat images a small one; growRefs covers underestimates. The
// pixels are counted in every rleSampleStep-th row only (all rows below
// rleSampleMinRows): a full pass took 3% of a level 0 encode.
func initRefsCap(argb []uint32, w, h int) int {
n := w * h
if n <= 4096 {
return n
}
step := 1
if h >= rleSampleMinRows {
step = rleSampleStep
}
// (The first row, which has no row above, is counted apart.)
est, rows := 0, 0
for y := step; y < h; y += step {
est += newPixels(argb[y*w:(y+1)*w], argb[(y-1)*w:y*w], argb[y*w-1])
rows++
}
if step > 1 {
est = int(int64(est) * int64(h-1) / int64(rows))
}
est += 1 + newPixels(argb[1:w], nil, argb[0])
return refsCapFromEstimate(n, est)
}
// refsCapFromEstimate is initRefsCap for an image of n pixels of which est
// differ from their left and top neighbors.
func refsCapFromEstimate(n, est int) int {
if n <= 4096 {
return n
}
return min(n, est+est/2+4096)
}
// newPixels returns the number of pixels of row that differ from their left
// neighbor (left for the first one) and, if up is not nil, from their top
// neighbor in up.
func newPixels(row, up []uint32, left uint32) int {
n := 0
if up == nil {
for _, p := range row {
if p != left {
n++
}
left = p
}
return n
}
up = up[:len(row)]
for x, p := range row {
if p != left && p != up[x] {
n++
}
left = p
}
return n
}
// growRefs returns refs with room for at least one more entry, doubling its
// capacity but never beyond limit entries (the most a parse of limit pixels
// can produce) unless needed.
func growRefs(refs []pixOrCopy, limit int) []pixOrCopy {
c := max(min(2*cap(refs), limit), cap(refs)+1, 64)
r := make([]pixOrCopy, len(refs), c)
copy(r, refs)
return r
}
// lz77ReachGo returns the length of the copy at i of backwardRefsLz77,
// for a match of length l at i reaching at least jMax (jMax < n): libwebp
// keeps the part of the match up to the position j in (i, jMax] from
// which the longest match (or a literal) reaches farthest, the first such
// j, and stops at the first j reaching n (l is kept when jMax <= i). It
// is the Go reference of lz77Reach (dsp_amd64.go, dsp_arm64.go,
// dsp_generic.go).
func lz77ReachGo(ol []uint32, i, jMax, n, l int) int {
maxReach := 0
for j := i + 1; j <= jMax; j++ {
lj := int(ol[j] & (1<<maxLengthBits - 1))
reach := j + 1
if lj >= minLength {
reach = j + lj
}
if reach > maxReach {
l = j - i
maxReach = reach
if maxReach >= n {
break
}
}
}
return l
}
// backwardRefsLz77 computes greedy LZ77 references with one-step lookahead.
func backwardRefsLz77(n int, argb []uint32, hc *hashChain, refs []pixOrCopy) []pixOrCopy {
refs = refs[:0]
ol := hc.ol[:n]
for i := 0; i < n; {
v := ol[i]
l := int(v & (1<<maxLengthBits - 1))
off := v >> maxLengthBits
if l >= minLength {
l = lz77Reach(ol, i, min(i+l, n-1), n, l)
} else {
l = 1
}
if len(refs) == cap(refs) {
refs = growRefs(refs, n)
}
if l == 1 {
refs = append(refs, mkLiteral(argb[i]))
} else {
refs = append(refs, mkCopy(off, l))
}
i += l
}
return refs
}
// rleSampleStep is the row sampling of the estimates of the parse sizes
// (initRefsCap, rleRefsEstimate) for images of at least rleSampleMinRows
// rows.
const (
rleSampleStep = 16
rleSampleMinRows = 64
)
// rleRefsEstimate estimates the number of entries of the RLE parse of the
// w x h image argb (backwardRefsRle) from its entries starting in every
// rleSampleStep-th row (it counts them all in images of fewer than
// rleSampleMinRows rows). initRefsCap undercounts them on photos (pixels
// equal to a neighbor are often literals of the RLE parse, in runs too short
// for a copy), whose RLE parse would then outgrow its buffer (a copy into
// a buffer of one entry per pixel, both alive at once).
func rleRefsEstimate(argb []uint32, w, h int) int {
n := w * h
argb = argb[:n]
if h < rleSampleMinRows {
return rleEntries(argb, w, 0, n)
}
// (The first row, which has no row above, is counted apart.)
count, rows := 0, 0
for y := rleSampleStep; y < h; y += rleSampleStep {
count += rleEntries(argb, w, y*w, (y+1)*w)
rows++
}
return rleEntries(argb, w, 0, w) + int(int64(count)*int64(h-1)/int64(rows))
}
// rleEntries returns the number of entries of backwardRefsRle that start
// in argb[lo:hi] (w pixels wide), as if one started at lo.
func rleEntries(argb []uint32, w, lo, hi int) int {
n := len(argb)
i, k := lo, 0
if i == 0 {
k, i = 1, 1 // the first pixel is a literal
}
for ; i < hi; k++ {
maxLen := min(n-i, maxLength)
cur := argb[i : i+maxLen]
rle := vectorMismatch(cur, argb[i-1:], maxLen)
prow := 0
if i >= w {
prow = vectorMismatch(cur, argb[i-w:], maxLen)
}
switch {
case rle >= prow && rle >= minLength:
i += rle
case prow >= minLength:
i += prow
default:
i++
}
}
return k
}
// backwardRefsRleGo computes references using only distance 1 and xsize.
// It is the Go reference of backwardRefsRle (dsp_amd64.go, dsp_arm64.go,
// dsp_generic.go).
func backwardRefsRleGo(xsize, n int, argb []uint32, refs []pixOrCopy) []pixOrCopy {
refs = refs[:0]
argb = argb[:n]
if cap(refs) == 0 {
refs = growRefs(refs, n)
}
refs = append(refs, mkLiteral(argb[0]))
for i := 1; i < n; {
if len(refs) == cap(refs) {
refs = growRefs(refs, n)
}
maxLen := n - i
if maxLen > maxLength {
maxLen = maxLength
}
cur := argb[i : i+maxLen]
rle := vectorMismatch(cur, argb[i-1:], maxLen)
prow := 0
if i >= xsize {
prow = vectorMismatch(cur, argb[i-xsize:], maxLen)
}
if rle >= prow && rle >= minLength {
refs = append(refs, mkCopy(1, rle))
i += rle
} else if prow >= minLength {
refs = append(refs, mkCopy(uint32(xsize), prow))
i += prow
} else {
refs = append(refs, mkLiteral(argb[i]))
i++
}
}
return refs
}
// applyColorCache converts literals into cache references where possible.
func applyColorCache(argb []uint32, cacheBits int, refs []pixOrCopy, cache []uint32) {
if cacheBits == 0 {
return
}
cache = cache[:1<<uint(cacheBits)]
for i := range cache {
cache[i] = 0
}
shift := uint(32 - cacheBits)
pos := 0
// The cache starts zero-filled but an index is only used on an exact
// hit, and a hit on an unset slot would require argb == 0 which is
// valid since the decoder's cache is zero-initialised as well.
for k, r := range refs {
if r.mode() == modeLiteral {
a := r.val
key := colorCacheHash(a, shift)
if cache[key] == a {
refs[k] = mkCache(key)
} else {
cache[key] = a
}
pos++
} else {
l := r.length()
// Runs of the same color insert it once.
prev := ^argb[pos]
for _, a := range argb[pos : pos+l] {
if a != prev {
cache[colorCacheHash(a, shift)] = a
prev = a
}
}
pos += l
}
}
}
// cacheHistos are the histograms of bestCacheBits for each cache size i
// (0: no cache), as the counting kernels of dsp_amd64.go and dsp_arm64.go
// lay them out: the literal histogram (green, length prefixes and cache
// indices) and the cache are in a scratch buffer.
type cacheHistos struct {
lit, cache [maxColorCacheBits + 1]*uint32
red, blue, alpha [maxColorCacheBits + 1][256]uint32
}
// bestCacheBitsGo returns the color cache size minimizing the estimated
// entropy of refs (which must contain no cache references). It is the Go
// reference of bestCacheBits (dsp_amd64.go, dsp_arm64.go, dsp_generic.go).
func bestCacheBitsGo(argb []uint32, quality int, refs []pixOrCopy, maxBits int, sc *scratch) int {
if quality <= 25 || maxBits == 0 {
return 0
}
type cacheHisto struct {
lit []uint32
red, blue, alpha [256]uint32
}
// Literal histograms: [0..280) + cache indices.
var hs [maxColorCacheBits + 1]cacheHisto
total := 0
for i := 0; i <= maxBits; i++ {
n := numLiteralCodes + numLengthCodes
if i > 0 {
n += 1 << uint(i)
}
total += n
}
buf := sc.u32a(total + (2 << uint(maxBits)))
for i := range buf {
buf[i] = 0
}
off := 0
var caches [maxColorCacheBits + 1][]uint32
for i := 0; i <= maxBits; i++ {
n := numLiteralCodes + numLengthCodes
if i > 0 {
n += 1 << uint(i)
}
hs[i].lit = buf[off : off+n]
off += n
}
for i := 1; i <= maxBits; i++ {
caches[i] = buf[off : off+(1<<uint(i))]
off += 1 << uint(i)
}
shift := uint(32 - maxBits)
pos := 0
for _, r := range refs {
if r.mode() == modeLiteral {
pix := argb[pos]
pos++
a, rr, g, b := pix>>24, (pix>>16)&0xff, (pix>>8)&0xff, pix&0xff
key := colorCacheHash(pix, shift)
hs[0].alpha[a]++
hs[0].red[rr]++
hs[0].lit[g]++
hs[0].blue[b]++
for i := maxBits; i >= 1; i-- {
c := caches[i]
if c[key] == pix {
hs[i].lit[numLiteralCodes+numLengthCodes+int(key)]++
} else {
c[key] = pix
hs[i].alpha[a]++
hs[i].red[rr]++
hs[i].lit[g]++
hs[i].blue[b]++
}
key >>= 1
}
} else {
l := r.length()
code := prefixCode(l)
for i := 0; i <= maxBits; i++ {
hs[i].lit[numLiteralCodes+code]++
}
prev := argb[pos] ^ 0xffffffff
for _, p := range argb[pos : pos+l] {
if p != prev {
key := colorCacheHash(p, shift)
for i := maxBits; i >= 1; i-- {
caches[i][key] = p
key >>= 1
}
prev = p
}
}
pos += l
}
}
best := 0
bestCost := math.MaxFloat64
for i := 0; i <= maxBits; i++ {
c := populationCost(hs[i].lit) + populationCost(hs[i].red[:]) +
populationCost(hs[i].blue[:]) + populationCost(hs[i].alpha[:]) +
extraCost(hs[i].lit[numLiteralCodes:numLiteralCodes+numLengthCodes])
if i == 0 || c < bestCost {
bestCost = c
best = i
}
}
return best
}
// ---- cost-based optimal parsing ----
//
// Port of libwebp 1.6 src/enc/backward_references_cost_enc.c (BSD-3-Clause),
// with its fixed-point costs.
// costModel holds per-symbol bit cost estimates (fixed point).
type costModel struct {
alpha, red, blue [256]uint32
lit []uint32 // green + length prefixes + cache
dist [numDistanceCodes]uint32
}
// popToBits is libwebp's ConvertPopulationCountTableToBitEstimates.
func popToBits(pop []uint32, out []uint32) {
var sum uint32
nz := 0
for _, v := range pop {
sum += v
if v > 0 {
nz++
}
}
if nz <= 1 {
clear(out)
return
}
ls := fastLog2(sum)
for i, v := range pop {
out[i] = ls - fastLog2(v)
}
}
func (m *costModel) build(xsize int, refs []pixOrCopy, h *histo, hs *histoSet) {
hs.clear(h)
hs.addRefs(h, refs, xsize)
L := hs.litLen
d := h.d
if cap(m.lit) < L {
m.lit = make([]uint32, L)
}
m.lit = m.lit[:L]
popToBits(d[:L], m.lit)
popToBits(d[L:L+256], m.red[:])
popToBits(d[L+256:L+512], m.blue[:])
popToBits(d[L+512:L+768], m.alpha[:])
popToBits(d[L+768:L+808], m.dist[:])
}
// prefixEncodeBits is libwebp's VP8LPrefixEncodeBits (0 maps to code 0).
func prefixEncodeBits(v int) (code, nbits int) {
if v == 0 {
return 0, 0
}
code, nbits, _ = prefixEncode(v)
return
}
func (m *costModel) lengthCost(length int) int64 {
code, nb := prefixEncodeBits(length)
return int64(m.lit[numLiteralCodes+code]) + int64(nb)<<log2PrecisionBits
}
func (m *costModel) distanceCost(planeCode int) int64 {
code, nb := prefixEncodeBits(planeCode)
return int64(m.dist[code]) + int64(nb)<<log2PrecisionBits
}
// costInterval is a range [start, end) of pixels whose cost may be lowered
// to cost by a copy starting at index.
type costInterval struct {
cost int64
start, end, idx int
prev, next *costInterval
}
type costCacheInterval struct {
cost int64
start, end int
}
const (
costCacheIntervalSizeMax = 500
// A copy found at pixel j <= i+maxLength (see the reach logic in
// traceBackwards) covers pixels up to j+maxLength-1, so costs are
// written at most costAhead pixels ahead of the current one.
costAhead = 2*maxLength + 2
costChunk = 4096
costRing = 1 << 15 // > costAhead + costChunk + 1
costMask = costRing - 1
)
// costManager keeps the minimal copy costs of the pixels ahead as
// non-overlapping intervals sorted by start (libwebp CostManager). At most
// costCacheIntervalSizeMax intervals exist at a time; they live in slab.
type costManager struct {
slab [costCacheIntervalSizeMax]costInterval
used int // slab[:used] have been handed out
free *costInterval
head *costInterval
count int
cacheIv []costCacheInterval
costCache []int64
// costs holds the cost of pixels [i-1, i+costAhead+costChunk) (i being
// the current pixel) in a ring indexed by pixel&costMask: older costs
// are never read again.
costs *[costRing]int64
n int
initUpTo int // the costs of pixels below initUpTo are initialized
dist []uint16
}
func (cm *costManager) init(dist []uint16, costs *[costRing]int64, n int, m *costModel) {
cm.used = 0
cm.free = nil
cm.head = nil
cm.count = 0
cm.dist = dist
sz := min(n, maxLength)
if cap(cm.costCache) < sz {
cm.costCache = make([]int64, sz)
}
cm.costCache = cm.costCache[:sz]
for i := range cm.costCache {
cm.costCache[i] = m.lengthCost(i)
}
cm.cacheIv = cm.cacheIv[:0]
cur := costCacheInterval{cost: cm.costCache[0], start: 0, end: 1}
for i := 1; i < sz; i++ {
if c := cm.costCache[i]; c != cur.cost {
cm.cacheIv = append(cm.cacheIv, cur)
cur = costCacheInterval{cost: c, start: i}
}
cur.end = i + 1
}
cm.cacheIv = append(cm.cacheIv, cur)
cm.costs = costs
cm.n = n
cm.initUpTo = 0
}
// prepare initializes (to MaxInt64) the costs of the pixels that may be
// written while processing pixel i.
func (cm *costManager) prepare(i int) {
need := min(i+costAhead, cm.n)
if need <= cm.initUpTo {
return
}
end := min(need+costChunk, cm.n)
for k := cm.initUpTo; k < end; {
// Fill up to the end of the ring or to end.
lo := k & costMask
c := cm.costs[lo:min(costRing, lo+end-k)]
for j := range c {
c[j] = math.MaxInt64
}
k += len(c)
}
cm.initUpTo = end
}
func (cm *costManager) updateCost(i, position int, cost int64) {
if c := &cm.costs[i&costMask]; *c > cost {
*c = cost
cm.dist[i] = uint16(i - position + 1)
}
}
func (cm *costManager) updateCostPerInterval(start, end, position int, cost int64) {
for i := start; i < end; i++ {
cm.updateCost(i, position, cost)
}
}
func (cm *costManager) connect(prev, next *costInterval) {
if prev != nil {
prev.next = next
} else {
cm.head = next
}
if next != nil {
next.prev = prev
}
}
func (cm *costManager) pop(iv *costInterval) {
if iv == nil {
return
}
cm.connect(iv.prev, iv.next)
iv.next = cm.free
cm.free = iv
cm.count--
}
// updateCostAtIndex lowers the cost of pixel i with the intervals covering
// it; with clean, it drops the intervals ending before i.
func (cm *costManager) updateCostAtIndex(i int, clean bool) {
cur := cm.head
for cur != nil && cur.start <= i {
next := cur.next
if cur.end <= i {
if clean {
cm.pop(cur)
}
} else if c := &cm.costs[i&costMask]; *c > cur.cost {
*c = cur.cost
cm.dist[i] = uint16(i - cur.idx + 1)
}
cur = next
}
}
// positionOrphan links the unlinked interval cur into the list, using prev
// as a hint.
func (cm *costManager) positionOrphan(cur, prev *costInterval) {
if prev == nil {
prev = cm.head
}
start := cur.start
for prev != nil && start < prev.start {
prev = prev.prev
}
for prev != nil && prev.next != nil && prev.next.start < start {
prev = prev.next
}
if prev != nil {
cm.connect(cur, prev.next)
} else {
cm.connect(cur, cm.head)
}
cm.connect(prev, cur)
}
func (cm *costManager) insert(hint *costInterval, cost int64, position, start, end int) {
if start >= end {
return
}
if cm.count >= costCacheIntervalSizeMax {
cm.updateCostPerInterval(start, end, position, cost)
return
}
var iv *costInterval
if cm.free != nil {
iv = cm.free
cm.free = iv.next
} else {
iv = &cm.slab[cm.used]
cm.used++
}
*iv = costInterval{cost: cost, idx: position, start: start, end: end}
cm.positionOrphan(iv, hint)
cm.count++
}
// push adds the contributions of a copy of up to len pixels at position
// whose distance cost (plus the cost before position) is distCost.
func (cm *costManager) push(distCost int64, position, length int) {
const skipDistance = 10
if length < skipDistance {
cc := cm.costCache[:length]
for k, c := range cc {
c += distCost
if p := &cm.costs[(position+k)&costMask]; *p > c {
*p = c
cm.dist[position+k] = uint16(k + 1)
}
}
return
}
iv := cm.head
for _, ci := range cm.cacheIv {
if ci.start >= length {
break
}
start := position + ci.start
end := position + min(ci.end, length)
cost := distCost + ci.cost
for iv != nil && iv.start < end {
next := iv.next
if start >= iv.end {
iv = next
continue
}
if cost >= iv.cost {
startNew := iv.end
cm.insert(iv, cost, position, start, iv.start)
start = startNew
if start >= end {
break
}
iv = next
continue
}
if start <= iv.start {
if iv.end <= end {
cm.pop(iv)
} else {
iv.start = end
break
}
} else {
if end < iv.end {
endOrig := iv.end
iv.end = start
cm.insert(iv, iv.cost, iv.idx, end, endOrig)
iv = iv.next
break
}
iv.end = start
}
iv = next
}
cm.insert(iv, cost, position, start, end)
}
}
// traceBackwards computes cost-optimal references using the matches found by
// the hash chain and the statistics of an initial parse (refsIn), like
// libwebp's VP8LBackwardReferencesTraceBackwards. The returned references
// use no color cache (applyColorCache converts them).
func traceBackwards(xsize, n int, argb []uint32, cacheBits int, hc *hashChain,
refsIn []pixOrCopy, refsOut []pixOrCopy, sc *scratch) []pixOrCopy {
m := &sc.cm
h := sc.tmpHisto(cacheBits)
m.build(xsize, refsIn, h, &sc.tmpSet)
dist := sc.u16(n)
cm := &sc.costMgr
if sc.costRing == nil {
sc.costRing = new([costRing]int64)
}
cm.init(dist, sc.costRing, n, m)
costs := cm.costs
var cache []uint32
shift := uint(32 - cacheBits)
if cacheBits > 0 {
cache = sc.cacheBuf(1 << uint(cacheBits))
}
argb = argb[:n]
ol := hc.ol[:n]
dist = dist[:n]
// Literal costs are scaled by 82/100 and cache costs by 68/100 (with
// rounding, both positive), as in libwebp.
lit := m.lit
cacheLit := lit[numLiteralCodes+numLengthCodes:]
alpha, red, blue := &m.alpha, &m.red, &m.blue
green := (*[256]uint32)(lit[:256])
dist[0] = 0
offsetPrev, lenPrev := -1, -1
var offsetCost int64 = -1
firstOffsetIsConstant := -1
reach := 0
var cacheCost []int64
if cacheBits > 0 {
cacheCost = sc.cacheCosts(1 << uint(cacheBits))
for k := range cacheCost {
cacheCost[k] = (int64(cacheLit[k])*68 + 50) / 100
}
}
cm.prepare(0)
initUpTo := cm.initUpTo
// The cost before pixel 0 is 0; its ring slot (that of the pixel
// costRing-1) is reinitialized before that pixel is reached.
costs[costMask] = 0
for i := 0; i < n; i++ {
if i+costAhead > initUpTo {
cm.prepare(i)
initUpTo = cm.initUpTo
}
prevCost := costs[(i-1)&costMask]
// The pixel as a literal (or cache hit).
c := argb[i]
v := prevCost
if cacheBits > 0 {
key := colorCacheHash(c, shift)
if cache[key] == c {
v += cacheCost[key]
} else {
cache[key] = c
lc := uint64(alpha[c>>24]) + uint64(red[(c>>16)&0xff]) + uint64(green[(c>>8)&0xff]) + uint64(blue[c&0xff])
v += int64((lc*82 + 50) / 100)
}
} else {
lc := uint64(alpha[c>>24]) + uint64(red[(c>>16)&0xff]) + uint64(green[(c>>8)&0xff]) + uint64(blue[c&0xff])
v += int64((lc*82 + 50) / 100)
}
if c := &costs[i&costMask]; *c > v {
*c = v
dist[i] = 1
}
// (Pixel 0 has no match: offset and length are 0.)
offset := int(ol[i] >> maxLengthBits)
length := int(ol[i] & (1<<maxLengthBits - 1))
if length >= 2 {
if offset != offsetPrev {
offsetCost = m.distanceCost(distanceToPlaneCode(xsize, offset))
firstOffsetIsConstant = 1
cm.push(prevCost+offsetCost, i, length)
} else {
if firstOffsetIsConstant == 1 {
reach = i - 1 + lenPrev - 1
firstOffsetIsConstant = 0
}
if i+length-1 > reach {
var lenJ int
j := i
for ; j <= reach; j++ {
if int(ol[j+1]>>maxLengthBits) != offset {
lenJ = int(ol[j] & (1<<maxLengthBits - 1))
break
}
lenJ = int(ol[j+1] & (1<<maxLengthBits - 1))
}
cm.updateCostAtIndex(j-1, false)
cm.updateCostAtIndex(j, false)
cm.push(costs[(j-1)&costMask]+offsetCost, j, lenJ)
reach = j + lenJ - 1
}
}
}
if h := cm.head; h != nil && h.start <= i {
if h.end > i && (h.next == nil || h.next.start > i) {
// Fast path: only the head interval covers i.
if c := &costs[i&costMask]; *c > h.cost {
*c = h.cost
dist[i] = uint16(i - h.idx + 1)
}
} else {
cm.updateCostAtIndex(i, true)
}
}
offsetPrev = offset
lenPrev = length
}
// Trace back the chosen path, packing it at the end of dist.
p := n
for cur := n - 1; cur >= 0; {
k := int(dist[cur])
p--
dist[p] = uint16(k)
cur -= k
}
path := dist[p:]
if cap(refsOut) < len(path) {
refsOut = make([]pixOrCopy, 0, len(path))
}
refsOut = refsOut[:0]
pos := 0
for _, s := range path {
if s != 1 {
refsOut = append(refsOut, mkCopy(ol[pos]>>maxLengthBits, int(s)))
} else {
refsOut = append(refsOut, mkLiteral(argb[pos]))
}
pos += int(s)
}
return refsOut
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import (
"encoding/binary"
"slices"
)
// bitWriter writes VP8L bits LSB-first using a 64-bit accumulator.
type bitWriter struct {
buf []byte
acc uint64
nbits uint
}
// putBits writes the n low bits of v (n <= 32; v must fit in n bits).
func (w *bitWriter) putBits(v uint32, n uint) {
w.acc |= uint64(v) << w.nbits
w.nbits += n
if w.nbits >= 32 {
w.buf = binary.LittleEndian.AppendUint32(w.buf, uint32(w.acc))
w.acc >>= 32
w.nbits -= 32
}
}
// reserve makes room for at least n more bytes in the buffer.
func (w *bitWriter) reserve(n int) {
if n > 0 && cap(w.buf)-len(w.buf) < n {
w.buf = slices.Grow(w.buf, n)
}
}
// numBits returns the number of bits written so far.
func (w *bitWriter) numBits() int { return len(w.buf)*8 + int(w.nbits) }
// reset clears the writer, keeping its buffer capacity.
func (w *bitWriter) reset() {
w.buf = w.buf[:0]
w.acc = 0
w.nbits = 0
}
// appendWriter appends all bits of o to w.
func (w *bitWriter) appendWriter(o *bitWriter) {
if w.nbits == 0 {
w.buf = append(w.buf, o.buf...)
} else {
for i := 0; i+4 <= len(o.buf); i += 4 {
w.putBits(binary.LittleEndian.Uint32(o.buf[i:]), 32)
}
for i := len(o.buf) &^ 3; i < len(o.buf); i++ {
w.putBits(uint32(o.buf[i]), 8)
}
}
n := o.nbits
acc := o.acc
for n > 0 {
k := n
if k > 32 {
k = 32
}
w.putBits(uint32(acc)&uint32((uint64(1)<<k)-1), k)
acc >>= k
n -= k
}
}
// finish flushes the pending bits and returns the byte slice.
func (w *bitWriter) finish() []byte {
for w.nbits > 0 {
w.buf = append(w.buf, byte(w.acc))
w.acc >>= 8
if w.nbits >= 8 {
w.nbits -= 8
} else {
w.nbits = 0
}
}
w.acc = 0
return w.buf
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package vp8lenc implements a pure-Go WebP lossless (VP8L) encoder.
//
// The encoder implements the full VP8L toolbox: subtract-green, spatial
// prediction with per-tile mode selection, cross-color decorrelation,
// color indexing (palette) with pixel bundling, a color cache, LZ77 backward
// references (hash chain, RLE and cost-based optimal parsing), 2D distance
// codes, meta-Huffman (entropy image) clustering and length-limited Huffman
// codes with run-length compressed code-length codes.
//
// Algorithm adapted from libwebp (BSD-3-Clause).
package vp8lenc
import "math/bits"
const (
numLiteralCodes = 256
numLengthCodes = 24
numDistanceCodes = 40
maxColorCacheBits = 10
codeLengthCodes = 19
maxLength = 4095 // maximum LZ77 copy length
maxLengthBits = 12
minLength = 4
windowSize = (1 << 20) - 120
maxDim = 16383
maxHuffImageSize = 2600
minHuffmanBits = 2
maxHuffmanBits = 9
minTransformBits = 2
maxTransformBits = 9 // MIN_TRANSFORM_BITS + (1 << NUM_TRANSFORM_BITS) - 1
// maxPredictorImageSize bounds the size of the predictor image (in
// tiles) when choosing its sampling.
maxPredictorImageSize = 1 << 14
argbBlack = 0xff000000
// Transform types.
predictorTransform = 0
crossColorTransform = 1
subtractGreenTransform = 2
colorIndexingTransform = 3
vp8lSignature = 0x2f
)
// codeToPlane maps a 2D distance code (1-based, minus 1) to (yoffset<<4)|(8-xoffset).
var codeToPlane = [120]uint8{
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a,
0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a,
0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b,
0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03,
0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c,
0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e,
0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b,
0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f,
0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b,
0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41,
0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f,
0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
}
// planeToCode is the inverse of codeToPlane.
var planeToCode [128]uint8
func init() {
for i, p := range codeToPlane {
planeToCode[p] = uint8(i)
}
}
// distanceToPlaneCode converts a linear backward distance into the VP8L
// distance code (1..120 for short 2D distances, dist+120 otherwise).
func distanceToPlaneCode(xsize int, dist int) int {
yoff := dist / xsize
xoff := dist - yoff*xsize
if xoff <= 8 && yoff < 8 {
return int(planeToCode[yoff*16+8-xoff]) + 1
} else if xoff > xsize-8 && yoff < 7 {
return int(planeToCode[(yoff+1)*16+8+(xsize-xoff)]) + 1
}
return dist + 120
}
// prefixEncode splits a length or distance code value (>= 1) into its prefix
// symbol, number of extra bits and extra bits value.
func prefixEncode(v int) (code, nbits, extra int) {
d := uint32(v - 1)
if d < 4 {
return int(d), 0, 0
}
hb := bits.Len32(d) - 1
shb := int(d>>(uint(hb)-1)) & 1
nbits = hb - 1
extra = int(d) & (1<<uint(nbits) - 1)
return 2*hb + shb, nbits, extra
}
// prefixCode returns only the prefix symbol of v.
func prefixCode(v int) int {
d := uint32(v - 1)
if d < 4 {
return int(d)
}
hb := bits.Len32(d) - 1
return 2*hb + int(d>>(uint(hb)-1))&1
}
func subSampleSize(size, bits int) int {
return (size + (1 << uint(bits)) - 1) >> uint(bits)
}
func log2Floor(v uint32) int { return bits.Len32(v) - 1 }
// subPixels returns the per-channel difference a-b (mod 256).
func subPixels(a, b uint32) uint32 {
ag := 0x00ff00ff + (a & 0xff00ff00) - (b & 0xff00ff00)
rb := 0xff00ff00 + (a & 0x00ff00ff) - (b & 0x00ff00ff)
return (ag & 0xff00ff00) | (rb & 0x00ff00ff)
}
// subtractGreenGo applies the subtract-green transform to p in place: green
// is subtracted (mod 256) from red and blue. It is the Go reference of
// subtractGreen (dsp_write_amd64.go, dsp_arm64.go, dsp_generic.go).
func subtractGreenGo(p []uint32) {
for i, px := range p {
g := (px >> 8) & 0xff
p[i] = px&0xff00ff00 | (((px >> 16) - g) & 0xff << 16) | ((px - g) & 0xff)
}
}
// colorCacheHash returns the color cache key of argb for the given bits.
func colorCacheHash(argb uint32, shift uint) uint32 {
return (argb * 0x1e35a7bd) >> shift
}
// ---- pooled scratch buffers ----
// getU32 returns a []uint32 of length n (contents unspecified), from the
// pool (see freelist.go) when it holds one of about that size.
func getU32(n int) []uint32 { return u32Pool.Get(n) }
// putU32 returns b to the pool, if the budget allows it.
func putU32(b []uint32) { u32Pool.Put(b) }
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
// Cross-color (color space) transform.
// Algorithm adapted from libwebp (BSD-3-Clause).
type multipliers struct {
greenToRed, greenToBlue, redToBlue uint8
}
func (m multipliers) code() uint32 {
return argbBlack | uint32(m.redToBlue)<<16 | uint32(m.greenToBlue)<<8 | uint32(m.greenToRed)
}
func multipliersFromCode(c uint32) multipliers {
return multipliers{greenToRed: uint8(c), greenToBlue: uint8(c >> 8), redToBlue: uint8(c >> 16)}
}
func colorTransformDelta(pred, color int8) int32 {
return (int32(pred) * int32(color)) >> 5
}
// The cost of a multiplier candidate only depends on the histogram of the
// transformed red (or blue) channel of the tile, which only depends on the
// distinct (green, red) pairs (or (green, red, blue) triples) of the tile and
// their counts. Tiles of photos have 25-40% distinct triples and graphics far
// fewer, so the candidates are evaluated on the distinct values, weighted by
// their counts (exact: the histograms are integer counts).
const (
ccTabBits = 13
ccTabSize = 1 << ccTabBits
// ccMaxTilePixels bounds the tiles that are deduplicated (keeping the
// tables at most half full); larger tiles (not produced by the encoder:
// its transform bits are at most 6) list every pixel.
ccMaxTilePixels = ccTabSize / 2
)
// ccTable is an open-addressing set of keys (at most 24 bits) mapping to the
// index of their entry. A slot is in use for the current generation gen
// when slot&0xff == gen, so that the table is cleared only every 255 tiles.
type ccTable struct {
slot [ccTabSize]uint32 // key<<8 | generation
idx [ccTabSize]uint16
}
// ccTables are the deduplication tables of a tilePixels (allocated on first
// use: about 96 KB).
type ccTables struct {
pairs, triples ccTable
gen uint32 // 1..255
}
// tilePixels holds the distinct (green, red) pairs and (green, red, blue)
// triples of one tile, as signed bytes, with their pixel counts.
type tilePixels struct {
pg, pr []int8 // distinct (green, red) pairs
pc []int32
tg, tr, tb []int8 // distinct (green, red, blue) triples
tc []int32
tabs *ccTables
}
func (t *tilePixels) reset(n int) {
if cap(t.pg) < n {
t.pg, t.pr, t.pc = make([]int8, 0, n), make([]int8, 0, n), make([]int32, 0, n)
t.tg, t.tr, t.tb, t.tc = make([]int8, 0, n), make([]int8, 0, n), make([]int8, 0, n), make([]int32, 0, n)
}
t.pg, t.pr, t.pc = t.pg[:0], t.pr[:0], t.pc[:0]
t.tg, t.tr, t.tb, t.tc = t.tg[:0], t.tr[:0], t.tb[:0], t.tc[:0]
}
// load collects the distinct pairs and triples of the w x h tile at (x0, y0)
// of argb (whose rows are stride pixels apart).
func (t *tilePixels) load(argb []uint32, stride, x0, y0, w, h int) {
n := w * h
t.reset(min(n, ccMaxTilePixels))
if n > ccMaxTilePixels {
// Not deduplicated: one entry per pixel.
for y := 0; y < h; y++ {
for _, p := range argb[(y0+y)*stride+x0 : (y0+y)*stride+x0+w] {
g, r := int8(p>>8), int8(p>>16)
t.pg, t.pr, t.pc = append(t.pg, g), append(t.pr, r), append(t.pc, 1)
t.tg, t.tr, t.tb, t.tc = append(t.tg, g), append(t.tr, r), append(t.tb, int8(p)), append(t.tc, 1)
}
}
return
}
if t.tabs == nil {
t.tabs = new(ccTables)
}
tabs := t.tabs
tabs.gen++
if tabs.gen > 0xff {
clear(tabs.pairs.slot[:])
clear(tabs.triples.slot[:])
tabs.gen = 1
}
gen := tabs.gen
pairs, triples := &tabs.pairs, &tabs.triples
// The entries of the previous pixel (neighbors are often equal).
last := ^uint32(0)
lastPair, lastTriple := 0, 0
for y := 0; y < h; y++ {
for _, p := range argb[(y0+y)*stride+x0 : (y0+y)*stride+x0+w] {
p &= 0xffffff // r<<16 | g<<8 | b
if p == last {
t.pc[lastPair]++
t.tc[lastTriple]++
continue
}
if p>>8 != last>>8 {
key := p >> 8 // r<<8 | g
h := (key * 0x9e3779b1) >> (32 - ccTabBits)
for {
s := pairs.slot[h]
if s&0xff != gen {
pairs.slot[h] = key<<8 | gen
lastPair = len(t.pc)
pairs.idx[h] = uint16(lastPair)
t.pg, t.pr, t.pc = append(t.pg, int8(p>>8)), append(t.pr, int8(p>>16)), append(t.pc, 1)
break
}
if s>>8 == key {
lastPair = int(pairs.idx[h])
t.pc[lastPair]++
break
}
h = (h + 1) & (ccTabSize - 1)
}
} else {
t.pc[lastPair]++
}
h := (p * 0x9e3779b1) >> (32 - ccTabBits)
for {
s := triples.slot[h]
if s&0xff != gen {
triples.slot[h] = p<<8 | gen
lastTriple = len(t.tc)
triples.idx[h] = uint16(lastTriple)
t.tg, t.tr, t.tb, t.tc = append(t.tg, int8(p>>8)), append(t.tr, int8(p>>16)), append(t.tb, int8(p)), append(t.tc, 1)
break
}
if s>>8 == p {
lastTriple = int(triples.idx[h])
t.tc[lastTriple]++
break
}
h = (h + 1) & (ccTabSize - 1)
}
last = p
}
}
}
func predictionCostCrossColor(acc, counts *[256]int32, ae *accEntropy) float64 {
return combinedShannonEntropy(counts, acc, ae) + predictionCostSpatial(counts, 3, 2.4)
}
// ccHistoRedGo adds to histo the counts c of the red values r transformed
// with the green-to-red multiplier m (g holds their greens). It is the Go
// reference of ccHistoRed (dsp_amd64.go, dsp_generic.go).
func ccHistoRedGo(histo *[256]int32, r, g []int8, c []int32, m int8) {
g = g[:len(r)]
c = c[:len(r)]
for i, rv := range r {
nr := int32(rv) - colorTransformDelta(m, g[i])
histo[uint8(nr)] += c[i]
}
}
// ccHistoBlueGo adds to histo the counts c of the blue values b transformed
// with the green-to-blue and red-to-blue multipliers mg and mr (g and r
// hold their greens and reds). It is the Go reference of ccHistoBlue
// (dsp_amd64.go, dsp_generic.go).
func ccHistoBlueGo(histo *[256]int32, b, g, r []int8, c []int32, mg, mr int8) {
g = g[:len(b)]
r = r[:len(b)]
c = c[:len(b)]
for i, bv := range b {
nb := int32(bv) - colorTransformDelta(mg, g[i]) - colorTransformDelta(mr, r[i])
histo[uint8(nb)] += c[i]
}
}
func (t *tilePixels) costRed(g2r int, prevX, prevY multipliers, acc *[256]int32, ae *accEntropy, histo *[256]int32) float64 {
*histo = [256]int32{}
ccHistoRed(histo, t.pr, t.pg, t.pc, int8(g2r))
d := predictionCostCrossColor(acc, histo, ae)
if uint8(g2r) == prevX.greenToRed {
d -= 3
}
if uint8(g2r) == prevY.greenToRed {
d -= 3
}
if g2r == 0 {
d -= 3
}
return d
}
func (t *tilePixels) costBlue(g2b, r2b int, prevX, prevY multipliers, acc *[256]int32, ae *accEntropy, histo *[256]int32) float64 {
*histo = [256]int32{}
ccHistoBlue(histo, t.tb, t.tg, t.tr, t.tc, int8(g2b), int8(r2b))
d := predictionCostCrossColor(acc, histo, ae)
if uint8(g2b) == prevX.greenToBlue {
d -= 3
}
if uint8(g2b) == prevY.greenToBlue {
d -= 3
}
if uint8(r2b) == prevX.redToBlue {
d -= 3
}
if uint8(r2b) == prevY.redToBlue {
d -= 3
}
if g2b == 0 {
d -= 3
}
if r2b == 0 {
d -= 3
}
return d
}
// visitedSet records the candidates already evaluated by a search. The cost
// of a candidate is a pure function of it, and a candidate replaces the best
// one only if its cost is strictly lower, so a candidate seen before can never
// win again and is skipped. The candidates stay within [-63, 63] (sums of the
// search steps), so their byte keys do not alias.
type visitedSet struct {
n int
keys [64]uint16
}
// seen reports whether k was added before, and adds it otherwise (when the
// set is full, k is not added: it would only be evaluated again).
func (v *visitedSet) seen(k uint16) bool {
for _, x := range v.keys[:v.n] {
if x == k {
return true
}
}
if v.n < len(v.keys) {
v.keys[v.n] = k
v.n++
}
return false
}
func (t *tilePixels) bestTransform(prevX, prevY multipliers, quality int, accRed, accBlue *[256]int32) multipliers {
var histo [256]int32
var best multipliers
var aeR, aeB accEntropy
aeR.init(accRed)
aeB.init(accBlue)
// Green to red.
{
var vis visitedSet
maxIters := 4 + (7*quality)>>8
g2rBest := 0
bestDiff := t.costRed(0, prevX, prevY, accRed, &aeR, &histo)
vis.seen(0)
for iter := 0; iter < maxIters; iter++ {
delta := 32 >> uint(iter)
for off := -delta; off <= delta; off += 2 * delta {
cur := off + g2rBest
if vis.seen(uint16(uint8(cur))) {
continue
}
d := t.costRed(cur, prevX, prevY, accRed, &aeR, &histo)
if d < bestDiff {
bestDiff = d
g2rBest = cur
}
}
}
best.greenToRed = uint8(g2rBest)
}
// Green and red to blue.
{
offsets := [8][2]int{{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}
deltaLut := [7]int{16, 16, 8, 4, 2, 2, 2}
iters := 4
if quality < 25 {
iters = 1
} else if quality > 50 {
iters = 7
}
var vis visitedSet
g2b, r2b := 0, 0
bestDiff := t.costBlue(0, 0, prevX, prevY, accBlue, &aeB, &histo)
vis.seen(0)
for iter := 0; iter < iters; iter++ {
delta := deltaLut[iter]
for axis := 0; axis < 8; axis++ {
cg := offsets[axis][0]*delta + g2b
cr := offsets[axis][1]*delta + r2b
if !vis.seen(uint16(uint8(cg)) | uint16(uint8(cr))<<8) {
d := t.costBlue(cg, cr, prevX, prevY, accBlue, &aeB, &histo)
if d < bestDiff {
bestDiff = d
g2b, r2b = cg, cr
}
}
if quality < 25 && iter == 4 {
break
}
}
if delta == 2 && g2b == 0 && r2b == 0 {
break
}
}
best.greenToBlue = uint8(g2b)
best.redToBlue = uint8(r2b)
}
return best
}
// transformColor applies the forward cross-color transform to one pixel.
func transformColor(m multipliers, p uint32) uint32 {
g := int8(p >> 8)
r := int8(p >> 16)
nr := int32(p>>16) & 0xff
nb := int32(p) & 0xff
nr -= colorTransformDelta(int8(m.greenToRed), g)
nr &= 0xff
nb -= colorTransformDelta(int8(m.greenToBlue), g)
nb -= colorTransformDelta(int8(m.redToBlue), r)
nb &= 0xff
return p&0xff00ff00 | uint32(nr)<<16 | uint32(nb)
}
// colorSpaceTransform selects per-tile multipliers and applies them to argb.
// image receives the multipliers; like libwebp 1.6, its sampling is then
// reduced when it is made of uniform squares, and the resulting bits are
// returned.
func colorSpaceTransform(width, height, bits, quality int, argb []uint32, image []uint32, sc *scratch) int {
tile := 1 << uint(bits)
tilesX := subSampleSize(width, bits)
tilesY := subSampleSize(height, bits)
var accRed, accBlue [256]int32
var prevX, prevY multipliers
tp := &sc.tile
for ty := 0; ty < tilesY && !sc.interrupted(); ty++ {
for tx := 0; tx < tilesX; tx++ {
x0 := tx * tile
y0 := ty * tile
xMax := min(x0+tile, width)
yMax := min(y0+tile, height)
off := ty*tilesX + tx
if ty != 0 {
prevY = multipliersFromCode(image[off-tilesX])
}
tp.load(argb, width, x0, y0, xMax-x0, yMax-y0)
prevX = tp.bestTransform(prevX, prevY, quality, &accRed, &accBlue)
image[off] = prevX.code()
for y := y0; y < yMax; y++ {
row := argb[y*width+x0 : y*width+xMax]
for i, p := range row {
row[i] = transformColor(prevX, p)
}
}
for y := y0; y < yMax; y++ {
ix := y*width + x0
end := y*width + xMax
for ; ix < end; ix++ {
pix := argb[ix]
if ix >= 2 && pix == argb[ix-2] && pix == argb[ix-1] {
continue
}
if ix >= width+2 && argb[ix-2] == argb[ix-width-2] &&
argb[ix-1] == argb[ix-width-1] && pix == argb[ix-width] {
continue
}
accRed[(pix>>16)&0xff]++
accBlue[pix&0xff]++
}
}
}
}
return optimizeSampling(image, width, height, bits, maxTransformBits)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8lenc
import (
"math"
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
)
// SSE4.1, AVX2 and AVX-512 implementations of the kernel entry points,
// written in dsp_amd64.s and dsp_avx512_amd64.s. The wrappers below check
// every bound before calling the assembly, which then reads and writes
// exactly the elements the Go reference touches (no access past the end of
// a slice: the tails are handled by an overlapping last block, by the Go
// code, or, in the AVX-512 kernels, by masked loads and stores, whose
// masked-off lanes are not accessed even when their addresses lie outside
// the slice). All kernels are bit-exact with the Go reference, so the
// encoded bytes do not depend on the machine.
// x86Level selects the kernels: the highest level of this machine, lowered
// by the tests to run every level against the Go reference.
var x86Level = cpuinfo.Max
// The kernels that walk a whole image or parse are called on chunks of it,
// each through a Go function that is not inlined (the *Chunk functions):
// an assembly kernel cannot be preempted, so a stop-the-world of the
// process (each garbage collection has two) waits until the goroutine
// reaches a preemption point, and every other goroutine with it. The
// kernels have none (no stack check), and a Go loop that spends nearly all
// its time in them is not preempted either (the asynchronous preemption
// signal practically never lands in its few instructions); the stack check
// of the Go function around each chunk is one. Whole-image calls made that
// wait 0.5 s at level 6 and 50 ms at level 0 on a 5 MP photo, against well
// under 1 ms for the Go code; one chunk takes about 0.1 ms or less on
// ordinary images, and the extra calls cost nothing measurable. (Variables
// for the tests.)
var (
// hcChunk is the most positions one hcRunSSE41 or hcRunAVX512 call
// searches.
hcChunk = 1024
// refsChunk is the most references one call of rleSSE41, rleAVX512,
// addRefsSSE41, addTileRefsSSE41 or writeImageDataSSE41 takes.
refsChunk = 4096
// cacheChunk is the most references one cacheCountsSSE41 call counts
// (a copy inserts up to 4096 pixels into every cache).
cacheChunk = 256
// pixChunk is the most pixels one subtractGreen kernel call transforms
// (a multiple of 8).
pixChunk = 1 << 16
)
// maxKernelLevel is the highest level with kernels of its own: the levels
// above it run its kernels. (The AVX512 level has two, hcRunAVX512 and
// rleAVX512; its other kernels are those of the levels below.)
const maxKernelLevel = cpuinfo.AVX512
// hcRunChunk is hcRunSSE41, or hcRunAVX512 at the AVX512 level, behind a
// preemption point (see hcChunk).
//
//go:noinline
func hcRunChunk(s *hcSearcher, hi, lo, stop int, marks *uint64) (last, next int) {
if x86Level >= cpuinfo.AVX512 {
return hcRunAVX512(s, hi, lo, stop, marks, hcPrefetch)
}
return hcRunSSE41(s, hi, lo, stop, marks, hcPrefetch)
}
// cacheCountsChunk is cacheCountsSSE41 behind a preemption point (see
// hcChunk).
//
//go:noinline
func cacheCountsChunk(argb *uint32, npix int, refs *pixOrCopy, nrefs, maxBits int, h *cacheHistos) int {
return cacheCountsSSE41(argb, npix, refs, nrefs, maxBits, h)
}
// rleChunk is rleSSE41, or rleAVX512 at the AVX512 level, behind a
// preemption point (see hcChunk).
//
//go:noinline
func rleChunk(argb *uint32, n, xsize, i int, refs *pixOrCopy, room int) (count, next int) {
if x86Level >= cpuinfo.AVX512 {
return rleAVX512(argb, n, xsize, i, refs, room)
}
return rleSSE41(argb, n, xsize, i, refs, room)
}
//go:noescape
func predictRowSSE41(mode int, cur, up, out *uint32, n int)
//go:noescape
func predictRowAVX2(mode int, cur, up, out *uint32, n int)
// predictRow is predictRowGo: 4 pixels per step with SSE4.1, 8 with AVX2
// (rows of at least that many pixels).
func predictRow(mode int, cur, up []uint32, x0, x1 int, out []uint32) {
n := x1 - x0
if x86Level >= cpuinfo.SSE41 && n >= 4 && x0 >= 1 && uint(mode) < numPredModes {
// The kernel reads cur[x0-1:x1] and up[x0-1:x1+1], and writes
// out[:n].
_ = up[x1]
_ = cur[x1-1]
out = out[:n]
if x86Level >= cpuinfo.AVX2 && n >= 8 {
predictRowAVX2(mode, &cur[x0], &up[x0], &out[0], n)
} else {
predictRowSSE41(mode, &cur[x0], &up[x0], &out[0], n)
}
return
}
predictRowGo(mode, cur, up, x0, x1, out)
}
//go:noescape
func combinedShannonEntropySSE41(x, y *[256]int32, acc *accEntropy) float64
// combinedShannonEntropy is combinedShannonEntropyGo: the kernel visits
// only the non-zero bins of x (a bit mask built 16 bins at a time) instead
// of branching on every bin, and adds the same terms in the same order.
func combinedShannonEntropy(x, y *[256]int32, acc *accEntropy) float64 {
if x86Level >= cpuinfo.SSE41 {
return combinedShannonEntropySSE41(x, y, acc)
}
return combinedShannonEntropyGo(x, y, acc)
}
//go:noescape
func hcRunSSE41(s *hcSearcher, hi, lo, stop int, marks *uint64, pf int) (last, next int)
//go:noescape
func hcRunAVX512(s *hcSearcher, hi, lo, stop int, marks *uint64, pf int) (last, next int)
// hcPrefetch is how many searches ahead the kernel prefetches the first
// node of the hash chain (a variable for the benchmarks; 0: none). (4: -2%
// at level 6 on the photo, 8 and 16 less; the chains are short, 1.8 links
// per search at level 0 and 4.9 at level 6 on the photo.)
var hcPrefetch = 4
// run is runGo: the kernel runs the same searches and extensions, with the
// match lengths compared 4 pixels at a time (hcRunSSE41) or 16 at a time
// and the extensions done 16 positions at a time (hcRunAVX512), and
// prefetches the pixels and the next link of the first chain node of the
// search hcPrefetch positions below (the searches go down by one position
// most of the time).
//
// The kernel trusts the chain (buildChain): every link from a position is
// -1 or a lower position, as are the links of the positions it searches.
func (s *hcSearcher) run(hi, lo, stop int, marks []uint64) (last, next int) {
if x86Level >= cpuinfo.SSE41 && stop >= 1 && hi <= s.size-2 && s.size >= 2 {
// Every access is below size: positions and links are below hi.
_ = s.argb[s.size-1]
_ = s.chain[s.size-1]
_ = s.ol[s.size-1]
var m *uint64
if marks != nil && hi >= stop {
_ = marks[hi>>6]
m = &marks[0]
}
// The searches from hi down to stop, at most hcChunk per call (each
// call searches at least its first position).
next = hi
for next >= stop {
last, next = hcRunChunk(s, next, lo, max(stop, next-hcChunk+1), m)
}
return last, next
}
return s.runGo(hi, lo, stop, marks)
}
//go:noescape
func cacheCountsSSE41(argb *uint32, npix int, refs *pixOrCopy, nrefs, maxBits int, h *cacheHistos) int
// bestCacheBits is bestCacheBitsGo, with the histograms of every cache
// size counted by cacheCountsSSE41 (the counting loop of bestCacheBitsGo
// without bound checks; it returns -1, and the Go code then runs, if refs
// does not fit argb). The costs are computed as in the Go code.
func bestCacheBits(argb []uint32, quality int, refs []pixOrCopy, maxBits int, sc *scratch) int {
if x86Level < cpuinfo.SSE41 || quality <= 25 || maxBits <= 0 || maxBits > maxColorCacheBits || len(refs) == 0 || len(argb) == 0 {
return bestCacheBitsGo(argb, quality, refs, maxBits, sc)
}
var h cacheHistos
var lits [maxColorCacheBits + 1][]uint32
total := 0
for i := 0; i <= maxBits; i++ {
n := numLiteralCodes + numLengthCodes
if i > 0 {
n += 1 << uint(i)
}
total += n
}
buf := sc.u32a(total + (2 << uint(maxBits)))
clear(buf)
off := 0
for i := 0; i <= maxBits; i++ {
n := numLiteralCodes + numLengthCodes
if i > 0 {
n += 1 << uint(i)
}
lits[i] = buf[off : off+n]
h.lit[i] = &buf[off]
off += n
}
for i := 1; i <= maxBits; i++ {
h.cache[i] = &buf[off]
off += 1 << uint(i)
}
_ = buf[off-1]
// The references, cacheChunk per call; each call starts at the pixel of
// its first reference (none left: that reference does not fit argb).
for k, pos := 0, 0; k < len(refs); k += cacheChunk {
c := -1
if pos < len(argb) {
c = cacheCountsChunk(&argb[pos], len(argb)-pos, &refs[k], min(len(refs)-k, cacheChunk), maxBits, &h)
}
if c < 0 {
return bestCacheBitsGo(argb, quality, refs, maxBits, sc)
}
pos += c
}
best := 0
bestCost := math.MaxFloat64
for i := 0; i <= maxBits; i++ {
c := populationCost(lits[i]) + populationCost(h.red[i][:]) +
populationCost(h.blue[i][:]) + populationCost(h.alpha[i][:]) +
extraCost(lits[i][numLiteralCodes:numLiteralCodes+numLengthCodes])
if i == 0 || c < bestCost {
bestCost = c
best = i
}
}
return best
}
//go:noescape
func rleSSE41(argb *uint32, n, xsize, i int, refs *pixOrCopy, room int) (count, next int)
//go:noescape
func rleAVX512(argb *uint32, n, xsize, i int, refs *pixOrCopy, room int) (count, next int)
// backwardRefsRle is backwardRefsRleGo: the kernel parses from position i
// until the end or until refs is full (the buffer then grows as in the Go
// code). rleSSE41 takes a pixel equal to neither its left nor its top
// neighbor as a literal at once and compares the match lengths 4 pixels at
// a time; rleAVX512 finds the matches of 32 positions at once from masks of
// the pixels equal to their neighbors, writes the literals before each
// with masked stores, and measures the matches from the same masks.
func backwardRefsRle(xsize, n int, argb []uint32, refs []pixOrCopy) []pixOrCopy {
if x86Level < cpuinfo.SSE41 || n < 1 || xsize < 1 {
return backwardRefsRleGo(xsize, n, argb, refs)
}
refs = refs[:0]
argb = argb[:n]
if cap(refs) == 0 {
refs = growRefs(refs, n)
}
refs = append(refs, mkLiteral(argb[0]))
for i := 1; i < n; {
if len(refs) == cap(refs) {
refs = growRefs(refs, n)
}
room := refs[len(refs):cap(refs)]
k, next := rleChunk(&argb[0], n, xsize, i, &room[0], min(len(room), refsChunk))
refs = refs[:len(refs)+k]
i = next
}
return refs
}
//go:noescape
func popStatsSSE41(a, b *uint32, n int, st *popStats)
// combinedPopulationCost is combinedPopulationCostGo: the kernel finds the
// ends of the streaks of a+b 16 bins at a time (a bit mask) and updates the
// statistics of each streak without branches, with the floating-point
// operations of the Go code in its order; the cost is then computed from
// the statistics as in the Go code.
func combinedPopulationCost(a, b []uint32) float64 {
n := len(a)
if x86Level >= cpuinfo.SSE41 && n > 16 && n < 1<<16 {
b = b[:n]
var st popStats
popStatsSSE41(&a[0], &b[0], n, &st)
st.e.entropy += slog2(st.e.sum)
return st.e.refine() + st.s.finalHuffmanCost()
}
return combinedPopulationCostGo(a, b)
}
// zeroPop is the second operand of popStatsSSE41 for populationCost: zeros
// as long as the longest population (the literal histogram with the
// largest color cache). Never written.
var zeroPop [numLiteralCodes + numLengthCodes + 1<<maxColorCacheBits]uint32
// populationCost is populationCostGo, which is combinedPopulationCostGo
// with a zero second operand: the same kernel with zeroPop as that operand
// (pop[i]+0 == pop[i]), so the statistics and the cost are those of the Go
// code.
func populationCost(pop []uint32) float64 {
n := len(pop)
if x86Level >= cpuinfo.SSE41 && n > 16 && n <= len(zeroPop) {
var st popStats
popStatsSSE41(&pop[0], &zeroPop[0], n, &st)
st.e.entropy += slog2(st.e.sum)
return st.e.refine() + st.s.finalHuffmanCost()
}
return populationCostGo(pop)
}
//go:noescape
func accEntropyInitSSE41(h *[256]int32, a *accEntropy)
// init is initGo: the kernel adds up the bins with vector adds, stores
// zeros for the zero bins and visits only the non-zero ones (a bit mask
// built 16 bins at a time), whose terms it adds to the total in the order
// of the Go code. The skipped terms of the Go code are slog2(0) = +0, and
// x + (+0) == x for every total it can reach (a sum of non-negative terms
// from +0, never -0), so the total is bit-identical.
func (a *accEntropy) init(h *[256]int32) {
if x86Level >= cpuinfo.SSE41 {
accEntropyInitSSE41(h, a)
return
}
a.initGo(h)
}
//go:noescape
func ccHistoSSE41(histo *[256]int32, d, s1, s2 *int8, c *int32, n int, m1, m2 int)
// ccHistoRed is ccHistoRedGo: the kernel computes the transformed values 8
// at a time in 16-bit lanes (the products of two int8 fit), then adds the
// counts to their bins one by one. The red transform is the blue one with
// a zero second multiplier.
func ccHistoRed(histo *[256]int32, r, g []int8, c []int32, m int8) {
n := len(r)
if x86Level >= cpuinfo.SSE41 && n > 0 {
g = g[:n]
c = c[:n]
ccHistoSSE41(histo, &r[0], &g[0], &g[0], &c[0], n, int(m), 0)
return
}
ccHistoRedGo(histo, r, g, c, m)
}
// ccHistoBlue is ccHistoBlueGo (see ccHistoRed).
func ccHistoBlue(histo *[256]int32, b, g, r []int8, c []int32, mg, mr int8) {
n := len(b)
if x86Level >= cpuinfo.SSE41 && n > 0 {
g = g[:n]
r = r[:n]
c = c[:n]
ccHistoSSE41(histo, &b[0], &g[0], &r[0], &c[0], n, int(mg), int(mr))
return
}
ccHistoBlueGo(histo, b, g, r, c, mg, mr)
}
//go:noescape
func lz77ReachSSE41(ol *uint32, i, jMax, n int) (l int)
// lz77ReachMin is the smallest jMax-i for which lz77Reach runs its kernel
// (at least 4; a variable for the tests).
var lz77ReachMin = 8
// lz77Reach is lz77ReachGo: the kernel computes the reaches 4 positions at
// a time, capped at n (the Go loop stops at the first position reaching
// n, which is then the first one with the maximal capped reach), and
// looks for the first position of a block maximum only when it beats the
// best reach so far.
func lz77Reach(ol []uint32, i, jMax, n, l int) int {
if x86Level >= cpuinfo.SSE41 && jMax-i >= lz77ReachMin && i >= 0 && n > 0 && n < 1<<30 && jMax < 1<<30 {
_ = ol[jMax]
return lz77ReachSSE41(&ol[0], i, jMax, n)
}
return lz77ReachGo(ol, i, jMax, n, l)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build amd64 && !purego
package vp8lenc
import (
"slices"
"github.com/kolesa-team/go-webp/v2/internal/cpuinfo"
)
// Kernels of the input conversion, the histograms of a parse and the
// entropy-coded pixel writer, written in dsp_write_amd64.s. As in
// dsp_amd64.go, the wrappers check every bound the assembly relies on, and
// the kernels are bit-exact with their Go references.
//go:noescape
func nrgbaRowSSE41(dst *uint32, src *byte, n int, exact bool) (flags int)
//go:noescape
func nrgbaRowAVX2(dst *uint32, src *byte, n int, exact bool) (flags int)
// nrgbaRow is nrgbaRowGo: 4 pixels per step with SSE4.1, 8 with AVX2 (rows
// of at least that many pixels). dst must not overlap src.
func nrgbaRow(dst []uint32, src []byte, exact bool) (hasAlpha, transparent bool) {
n := len(dst)
if x86Level >= cpuinfo.SSE41 && n >= 4 {
src = src[:4*n]
var f int
if x86Level >= cpuinfo.AVX2 && n >= 8 {
f = nrgbaRowAVX2(&dst[0], &src[0], n, exact)
} else {
f = nrgbaRowSSE41(&dst[0], &src[0], n, exact)
}
return f&1 != 0, f&2 != 0
}
return nrgbaRowGo(dst, src, exact)
}
//go:noescape
func subtractGreenSSE41(p *uint32, n int)
//go:noescape
func subtractGreenAVX2(p *uint32, n int)
// subtractGreen is subtractGreenGo: the kernels transform the pixels 4
// (SSE4.1) or 8 (AVX2) at a time, as many as fill whole blocks; the Go
// code transforms the rest. (The transform is not idempotent, so the last
// block cannot overlap pixels already transformed.)
func subtractGreen(p []uint32) {
n := len(p)
// (pixChunk pixels per call at most, see hcChunk.)
m, avx2 := 0, false
switch {
case x86Level >= cpuinfo.AVX2 && n >= 8:
m, avx2 = n&^7, true
case x86Level >= cpuinfo.SSE41 && n >= 4:
m = n &^ 3
}
for i := 0; i < m; i += pixChunk {
subtractGreenChunk(&p[i], min(m-i, pixChunk), avx2)
}
subtractGreenGo(p[m:])
}
// subtractGreenChunk is the AVX2 kernel (n a multiple of 8) or the SSE4.1
// one (n a multiple of 4) behind a preemption point (see hcChunk).
//
//go:noinline
func subtractGreenChunk(p *uint32, n int, avx2 bool) {
if avx2 {
subtractGreenAVX2(p, n)
} else {
subtractGreenSSE41(p, n)
}
}
//go:noescape
func addRefsSSE41(q *uint32, stride, litLen int, refs *pixOrCopy, n, xsize int, raw bool) (done int)
// addRefsChunk is addRefsSSE41 behind a preemption point (see hcChunk).
//
//go:noinline
func addRefsChunk(q *uint32, stride, litLen int, refs *pixOrCopy, n, xsize int, raw bool) (done int) {
return addRefsSSE41(q, stride, litLen, refs, n, xsize, raw)
}
// addRefsMin is the smallest parse the addRefs kernel takes (below, clearing
// and adding up its 4 partial histograms costs more than it saves; a
// variable for the tests).
var addRefsMin = 2048
// addRefs is addRefsGo (addRefsRawDistGo when raw): the kernel adds the
// references in turn to 4 partial histograms, so that the increments of
// consecutive references do not wait for each other when they hit the
// same bins (the alpha bin of an opaque image, for one: 4.5 -> 1.6 ms for
// the literals of a 1.2 MP photo); they are then added to h. The sums are
// the Go ones (integer counts).
func (s *histoSet) addRefs(h *histo, refs []pixOrCopy, xsize int) {
if !s.addRefsAsm(h, refs, xsize, false) {
s.addRefsGo(h, refs, xsize)
}
}
// addRefsRawDist is addRefsRawDistGo (see addRefs).
func (s *histoSet) addRefsRawDist(h *histo, refs []pixOrCopy) {
if !s.addRefsAsm(h, refs, 0, true) {
s.addRefsRawDistGo(h, refs)
}
}
func (s *histoSet) addRefsAsm(h *histo, refs []pixOrCopy, xsize int, raw bool) bool {
d := h.d
L := s.litLen
n := len(d)
// The literal bins (below 256 and L+768) are in range when
// L >= numLiteralCodes; the kernel checks the cache indices against n
// and the distance codes against numDistanceCodes.
if x86Level < cpuinfo.SSE41 || len(refs) < addRefsMin || L < numLiteralCodes+numLengthCodes ||
n != L+3*256+numDistanceCodes || !raw && (xsize < 1 || xsize > maxDim) {
return false
}
if cap(s.quad) < 4*n {
s.quad = make([]uint32, 4*n)
}
q := s.quad[:4*n]
clear(q)
// refsChunk references per call at most (see hcChunk).
k := 0
for k < len(refs) {
m := min(len(refs)-k, refsChunk)
d := addRefsChunk(&q[0], n, L, &refs[k], m, xsize, raw)
k += d
if d < m {
break
}
}
q0, q1, q2, q3 := q[:n], q[n:2*n], q[2*n:3*n], q[3*n:4*n]
for i := range d {
d[i] += q0[i] + q1[i] + q2[i] + q3[i]
}
if k < len(refs) {
// refs[k] is out of range: the Go code panics on it.
if raw {
s.addRefsRawDistGo(h, refs[k:])
} else {
s.addRefsGo(h, refs[k:], xsize)
}
}
return true
}
//go:noescape
func addTileRefsSSE41(data *uint32, stride, litLen int, refs *pixOrCopy, n, xsize, hb, hx, ntiles, x0, y0 int) (done, x, y int)
// addTileRefsChunk is addTileRefsSSE41 behind a preemption point (see
// hcChunk).
//
//go:noinline
func addTileRefsChunk(data *uint32, stride, litLen int, refs *pixOrCopy, n, xsize, hb, hx, ntiles, x0, y0 int) (done, x, y int) {
return addTileRefsSSE41(data, stride, litLen, refs, n, xsize, hb, hx, ntiles, x0, y0)
}
// addTileRefs is addTileRefsGo: the kernel adds the references to the
// histograms of their tiles as addRefsGo does, with the alpha increments
// of consecutive literals to the same bin counted in a register and added
// at once (the alpha bin of an opaque image would otherwise make every
// literal wait for the previous one).
func (s *histoSet) addTileRefs(refs []pixOrCopy, xsize, histoBits, hx int) {
L, n, nt := s.litLen, s.stride, len(s.h)
if x86Level < cpuinfo.SSE41 || len(refs) == 0 || nt == 0 || L < numLiteralCodes+numLengthCodes ||
n != L+3*256+numDistanceCodes || len(s.data) != nt*n || xsize < 1 || xsize > maxDim ||
histoBits < 0 || histoBits > 16 || hx < 1 {
s.addTileRefsGo(refs, xsize, histoBits, hx)
return
}
// The kernel adds to tile i at data[i*n:]: the histograms must be
// these views (as init makes them).
for i := range s.h {
if d := s.h[i].d; len(d) != n || &d[0] != &s.data[i*n] {
s.addTileRefsGo(refs, xsize, histoBits, hx)
return
}
}
// refsChunk references per call at most (see hcChunk), each call
// starting at the position (x, y) where the previous one ended.
x, y := 0, 0
for k := 0; k < len(refs); {
m := min(len(refs)-k, refsChunk)
d, nx, ny := addTileRefsChunk(&s.data[0], n, L, &refs[k], m, xsize, histoBits, hx, nt, x, y)
k, x, y = k+d, nx, ny
if d < m {
// refs[k] is out of range: the Go code panics on it.
s.addTileRefsFrom(refs[k:], xsize, histoBits, hx, x, y)
return
}
}
}
//go:noescape
func writeImageDataSSE41(st *imgWriter, refs *pixOrCopy, n int) (done int)
// writeImageDataChunk is writeImageDataSSE41 behind a preemption point
// (see hcChunk).
//
//go:noinline
func writeImageDataChunk(st *imgWriter, refs *pixOrCopy, n int) (done int) {
return writeImageDataSSE41(st, refs, n)
}
// writeImageData is writeImageDataGo: the kernel writes the bits of the
// references with the same putBits sequence, but without bound checks and
// with branchless flushes (the flush of every other literal is not
// predictable), stopping when the buffer is nearly full (it then grows here
// as the Go code would let it grow).
func writeImageData(bw *bitWriter, w int, refs []pixOrCopy, histoBits int, symbols []uint16, codes []huffCode) {
ng := len(codes) / 5
if x86Level < cpuinfo.SSE41 || len(refs) == 0 || w < 1 || w > maxDim || ng == 0 ||
symbols != nil && (len(symbols) == 0 || histoBits < 0 || histoBits > 16) {
writeImageDataGo(bw, w, refs, histoBits, symbols, codes)
return
}
st := imgWriter{acc: bw.acc, nbits: uint64(bw.nbits), w: w, g: &codes[0], codes: &codes[0], ngroups: ng,
len0: maxDim, len4: maxDim}
// Every literal symbol must be in range in every group.
for i := range 5 * ng {
c := &codes[i]
l := min(len(c.lengths), len(c.codes))
switch i % 5 {
case 0:
st.len0 = min(st.len0, l)
case 4:
st.len4 = min(st.len4, l)
default:
if l < 256 {
writeImageDataGo(bw, w, refs, histoBits, symbols, codes)
return
}
}
}
if st.len0 < 256 || st.nbits >= 32 {
writeImageDataGo(bw, w, refs, histoBits, symbols, codes)
return
}
if symbols != nil {
st.hb = histoBits
st.tileMask = ^(1<<uint(histoBits) - 1)
st.hx = subSampleSize(w, histoBits)
st.tileX, st.tileY = -1, -1
st.symbols = &symbols[0]
st.nsym = len(symbols)
}
start, acc0, nbits0 := len(bw.buf), bw.acc, bw.nbits
all := refs
for len(refs) > 0 {
// A reference writes at most 8 bytes, plus 4 bytes the kernel
// stores at the current position whether it flushes or not.
if cap(bw.buf)-len(bw.buf) < 16 {
bw.buf = slices.Grow(bw.buf, 16)
}
b := bw.buf[:cap(bw.buf)]
st.buf, st.pos, st.limit = &b[0], len(bw.buf), len(b)-16
k := writeImageDataChunk(&st, &refs[0], min(len(refs), refsChunk))
bw.buf = bw.buf[:st.pos]
refs = refs[k:]
if st.err != 0 {
// A reference or a tile is out of range: the Go code panics on
// it, after writing the same bits.
bw.buf, bw.acc, bw.nbits = bw.buf[:start], acc0, nbits0
writeImageDataGo(bw, w, all, histoBits, symbols, codes)
return
}
}
bw.acc, bw.nbits = st.acc, uint(st.nbits)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
// Algorithm adapted from libwebp (BSD-3-Clause): src/enc/vp8l_enc.c (entropy analysis, crunch
// configurations, stream layout).
import (
"errors"
"image"
"math"
"slices"
)
// Config controls the lossless encoder. Field semantics follow libwebp's
// WebPConfig for lossless encoding.
type Config struct {
// Quality in 0..100 is the effort within a method: higher is slower and
// produces smaller output.
Quality float32
// Method in 0..6 selects the speed/size trade-off (0 fastest, 6 best).
Method int
// Exact preserves the RGB values under fully transparent pixels. When
// false, such pixels are replaced by transparent black for better
// compression.
Exact bool
// NearLossless in 0..100 enables near-lossless preprocessing (100 = off).
// It is ignored for images that can be palettized.
NearLossless int
// UseDeltaPalette is accepted for compatibility with libwebp and ignored
// (it is an experimental libwebp option).
UseDeltaPalette bool
// LowMemory lowers the peak memory where the encoder would hold more
// than one candidate at a time, at some cost in speed or size: no
// trial parse without color cache (tryNoCache: two more reference
// buffers), no box parse (a second match table) and no ThreadLevel. It
// also caps the LZ77 window at 65536 pixels, which saves no memory and
// can make the output larger.
LowMemory bool
// ThreadLevel allows helper goroutines from the process-wide budget of
// internal/workers (see parallel.go): candidate encodings are evaluated
// two at a time (up to 8 MP), and the match search, the predictor mode
// search and the histogram remap of large images are split among
// helpers, started at the beginning of each of these phases and ended
// with it. The output does not depend on it. Ignored with LowMemory.
ThreadLevel bool
// ImageHint is libwebp's WebPImageHint (0 default, 1 picture, 2 photo,
// 3 graph). With 3 (graph), palette images additionally try the
// palette+spatial combination.
ImageHint int
// Interrupt, if not nil, is polled every 16 rows while the picture is
// read in and between the major passes of the encode; when it returns
// true, the encode stops and returns ErrInterrupted. It must be safe
// for concurrent use and, once it has returned true, keep doing so.
Interrupt func() bool
// pairGate and stageGate are AlphaEncoder.PairGate and StageGate.
pairGate, stageGate func() bool
}
// ErrInterrupted is returned when Config.Interrupt (or
// AlphaEncoder.Interrupt) asked the encoder to stop.
var ErrInterrupted = errors.New("vp8lenc: interrupted")
var (
errNilImage = errors.New("vp8lenc: nil image")
errDimensions = errors.New("vp8lenc: image dimensions must be in 1..16383")
errPlane = errors.New("vp8lenc: alpha plane too small for the given dimensions")
errPixels = errors.New("vp8lenc: image pixel buffer too small for its bounds")
)
// entropy modes (libwebp EntropyIx).
const (
modeDirect = iota
modeSpatial
modeSubGreen
modeSpatialSubGreen
modePalette
modePaletteAndSpatial
numEntropyModes
)
const (
sortDefault = iota // ascending
sortMinimizeDelta
)
type crunchConfig struct {
entropy int
paletteSort int
}
// params are the derived encoding parameters shared by all crunch configs.
type params struct {
quality int
method int
lowEffort bool
histoBits int
transBits int
useCache bool
tryNoCache bool
tryBox bool // also try the box LZ77 parse (at most 16 colors)
rbZero bool // red and blue always zero (skip cross color)
windowCap int
nearLossless int
// cleanTransparent enables libwebp's exact=0 predictor behaviour: the
// RGB residual of a fully transparent pixel is zeroed and the pixel
// replaced by its prediction (only set when such pixels exist).
cleanTransparent bool
// opaque: every pixel has alpha 0xff (see predictorImage).
opaque bool
parallel bool
pairGate func() bool // Config.pairGate (when parallel)
stageGate func() bool // Config.stageGate (when parallel)
paletteSorts [2][]uint32
interrupt func() bool // Config.Interrupt
}
// interrupted polls Config.Interrupt. After it returned true the output of
// the current encode is garbage: the caller reports ErrInterrupted instead.
func (p *params) interrupted() bool { return p.interrupt != nil && p.interrupt() }
func clampInt(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
func normalize(cfg *Config) (quality, method int) {
q := float32(75)
m := 4
if cfg != nil {
q = cfg.Quality
m = cfg.Method
}
if q != q { // NaN
q = 75
}
quality = clampInt(int(q), 0, 100)
method = clampInt(m, 0, 6)
return
}
// Encode encodes img as a VP8L chunk payload: the 0x2f signature, the 14-bit
// width-1 and height-1, the alpha_is_used bit, a 3-bit version (0) and the
// lossless bitstream. The image bounds may have a non-zero origin.
func Encode(img *image.NRGBA, cfg *Config) ([]byte, error) {
return EncodeWithHeadroom(img, cfg, 0)
}
// EncodeWithHeadroom is Encode, but the returned buffer starts with
// headroom unspecified bytes followed by the VP8L chunk payload, and has at
// least one byte of spare capacity, so that a container header (and a
// padding byte) can be added without copying the payload.
func EncodeWithHeadroom(img *image.NRGBA, cfg *Config, headroom int) ([]byte, error) {
if img == nil {
return nil, errNilImage
}
b := img.Rect
w, h := b.Dx(), b.Dy()
if w < 1 || h < 1 || w > maxDim || h > maxDim {
return nil, errDimensions
}
if img.Stride < 4*w || len(img.Pix) < (h-1)*img.Stride+4*w {
return nil, errPixels
}
return encodeRows(w, h, func(y int) []byte {
return img.Pix[y*img.Stride : y*img.Stride+4*w]
}, cfg, headroom)
}
// EncodeRowsWithHeadroom is EncodeWithHeadroom for a w x h picture that the
// caller converts a row at a time instead of passing an *image.NRGBA:
// rowAt(y) returns row y of the picture as non-premultiplied RGBA (at
// least 4*w bytes, laid out as in an *image.NRGBA), for every y from 0 to
// h-1 in order, unless Config.Interrupt stops the encode first; the row
// is not used after the next call. Each row goes from there straight into
// the encoder's working image, so that a picture of another type is
// encoded without a full-size NRGBA copy (4 bytes per pixel).
func EncodeRowsWithHeadroom(w, h int, rowAt func(y int) []byte, cfg *Config, headroom int) ([]byte, error) {
if w < 1 || h < 1 || w > maxDim || h > maxDim {
return nil, errDimensions
}
return encodeRows(w, h, rowAt, cfg, headroom)
}
// encodeRows is EncodeRowsWithHeadroom with valid dimensions.
func encodeRows(w, h int, rowAt func(y int) []byte, cfg *Config, headroom int) ([]byte, error) {
if headroom < 0 {
headroom = 0
}
if cfg == nil {
cfg = &Config{Quality: 75, Method: 4, NearLossless: 100}
}
n := w * h
argb := getU32(n)
defer putU32(argb)
// The conversion also finds what encodeARGB would otherwise scan the
// image for: fully transparent pixels and the palette.
hasAlpha, transparent := false, false
var colors colorSet
for y := 0; y < h; y++ {
// rowAt may convert a picture of another type (the one-shot encode
// of package encoder), which takes a few hundred milliseconds for a
// 12 MP *image.YCbCr on a loaded machine: Interrupt is polled every
// 16 rows, as the lossy encoder polls once per macroblock row, and
// once more after the last row, so that a canceled encode does not
// first finish the conversion.
if y%16 == 0 && cfg.Interrupt != nil && cfg.Interrupt() {
return nil, ErrInterrupted
}
src := rowAt(y)
dst := argb[y*w : (y+1)*w]
a, t := nrgbaRow(dst, src, cfg.Exact)
hasAlpha = hasAlpha || a
transparent = transparent || t
colors.add(dst) // (a no-op past 256 colors)
}
if cfg.Interrupt != nil && cfg.Interrupt() {
return nil, ErrInterrupted
}
var palBuf [maxPaletteSize]uint32
info := imageInfo{known: true, transparent: transparent, opaque: !hasAlpha, palette: colors.palette(palBuf[:0])}
out, _ := encodeARGB(argb, w, h, cfg, true, headroom+5, nil, nil, &info)
if cfg.Interrupt != nil && cfg.Interrupt() {
return nil, ErrInterrupted
}
hdr := out[headroom : headroom+5]
hdr[0] = vp8lSignature
v := uint32(w-1) | uint32(h-1)<<14
if hasAlpha {
v |= 1 << 28
}
hdr[1] = byte(v)
hdr[2] = byte(v >> 8)
hdr[3] = byte(v >> 16)
hdr[4] = byte(v >> 24)
return out, nil
}
// nrgbaRowGo converts the NRGBA pixels of src (4 bytes each, at least
// 4*len(dst) bytes) to ARGB into dst, with the fully transparent pixels
// zeroed unless exact, and reports whether a pixel is not opaque and
// whether one is fully transparent. It is the Go reference of nrgbaRow
// (dsp_write_amd64.go, dsp_arm64.go, dsp_generic.go).
func nrgbaRowGo(dst []uint32, src []byte, exact bool) (hasAlpha, transparent bool) {
src = src[:4*len(dst)]
for x := range dst {
s := src[4*x : 4*x+4 : 4*x+4]
a := uint32(s[3])
if a != 0xff {
hasAlpha = true
if a == 0 {
transparent = true
if !exact {
dst[x] = 0
continue
}
}
}
dst[x] = a<<24 | uint32(s[0])<<16 | uint32(s[1])<<8 | uint32(s[2])
}
return hasAlpha, transparent
}
// EncodeAlpha encodes an alpha plane as an ALPH compression-method-1 stream:
// a headerless VP8L image stream whose green channel carries the alpha values.
// method (0..6) and quality (0..100) map like libwebp's alpha encoder: the
// lossless quality is 8*method, or 100 when method is 6 and quality is 100.
// As in libwebp 1.6 (whose VP8LEncodeStream no longer has a use_cache
// argument), the color cache may be used.
func EncodeAlpha(plane []byte, width, height, stride int, method int, quality float32) ([]byte, error) {
var a AlphaEncoder
defer a.Release()
return a.Encode(plane, width, height, stride, method, quality)
}
// AlphaEncoder encodes several alpha planes (typically the candidate
// filterings of one image) with one set of working buffers, so that only
// the first plane pays for allocating them. The zero value is ready to use;
// Release must be called when done. An AlphaEncoder is not safe for
// concurrent use: concurrent encodes need one AlphaEncoder each (and hold
// one working set each).
type AlphaEncoder struct {
sc *scratch
argb []uint32
spare []byte // output buffer for the next encodeStream
// Interrupt is Config.Interrupt for Encode.
Interrupt func() bool
// ThreadLevel is Config.ThreadLevel for Encode: the match search, the
// predictor search and the histogram remap of large planes are split
// among helpers, and at the brute-force level (method 6, quality 100)
// two candidate configurations are encoded at a time. The output does
// not depend on it.
ThreadLevel bool
// PairGate and StageGate, if not nil, are called (with ThreadLevel)
// before a helper goroutine would be started, on top of the budget
// check: PairGate for the second candidate configuration in flight,
// StageGate for the helpers of the parallel stages. When the gate
// returns false the helper is not started: the configurations try
// again each time the encode starts one, and a stage held back runs
// its sequential version. They let the alpha plane of a lossy encode
// leave the budget to the VP8 frame coded alongside. They must be safe
// for concurrent use.
PairGate, StageGate func() bool
}
// Encode is EncodeAlpha using the encoder's buffers.
func (a *AlphaEncoder) Encode(plane []byte, width, height, stride int, method int, quality float32) ([]byte, error) {
if width < 1 || height < 1 || width > maxDim || height > maxDim {
return nil, errDimensions
}
if stride < width || len(plane) < (height-1)*stride+width {
return nil, errPlane
}
method = clampInt(method, 0, 6)
q := float32(8 * method)
if method == 6 && quality >= 100 {
q = 100
}
n := width * height
if cap(a.argb) < n {
putU32(a.argb)
a.argb = getU32(n)
}
argb := a.argb[:n]
// Like libwebp's WebPDispatchAlphaToGreen, the alpha, red and blue
// channels are left to 0 (the alpha channel is not transmitted). The
// plane has at most 256 values: its palette is collected on the way.
var seen [256]bool
for y := 0; y < height; y++ {
row := plane[y*stride : y*stride+width]
dst := argb[y*width : (y+1)*width]
for x, a := range row {
dst[x] = uint32(a) << 8
seen[a] = true
}
}
var palBuf [maxPaletteSize]uint32
info := imageInfo{known: true, palette: palBuf[:0]}
for v, ok := range seen {
if ok {
info.palette = append(info.palette, uint32(v)<<8)
}
}
if a.sc == nil {
a.sc = getScratch(n)
}
cfg := &Config{Quality: q, Method: method, Exact: true, NearLossless: 100, ThreadLevel: a.ThreadLevel, Interrupt: a.Interrupt, pairGate: a.PairGate, stageGate: a.StageGate}
out, spare := encodeARGB(argb, width, height, cfg, true, 0, a.sc, a.spare, &info)
a.spare = spare
if cfg.Interrupt != nil && cfg.Interrupt() {
a.Recycle(out)
return nil, ErrInterrupted
}
return out, nil
}
// Recycle hands a stream returned by Encode back to the encoder once the
// caller is done with it (e.g. after copying it, or when another filter
// candidate won), so that the next Encode writes into it instead of
// allocating a new output buffer.
func (a *AlphaEncoder) Recycle(b []byte) {
if cap(b) > cap(a.spare) {
a.spare = b[:0]
}
}
// Release returns the encoder's buffers to the pools (large ones are left
// to the garbage collector). The encoder may be reused afterwards.
func (a *AlphaEncoder) Release() {
if a.sc != nil {
putScratch(a.sc)
a.sc = nil
}
if a.argb != nil {
putU32(a.argb)
a.argb = nil
}
a.spare = nil
}
// clampBits clamps histogram and transform bits (libwebp ClampBits): bits
// is raised until the sub-image has at most imageSizeMax pixels, then
// lowered to the smallest value still giving a 1-pixel sub-image.
func clampBits(width, height, bits, minBits, maxBits, imageSizeMax int) int {
bits = clampInt(bits, minBits, maxBits)
size := subSampleSize(width, bits) * subSampleSize(height, bits)
for bits < maxBits && size > imageSizeMax {
bits++
size = subSampleSize(width, bits) * subSampleSize(height, bits)
}
for bits > minBits && size == 1 {
size = subSampleSize(width, bits-1) * subSampleSize(height, bits-1)
if size != 1 {
break
}
bits--
}
return bits
}
func getHistoBits(method int, usePalette bool, width, height int) int {
hb := 7 - method
if usePalette {
hb = 9 - method
}
return clampBits(width, height, hb, minHuffmanBits, maxHuffmanBits, maxHuffImageSize)
}
func getTransformBits(method, histoBits int) int {
m := 5
if method < 4 {
m = 6
} else if method > 4 {
m = 4
}
if histoBits > m {
return m
}
return histoBits
}
// imageInfo is what the caller of encodeARGB found out about the image
// while converting it, saving encodeARGB a scan of its own.
type imageInfo struct {
known bool // the fields below are set
transparent bool // some pixel is fully transparent (alpha 0)
opaque bool // every pixel has alpha 0xff
palette []uint32 // the sorted distinct colors, nil if more than 256
}
// encodeARGB encodes argb (which may be modified: the caller must not use
// it afterwards) and
// returns a freshly allocated slice holding prefix zero bytes followed by the
// image stream. sc, if not nil, is the scratch to use (owned by the caller);
// otherwise one is taken from the pool.
//
// spare, if not nil, is an output buffer that may be reused (see
// encodeStream). Besides the smallest stream, encodeARGB returns a buffer of
// a losing candidate (or spare itself if unused), which the caller may pass
// as spare to a later call.
func encodeARGB(argb []uint32, w, h int, cfg *Config, useCache bool, prefix int, sc *scratch, spare []byte, info *imageInfo) (best, spareOut []byte) {
quality, method := normalize(cfg)
p := params{
quality: quality,
method: method,
lowEffort: method == 0,
useCache: useCache,
parallel: cfg.ThreadLevel && !cfg.LowMemory,
interrupt: cfg.Interrupt,
}
if p.parallel {
p.pairGate, p.stageGate = cfg.pairGate, cfg.stageGate
}
n := w * h
var palette []uint32
if info != nil && info.known {
p.cleanTransparent = !cfg.Exact && info.transparent
p.opaque = info.opaque
palette = info.palette
} else {
p.opaque = true
for _, c := range argb[:n] {
if c < 0xff000000 {
p.opaque = false
if c < 0x01000000 && !cfg.Exact {
p.cleanTransparent = true
break
}
}
}
var palBuf [maxPaletteSize]uint32
palette = collectPalette(argb[:n], palBuf[:0])
}
if cfg.LowMemory {
p.windowCap = 1 << 16
}
usePalette := palette != nil
p.nearLossless = clampInt(cfg.NearLossless, 0, 100)
p.histoBits = getHistoBits(method, usePalette, w, h)
p.transBits = getTransformBits(method, p.histoBits)
var configs []crunchConfig
if p.lowEffort {
if usePalette {
configs = append(configs, crunchConfig{modePalette, sortDefault})
} else {
configs = append(configs, crunchConfig{modeSpatialSubGreen, sortDefault})
}
p.rbZero = true
} else {
best, rbZero := analyzeEntropy(argb[:n], w, h, usePalette, len(palette), p.transBits)
p.rbZero = rbZero
if method == 6 && quality == 100 {
p.tryNoCache = true
for m := 0; m < numEntropyModes; m++ {
if m == modePalette || m == modePaletteAndSpatial {
if usePalette {
configs = append(configs, crunchConfig{m, sortDefault}, crunchConfig{m, sortMinimizeDelta})
}
continue
}
configs = append(configs, crunchConfig{m, sortDefault})
}
// As in libwebp 1.6, rbZero (from the analysis of the guessed
// best mode) also applies to the brute-force configurations.
} else {
configs = append(configs, crunchConfig{best, sortMinimizeDelta})
if quality >= 75 && method == 5 {
p.tryNoCache = true
if best == modePalette {
configs = append(configs, crunchConfig{modePaletteAndSpatial, sortMinimizeDelta})
}
} else if cfg.ImageHint == 3 && best == modePalette && method >= 4 {
configs = append(configs, crunchConfig{modePaletteAndSpatial, sortMinimizeDelta})
}
}
}
if cfg.LowMemory {
p.tryNoCache = false
}
// Like libwebp, images with few colors also try the box LZ77 parse
// (which needs a second match table: skipped with LowMemory).
p.tryBox = !p.lowEffort && !cfg.LowMemory && usePalette && len(palette) <= 16
if usePalette {
p.paletteSorts[sortDefault] = palette
p.paletteSorts[sortMinimizeDelta] = paletteSortMinimizeDeltas(palette, make([]uint32, 0, len(palette)))
}
if sc == nil {
sc = getScratch(n)
defer putScratch(sc)
}
// The helpers of the parallel stages end with the encode (before the
// scratch goes back to its pool).
defer sc.crew.stop()
if len(configs) == 1 {
// argb is private to the caller and not needed afterwards: let the
// transforms work in place (libwebp also transforms the picture's
// argb in place).
return encodeStream(argb[:n], true, w, h, &p, configs[0], prefix, sc, spare), nil
}
return encodeConfigs(argb[:n], w, h, &p, configs, prefix, sc, spare, p.configHelpersFor(n))
}
// hashPix approximates palette entropy with a multiplicative hash.
func hashPix(pix uint32) uint32 {
return uint32(((uint64(pix) + uint64(pix>>19)) * 0x39c5fba7) & 0xffffffff >> 24)
}
const (
hAlpha = iota
hRed
hGreen
hBlue
hAlphaPred
hRedPred
hGreenPred
hBluePred
hRedSubGreen
hBlueSubGreen
hRedPredSubGreen
hBluePredSubGreen
hPalette
hTotal
)
// analyzeEntropy guesses the best entropy mode (libwebp AnalyzeEntropy).
func analyzeEntropy(argb []uint32, w, h int, usePalette bool, paletteSize, transBits int) (int, bool) {
if usePalette && paletteSize <= 16 {
return modePalette, true
}
histo := getU32(hTotal * 256)
defer putU32(histo)
for i := range histo {
histo[i] = 0
}
var hh [hTotal][]uint32
for i := range hh {
hh[i] = histo[i*256 : (i+1)*256 : (i+1)*256]
}
pixPrev := argb[0]
for y := 0; y < h; y++ {
cur := argb[y*w : (y+1)*w]
var prevRow []uint32
if y > 0 {
prevRow = argb[(y-1)*w : y*w]
}
for x, pix := range cur {
diff := subPixels(pix, pixPrev)
pixPrev = pix
if diff == 0 || (prevRow != nil && pix == prevRow[x]) {
continue
}
hh[hAlpha][pix>>24]++
hh[hRed][(pix>>16)&0xff]++
hh[hGreen][(pix>>8)&0xff]++
hh[hBlue][pix&0xff]++
hh[hAlphaPred][diff>>24]++
hh[hRedPred][(diff>>16)&0xff]++
hh[hGreenPred][(diff>>8)&0xff]++
hh[hBluePred][diff&0xff]++
g := pix >> 8
hh[hRedSubGreen][((pix>>16)-g)&0xff]++
hh[hBlueSubGreen][(pix-g)&0xff]++
dg := diff >> 8
hh[hRedPredSubGreen][((diff>>16)-dg)&0xff]++
hh[hBluePredSubGreen][(diff-dg)&0xff]++
hh[hPalette][hashPix(pix)]++
}
}
hh[hRedPredSubGreen][0]++
hh[hBluePredSubGreen][0]++
hh[hRedPred][0]++
hh[hGreenPred][0]++
hh[hBluePred][0]++
hh[hAlphaPred][0]++
var ec [hTotal]float64
for i := range ec {
ec[i] = bitsEntropy(hh[i])
}
var e [modePalette + 1]float64
e[modeDirect] = ec[hAlpha] + ec[hRed] + ec[hGreen] + ec[hBlue]
e[modeSpatial] = ec[hAlphaPred] + ec[hRedPred] + ec[hGreenPred] + ec[hBluePred]
e[modeSubGreen] = ec[hAlpha] + ec[hRedSubGreen] + ec[hGreen] + ec[hBlueSubGreen]
e[modeSpatialSubGreen] = ec[hAlphaPred] + ec[hRedPredSubGreen] + ec[hGreenPred] + ec[hBluePredSubGreen]
e[modePalette] = ec[hPalette]
tiles := float64(subSampleSize(w, transBits) * subSampleSize(h, transBits))
e[modeSpatial] += tiles * math.Log2(14)
e[modeSpatialSubGreen] += tiles * math.Log2(24)
e[modePalette] += float64(paletteSize * 8)
last := modeSpatialSubGreen
if usePalette {
last = modePalette
}
best := modeDirect
for k := modeDirect + 1; k <= last; k++ {
if e[best] > e[k] {
best = k
}
}
pairs := [5][2]int{{hRed, hBlue}, {hRedPred, hBluePred}, {hRedSubGreen, hBlueSubGreen},
{hRedPredSubGreen, hBluePredSubGreen}, {hRed, hBlue}}
rb := true
r, bl := hh[pairs[best][0]], hh[pairs[best][1]]
for i := 1; i < 256; i++ {
if r[i]|bl[i] != 0 {
rb = false
break
}
}
return best, rb
}
// streamHeadroom is the initial output capacity of a stream (beyond the
// prefix): room for the transforms and their sub-images.
const streamHeadroom = 16 << 10
// encodeStream encodes src with one crunch configuration and returns a
// byte slice with prefix zero bytes followed by the image stream (with one
// spare byte of capacity for a RIFF padding byte). The stream is written
// into buf if its capacity is at least prefix+streamHeadroom (growing it
// when needed), else into a new buffer. src is modified only if mutable is
// set.
func encodeStream(src []uint32, mutable bool, w, h int, p *params, cc crunchConfig, prefix int, sc *scratch, buf []byte) []byte {
sc.noteSize(w * h)
sc.interrupt = p.interrupt
sc.crew.gate = p.stageGate
// The output is written straight into the returned buffer (no final
// copy). It is first sized for the transforms (small sub-images), then
// grown once to the size estimate of the main image before writing it
// (encodeImageInternal).
if need := prefix + streamHeadroom; cap(buf) >= need {
buf = buf[:prefix]
clear(buf)
} else {
buf = make([]byte, prefix, need)
}
if p.interrupted() {
return buf
}
bw := &bitWriter{buf: buf}
usePalette := cc.entropy == modePalette || cc.entropy == modePaletteAndSpatial
useSubGreen := cc.entropy == modeSubGreen || cc.entropy == modeSpatialSubGreen
usePredict := cc.entropy == modeSpatial || cc.entropy == modeSpatialSubGreen || cc.entropy == modePaletteAndSpatial
useCrossColor := !p.lowEffort && !usePalette && usePredict && !p.rbZero
quality := p.quality
width := w
var cur []uint32
refsCap := -1 // initRefsCap of the main image, when known
cacheBitsMax := 0
if p.useCache {
cacheBitsMax = maxColorCacheBits
}
if usePalette {
pal := p.paletteSorts[cc.paletteSort]
xbits := paletteXBits(len(pal))
width = subSampleSize(w, xbits)
if mutable {
// In place: row y is read entirely before the (at most as wide)
// bundled row y is written at y*width <= y*w, so no row is
// overwritten before it has been read.
cur = src[:width*h]
} else {
cur = sc.curBuf(width * h)
}
refsCap = applyPalette(src, w, h, pal, cur, sc.idx(w))
// Write the palette transform.
bw.putBits(1, 1)
bw.putBits(colorIndexingTransform, 2)
bw.putBits(uint32(len(pal)-1), 8)
delta := make([]uint32, len(pal))
delta[0] = pal[0]
for i := 1; i < len(pal); i++ {
delta[i] = subPixels(pal[i], pal[i-1])
}
encodeImageNoHuffman(bw, delta, len(pal), 1, 20, p.lowEffort, sc.child())
if p.useCache && len(pal) < 1<<maxColorCacheBits {
cacheBitsMax = log2Floor(uint32(len(pal))) + 1
}
} else if mutable {
cur = src
} else {
cur = sc.curBuf(len(src))
copy(cur, src)
}
if !usePalette && !usePredict && p.nearLossless < 100 {
applyNearLossless(width, h, p.nearLossless, cur)
}
if useSubGreen {
subtractGreen(cur)
bw.putBits(1, 1)
bw.putBits(subtractGreenTransform, 2)
}
if usePredict {
// As in libwebp 1.6 (ApplyPredictFilter), methods 5 and 6 also
// search smaller predictor tiles.
maxBits := clampBits(width, h, p.transBits, minTransformBits, maxTransformBits, maxPredictorImageSize)
minBits := clampBits(width, h, maxBits-2*max(p.method-4, 0), minTransformBits, maxTransformBits, maxPredictorImageSize)
modes := make([]uint32, subSampleSize(width, minBits)*subSampleSize(h, minBits))
maxQuant := 1
if !usePalette && p.nearLossless < 100 {
maxQuant = 1 << uint(nearLosslessBits(p.nearLossless))
}
// (Palette indices are opaque.)
opaque := p.opaque || usePalette
bits := predictorImage(width, h, minBits, maxBits, p.lowEffort, maxQuant, useSubGreen, p.cleanTransparent, opaque, cur, modes, sc,
p.stageHelpers(width*h))
tw, th := subSampleSize(width, bits), subSampleSize(h, bits)
bw.putBits(1, 1)
bw.putBits(predictorTransform, 2)
bw.putBits(uint32(bits-minTransformBits), 3)
encodeImageNoHuffman(bw, modes[:tw*th], tw, th, quality, p.lowEffort, sc.child())
if p.interrupted() {
return bw.buf
}
}
if useCrossColor {
bits := p.transBits
img := make([]uint32, subSampleSize(width, bits)*subSampleSize(h, bits))
bits = colorSpaceTransform(width, h, bits, quality, cur, img, sc)
tw, th := subSampleSize(width, bits), subSampleSize(h, bits)
bw.putBits(1, 1)
bw.putBits(crossColorTransform, 2)
bw.putBits(uint32(bits-minTransformBits), 3)
encodeImageNoHuffman(bw, img[:tw*th], tw, th, quality, p.lowEffort, sc.child())
if p.interrupted() {
return bw.buf
}
}
bw.putBits(0, 1) // no more transforms
if usePredict {
refsCap = -1 // cur is now the residual image
}
encodeImageInternal(bw, cur, width, h, p, cacheBitsMax, refsCap, sc)
out := bw.finish()
if len(out) == cap(out) {
out = append(out, 0)[:len(out)] // room for a RIFF padding byte
}
return out
}
// refsCandidate is one backward reference parse with its cache size.
type refsCandidate struct {
refs []pixOrCopy
cacheBits int
// bits estimates the coded size of the parse with a single histogram
// (see histoCost); the clustered meta-Huffman coding is usually
// smaller.
bits float64
}
// histoCost estimates the size of a parse. With raw set, distances are
// counted as linear distances like libwebp does when it compares candidate
// parses (see addRefsRawDist); this decides, as in libwebp, whether the
// cost-based parse is tried. Otherwise they are counted as the plane codes
// actually written, a better estimate used when no cost-based parse
// follows.
func histoCost(refs []pixOrCopy, xsize, cacheBits int, raw bool, sc *scratch) float64 {
h := sc.tmpHisto(cacheBits)
if raw {
sc.tmpSet.addRefsRawDist(h, refs)
} else {
sc.tmpSet.addRefs(h, refs, xsize)
}
return sc.tmpSet.estimate(h)
}
// Parse types (libwebp VP8LLZ77Type).
const (
lz77Standard = 1
lz77RLE = 2
lz77Box = 4
)
// getBackwardRefs computes the best references for argb, like libwebp 1.6's
// VP8LGetBackwardReferences (except for lowEffort, see below), from the
// matches of sc.hc (which the caller fills). With box, only the "box" LZ77
// parse (matches restricted to short 2D distances) is tried, otherwise the
// standard LZ77 and RLE ones. It returns the best parse with its color
// cache size and, when tryNoCache is set and that cache size is not 0, the
// best parse without color cache (searched separately).
func getBackwardRefs(argb []uint32, w, h int, quality int, lowEffort, box bool, cacheBitsMax int,
tryNoCache bool, refsCap int, sc *scratch, cands []refsCandidate) []refsCandidate {
n := w * h
if refsCap < 0 {
refsCap = initRefsCap(argb, w, h)
}
types := []int{lz77Standard, lz77RLE}
if box {
types = []int{lz77Box}
sc.hcBox.fillBox(argb, w, n, &sc.hc, sc)
}
// Unlike libwebp, the low effort mode also tries the RLE parse and a
// color cache (but not the cost-based parse): the low-effort hash chain
// does not find runs, and this keeps method 0 output much smaller than
// libwebp's for a small cost.
cacheBuf := sc.cacheBuf(1 << maxColorCacheBits)
trace := quality >= 25 && !lowEffort
if !tryNoCache {
return append(cands[:0], bestRefs(argb, w, n, quality, types, trace, cacheBitsMax, refsCap, cacheBuf, sc))
}
// sc.refs slots: best[0] with cache, best[1] without (tryNoCache), tmp.
best := [2]int{0, 1}
tmp := 2
bestCost := [2]float64{math.Inf(1), math.Inf(1)}
bestType := [2]int{0, 0}
bestCB := 0
for _, typ := range types {
var r []pixOrCopy
switch typ {
case lz77Standard:
r = backwardRefsLz77(n, argb, &sc.hc, sc.refsBuf(tmp, refsCap))
case lz77RLE:
r = backwardRefsRle(w, n, argb, sc.refsBuf(tmp, refsCap))
default:
r = backwardRefsLz77(n, argb, &sc.hcBox, sc.refsBuf(tmp, refsCap))
}
sc.refs[tmp] = r
var noCacheCost float64
if tryNoCache {
noCacheCost = histoCost(r, w, 0, trace, sc)
if noCacheCost < bestCost[1] {
sc.refs[best[1]] = append(sc.refsBuf(best[1], len(r)), r...)
bestCost[1] = noCacheCost
bestType[1] = typ
}
}
cb := bestCacheBits(argb, quality, r, cacheBitsMax, sc)
var cost float64
if tryNoCache && cb == 0 {
cost = noCacheCost
} else {
applyColorCache(argb, cb, r, cacheBuf)
cost = histoCost(r, w, cb, trace, sc)
}
if cost < bestCost[0] {
best[0], tmp = tmp, best[0]
bestCost[0] = cost
bestType[0] = typ
bestCB = cb
}
}
// Improve on the simple LZ77 with the cost-based parse (only for high
// quality, as it is costly).
for i := 1; i >= 0; i-- {
if i == 1 && !tryNoCache {
continue
}
cb := 0
if i == 0 {
cb = bestCB
}
if (bestType[i] == lz77Standard || bestType[i] == lz77Box) && trace {
hc := &sc.hc
if bestType[i] == lz77Box {
hc = &sc.hcBox
}
r := traceBackwards(w, n, argb, cb, hc, sc.refs[best[i]], sc.refsBuf(tmp, 0), sc)
applyColorCache(argb, cb, r, cacheBuf)
sc.refs[tmp] = r
if c := histoCost(r, w, cb, true, sc); c < bestCost[i] {
best[i], tmp = tmp, best[i]
}
}
if i == 1 && bestType[0] == bestType[1] && bestCB == 0 {
// Same parse type without cache: use the no-cache result.
sc.refs[best[0]] = append(sc.refsBuf(best[0], len(sc.refs[best[1]])), sc.refs[best[1]]...)
break
}
}
// (A cost-based parse only replaces a candidate when cheaper, so
// bestCost bounds the estimate of the returned parses.)
cands = append(cands[:0], refsCandidate{sc.refs[best[0]], bestCB, bestCost[0]})
if tryNoCache && bestCB > 0 {
cands = append(cands, refsCandidate{sc.refs[best[1]], 0, bestCost[1]})
}
return cands
}
// parseRefs computes the parse of type typ of argb into refs.
func parseRefs(typ, w, n int, argb []uint32, sc *scratch, refs []pixOrCopy) []pixOrCopy {
switch typ {
case lz77Standard:
return backwardRefsLz77(n, argb, &sc.hc, refs)
case lz77RLE:
return backwardRefsRle(w, n, argb, refs)
}
return backwardRefsLz77(n, argb, &sc.hcBox, refs)
}
// sparseRefs: a parse estimated at no more than one entry per sparseRefs
// pixels is sparse (see bestRefs).
const sparseRefs = 8
// bestRefs is getBackwardRefs without tryNoCache. A dense parse (a photo:
// up to one entry, 8 bytes, per pixel) is kept in a single buffer
// (sc.refs[0]): every parse type is evaluated in the same buffer, and the
// best one is computed again (the parses are deterministic) when a later
// candidate has overwritten it. Usually it has not: the last candidate
// (the RLE parse, which the residuals of a photo favor), or the cost-based
// parse, wins. A sparse parse (graphics: at most one entry per sparseRefs
// pixels, estimated) costs little memory but as much to recompute (a pass
// over all the pixels): the best one so far keeps its buffer (sc.refs[0] or
// sc.refs[1]) and the next candidate goes to the other one.
func bestRefs(argb []uint32, w, n, quality int, types []int, trace bool, cacheBitsMax, refsCap int, cacheBuf []uint32, sc *scratch) refsCandidate {
if refsCap < n && slices.Contains(types, lz77RLE) {
// The buffer holds the RLE parse in turn, often the longest one:
// size it for that parse too, rather than growing it during the
// parse (a copy, with both buffers alive).
e := rleRefsEstimate(argb, w, n/w)
refsCap = max(refsCap, min(n, e+e/8+4096))
}
sparse := refsCap <= n/sparseRefs
var bufs [2][]pixOrCopy
var inBuf [2]int // parse type in bufs[k] (0: none)
cur, best := 0, 0
buf := func(k int) []pixOrCopy {
if bufs[k] == nil {
bufs[k] = sc.refsBuf(k, refsCap)
}
return bufs[k]
}
bestCost := math.Inf(1)
bestType, bestCB := 0, 0
for _, typ := range types {
r := parseRefs(typ, w, n, argb, sc, buf(cur))
bufs[cur], inBuf[cur] = r, typ
cb := bestCacheBits(argb, quality, r, cacheBitsMax, sc)
applyColorCache(argb, cb, r, cacheBuf)
cost := histoCost(r, w, cb, trace, sc)
if cost < bestCost || bestType == 0 {
bestCost, bestType, bestCB = cost, typ, cb
best = cur
}
if sparse {
cur = 1 - best
}
}
redo := func(r []pixOrCopy) []pixOrCopy {
r = parseRefs(bestType, w, n, argb, sc, r)
applyColorCache(argb, bestCB, r, cacheBuf)
return r
}
r := bufs[best]
if inBuf[best] != bestType {
r = redo(r)
}
// Improve on the simple LZ77 with the cost-based parse (only for high
// quality, as it is costly).
if (bestType == lz77Standard || bestType == lz77Box) && trace {
hc := &sc.hc
if bestType == lz77Box {
hc = &sc.hcBox
}
// traceBackwards reads its input parse only before it writes its
// output: both can share the buffer of a dense parse.
out := r[:0]
if sparse {
out = buf(1 - best)[:0]
}
t := traceBackwards(w, n, argb, bestCB, hc, r, out, sc)
applyColorCache(argb, bestCB, t, cacheBuf)
switch {
case histoCost(t, w, bestCB, true, sc) < bestCost:
if sparse {
bufs[1-best] = t
best = 1 - best
}
r = t
case sparse:
bufs[1-best] = t // (keeps its capacity)
default:
r = redo(t)
}
bufs[best] = r
}
for k := range bufs {
if bufs[k] != nil {
sc.refs[k] = bufs[k]
}
}
// (A cost-based parse only replaces a candidate when cheaper, so
// bestCost bounds the estimate of the returned parse.)
return refsCandidate{r, bestCB, bestCost}
}
// encodeImageNoHuffman encodes a sub-image (transform data, entropy image or
// palette) without color cache and meta Huffman codes. As in libwebp,
// lowEffort only affects the match search (hash chain).
func encodeImageNoHuffman(bw *bitWriter, argb []uint32, w, h int, quality int, lowEffort bool, sc *scratch) {
n := w * h
sc.hc.fill(argb, w, h, quality, lowEffort, 0)
refsCap := initRefsCap(argb, w, h)
r0 := backwardRefsLz77(n, argb, &sc.hc, sc.refsBuf(0, refsCap))
sc.refs[0] = r0
r1 := backwardRefsRle(w, n, argb, sc.refsBuf(1, refsCap))
sc.refs[1] = r1
best := r0
trace := quality >= 25
bestCost := histoCost(r0, w, 0, trace, sc)
if c := histoCost(r1, w, 0, trace, sc); c < bestCost {
best, bestCost = r1, c
} else if trace {
r2 := traceBackwards(w, n, argb, 0, &sc.hc, r0, sc.refsBuf(2, 0), sc)
sc.refs[2] = r2
if c := histoCost(r2, w, 0, true, sc); c < bestCost {
best = r2
}
}
sc.out.init(1, 0)
sc.out.addRefs(&sc.out.h[0], best, w)
bw.putBits(0, 1) // no color cache
codes := buildCodes(&sc.out, sc)
for i := range codes {
sc.huff.storeHuffmanCode(bw, &codes[i])
clearIfOneSymbol(&codes[i])
}
writeImageData(bw, w, best, 0, nil, codes)
}
// buildCodes creates the 5 Huffman codes of every histogram in s.
func buildCodes(s *histoSet, sc *scratch) []huffCode {
ng := len(s.h)
per := s.litLen + 3*256 + numDistanceCodes
total := ng * per
if cap(sc.lens) < total {
sc.lens = make([]uint8, total)
sc.codes = make([]uint16, total)
}
lens := sc.lens[:total]
codes := sc.codes[:total]
if cap(sc.hcodes) < 5*ng {
sc.hcodes = make([]huffCode, 5*ng)
}
hc := sc.hcodes[:5*ng]
sizes := [5]int{s.litLen, 256, 256, 256, numDistanceCodes}
for g := 0; g < ng; g++ {
d := s.h[g].d
off := g * per
hoff := 0
for k := 0; k < 5; k++ {
sz := sizes[k]
c := &hc[5*g+k]
c.lengths = lens[off : off+sz]
c.codes = codes[off : off+sz]
sc.huff.createHuffmanTree(d[hoff:hoff+sz], 15, c)
off += sz
hoff += sz
}
}
return hc
}
// encodeImageInternal encodes the main (transformed) image with color cache
// and meta Huffman codes, choosing the smallest of the candidate parses.
// Like libwebp, images with at most 16 colors also try the "box" LZ77
// parse.
func encodeImageInternal(bw *bitWriter, argb []uint32, w, h int, p *params, cacheBitsMax, refsCap int, sc *scratch) {
if refsCap < 0 {
refsCap = initRefsCap(argb, w, h)
}
sc.hc.fillPar(argb, w, h, p.quality, p.lowEffort, p.windowCap, p.stageHelpers(w*h), sc)
if p.interrupted() {
return
}
var candBuf [2]refsCandidate
cands := getBackwardRefs(argb, w, h, p.quality, p.lowEffort, false, cacheBitsMax, p.tryNoCache, refsCap, sc, candBuf[:0])
if p.interrupted() {
return
}
if len(cands) == 1 && !p.tryBox {
bw.reserve(mainImageReserve(cands[0].bits))
writeMainImage(bw, w, h, p, cands[0], sc)
return
}
// Write each candidate into the spare writer, keeping the smallest.
bestIdx := -1
try := func(c refsCandidate) {
i := 0
if bestIdx == 0 {
i = 1
}
t := &sc.bwTmp[i]
t.reset()
writeMainImage(t, w, h, p, c, sc)
if bestIdx < 0 || t.numBits() < sc.bwTmp[bestIdx].numBits() {
bestIdx = i
}
}
for _, c := range cands {
try(c)
}
if p.tryBox && !p.interrupted() {
cands = getBackwardRefs(argb, w, h, p.quality, p.lowEffort, true, cacheBitsMax, p.tryNoCache, refsCap, sc, candBuf[:0])
for _, c := range cands {
try(c)
}
}
// Exact size (plus a RIFF padding byte).
bw.reserve(len(sc.bwTmp[bestIdx].buf) + 9)
bw.appendWriter(&sc.bwTmp[bestIdx])
}
// mainImageReserve returns the number of bytes to reserve in the output for
// the main image of a parse whose single-histogram size estimate is bits:
// the estimate plus a 1/8 margin. The clustered stream is usually 0-30%
// smaller than the estimate, up to 8% larger for low-effort encodes of
// images with transparency; when it does not fit, the writer grows by
// append.
func mainImageReserve(bits float64) int {
b := bits / 8
if !(b < 1<<30) { // also NaN
b = 1 << 30
}
return int(b+b/8) + 4096
}
func writeMainImage(bw *bitWriter, w, h int, p *params, c refsCandidate, sc *scratch) {
if c.cacheBits > 0 {
bw.putBits(1, 1)
bw.putBits(uint32(c.cacheBits), 4)
} else {
bw.putBits(0, 1)
}
hb := p.histoBits
sc.clus.interrupt, sc.clus.crew = p.interrupt, &sc.crew
ng := sc.clus.buildHistoImage(w, h, c.refs, p.quality, p.lowEffort, hb, c.cacheBits, &sc.out, p.remapHelpers())
sc.clus.interrupt, sc.clus.crew = nil, nil
if p.interrupted() {
return
}
var symbols []uint16
if ng > 1 {
// Reduce the sampling of the entropy image if it is made of uniform
// squares (libwebp 1.6 VP8LOptimizeSampling).
syms := sc.clus.symbols
hb = optimizeSampling(syms, w, h, hb, maxHuffmanBits)
syms = syms[:subSampleSize(w, hb)*subSampleSize(h, hb)]
bw.putBits(1, 1)
bw.putBits(uint32(hb-2), 3)
img := make([]uint32, len(syms))
for i, s := range syms {
img[i] = uint32(s) << 8
}
encodeImageNoHuffman(bw, img, subSampleSize(w, hb), subSampleSize(h, hb), p.quality, p.lowEffort, sc.child())
symbols = syms
} else {
bw.putBits(0, 1)
}
codes := buildCodes(&sc.out, sc)
for i := range codes {
sc.huff.storeHuffmanCode(bw, &codes[i])
clearIfOneSymbol(&codes[i])
}
if ng > 1 {
writeImageData(bw, w, c.refs, hb, symbols, codes)
} else {
writeImageData(bw, w, c.refs, 0, nil, codes)
}
}
// imgWriter is the state of the writeImageData kernels (dsp_write_amd64.go,
// dsp_arm64.go): the bit writer, the position in the image and the current
// tile and its codes (g, the 5 codes of the tile's histogram group), with
// the image constants.
type imgWriter struct {
buf *byte // the bit writer's buffer, from its start
pos, limit int // its length; no reference is written past limit
acc, nbits uint64
x, y int
tileX, tileY int
g *huffCode
w, hb int
tileMask int
hx int
symbols *uint16
nsym int
codes *huffCode
ngroups int
len0, len4 int // the entries every group has in its codes 0 and 4
err int
}
// writeImageDataGo writes the entropy-coded pixels. It is the Go reference
// of writeImageData (dsp_write_amd64.go, dsp_arm64.go, dsp_generic.go).
func writeImageDataGo(bw *bitWriter, w int, refs []pixOrCopy, histoBits int, symbols []uint16, codes []huffCode) {
x, y := 0, 0
tileMask := 0
hx := 0
if symbols != nil {
tileMask = ^((1 << uint(histoBits)) - 1)
hx = subSampleSize(w, histoBits)
}
tileX, tileY := -1, -1
g := codes[0:5]
if symbols == nil {
tileX, tileY = 0, 0
}
for _, r := range refs {
if symbols != nil && (x&tileMask != tileX || y&tileMask != tileY) {
tileX = x & tileMask
tileY = y & tileMask
ix := int(symbols[(y>>uint(histoBits))*hx+(x>>uint(histoBits))])
g = codes[5*ix : 5*ix+5]
}
l := 1
switch r.mode() {
case modeLiteral:
a := r.val
gr := (a >> 8) & 0xff
rd := (a >> 16) & 0xff
bl := a & 0xff
al := a >> 24
c0, c1, c2, c3 := &g[0], &g[1], &g[2], &g[3]
n0, n1 := uint(c0.lengths[gr]), uint(c1.lengths[rd])
bw.putBits(uint32(c0.codes[gr])|uint32(c1.codes[rd])<<n0, n0+n1)
n2, n3 := uint(c2.lengths[bl]), uint(c3.lengths[al])
bw.putBits(uint32(c2.codes[bl])|uint32(c3.codes[al])<<n2, n2+n3)
case modeCache:
s := numLiteralCodes + numLengthCodes + r.val
bw.putBits(uint32(g[0].codes[s]), uint(g[0].lengths[s]))
default:
l = r.length()
code, nb, extra := prefixEncode(l)
s := numLiteralCodes + code
bw.putBits(uint32(g[0].codes[s]), uint(g[0].lengths[s]))
bw.putBits(uint32(extra), uint(nb))
dcode, dnb, dextra := prefixEncode(distanceToPlaneCode(w, int(r.val)))
bw.putBits(uint32(g[4].codes[dcode]), uint(g[4].lengths[dcode]))
bw.putBits(uint32(dextra), uint(dnb))
}
x += l
for x >= w {
x -= w
y++
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import (
"math"
"math/bits"
)
// Entropy estimation helpers. Algorithm adapted from libwebp (BSD-3-Clause).
const logTabSize = 4096
var (
slog2Tab [logTabSize]float64 // v*log2(v)
log2Tab [logTabSize]float64 // log2(v), log2(0) = 0
)
func init() {
for i := 1; i < logTabSize; i++ {
f := float64(i)
log2Tab[i] = math.Log2(f)
slog2Tab[i] = f * log2Tab[i]
}
}
// slog2 returns v*log2(v).
func slog2(v uint32) float64 {
if v < logTabSize {
return slog2Tab[v]
}
return slog2Slow(v)
}
// log2Slow approximates log2(v) for v >= logTabSize from the table using the
// 12 most significant bits plus a linear correction of the remainder.
func log2Slow(v uint32) float64 {
shift := uint(bits.Len32(v) - 12)
m := v >> shift
rem := v & (1<<shift - 1)
// log2(m + r) ~= log2(m) + r/(m*ln2)
return log2Tab[m] + float64(shift) + float64(rem)/(float64(m)*math.Ln2*float64(uint32(1)<<shift))
}
func slog2Slow(v uint32) float64 {
return float64(v) * log2Slow(v)
}
type bitEntropy struct {
entropy float64
sum uint32
nonzeros int
maxVal uint32
}
type streaks struct {
counts [2]int // [zero/nonzero] number of streaks longer than 3
streaks [2][2]int // [zero/nonzero][short/long] total streak length
}
// refine returns the refined bit entropy estimate (libwebp BitsEntropyRefine).
func (e *bitEntropy) refine() float64 {
var mix float64
if e.nonzeros < 5 {
if e.nonzeros <= 1 {
return 0
}
if e.nonzeros == 2 {
return 0.99*float64(e.sum) + 0.01*e.entropy
}
if e.nonzeros == 3 {
mix = 0.95
} else {
mix = 0.7
}
} else {
mix = 0.627
}
minLimit := 2*float64(e.sum) - float64(e.maxVal)
minLimit = mix*minLimit + (1-mix)*e.entropy
if e.entropy < minLimit {
return minLimit
}
return e.entropy
}
// finalHuffmanCost estimates the cost of storing a Huffman code from its
// streak statistics.
func (s *streaks) finalHuffmanCost() float64 {
r := float64(codeLengthCodes*3) - 9.1
r += float64(s.counts[0])*1.5625 + 0.234375*float64(s.streaks[0][1])
r += float64(s.counts[1])*2.578125 + 0.703125*float64(s.streaks[1][1])
r += 1.796875 * float64(s.streaks[0][0])
r += 3.28125 * float64(s.streaks[1][0])
return r
}
// popStats are the streak statistics of combinedPopulationCostGo, as the
// kernels of dsp_amd64.go and dsp_arm64.go compute them.
type popStats struct {
e bitEntropy
s streaks
}
// bitsEntropy returns the refined Shannon entropy of a population.
func bitsEntropy(pop []uint32) float64 {
var e bitEntropy
for _, v := range pop {
if v != 0 {
e.sum += v
e.nonzeros++
e.entropy -= slog2(v)
if v > e.maxVal {
e.maxVal = v
}
}
}
e.entropy += slog2(e.sum)
return e.refine()
}
// populationCostGo estimates the number of bits to code pop with a Huffman
// code, including the cost of storing the code itself. It is the Go
// reference of populationCost (dsp_amd64.go, dsp_arm64.go, dsp_generic.go),
// and combinedPopulationCostGo with a zero second operand.
func populationCostGo(pop []uint32) float64 {
var e bitEntropy
var s streaks
n := len(pop)
if n == 0 {
return 0
}
prev := pop[0]
iPrev := 0
for i := 1; i <= n; i++ {
var v uint32
if i < n {
v = pop[i]
if v == prev {
continue
}
}
streak := i - iPrev
nz := 0
if prev != 0 {
nz = 1
e.sum += prev * uint32(streak)
e.nonzeros += streak
e.entropy -= slog2(prev) * float64(streak)
if e.maxVal < prev {
e.maxVal = prev
}
}
long := 0
if streak > 3 {
long = 1
}
s.counts[nz] += long
s.streaks[nz][long] += streak
prev = v
iPrev = i
}
e.entropy += slog2(e.sum)
return e.refine() + s.finalHuffmanCost()
}
// combinedPopulationCostGo is populationCost(a+b) without materializing
// a+b. It is the Go reference of combinedPopulationCost (dsp_amd64.go,
// dsp_arm64.go, dsp_generic.go).
func combinedPopulationCostGo(a, b []uint32) float64 {
var e bitEntropy
var s streaks
n := len(a)
if n == 0 {
return 0
}
b = b[:n]
prev := a[0] + b[0]
iPrev := 0
for i := 1; i <= n; i++ {
var v uint32
if i < n {
v = a[i] + b[i]
if v == prev {
continue
}
}
streak := i - iPrev
nz := 0
if prev != 0 {
nz = 1
e.sum += prev * uint32(streak)
e.nonzeros += streak
e.entropy -= slog2(prev) * float64(streak)
if e.maxVal < prev {
e.maxVal = prev
}
}
long := 0
if streak > 3 {
long = 1
}
s.counts[nz] += long
s.streaks[nz][long] += streak
prev = v
iPrev = i
}
e.entropy += slog2(e.sum)
return e.refine() + s.finalHuffmanCost()
}
// extraCost returns the number of extra bits implied by a prefix-code
// population of the given length.
func extraCost(pop []uint32) float64 {
var cost uint64
for i := 4; i < len(pop); i++ {
cost += uint64((i-2)>>1) * uint64(pop[i])
}
return float64(cost)
}
// accEntropy caches per-bin x*log2(x) of an accumulated histogram, so that
// combinedShannonEntropy only needs to visit the non-zero bins of the other
// operand.
type accEntropy struct {
s [256]float64
total float64
sum uint32
}
// initGo sets a to the entropy terms of h. It is the Go reference of init
// (dsp_amd64.go, dsp_arm64.go, dsp_generic.go).
func (a *accEntropy) initGo(h *[256]int32) {
a.total = 0
a.sum = 0
for i, v := range h {
f := slog2(uint32(v))
a.s[i] = f
a.total += f
a.sum += uint32(v)
}
}
// combinedShannonEntropyGo returns the entropy of X plus the entropy of X+Y
// (libwebp VP8LCombinedShannonEntropy), where Y is described by acc. It is
// the Go reference of combinedShannonEntropy (dsp_amd64.go, dsp_arm64.go,
// dsp_generic.go).
func combinedShannonEntropyGo(x, y *[256]int32, acc *accEntropy) float64 {
r := -acc.total
var sumX uint32
for i := 0; i < 256; i++ {
xv := uint32(x[i])
if xv != 0 {
sumX += xv
r += acc.s[i] - slog2(xv) - slog2(xv+uint32(y[i]))
}
}
return r + slog2(sumX) + slog2(sumX+acc.sum)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import (
"math"
"math/bits"
)
// Fixed-point entropy helpers matching libwebp 1.6 (src/dsp/lossless_enc.c,
// BSD-3-Clause), so that cost comparisons resolve ties like libwebp does.
const (
log2PrecisionBits = 23
log2Reciprocal = 12102203 // round((1 << log2PrecisionBits) / ln(2))
// log2ReciprocalDouble is (1 << log2PrecisionBits) / ln(2).
log2ReciprocalDouble = 12102203.161561485379934310913085937500
approxLogMax = 4096
approxLogCorrMax = 65536
)
// fastLog2 returns log2(v) in fixed point (libwebp VP8LFastLog2).
func fastLog2(v uint32) uint32 {
if v < 256 {
return kLog2Table[v]
}
if v < approxLogCorrMax {
logCnt := uint32(bits.Len32(v)) - 1 - 7
y := uint32(1) << logCnt
r := kLog2Table[v>>logCnt] + logCnt<<log2PrecisionBits
if v >= approxLogMax {
corr := uint64(log2Reciprocal) * uint64(v&(y-1))
r += uint32(divRound(int64(corr), int64(v)))
}
return r
}
return uint32(log2ReciprocalDouble*math.Log(float64(v)) + .5)
}
// fastSLog2 returns v*log2(v) in fixed point (libwebp VP8LFastSLog2).
func fastSLog2(v uint32) uint64 {
if v < 256 {
return kSLog2Table[v]
}
if v < approxLogCorrMax {
logCnt := uint32(bits.Len32(v)) - 1 - 7
y := uint32(1) << logCnt
corr := uint64(log2Reciprocal) * uint64(v&(y-1))
return uint64(v)*(uint64(kLog2Table[v>>logCnt])+uint64(logCnt)<<log2PrecisionBits) + corr
}
return uint64(log2ReciprocalDouble*float64(v)*math.Log(float64(v)) + .5)
}
// divRound is libwebp's DivRound: a/b rounded half away from zero.
func divRound(a, b int64) int64 {
if (a < 0) == (b < 0) {
return (a + b/2) / b
}
return (a - b/2) / b
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import (
"reflect"
"github.com/kolesa-team/go-webp/v2/internal/bufpool"
)
// Reuse of the large working buffers between encodes.
//
// The scratch of an encode (10-40 bytes per pixel) and the ARGB copy of the
// image are kept between encodes in a list and a pool of internal/bufpool,
// under the process-wide budget of retained bytes shared with the rest of
// the codec (256 MiB by default, an eighth of the Go memory limit when that
// is lower). A sync.Pool alone loses them: it drops its objects at every
// other garbage collection, which the encodes themselves trigger, and it
// cannot hold the buffers of large images without leaving hundreds of MB to
// the next collection (it used to keep nothing above 2 MP).
//
// Keeping the working set of a large encode matters beyond the allocations
// it saves: the garbage collector paces itself on the heap it found live,
// which during a large encode is mostly its working set, so encodes that
// allocate their working set anew, back to back, can reach about twice the
// peak memory of one encode before a collection reclaims the previous ones.
//
// - A scratch is kept as a whole (with all its buffers) while the budget
// allows; scratches that do not fit still go to a sync.Pool if they
// served at most 2 MP, as before.
// - getScratch takes the most recently returned scratch that was not
// sized for a much larger image, so that small encodes do not hold the
// buffers a large one could reuse.
// - Objects unused for 15 s are dropped at the next garbage collection.
//
// Objects are taken and returned by the goroutine that uses them.
var (
scratchFree bufpool.List[*scratch]
u32Pool bufpool.Pool[uint32]
)
// sliceBytes returns the bytes of the backing array of s.
func sliceBytes[T any](s []T) int64 {
return int64(cap(s)) * int64(reflect.TypeFor[T]().Size())
}
// bytes returns (approximately: buffers below 1 KB are left out) the
// memory retained by the buffers of s.
func (s *scratch) bytes() int64 {
if s == nil {
return 0
}
n := sliceBytes(s.hc.ol) + sliceBytes(s.hcBox.ol) + sliceBytes(s.counts) +
sliceBytes(s.cm.lit) + sliceBytes(s.costMgr.cacheIv) + sliceBytes(s.costMgr.costCache) +
sliceBytes(s.tmpSet.data) + sliceBytes(s.tmpSet.h) +
sliceBytes(s.clus.orig.data) + sliceBytes(s.clus.orig.h) + sliceBytes(s.clus.symbols) +
sliceBytes(s.clus.mapping) + sliceBytes(s.clus.queue.q) + sliceBytes(s.clus.set) +
sliceBytes(s.clus.owned) + sliceBytes(s.clus.freeOwned) +
sliceBytes(s.out.data) + sliceBytes(s.out.h) +
sliceBytes(s.lens) + sliceBytes(s.codes) + sliceBytes(s.hcodes) +
sliceBytes(s.ccost) + sliceBytes(s.u16buf) + sliceBytes(s.cache) + sliceBytes(s.u32abuf) +
sliceBytes(s.resid) + sliceBytes(s.curbuf) + sliceBytes(s.rowa) + sliceBytes(s.rowb) +
sliceBytes(s.idxRow) + sliceBytes(s.md) + sliceBytes(s.predMode) + sliceBytes(s.predHist) +
sliceBytes(s.predAccH) + sliceBytes(s.predBatch) + sliceBytes(s.predWork) +
sliceBytes(s.hcChain) + sliceBytes(s.hcMarks) + sliceBytes(s.hcExits) +
sliceBytes(s.tile.pg) + sliceBytes(s.tile.pr) + sliceBytes(s.tile.pc) +
sliceBytes(s.tile.tg) + sliceBytes(s.tile.tr) + sliceBytes(s.tile.tb) + sliceBytes(s.tile.tc) +
sliceBytes(s.bwTmp[0].buf) + sliceBytes(s.bwTmp[1].buf)
for i := range s.refs {
n += sliceBytes(s.refs[i])
}
for _, h := range s.clus.owned {
n += sliceBytes(h.d)
}
for i := range s.predWork {
w := &s.predWork[i]
n += sliceBytes(w.resid) + sliceBytes(w.rowCur) + sliceBytes(w.rowUp)
}
if s.costRing != nil {
n += int64(reflect.TypeFor[[costRing]int64]().Size())
}
if s.tile.tabs != nil {
n += int64(reflect.TypeFor[ccTables]().Size())
}
return n + int64(reflect.TypeFor[scratch]().Size()) + s.sub.bytes()
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import "sync"
// Hash chain based longest-match search.
// Algorithm adapted from libwebp (BSD-3-Clause).
const (
hashBits = 18
hashSize = 1 << hashBits
)
var hashTablePool = sync.Pool{New: func() any { t := make([]int32, hashSize); return &t }}
// hashChain stores, for every pixel, the best match as dist<<12 | length.
type hashChain struct {
ol []uint32
}
func maxItersForQuality(quality int) int {
return 8 + quality*quality/128
}
func windowSizeForHashChain(quality, xsize int) int {
var w int
switch {
case quality > 75:
w = windowSize
case quality > 50:
w = xsize << 8
case quality > 25:
w = xsize << 6
default:
w = xsize << 4
}
if w > windowSize {
w = windowSize
}
return w
}
func pixPairHash(a0, a1 uint32) uint32 {
key := a1 * 0xc6a4a793
key += a0 * 0x5bd1e996
return key >> (32 - hashBits)
}
// vectorMismatch returns the length of the common prefix of a and b, at most max.
func vectorMismatch(a, b []uint32, max int) int {
a = a[:max]
b = b[:max]
i := 0
for i+2 <= max {
if a[i] != b[i] {
return i
}
if a[i+1] != b[i+1] {
return i + 1
}
i += 2
}
if i < max && a[i] == b[i] {
i++
}
return i
}
// findMatchLength is vectorMismatch with a quick reject on the bestLen pixel.
func findMatchLength(a, b []uint32, bestLen, max int) int {
if a[bestLen] != b[bestLen] {
return 0
}
return vectorMismatch(a, b, max)
}
// fill computes the best match (distance, length) for every pixel.
func (hc *hashChain) fill(argb []uint32, xsize, ysize, quality int, lowEffort bool, windowCap int) {
hc.fillPar(argb, xsize, ysize, quality, lowEffort, windowCap, 0, nil)
}
// fillPar is fill, with the match search spread over the caller and up to
// helpers helper goroutines when helpers > 0 (see fillStripes); sc then
// provides the extra buffers.
func (hc *hashChain) fillPar(argb []uint32, xsize, ysize, quality int, lowEffort bool, windowCap int, helpers int, sc *scratch) {
size := xsize * ysize
if cap(hc.ol) < size {
hc.ol = make([]uint32, size)
}
ol := hc.ol[:size]
hc.ol = ol
if size <= 2 {
ol[0] = 0
ol[size-1] = 0
return
}
argb = argb[:size]
window := windowSizeForHashChain(quality, xsize)
if windowCap > 0 && window > windowCap {
window = windowCap
}
s := hcSearcher{argb: argb, ol: ol, xsize: xsize, size: size,
iterMax: maxItersForQuality(quality), window: window, lowEffort: lowEffort}
if helpers > 0 {
// The chain must stay intact while the stripes write ol.
s.chain = sc.hcChainBuf(size)
buildChain(argb, s.chain)
ol[0] = 0
ol[size-1] = 0
s.fillStripes(helpers, sc)
return
}
s.chain = ol // reused as int32 chain storage
buildChain(argb, s.chain)
ol[0] = 0
ol[size-1] = 0
// The searches go from the end to the start; each one writes the
// results of the positions it covers (at and below it), so the chain
// entries it reads (below it) are still intact.
s.run(size-2, 0, 1, nil)
}
// buildChain links every position of argb (but the last) to the previous
// position with the same hash of its pixel pair (or of the color and run
// length in runs), as int32 (-1: none) in chain.
func buildChain(argb []uint32, chain []uint32) {
size := len(argb)
tp := hashTablePool.Get().(*[]int32)
// first[h] is 1 + the last position with hash h (0: none), so that the
// table is reset by clear, a memclr (a -1 fill loop took 9% of a level
// 0 encode of a 875x348 graphic).
first := *tp
clear(first)
argbComp := argb[0] == argb[1]
pos := 0
for pos < size-2 {
argbCompNext := argb[pos+1] == argb[pos+2]
if argbComp && argbCompNext {
// Run of identical pixels: hash the color with the run length.
length := 1
c := argb[pos]
for pos+length+2 < size && argb[pos+length+2] == c {
length++
}
if length > maxLength {
for k := 0; k < length-maxLength; k++ {
chain[pos+k] = 0xffffffff
}
pos += length - maxLength
length = maxLength
}
for length > 0 {
h := pixPairHash(c, uint32(length))
length--
chain[pos] = uint32(first[h] - 1)
first[h] = int32(pos + 1)
pos++
}
argbComp = false
} else {
h := pixPairHash(argb[pos], argb[pos+1])
chain[pos] = uint32(first[h] - 1)
first[h] = int32(pos + 1)
pos++
argbComp = argbCompNext
}
}
chain[pos] = uint32(first[pixPairHash(argb[pos], argb[pos+1])] - 1)
hashTablePool.Put(tp)
}
// hcSearcher holds the state of the match search of hashChain.fill.
type hcSearcher struct {
argb []uint32
chain []uint32 // int32 links (buildChain)
ol []uint32
xsize, size int
iterMax, window int
lowEffort bool
}
// run is the search loop of fill: it searches the best match at hi, writes
// it, extended to the left as far as possible, into ol, and repeats from the
// next position while it is at least stop. Positions below lo are never
// written: an extension stops there. When marks is not nil, every searched
// position is marked in it. run returns the last position searched and the
// next position (below stop).
//
// The position following a search only depends on the searched position,
// so the searches form a chain from size-2 down to 0 (see fillStripes).
// (One loop for all uses: a call per search costs the sequential path
// 7-19%.)
//
// runGo is the Go reference of run (dsp_amd64.go, dsp_arm64.go,
// dsp_generic.go). It needs 1 <= stop and hi <= size-2.
func (s *hcSearcher) runGo(hi, lo, stop int, marks []uint64) (last, next int) {
argb, chain, ol := s.argb, s.chain, s.ol
xsize, size, window, iterMax, lowEffort := s.xsize, s.size, s.window, s.iterMax, s.lowEffort
base := hi
for base >= stop {
var bestLen, bestDist int
{
maxLen := size - 1 - base
if maxLen > maxLength {
maxLen = maxLength
}
start := argb[base:]
iter := iterMax
minPos := 0
if base > window {
minPos = base - window
}
lengthMax := maxLen
if lengthMax > 256 {
lengthMax = 256
}
p := int(int32(chain[base]))
if !lowEffort {
if base >= xsize {
l := findMatchLength(argb[base-xsize:], start, bestLen, maxLen)
if l > bestLen {
bestLen = l
bestDist = xsize
}
iter--
}
l := findMatchLength(argb[base-1:], start, bestLen, maxLen)
if l > bestLen {
bestLen = l
bestDist = 1
}
iter--
if bestLen == maxLength {
p = minPos - 1
}
}
bestArgb := start[bestLen]
for ; p >= minPos; p = int(int32(chain[p])) {
iter--
if iter <= 0 {
break
}
if argb[p+bestLen] != bestArgb {
continue
}
l := vectorMismatch(argb[p:], start, maxLen)
if bestLen < l {
bestLen = l
bestDist = base - p
bestArgb = start[bestLen]
if bestLen >= lengthMax {
break
}
}
}
if marks != nil {
marks[base>>6] |= 1 << uint(base&63)
}
}
last = base
// Extend the match to the left as far as possible.
maxBase := base
for {
ol[base] = uint32(bestDist)<<maxLengthBits | uint32(bestLen)
base--
if bestDist == 0 || base == 0 || base < lo {
break
}
if base < bestDist || argb[base-bestDist] != argb[base] {
break
}
if bestLen == maxLength && bestDist != 1 && base+maxLength < maxBase {
break
}
if bestLen < maxLength {
bestLen++
maxBase = base
}
}
}
return last, base
}
// minHCStripe is the smallest stripe of fillStripes, in positions (a
// multiple of 64; a variable for the tests).
var minHCStripe = 1 << 16
// fillStripes is the search loop of fill, run speculatively in stripes.
//
// The sequential search visits a chain of positions, from size-2 down: each
// search at base writes the positions from base down to the next search
// position, which only depends on base. Each stripe of positions starts
// such a chain at its top, writing only within the stripe and recording
// the positions it searched. The chain of a stripe does not start where
// the true chain enters it, but as soon as the true chain hits a position
// the stripe searched, both coincide below it (and the positions at or
// below a position are only written by searches at or below it). So a
// sequential fix-up follows the true chain from the top: it searches
// positions itself until it hits a position its stripe searched, then
// jumps to that stripe's exit search, whose extension (into the stripes
// below) it replays. In practice the chains meet within a few searches, so
// the fix-up is short, and the result is identical to fill's.
func (s *hcSearcher) fillStripes(helpers int, sc *scratch) {
size := s.size
workers := helpers + 1
// Stripes of a multiple of 64 positions (the searched-position bitmap
// words are not shared), at least minHCStripe, a few per worker for
// balance.
per := (size + 4*workers - 1) / (4 * workers)
per = max((per+63)&^63, minHCStripe)
stripes := (size-2)/per + 1 // stripe k covers [k*per, (k+1)*per) within [1, size-2]
marks := sc.hcMarkBuf((size + 63) / 64)
exits := sc.hcExitBuf(stripes)
sc.crew.run(stripes, helpers, func(worker int, claim func() (int, bool)) {
for {
k, ok := claim()
if !ok || sc.interrupted() {
return
}
k = stripes - 1 - k // top stripes first: the fix-up starts there
lo := max(k*per, 1)
exits[k], _ = s.run(min((k+1)*per-1, size-2), lo, lo, marks)
}
})
sc.crew.stop() // (no helpers held through the sequential parse that follows)
if sc.interrupted() {
// Some stripes may not have run: the matches are garbage, and the
// caller (encodeImageInternal) stops right after the fill.
return
}
// Fix-up, from the top: every position above t is final.
for t := size - 2; t > 0; {
if marks[t>>6]&(1<<uint(t&63)) != 0 {
// The stripe's chain from t is the true one: its results are
// final down to its exit, whose search is redone, with its
// extension in full.
e := exits[t/per]
_, t = s.run(e, 0, e, nil)
continue
}
_, t = s.run(t, 0, t, nil)
}
}
func (hc *hashChain) findLength(pos int) int { return int(hc.ol[pos] & (1<<maxLengthBits - 1)) }
func (hc *hashChain) findOffset(pos int) int { return int(hc.ol[pos] >> maxLengthBits) }
// windowOffsetsMax bounds the 2D distances considered by the box parse.
const windowOffsetsMax = 32
// fillBox computes, for every pixel, the longest match among the short 2D
// distances only (the 32 first plane codes), using best (the regular hash
// chain) to skip pixels that already have a maximal match at such a
// distance. Port of libwebp's BackwardReferencesLz77Box.
func (hc *hashChain) fillBox(argb []uint32, xsize, n int, best *hashChain, sc *scratch) {
if cap(hc.ol) < n {
hc.ol = make([]uint32, n)
}
ol := hc.ol[:n]
hc.ol = ol
argb = argb[:n]
if cap(sc.counts) < n {
sc.counts = make([]uint16, n)
}
counts := sc.counts[:n]
// counts[i] is how many times argb[i] repeats from i (at most maxLength).
counts[n-1] = 1
for i := n - 2; i >= 0; i-- {
if argb[i] == argb[i+1] {
c := counts[i+1]
if c != maxLength {
c++
}
counts[i] = c
} else {
counts[i] = 1
}
}
// The window offsets around a pixel, in plane code order, and those
// that reach pixels unreachable from the previous pixel.
var offsets, offsetsNew [windowOffsetsMax]int
for y := 0; y <= 6; y++ {
for x := -6; x <= 6; x++ {
off := y*xsize + x
if off <= 0 {
continue
}
code := distanceToPlaneCode(xsize, off) - 1
if code >= windowOffsetsMax {
continue
}
offsets[code] = off
}
}
nOff := 0
for _, o := range offsets {
if o != 0 {
offsets[nOff] = o
nOff++
}
}
nNew := 0
for i := 0; i < nOff; i++ {
reachable := false
for j := 0; j < nOff && !reachable; j++ {
reachable = offsets[i] == offsets[j]+1
}
if !reachable {
offsetsNew[nNew] = offsets[i]
nNew++
}
}
ol[0] = 0
bestOffsetPrev, bestLengthPrev := -1, -1
for i := 1; i < n; i++ {
bestLength := best.findLength(i)
var bestOffset int
compute := true
if bestLength >= maxLength {
// Keep a maximal match already in the window.
bestOffset = best.findOffset(i)
for _, o := range offsets[:nOff] {
if bestOffset == o {
compute = false
break
}
}
}
if compute {
// Start from the previous pixel's match (shortened by one), then
// only look at the offsets it could not reach.
usePrev := bestLengthPrev > 1 && bestLengthPrev < maxLength
offs := offsets[:nOff]
bestLength, bestOffset = 0, 0
if usePrev {
offs = offsetsNew[:nNew]
bestLength, bestOffset = bestLengthPrev-1, bestOffsetPrev
}
for _, o := range offs {
jOff := i - o
if jOff < 0 || argb[jOff] != argb[i] {
continue
}
// The match length is the sum of the repetition counts.
cur := 0
j := i
for {
cOff, cj := int(counts[jOff]), int(counts[j])
if cOff != cj {
cur += min(cOff, cj)
break
}
cur += cOff
jOff += cOff
j += cOff
if !(cur <= maxLength && j < n && argb[jOff] == argb[j]) {
break
}
}
if bestLength < cur {
bestOffset = o
if cur >= maxLength {
bestLength = maxLength
break
}
bestLength = cur
}
}
}
if bestLength <= minLength {
ol[i] = 0
bestOffsetPrev, bestLengthPrev = 0, 0
} else {
ol[i] = uint32(bestOffset)<<maxLengthBits | uint32(bestLength)
bestOffsetPrev, bestLengthPrev = bestOffset, bestLength
}
}
ol[0] = 0
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import "math"
// Histograms and histogram clustering for meta-Huffman codes.
// Algorithm adapted from libwebp (BSD-3-Clause).
// histo is a view on a flat population array laid out as
// literal[litLen] | red[256] | blue[256] | alpha[256] | dist[40].
type histo struct {
d []uint32
// Clustering state (libwebp VP8LHistogram): bitCost is the sum of the
// population costs of the 5 codes (without the extra bits), costs the
// cost of each code, trivial the single symbol of a code (or
// nonTrivialSym) and isUsed whether a code has any symbol. As in
// libwebp, trivial and isUsed are propagated (not recomputed) when
// histograms are merged.
bitCost float64
costs [5]float64
trivial [5]int32
isUsed [5]bool
binID int
used bool // the histogram is not empty
// shared marks a tile histogram of the clusterer (clusterer.orig) used
// as is in the working set: its populations and costs must not change
// (the working set copies it on write, see clusterer.mergeInto).
shared bool
}
// nonTrivialSym marks a code with zero or several symbols.
const nonTrivialSym = -1
// histoSet owns the storage of several histograms of the same layout.
type histoSet struct {
litLen int
stride int
data []uint32
h []histo
// quad holds the 4 partial histograms of the addRefs kernels
// (dsp_write_amd64.go, dsp_arm64.go; unused elsewhere).
quad []uint32
}
func literalLen(cacheBits int) int {
n := numLiteralCodes + numLengthCodes
if cacheBits > 0 {
n += 1 << uint(cacheBits)
}
return n
}
// init prepares the set for n histograms with the given cache bits.
func (s *histoSet) init(n, cacheBits int) {
s.litLen = literalLen(cacheBits)
s.stride = s.litLen + 3*256 + numDistanceCodes
total := n * s.stride
if cap(s.data) < total {
s.data = make([]uint32, total)
} else {
s.data = s.data[:total]
for i := range s.data {
s.data[i] = 0
}
}
if cap(s.h) < n {
s.h = make([]histo, n)
}
s.h = s.h[:n]
for i := range s.h {
s.h[i] = histo{d: s.data[i*s.stride : (i+1)*s.stride : (i+1)*s.stride], used: true}
}
}
func (s *histoSet) clear(h *histo) {
for i := range h.d {
h.d[i] = 0
}
}
// addRef adds one reference to h.
func (s *histoSet) addRef(d []uint32, r pixOrCopy, xsize int) {
L := s.litLen
switch r.mode() {
case modeLiteral:
p := r.val
d[(p>>8)&0xff]++
d[L+int((p>>16)&0xff)]++
d[L+256+int(p&0xff)]++
d[L+512+int(p>>24)]++
case modeCache:
d[numLiteralCodes+numLengthCodes+int(r.val)]++
default:
d[numLiteralCodes+prefixCode(r.length())]++
d[L+768+prefixCode(distanceToPlaneCode(xsize, int(r.val)))]++
}
}
// addRefsRawDistGo is addRefsGo with the distances coded as linear
// distances instead of plane codes. libwebp compares candidate parses with
// such histograms (VP8LHistogramCreate in GetBackwardReferences, before
// BackwardReferences2DLocality), which favours short linear distances. It
// is the Go reference of addRefsRawDist (dsp_write_amd64.go,
// dsp_arm64.go, dsp_generic.go).
func (s *histoSet) addRefsRawDistGo(h *histo, refs []pixOrCopy) {
d := h.d
L := s.litLen
for _, r := range refs {
if r.mode() == modeCopy {
d[numLiteralCodes+prefixCode(r.length())]++
d[L+768+prefixCode(int(r.val))]++
continue
}
s.addRef(d, r, 0)
}
}
// addRefsGo adds the references refs of an image xsize pixels wide to h.
// It is the Go reference of addRefs (dsp_write_amd64.go, dsp_arm64.go,
// dsp_generic.go).
func (s *histoSet) addRefsGo(h *histo, refs []pixOrCopy, xsize int) {
d := h.d
for _, r := range refs {
s.addRef(d, r, xsize)
}
}
// addTileRefsGo adds each reference of refs, a parse of an image xsize
// pixels wide, to the histogram of its tile (tiles of 1<<histoBits pixels
// squared, hx per row; histogram i of s is tile i). It is the Go reference
// of addTileRefs (dsp_write_amd64.go, dsp_arm64.go, dsp_generic.go).
func (s *histoSet) addTileRefsGo(refs []pixOrCopy, xsize, histoBits, hx int) {
s.addTileRefsFrom(refs, xsize, histoBits, hx, 0, 0)
}
// addTileRefsFrom is addTileRefsGo for references starting at (x, y).
func (s *histoSet) addTileRefsFrom(refs []pixOrCopy, xsize, histoBits, hx, x, y int) {
for _, r := range refs {
ix := (y>>uint(histoBits))*hx + (x >> uint(histoBits))
s.addRef(s.h[ix].d, r, xsize)
x += r.length()
for x >= xsize {
x -= xsize
y++
}
}
}
// code returns the population of code k (0 literal, 1 red, 2 blue, 3
// alpha, 4 distance) of h.
func (s *histoSet) code(h *histo, k int) []uint32 {
L := s.litLen
switch k {
case 0:
return h.d[:L]
case 4:
return h.d[L+768 : L+808]
}
return h.d[L+256*(k-1) : L+256*k]
}
// estimate returns the estimated number of bits to code h, including the
// extra bits of lengths and distances (libwebp VP8LHistogramEstimateBits).
func (s *histoSet) estimate(h *histo) float64 {
L := s.litLen
d := h.d
return populationCost(d[:L]) + populationCost(d[L:L+256]) + populationCost(d[L+256:L+512]) +
populationCost(d[L+512:L+768]) +
populationCost(d[L+768:L+808]) +
extraCost(d[numLiteralCodes:numLiteralCodes+numLengthCodes]) +
extraCost(d[L+768:L+808])
}
// computeCost sets the clustering state of h from its populations (libwebp
// ComputeHistogramCost).
func (s *histoSet) computeCost(h *histo) {
h.bitCost = 0
for k := 0; k < 5; k++ {
pop := s.code(h, k)
h.costs[k] = populationCost(pop)
nz, sym := 0, 0
for i, v := range pop {
if v != 0 {
nz++
sym = i
if nz > 1 {
break
}
}
}
h.isUsed[k] = nz > 0
h.trivial[k] = nonTrivialSym
if nz == 1 {
h.trivial[k] = int32(sym)
}
h.bitCost += h.costs[k]
}
}
// combinedCost computes the cost of a+b (without extra bits) into costs and
// returns it, or ok = false if it is not below threshold (libwebp
// GetCombinedHistogramEntropy).
func (s *histoSet) combinedCost(a, b *histo, threshold float64, costs *[5]float64) (cost float64, ok bool) {
if threshold <= 0 {
return 0, false
}
for k := 0; k < 5; k++ {
var c float64
switch {
case a.trivial[k] != nonTrivialSym && a.trivial[k] == b.trivial[k], !a.isUsed[k] || !b.isUsed[k]:
if a.isUsed[k] {
c = a.costs[k]
} else {
c = b.costs[k]
}
default:
c = combinedPopulationCost(s.code(a, k), s.code(b, k))
}
costs[k] = c
cost += c
if cost >= threshold {
return cost, false
}
}
return cost, true
}
// addHisto sets out = a + b, propagating the clustering state like libwebp's
// HistogramAdd (out may be b).
func addHisto(a, b, out *histo) {
x, y, o := a.d, b.d[:len(a.d)], out.d[:len(a.d)]
for i := range o {
o[i] = x[i] + y[i]
}
for k := 0; k < 5; k++ {
if a.trivial[k] != b.trivial[k] {
out.trivial[k] = nonTrivialSym
} else {
out.trivial[k] = a.trivial[k]
}
out.isUsed[k] = a.isUsed[k] || b.isUsed[k]
}
}
// addInto adds b into a (data only).
func addInto(a, b *histo) {
x := a.d
y := b.d[:len(x)]
for i := range x {
x[i] += y[i]
}
}
// ---- clustering ----
//
// The clustering follows libwebp 1.6 (histogram_enc.c) closely, including the
// order in which histograms are removed from the working set (the last one
// takes the place of the removed one), since it drives the random pair
// selection and the final cluster order.
type histoPair struct {
i1, i2 int
costDiff float64
costCmb float64
costs [5]float64
}
// pairQueue keeps the best (lowest costDiff) pair at index 0.
type pairQueue struct {
q []histoPair
max int
}
func (pq *pairQueue) updateHead(k int) {
if pq.q[k].costDiff < pq.q[0].costDiff {
pq.q[k], pq.q[0] = pq.q[0], pq.q[k]
}
}
func (pq *pairQueue) pop(k int) {
last := len(pq.q) - 1
pq.q[k] = pq.q[last]
pq.q = pq.q[:last]
}
// fixPair replaces bad by good in p.
func fixPair(bad, good int, p *histoPair) {
if p.i1 == bad {
p.i1 = good
}
if p.i2 == bad {
p.i2 = good
}
if p.i1 > p.i2 {
p.i1, p.i2 = p.i2, p.i1
}
}
// updatePair evaluates the merge of h1 and h2 into p; it fails when the
// cost difference is not below threshold.
func updatePair(s *histoSet, h1, h2 *histo, threshold float64, p *histoPair) bool {
sum := h1.bitCost + h2.bitCost
cmb, ok := s.combinedCost(h1, h2, sum+threshold, &p.costs)
if !ok {
return false
}
p.costCmb = cmb
p.costDiff = cmb - sum
return true
}
// push evaluates the pair (i1,i2) and inserts it if merging gains more than
// threshold. Returns the cost difference (0 when not pushed).
func (pq *pairQueue) push(s *histoSet, set []*histo, i1, i2 int, threshold float64) float64 {
if len(pq.q) >= pq.max {
return 0
}
if i1 > i2 {
i1, i2 = i2, i1
}
p := histoPair{i1: i1, i2: i2}
if !updatePair(s, set[i1], set[i2], threshold, &p) {
return 0
}
pq.q = append(pq.q, p)
pq.updateHead(len(pq.q) - 1)
return p.costDiff
}
const numPartitions = 4
const binSize = numPartitions * numPartitions * numPartitions
const maxHistoGreedy = 100
func binID(min, max, v float64) int {
r := max - min
if r > 0 {
return int((numPartitions - 1e-6) * (v - min) / r)
}
return 0
}
// combineCostFactor is libwebp's GetCombineCostFactor, divided by 100.
func combineCostFactor(histoSize, quality int) float64 {
f := 16
if quality < 90 {
if histoSize > 256 {
f /= 2
}
if histoSize > 512 {
f /= 2
}
if histoSize > 1024 {
f /= 2
}
if quality <= 50 {
f /= 2
}
}
return float64(f) / 100
}
type clusterer struct {
orig histoSet // per-tile histograms
symbols []uint16
mapping []int
queue pairQueue
// set[:size] is the working set: the live histograms. It starts with
// the (shared) non-empty tile histograms themselves; a merge writes its
// result into a histogram of owned (copy on write), so that only the
// merged histograms take memory besides the tile histograms.
set []*histo
size int
combo *histo // scratch histogram of the entropy-bin combination
cacheBits int
binFirst [binSize]int
binFail [binSize]int
owned []*histo // working histograms (kept for later calls)
numOwned int // owned[:numOwned] are in use or in free
freeOwned []*histo
// interrupt is Config.Interrupt during buildHistoImage: when it fires,
// the clustering loops stop early (the clustering stays valid).
interrupt func() bool
// crew runs the parallel remap (the crew of the scratch, set during
// buildHistoImage).
crew *crew
}
// newHisto returns an unused working histogram (contents unspecified).
func (c *clusterer) newHisto() *histo {
var h *histo
if k := len(c.freeOwned); k > 0 {
h = c.freeOwned[k-1]
c.freeOwned = c.freeOwned[:k-1]
return h
}
if c.numOwned == len(c.owned) {
c.owned = append(c.owned, new(histo))
}
h = c.owned[c.numOwned]
c.numOwned++
stride := c.orig.stride
if cap(h.d) < stride {
h.d = make([]uint32, stride)
}
h.d = h.d[:stride:stride]
return h
}
// release hands h (no longer in the working set) back to newHisto if it is
// a working histogram.
func (c *clusterer) release(h *histo) {
if !h.shared {
c.freeOwned = append(c.freeOwned, h)
}
}
// mergeInto sets set[i] to set[j] + set[i] (libwebp HistogramAdd(set[j],
// set[i], set[i])), in place unless set[i] is a shared tile histogram.
func (c *clusterer) mergeInto(i, j int) *histo {
dst := c.set[i]
if dst.shared {
dst = c.newHisto()
}
addHisto(c.set[j], c.set[i], dst)
c.set[i] = dst
return dst
}
func (c *clusterer) interrupted() bool { return c.interrupt != nil && c.interrupt() }
// remove removes set[i], replacing it by the last histogram (libwebp
// HistogramSetRemoveHistogram).
func (c *clusterer) remove(i int) {
c.release(c.set[i])
c.set[i] = c.set[c.size-1]
c.size--
}
// minParallelRemap is the smallest remap (tiles times clusters) spread over
// helper goroutines (a variable for the tests).
var minParallelRemap = 1 << 12
// buildHistoImage computes the clustered histograms for refs. It returns the
// final histograms (in out) and fills c.symbols with the tile->histogram map.
// helpers > 0 allows a parallel remap.
func (c *clusterer) buildHistoImage(xsize, ysize int, refs []pixOrCopy, quality int,
lowEffort bool, histoBits, cacheBits int, out *histoSet, helpers int) int {
hx := subSampleSize(xsize, histoBits)
hy := subSampleSize(ysize, histoBits)
nt := hx * hy
c.cacheBits = cacheBits
c.orig.init(nt, cacheBits)
// Build per-tile histograms.
c.orig.addTileRefs(refs, xsize, histoBits, hx)
if cap(c.symbols) < nt {
c.symbols = make([]uint16, nt)
}
c.symbols = c.symbols[:nt]
// Analyze the tile histograms; the non-empty ones form the working set.
numUsed := 0
for i := range c.orig.h {
h := &c.orig.h[i]
c.orig.computeCost(h)
h.used = h.isUsed[0] || h.isUsed[1] || h.isUsed[2] || h.isUsed[3] || h.isUsed[4]
h.shared = true
if h.used {
numUsed++
}
}
if numUsed == 0 {
// Empty image (cannot happen for valid input); single histogram.
out.init(1, cacheBits)
clear(c.symbols)
return 1
}
if cap(c.set) < numUsed {
c.set = make([]*histo, numUsed)
}
c.set = c.set[:numUsed]
k := 0
for i := range c.orig.h {
if o := &c.orig.h[i]; o.used {
c.set[k] = o
k++
}
}
c.size = numUsed
c.numOwned = 0
c.freeOwned = c.freeOwned[:0]
c.combo = c.newHisto()
// The working histograms have the layout of the tile histograms: the
// combination steps use c.orig for it.
s := &c.orig
entropyBins := binSize
if lowEffort {
entropyBins = numPartitions
}
entropyCombine := numUsed > 2*entropyBins && quality < 100
if entropyCombine {
c.entropyBinCombine(s, entropyBins, lowEffort, combineCostFactor(nt, quality))
}
if !lowEffort || !entropyCombine {
thresholdSize := 1 + (quality*quality*quality*(maxHistoGreedy-1)+(100*100*100)/2)/(100*100*100)
if c.stochasticCombine(s, thresholdSize) {
c.greedyCombine(s)
}
}
c.remap(out, helpers)
return len(out.h)
}
// entropyBinCombine merges histograms with similar dominant costs (libwebp
// HistogramAnalyzeEntropyBin and HistogramCombineEntropyBin).
func (c *clusterer) entropyBinCombine(s *histoSet, numBins int, lowEffort bool, factor float64) {
set := c.set
litMin, litMax := math.MaxFloat64, -math.MaxFloat64
redMin, redMax := litMin, litMax
blueMin, blueMax := litMin, litMax
for _, h := range set[:c.size] {
litMin = math.Min(litMin, h.costs[0])
litMax = math.Max(litMax, h.costs[0])
redMin = math.Min(redMin, h.costs[1])
redMax = math.Max(redMax, h.costs[1])
blueMin = math.Min(blueMin, h.costs[2])
blueMax = math.Max(blueMax, h.costs[2])
}
// (binID is scratch state: it is also set on shared histograms.)
for _, h := range set[:c.size] {
b := binID(litMin, litMax, h.costs[0])
if !lowEffort {
b = b*numPartitions + binID(redMin, redMax, h.costs[1])
b = b*numPartitions + binID(blueMin, blueMax, h.costs[2])
}
h.binID = b
}
for i := 0; i < numBins; i++ {
c.binFirst[i] = -1
c.binFail[i] = 0
}
const maxCombineFailures = 32
for idx := 0; idx < c.size; {
h := set[idx]
b := h.binID
first := c.binFirst[b]
if first == -1 {
c.binFirst[b] = idx
idx++
continue
}
f := set[first]
if lowEffort {
c.mergeInto(first, idx)
c.remove(idx)
continue
}
thresh := -h.bitCost * factor
sum := f.bitCost + h.bitCost
combo := c.combo
cmb, ok := s.combinedCost(f, h, sum+thresh, &combo.costs)
if !ok {
idx++
continue
}
addHisto(f, h, combo)
combo.bitCost = cmb
// Merge only if the combination is trivial or both histograms are
// already non-trivial (unless merges keep failing for this bin).
try := combo.trivial[1] != nonTrivialSym && combo.trivial[2] != nonTrivialSym &&
combo.trivial[3] != nonTrivialSym
if !try {
try = (h.trivial[1] == nonTrivialSym || h.trivial[2] == nonTrivialSym || h.trivial[3] == nonTrivialSym) &&
(f.trivial[1] == nonTrivialSym || f.trivial[2] == nonTrivialSym || f.trivial[3] == nonTrivialSym)
}
if try || c.binFail[b] >= maxCombineFailures {
// combo replaces f, which becomes the scratch histogram (unless
// it is shared).
set[first], c.combo = combo, f
if f.shared {
c.combo = c.newHisto()
}
c.remove(idx)
} else {
c.binFail[b]++
idx++
}
}
if lowEffort {
// (The costs of the unmerged, shared histograms are up to date.)
for _, h := range set[:c.size] {
if !h.shared {
s.computeCost(h)
}
}
}
}
// myRand is libwebp's MyRand Lehmer generator.
func myRand(seed *uint32) uint32 {
*seed = uint32(uint64(*seed) * 48271 % 2147483647)
return *seed
}
// stochasticCombine merges random pairs until the number of histograms is
// below minClusterSize. Returns whether a greedy pass should follow.
func (c *clusterer) stochasticCombine(s *histoSet, minClusterSize int) bool {
if c.size < minClusterSize {
return true
}
set := c.set
const queueSize = 9
pq := &c.queue
pq.q = pq.q[:0]
pq.max = queueSize
seed := uint32(1)
outerIters := c.size
numTriesNoSuccess := outerIters / 2
triesNoSuccess := 0
for iter := 0; iter < outerIters && c.size >= minClusterSize && !c.interrupted(); iter++ {
triesNoSuccess++
if triesNoSuccess >= numTriesNoSuccess {
break
}
bestCost := 0.0
if len(pq.q) > 0 {
bestCost = pq.q[0].costDiff
}
randRange := uint32((c.size - 1) * c.size)
numTries := c.size / 2
for j := 0; c.size >= 2 && j < numTries; j++ {
t := myRand(&seed) % randRange
i1 := t / uint32(c.size-1)
i2 := t % uint32(c.size-1)
if i2 >= i1 {
i2++
}
cur := pq.push(s, set, int(i1), int(i2), bestCost)
if cur < 0 {
bestCost = cur
if len(pq.q) == pq.max {
break
}
}
}
if len(pq.q) == 0 {
continue
}
b1, b2 := pq.q[0].i1, pq.q[0].i2
m := c.mergeInto(b1, b2)
m.bitCost = pq.q[0].costCmb
m.costs = pq.q[0].costs
c.remove(b2)
for j := 0; j < len(pq.q); {
p := &pq.q[j]
is1 := p.i1 == b1 || p.i1 == b2
is2 := p.i2 == b1 || p.i2 == b2
if is1 && is2 {
pq.pop(j)
continue
}
if is1 || is2 {
fixPair(b2, b1, p)
if !updatePair(s, set[p.i1], set[p.i2], 0, p) {
pq.pop(j)
continue
}
}
fixPair(c.size, b2, p)
pq.updateHead(j)
j++
}
triesNoSuccess = 0
}
return c.size <= minClusterSize
}
// greedyCombine repeatedly merges the best pair while it reduces the cost.
func (c *clusterer) greedyCombine(s *histoSet) {
set := c.set
n := c.size
pq := &c.queue
pq.q = pq.q[:0]
pq.max = n * n
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
pq.push(s, set, i, j, 0)
}
}
for len(pq.q) > 0 && !c.interrupted() {
i1, i2 := pq.q[0].i1, pq.q[0].i2
m := c.mergeInto(i1, i2)
m.bitCost = pq.q[0].costCmb
m.costs = pq.q[0].costs
c.remove(i2)
for k := 0; k < len(pq.q); {
p := &pq.q[k]
if p.i1 == i1 || p.i2 == i1 || p.i1 == i2 || p.i2 == i2 {
pq.pop(k)
} else {
fixPair(c.size, i2, p)
pq.updateHead(k)
k++
}
}
for k := 0; k < c.size; k++ {
if k == i1 {
continue
}
pq.push(s, set, i1, k, 0)
}
}
}
// remapChunk is the number of tiles per work item of a parallel remap.
const remapChunk = 32
// remap assigns each tile histogram to the best final cluster (libwebp
// HistogramRemap), renumbers the clusters by first use (dropping the
// unused ones) and recomputes the final histograms into out. With helpers
// > 0 and enough work, the assignments (independent per tile) are spread
// over helper goroutines.
func (c *clusterer) remap(out *histoSet, helpers int) {
set := c.set[:c.size]
syms := c.symbols
orig := c.orig.h
if len(set) > 1 {
assign := func(lo, hi int) {
var costs [5]float64
for i := lo; i < hi; i++ {
if !orig[i].used {
continue
}
best := 0
bestBits := math.MaxFloat64
for k, h := range set {
cmb, ok := c.orig.combinedCost(h, &orig[i], h.bitCost+bestBits, &costs)
if ok {
bestBits = cmb - h.bitCost
best = k
}
}
syms[i] = uint16(best)
}
}
// Config.Interrupt is polled once per chunk of remapChunk tiles,
// also on the helpers; an interrupted remap leaves every tile in
// cluster 0 (a valid, if useless, clustering).
chunks := (len(orig) + remapChunk - 1) / remapChunk
if helpers > 0 && c.crew != nil && chunks > 1 && len(orig)*len(set) >= minParallelRemap {
c.crew.run(chunks, helpers, func(_ int, claim func() (int, bool)) {
for {
k, ok := claim()
if !ok || c.interrupted() {
return
}
assign(k*remapChunk, min((k+1)*remapChunk, len(orig)))
}
})
c.crew.stop() // (no helpers held through the entropy coding that follows)
} else {
for k := 0; k < chunks && !c.interrupted(); k++ {
assign(k*remapChunk, min((k+1)*remapChunk, len(orig)))
}
}
if c.interrupted() {
clear(syms)
} else {
// Unused tiles take the cluster of the previous tile.
for i := range orig {
if !orig[i].used {
if i > 0 {
syms[i] = syms[i-1]
} else {
syms[i] = 0
}
}
}
}
} else {
clear(syms)
}
// Renumber by first appearance; drop clusters nobody maps to.
order := c.mapping[:0]
for range set {
order = append(order, -1)
}
n := 0
for i, sym := range syms {
if order[sym] == -1 {
order[sym] = n
n++
}
syms[i] = uint16(order[sym])
}
c.mapping = order
out.init(n, c.cacheBits)
for i := range orig {
if orig[i].used {
addInto(&out.h[syms[i]], &orig[i])
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import "slices"
// Huffman code construction and storage.
// Algorithm adapted from libwebp (BSD-3-Clause).
// huffCode holds code lengths and bit-reversed codes for an alphabet.
type huffCode struct {
lengths []uint8
codes []uint16
}
type huffToken struct {
code uint8 // 0..15 literal length, 16..18 repeat codes
extra uint8
}
// huffScratch holds reusable buffers for Huffman tree construction.
type huffScratch struct {
keys []uint64
weight []uint64
parent []int32
depth []uint8
goodRLE []bool
counts []uint32
tokens []huffToken
}
// optimizeForRLE adjusts population counts so that the resulting code
// lengths compress better with the RLE code-length codes.
func optimizeForRLE(counts []uint32, good []bool) {
length := len(counts)
for ; length >= 0; length-- {
if length == 0 {
return
}
if counts[length-1] != 0 {
break
}
}
good = good[:length+1]
for i := range good {
good[i] = false
}
{
symbol := counts[0]
stride := 0
for i := 0; i < length+1; i++ {
if i == length || counts[i] != symbol {
if (symbol == 0 && stride >= 5) || (symbol != 0 && stride >= 7) {
for k := 0; k < stride; k++ {
good[i-k-1] = true
}
}
stride = 1
if i != length {
symbol = counts[i]
}
} else {
stride++
}
}
}
{
stride := uint32(0)
limit := counts[0]
sum := uint32(0)
for i := 0; i < length+1; i++ {
if i == length || good[i] || (i != 0 && good[i-1]) || !collapsible(counts[i], limit) {
if stride >= 4 || (stride >= 3 && sum == 0) {
count := (sum + stride/2) / stride
if count < 1 {
count = 1
}
if sum == 0 {
count = 0
}
for k := uint32(0); k < stride; k++ {
counts[i-int(k)-1] = count
}
}
stride = 0
sum = 0
if i < length-3 {
limit = (counts[i] + counts[i+1] + counts[i+2] + counts[i+3] + 2) / 4
} else if i < length {
limit = counts[i]
} else {
limit = 0
}
}
stride++
if i != length {
sum += counts[i]
if stride >= 4 {
limit = (sum + stride/2) / stride
}
}
}
}
}
func collapsible(a, b uint32) bool {
d := int64(a) - int64(b)
return d < 4 && d > -4
}
// generateOptimalTree computes depth-limited Huffman code lengths for hist.
func (s *huffScratch) generateOptimalTree(hist []uint32, limit int, depths []uint8) {
for i := range depths {
depths[i] = 0
}
n := 0
for _, c := range hist {
if c != 0 {
n++
}
}
if n == 0 {
return
}
if n == 1 {
for i, c := range hist {
if c != 0 {
depths[i] = 1
}
}
return
}
if cap(s.keys) < n {
s.keys = make([]uint64, n)
}
if cap(s.weight) < 2*n {
s.weight = make([]uint64, 2*n)
s.parent = make([]int32, 2*n)
s.depth = make([]uint8, 2*n)
}
keys := s.keys[:n]
weight := s.weight[:2*n]
parent := s.parent[:2*n]
depth := s.depth[:2*n]
for countMin := uint64(1); ; countMin *= 2 {
k := 0
for i, c := range hist {
if c != 0 {
w := uint64(c)
if w < countMin {
w = countMin
}
keys[k] = w<<16 | uint64(i)
k++
}
}
slices.Sort(keys)
for i, key := range keys {
weight[i] = key >> 16
}
// Two-queue Huffman construction: leaves [0,n), internal nodes [n,2n-1).
li, ii, next := 0, n, n
for next < 2*n-1 {
var a, b int
if li < n && (ii >= next || weight[li] <= weight[ii]) {
a = li
li++
} else {
a = ii
ii++
}
if li < n && (ii >= next || weight[li] <= weight[ii]) {
b = li
li++
} else {
b = ii
ii++
}
weight[next] = weight[a] + weight[b]
parent[a] = int32(next)
parent[b] = int32(next)
next++
}
root := 2*n - 2
depth[root] = 0
maxDepth := uint8(0)
for i := root - 1; i >= 0; i-- {
d := depth[parent[i]] + 1
depth[i] = d
if i < n && d > maxDepth {
maxDepth = d
}
}
if int(maxDepth) <= limit {
for i, key := range keys {
depths[key&0xffff] = depth[i]
}
return
}
}
}
// convertBitDepthsToSymbols assigns canonical, bit-reversed codes.
func convertBitDepthsToSymbols(c *huffCode) {
var depthCount [16]uint32
var nextCode [16]uint32
for _, d := range c.lengths {
depthCount[d]++
}
depthCount[0] = 0
code := uint32(0)
for i := 1; i < 16; i++ {
code = (code + depthCount[i-1]) << 1
nextCode[i] = code
}
for i, d := range c.lengths {
if d == 0 {
c.codes[i] = 0
continue
}
v := nextCode[d]
nextCode[d]++
c.codes[i] = uint16(reverseBits(v, uint(d)))
}
}
func reverseBits(v uint32, n uint) uint32 {
var r uint32
for i := uint(0); i < n; i++ {
r = r<<1 | (v & 1)
v >>= 1
}
return r
}
// createHuffmanTree builds a length-limited code for hist (hist is modified).
func (s *huffScratch) createHuffmanTree(hist []uint32, limit int, c *huffCode) {
if cap(s.goodRLE) < len(hist)+1 {
s.goodRLE = make([]bool, len(hist)+1)
}
optimizeForRLE(hist, s.goodRLE[:len(hist)+1])
s.generateOptimalTree(hist, limit, c.lengths)
convertBitDepthsToSymbols(c)
}
func codeRepeatedValues(reps int, toks []huffToken, value, prev uint8) []huffToken {
if value != prev {
toks = append(toks, huffToken{value, 0})
reps--
}
for reps >= 1 {
if reps < 3 {
for i := 0; i < reps; i++ {
toks = append(toks, huffToken{value, 0})
}
break
} else if reps < 7 {
toks = append(toks, huffToken{16, uint8(reps - 3)})
break
} else {
toks = append(toks, huffToken{16, 3})
reps -= 6
}
}
return toks
}
func codeRepeatedZeros(reps int, toks []huffToken) []huffToken {
for reps >= 1 {
if reps < 3 {
for i := 0; i < reps; i++ {
toks = append(toks, huffToken{0, 0})
}
break
} else if reps < 11 {
toks = append(toks, huffToken{17, uint8(reps - 3)})
break
} else if reps < 139 {
toks = append(toks, huffToken{18, uint8(reps - 11)})
break
} else {
toks = append(toks, huffToken{18, 0x7f})
reps -= 138
}
}
return toks
}
// compressedTokens RLE-encodes code lengths.
func compressedTokens(lengths []uint8, toks []huffToken) []huffToken {
toks = toks[:0]
prev := uint8(8)
n := len(lengths)
for i := 0; i < n; {
v := lengths[i]
k := i + 1
for k < n && lengths[k] == v {
k++
}
runs := k - i
if v == 0 {
toks = codeRepeatedZeros(runs, toks)
} else {
toks = codeRepeatedValues(runs, toks, v, prev)
prev = v
}
i += runs
}
return toks
}
var codeLengthOrder = [codeLengthCodes]uint8{17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
// storeHuffmanCode writes code c (simple or normal form) to bw.
func (s *huffScratch) storeHuffmanCode(bw *bitWriter, c *huffCode) {
count := 0
var symbols [2]int
for i, l := range c.lengths {
if l != 0 {
if count < 2 {
symbols[count] = i
}
count++
if count > 2 {
break
}
}
}
if count == 0 {
bw.putBits(0x01, 4)
return
}
if count <= 2 && symbols[0] < 256 && symbols[1] < 256 {
bw.putBits(1, 1)
bw.putBits(uint32(count-1), 1)
if symbols[0] <= 1 {
bw.putBits(0, 1)
bw.putBits(uint32(symbols[0]), 1)
} else {
bw.putBits(1, 1)
bw.putBits(uint32(symbols[0]), 8)
}
if count == 2 {
bw.putBits(uint32(symbols[1]), 8)
}
return
}
s.storeFullHuffmanCode(bw, c)
}
func (s *huffScratch) storeFullHuffmanCode(bw *bitWriter, c *huffCode) {
var clLengths [codeLengthCodes]uint8
var clCodes [codeLengthCodes]uint16
var clHist [codeLengthCodes]uint32
cl := huffCode{lengths: clLengths[:], codes: clCodes[:]}
bw.putBits(0, 1)
s.tokens = compressedTokens(c.lengths, s.tokens)
toks := s.tokens
for _, t := range toks {
clHist[t.code]++
}
s.createHuffmanTree(clHist[:], 7, &cl)
// Store the code length code lengths.
codesToStore := codeLengthCodes
for ; codesToStore > 4; codesToStore-- {
if clLengths[codeLengthOrder[codesToStore-1]] != 0 {
break
}
}
bw.putBits(uint32(codesToStore-4), 4)
for i := 0; i < codesToStore; i++ {
bw.putBits(uint32(clLengths[codeLengthOrder[i]]), 3)
}
clearIfOneSymbol(&cl)
trailingZeroBits := 0
trimmed := len(toks)
for i := len(toks) - 1; i >= 0; i-- {
ix := toks[i].code
if ix == 0 || ix == 17 || ix == 18 {
trimmed--
trailingZeroBits += int(clLengths[ix])
if ix == 17 {
trailingZeroBits += 3
} else if ix == 18 {
trailingZeroBits += 7
}
} else {
break
}
}
writeTrimmed := trimmed > 1 && trailingZeroBits > 12
length := len(toks)
if writeTrimmed {
length = trimmed
bw.putBits(1, 1)
if trimmed == 2 {
bw.putBits(0, 3+2)
} else {
nb := log2Floor(uint32(trimmed - 2))
nbitpairs := nb/2 + 1
bw.putBits(uint32(nbitpairs-1), 3)
bw.putBits(uint32(trimmed-2), uint(nbitpairs*2))
}
} else {
bw.putBits(0, 1)
}
for _, t := range toks[:length] {
ix := t.code
bw.putBits(uint32(clCodes[ix]), uint(clLengths[ix]))
switch ix {
case 16:
bw.putBits(uint32(t.extra), 2)
case 17:
bw.putBits(uint32(t.extra), 3)
case 18:
bw.putBits(uint32(t.extra), 7)
}
}
}
// clearIfOneSymbol zeroes the code when it has a single used symbol (the
// decoder reads zero bits for such codes).
func clearIfOneSymbol(c *huffCode) {
count := 0
for _, l := range c.lengths {
if l != 0 {
count++
if count > 1 {
return
}
}
}
for i := range c.lengths {
c.lengths[i] = 0
c.codes[i] = 0
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
// Near-lossless preprocessing.
// Algorithm adapted from libwebp (BSD-3-Clause).
const minDimForNearLossless = 64
// nearLosslessBits maps a near-lossless quality (0..100) to quantization bits.
func nearLosslessBits(q int) int { return 5 - q/20 }
func findClosestDiscretized(a uint32, bits uint) uint32 {
mask := uint32(1)<<bits - 1
biased := a + (mask >> 1) + ((a >> bits) & 1)
if biased > 0xff {
return 0xff
}
return biased &^ mask
}
func closestDiscretizedArgb(a uint32, bits uint) uint32 {
return findClosestDiscretized(a>>24, bits)<<24 |
findClosestDiscretized((a>>16)&0xff, bits)<<16 |
findClosestDiscretized((a>>8)&0xff, bits)<<8 |
findClosestDiscretized(a&0xff, bits)
}
func isNear(a, b uint32, limit int32) bool {
for k := uint(0); k < 32; k += 8 {
d := int32((a>>k)&0xff) - int32((b>>k)&0xff)
if d >= limit || d <= -limit {
return false
}
}
return true
}
func nearLosslessPass(xsize, ysize int, argb []uint32, limitBits int, buf []uint32) {
limit := int32(1) << uint(limitBits)
prev := buf[:xsize]
cur := buf[xsize : 2*xsize]
next := buf[2*xsize : 3*xsize]
copy(cur, argb[:xsize])
copy(next, argb[xsize:2*xsize])
for y := 0; y < ysize; y++ {
dst := argb[y*xsize : (y+1)*xsize]
if y != 0 && y != ysize-1 {
copy(next, argb[(y+1)*xsize:(y+2)*xsize])
for x := 1; x < xsize-1; x++ {
c := cur[x]
if isNear(c, cur[x-1], limit) && isNear(c, cur[x+1], limit) &&
isNear(c, prev[x], limit) && isNear(c, next[x], limit) {
dst[x] = c
} else {
dst[x] = closestDiscretizedArgb(c, uint(limitBits))
}
}
}
prev, cur, next = cur, next, prev
}
}
// applyNearLossless quantizes non-smooth pixels of argb in place.
func applyNearLossless(xsize, ysize int, quality int, argb []uint32) {
bits := nearLosslessBits(quality)
if bits <= 0 {
return
}
if (xsize < minDimForNearLossless && ysize < minDimForNearLossless) || ysize < 3 {
return
}
buf := getU32(3 * xsize)
for b := bits; b > 0; b-- {
nearLosslessPass(xsize, ysize, argb, b, buf)
}
putU32(buf)
}
// ---- near-lossless quantization inside the predictor ----
func addPixels(a, b uint32) uint32 {
ag := (a & 0xff00ff00) + (b & 0xff00ff00)
rb := (a & 0x00ff00ff) + (b & 0x00ff00ff)
return (ag & 0xff00ff00) | (rb & 0x00ff00ff)
}
func addGreenToBlueAndRed(p uint32) uint32 {
g := (p >> 8) & 0xff
rb := (p & 0x00ff00ff) + (g<<16 | g)
return p&0xff00ff00 | rb&0x00ff00ff
}
func maxDiffBetweenPixels(p1, p2 uint32) int {
m := 0
for k := uint(0); k < 32; k += 8 {
d := int((p1>>k)&0xff) - int((p2>>k)&0xff)
if d < 0 {
d = -d
}
if d > m {
m = d
}
}
return m
}
// computeMaxDiffs fills md with, for every interior pixel, the maximum
// channel difference to its 4 neighbours (libwebp MaxDiffsForRow).
func computeMaxDiffs(width, height int, argb []uint32, usedSubGreen bool, md []uint8) {
conv := func(p uint32) uint32 {
if usedSubGreen {
return addGreenToBlueAndRed(p)
}
return p
}
for y := 1; y+1 < height; y++ {
row := argb[y*width : (y+1)*width]
up := argb[(y-1)*width : y*width]
down := argb[(y+1)*width : (y+2)*width]
out := md[y*width : (y+1)*width]
if width <= 2 {
continue
}
cur := conv(row[0])
right := conv(row[1])
for x := 1; x < width-1; x++ {
left := cur
cur = right
right = conv(row[x+1])
u, d := conv(up[x]), conv(down[x])
m := max(maxDiffBetweenPixels(cur, u), maxDiffBetweenPixels(cur, d),
maxDiffBetweenPixels(cur, left), maxDiffBetweenPixels(cur, right))
if m > 255 {
m = 255
}
out[x] = uint8(m)
}
}
}
func nearLosslessComponent(value, predict, boundary, quant int) int {
residual := (value - predict) & 0xff
boundaryResidual := (boundary - predict) & 0xff
lower := residual &^ (quant - 1)
upper := lower + quant
bias := 0
if (boundary-value)&0xff < boundaryResidual {
bias = 1
}
if residual-lower < upper-residual+bias {
if residual > boundaryResidual && lower <= boundaryResidual {
return lower + quant>>1
}
return lower
}
if residual <= boundaryResidual && upper > boundaryResidual {
return lower + quant>>1
}
return upper & 0xff
}
// nearLosslessResidual quantizes the residual value-predict.
func nearLosslessResidual(value, predict uint32, maxQuant, maxDiff int, usedSubGreen bool) uint32 {
if maxDiff <= 2 {
return subPixels(value, predict)
}
q := maxQuant
for q >= maxDiff {
q >>= 1
}
var a int
va := int(value >> 24)
if va == 0 || va == 0xff {
a = (va - int(predict>>24)) & 0xff
} else {
a = nearLosslessComponent(va, int(predict>>24), 0xff, q)
}
g := nearLosslessComponent(int((value>>8)&0xff), int((predict>>8)&0xff), 0xff, q)
newGreen, greenDiff := 0, 0
if usedSubGreen {
newGreen = (int((predict>>8)&0xff) + g) & 0xff
greenDiff = (newGreen - int((value>>8)&0xff)) & 0xff
}
r := nearLosslessComponent((int((value>>16)&0xff)-greenDiff)&0xff, int((predict>>16)&0xff), 0xff-newGreen, q)
b := nearLosslessComponent((int(value&0xff)-greenDiff)&0xff, int(predict&0xff), 0xff-newGreen, q)
return uint32(a)<<24 | uint32(r)<<16 | uint32(g)<<8 | uint32(b)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import "slices"
// Color indexing (palette) transform.
// Algorithm adapted from libwebp (BSD-3-Clause).
const maxPaletteSize = 256
// collectPalette returns the sorted unique colors of argb, or nil when there
// are more than 256 of them.
func collectPalette(argb []uint32, dst []uint32) []uint32 {
var s colorSet
s.add(argb)
return s.palette(dst)
}
const (
colorSetBits = 11
colorSetSize = 1 << colorSetBits
)
// colorSet collects the distinct colors of an image (in any number of
// add calls) until there are more than maxPaletteSize of them. The zero
// value is an empty set.
type colorSet struct {
table [colorSetSize]uint32
inUse [colorSetSize]bool
n int
last uint32 // the last color added (valid when n > 0)
tooMany bool
}
// add adds the colors of argb.
func (s *colorSet) add(argb []uint32) {
if s.tooMany || len(argb) == 0 {
return
}
last := s.last
if s.n == 0 {
last = ^argb[0]
}
for _, p := range argb {
if p == last {
continue
}
last = p
key := (p * 0x1e35a7bd) >> (32 - colorSetBits)
for {
if !s.inUse[key] {
s.inUse[key] = true
s.table[key] = p
s.n++
if s.n > maxPaletteSize {
s.tooMany = true
return
}
break
} else if s.table[key] == p {
break
}
key = (key + 1) & (colorSetSize - 1)
}
}
s.last = last
}
// palette returns the sorted colors of the set in dst, or nil when there
// are more than maxPaletteSize of them.
func (s *colorSet) palette(dst []uint32) []uint32 {
if s.tooMany {
return nil
}
dst = dst[:0]
for i := range s.table {
if s.inUse[i] {
dst = append(dst, s.table[i])
}
}
slices.Sort(dst)
return dst
}
func paletteComponentDistance(v uint32) uint32 {
if v <= 128 {
return v
}
return 256 - v
}
func paletteColorDistance(c1, c2 uint32) uint32 {
d := subPixels(c1, c2)
s := paletteComponentDistance(d&0xff) + paletteComponentDistance((d>>8)&0xff) +
paletteComponentDistance((d>>16)&0xff)
s *= 9
s += paletteComponentDistance(d >> 24)
return s
}
// paletteHasNonMonotonousDeltas reports whether the sorted palette has
// deltas that change sign in some channel.
func paletteHasNonMonotonousDeltas(p []uint32) bool {
predict := uint32(0)
signFound := uint8(0)
for _, c := range p {
diff := subPixels(c, predict)
rd := (diff >> 16) & 0xff
gd := (diff >> 8) & 0xff
bd := diff & 0xff
if rd != 0 {
if rd < 0x80 {
signFound |= 1
} else {
signFound |= 2
}
}
if gd != 0 {
if gd < 0x80 {
signFound |= 8
} else {
signFound |= 16
}
}
if bd != 0 {
if bd < 0x80 {
signFound |= 64
} else {
signFound |= 128
}
}
predict = c
}
return signFound&(signFound<<1) != 0
}
// paletteSortMinimizeDeltas reorders the palette greedily so that
// consecutive entries are close (cheaper delta-coded palette).
func paletteSortMinimizeDeltas(sorted []uint32, out []uint32) []uint32 {
out = append(out[:0], sorted...)
if !paletteHasNonMonotonousDeltas(sorted) {
return out
}
n := len(out)
if n > 17 && out[0] == 0 {
n--
out[n], out[0] = out[0], out[n]
}
predict := uint32(0)
for i := 0; i < n; i++ {
bestIx := i
bestScore := ^uint32(0)
for k := i; k < n; k++ {
s := paletteColorDistance(out[k], predict)
if s < bestScore {
bestScore = s
bestIx = k
}
}
out[bestIx], out[i] = out[i], out[bestIx]
predict = out[i]
}
return out
}
// paletteXBits returns the pixel bundling shift for a palette size.
func paletteXBits(n int) int {
switch {
case n <= 2:
return 3
case n <= 4:
return 2
case n <= 16:
return 1
}
return 0
}
// applyPalette maps argb (width x height) to bundled palette indices in dst
// (packed width x height). dst may be argb itself: each row is read entirely
// (into idxRow) before its bundled row, which starts no later, is written.
// It returns initRefsCap of the bundled image (computed on the way).
func applyPalette(argb []uint32, width, height int, palette []uint32, dst []uint32, idxRow []uint8) (refsCap int) {
xbits := paletteXBits(len(palette))
pw := subSampleSize(width, xbits)
// Small open-addressing lookup table color -> index.
const tabBits = 10
var keys [1 << tabBits]uint32
var vals [1 << tabBits]int16
for i := range vals {
vals[i] = -1
}
for i, c := range palette {
k := (c * 0x1e35a7bd) >> (32 - tabBits)
for vals[k] >= 0 {
k = (k + 1) & (1<<tabBits - 1)
}
keys[k] = c
vals[k] = int16(i)
}
lookup := func(c uint32) uint8 {
k := (c * 0x1e35a7bd) >> (32 - tabBits)
for keys[k] != c || vals[k] < 0 {
k = (k + 1) & (1<<tabBits - 1)
}
return uint8(vals[k])
}
idxRow = idxRow[:width]
est := 1
for y := 0; y < height; y++ {
row := argb[y*width : (y+1)*width]
prevC := ^row[0]
var prevI uint8
for x, c := range row {
if c != prevC {
prevC = c
prevI = lookup(c)
}
idxRow[x] = prevI
}
out := dst[y*pw : (y+1)*pw]
bundleColorMap(idxRow, xbits, out)
if y == 0 {
est += newPixels(out[1:], nil, out[0])
} else {
est += newPixels(out, dst[(y-1)*pw:y*pw], dst[y*pw-1])
}
}
return refsCapFromEstimate(pw*height, est)
}
// bundleColorMap packs 1<<xbits palette indices per output pixel (green).
func bundleColorMap(row []uint8, xbits int, dst []uint32) {
if xbits > 0 {
bitDepth := uint(1) << uint(3-xbits)
mask := (1 << uint(xbits)) - 1
code := uint32(argbBlack)
for x, v := range row {
xsub := x & mask
if xsub == 0 {
code = argbBlack
}
code |= uint32(v) << (8 + bitDepth*uint(xsub))
dst[x>>uint(xbits)] = code
}
} else {
for x, v := range row {
dst[x] = argbBlack | uint32(v)<<8
}
}
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import (
"sync/atomic"
"github.com/kolesa-team/go-webp/v2/internal/workers"
)
// ThreadLevel parallelism.
//
// By default an encode runs on the caller's goroutine only. With
// Config.ThreadLevel, independent work items (candidate configurations,
// image stripes, histogram tiles) are spread over the caller and helper
// goroutines started through the process-wide budget of internal/workers:
// when no slot is free, the caller does all the work itself. Items are
// claimed through an atomic counter (no channel operation per item) and
// are coarse (at least about half a millisecond of work each). The
// candidate configurations are spread by parallel; the stages within an
// encoding run on the crew of its scratch, whose helpers are started once
// per parallel phase (the match search, the predictor mode search with its
// dozens of batches, the histogram remap) and released at its end. Every
// result is independent of the number of goroutines, so the output is
// byte-identical to the sequential encode.
// parallel runs body on the calling goroutine (worker 0) and on up to
// helpers helper goroutines (workers 1..helpers, never more than items-1),
// each started only while the process-wide budget has a free slot. The
// bodies claim the items 0..items-1 through claim, which hands out every
// item exactly once (in increasing order) and then reports false. parallel
// returns when every body has returned. A panic in a helper is re-raised on
// the caller once all helpers are done; when the caller's body panics, the
// helpers stop claiming items and are waited for before the panic unwinds
// further.
//
// A body must not block waiting for another body (the item it waits for
// may never be claimed when the budget is exhausted): items are
// independent, and per-worker state (e.g. a scratch taken from a pool) is
// acquired and released inside the body, on the goroutine that runs it.
//
// gate, if not nil, must also allow each helper (see AlphaEncoder.PairGate).
// The helpers it holds back are started later, when the caller claims an
// item while it allows them and at least two items are left (one for the
// caller, one for the helper).
func parallel(items, helpers int, gate func() bool, body func(worker int, claim func() (int, bool))) {
var next atomic.Int64
const stopped = 1 << 62
claim := func() (int, bool) {
i := next.Add(1) - 1
return int(i), i < int64(items)
}
helpers = min(helpers, items-1)
var tasks []*workers.Task
// start starts helper len(tasks)+1 and reports whether it could; only
// the caller starts helpers, so tasks needs no lock.
start := func() bool {
if gate != nil && !gate() {
return false
}
k := len(tasks) + 1
t := workers.Spawn(func() error {
body(k, claim)
return nil
})
if t == nil {
return false
}
tasks = append(tasks, t)
return true
}
finished := false
defer func() {
if !finished {
next.Store(stopped) // the caller panicked: stop the helpers early
}
var failed *workers.Task
for _, t := range tasks {
if t.Panicked() && failed == nil {
failed = t
}
}
if finished && failed != nil {
failed.Wait() // re-raises the helper's panic
}
}()
for len(tasks) < helpers && start() {
}
claim0 := claim
if gate != nil && len(tasks) < helpers {
// The caller claims its item before it starts a helper, so that
// the helper cannot take that item: it starts with the next one.
claim0 = func() (int, bool) {
i, ok := claim()
if ok && len(tasks) < helpers && next.Load() < int64(items) {
start()
}
return i, ok
}
}
body(0, claim0)
finished = true
}
// crew is the set of helper goroutines of the parallel stages of one
// encoding goroutine (hash chain stripes, predictor batches, histogram
// remap): instead of starting helpers for every stage (the predictor runs
// one stage per batch of tiles, dozens per image), the first stage starts
// them through the process-wide budget and the following ones reuse them,
// woken by a channel send each and joined through one channel; between
// stages they wait, blocked, on their channel. stop ends them.
//
// Each parallel phase stops the crew when it ends, so that its helpers do
// not hold budget slots, idle, through the sequential stages that follow:
// other calls may use them meanwhile (with 2 to 4 concurrent ThreadLevel
// encodes sharing 7 slots, holding them left about 2-3.5 helpers per stage
// instead of 5-6). The encode that started them also stops the crew before
// returning, also on a panic or an interruption (the crew of a scratch is
// stopped before the scratch goes back to its pool), so that no helper
// outlives it.
//
// The zero value is ready to use. A crew is used by one goroutine at a
// time (the one owning its scratch); run must not be called from a body.
type crew struct {
tasks []*workers.Task
start []chan bool // per helper: true runs body, false stops it
done chan struct{} // one value per helper and job
failed []bool // per helper: its body panicked (or exited)
// The current job, set before the helpers are woken.
body func(worker int, claim func() (int, bool))
next atomic.Int64
items int64
claimFn func() (int, bool) // c.claim, bound once
// gate is the stage gate of the encode the crew serves (see
// AlphaEncoder.StageGate): a helper it holds back may start at a later
// stage.
gate func() bool
}
func (c *crew) claim() (int, bool) {
i := c.next.Add(1) - 1
return int(i), i < c.items
}
// run is parallel on the crew: body runs on the calling goroutine (worker
// 0) and on up to helpers helpers of the crew (workers 1..helpers, never
// more than items-1), started if needed (and while the budget allows). It
// returns when every body has returned. A panic in a helper is re-raised on
// the caller (by its Task.Wait) once all bodies are done; when the caller's
// body panics, the helpers stop claiming items and are waited for before
// the panic unwinds further. The same rules as for parallel apply to body.
func (c *crew) run(items, helpers int, body func(worker int, claim func() (int, bool))) {
if c.claimFn == nil {
c.claimFn = c.claim
}
c.items = int64(items)
c.next.Store(0)
n := min(helpers, items-1)
if n <= 0 {
body(0, c.claimFn)
return
}
c.grow(n)
n = min(n, len(c.tasks))
c.body = body
sent := 0
for k := 0; k < n; k++ {
select {
case c.start[k] <- true:
sent++
case <-c.tasks[k].Done(): // (cannot happen: run re-raises panics)
}
}
finished := false
defer func() {
const stopped = 1 << 62
if !finished {
c.next.Store(stopped) // the caller panicked: stop the helpers early
}
for ; sent > 0; sent-- {
<-c.done
}
c.body = nil
if finished {
for k, f := range c.failed {
if f {
c.tasks[k].Wait() // re-raises the helper's panic
}
}
}
}()
body(0, c.claimFn)
finished = true
}
// grow starts helpers until the crew has n, while the budget (and c.gate)
// allows.
func (c *crew) grow(n int) {
if c.done == nil {
c.done = make(chan struct{}, intraHelpers)
}
for k := len(c.tasks); k < n; k++ {
if k == len(c.start) {
c.start = append(c.start, make(chan bool, 1))
c.failed = append(c.failed, false)
}
if c.gate != nil && !c.gate() {
return
}
start := c.start[k]
t := workers.Spawn(func() error {
for <-start {
c.work(k + 1)
}
return nil
})
if t == nil {
return
}
c.tasks = append(c.tasks, t)
}
}
// work runs the current job as worker w and reports it done, also when
// the body panics (the panic then ends the helper; run re-raises it).
func (c *crew) work(w int) {
ok := false
defer func() {
if !ok {
c.failed[w-1] = true
}
c.done <- struct{}{}
}()
c.body(w, c.claimFn)
ok = true
}
// stop ends the helpers of the crew and waits for them.
func (c *crew) stop() {
for k, t := range c.tasks {
select {
case c.start[k] <- false:
case <-t.Done():
}
}
for k, t := range c.tasks {
t.Panicked() // waits for t (a panic was re-raised by run, or another one is unwinding)
select {
case <-c.start[k]: // the stop value of a helper that had panicked
default:
}
c.tasks[k] = nil
c.failed[k] = false
}
c.tasks = c.tasks[:0]
}
// intraHelpers is the largest number of helper goroutines one parallel stage
// of an encode (hash chain stripes, predictor tiles, histogram remap) asks
// for; the process-wide budget may grant fewer.
const intraHelpers = 7
// minParallelPixels is the smallest image (in pixels) whose stages are run
// in parallel: below it, the hand-off costs more than it saves. (A variable
// for the tests.)
var minParallelPixels = 1 << 18
// stageHelpers returns the number of helpers for a parallel stage of an
// image of n pixels.
func (p *params) stageHelpers(n int) int {
if !p.parallel || n < minParallelPixels || !p.gateOpen() {
return 0
}
return intraHelpers
}
// remapHelpers returns the number of helpers of the histogram remap (gated
// on its amount of work instead of the image size).
func (p *params) remapHelpers() int {
if !p.parallel || !p.gateOpen() {
return 0
}
return intraHelpers
}
// gateOpen reports whether the stage gate (AlphaEncoder.StageGate) allows
// a helper now. A stage it holds back runs its sequential version: the
// parallel one, which splits the work into stripes, batches or chunks,
// costs more on one goroutine (about 10% on the alpha plane of a
// transparent 960x1280 photo).
func (p *params) gateOpen() bool { return p.stageGate == nil || p.stageGate() }
// configHelpers is the number of helper goroutines (besides the caller)
// that encode candidate configurations concurrently. Each encoding
// configuration holds a full working set (15-100 bytes per pixel), so, like
// libwebp's multi-threaded lossless encoder, at most two configurations
// are encoded at a time: at level 9 this halves the time of the sequential
// encode for about twice its peak memory (instead of one working set per
// configuration, up to 8).
const configHelpers = 1
// maxConfigPairPixels is the largest image (in pixels) whose configurations
// are encoded two at a time: a working set takes up to about 90 bytes per
// pixel at level 9 (1 GB for 12 MP), so larger images encode their
// configurations one after the other (each with the parallel stages). A
// variable for the tests.
var maxConfigPairPixels = 8 << 20
// configHelpersFor returns the number of helpers encoding configurations
// of an image of n pixels concurrently with the caller.
func (p *params) configHelpersFor(n int) int {
if !p.parallel || n > maxConfigPairPixels {
return 0
}
return configHelpers
}
// configCost ranks the configurations by expected encoding time (spatial
// prediction with its mode search and cross-color is the slowest, palette
// encodes the fastest), so that the slowest start first.
func configCost(cc crunchConfig) int {
switch cc.entropy {
case modeSpatial, modeSpatialSubGreen:
return 3
case modeDirect, modeSubGreen, modePaletteAndSpatial:
return 2
}
return 1
}
// configResult is the outcome of the configurations encoded by one worker:
// its smallest stream (lowest configuration index on ties) and a spare
// output buffer.
type configResult struct {
best, spare []byte
idx int
}
// encodeConfigs encodes argb with every configuration and returns the
// smallest stream (the first one in configuration order on ties) and a
// losing buffer (or spare if unused). Each worker writes each trial into
// the buffer of its previous loser, so it keeps at most two streams.
func encodeConfigs(argb []uint32, w, h int, p *params, configs []crunchConfig, prefix int, sc *scratch, spare []byte, helpers int) (best, spareOut []byte) {
order := make([]int, len(configs))
for i := range order {
order[i] = i
}
if helpers > 0 {
// Longest first (stable), for a better balance.
for i := 1; i < len(order); i++ {
for j := i; j > 0 && configCost(configs[order[j]]) > configCost(configs[order[j-1]]); j-- {
order[j], order[j-1] = order[j-1], order[j]
}
}
}
res := make([]configResult, 1+min(helpers, len(configs)-1))
parallel(len(configs), helpers, p.pairGate, func(worker int, claim func() (int, bool)) {
s, buf := sc, spare
if worker > 0 {
s, buf = getScratch(w*h), nil
defer putScratch(s)
defer s.crew.stop()
}
r := &res[worker]
r.idx = -1
for {
k, ok := claim()
if !ok {
break
}
i := order[k]
out := encodeStream(argb, false, w, h, p, configs[i], prefix, s, buf)
if r.best == nil || len(out) < len(r.best) || len(out) == len(r.best) && i < r.idx {
buf, r.best, r.idx = r.best, out, i
} else {
buf = out
}
}
r.spare = buf
})
bi := -1
for k := range res {
r := &res[k]
if r.best != nil && (bi < 0 || len(r.best) < len(res[bi].best) || len(r.best) == len(res[bi].best) && r.idx < res[bi].idx) {
bi = k
}
}
best = res[bi].best
for k := range res {
cands := [2][]byte{res[k].spare, res[k].best}
for c, b := range cands {
if (k != bi || c == 0) && cap(b) > cap(spareOut) {
spareOut = b
}
}
}
return best, spareOut
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
// Spatial prediction transform.
// Algorithm adapted from libwebp (BSD-3-Clause).
import "math"
const (
numPredModes = 14
spatialPredictorBias = 15.0
predLowEffort = 11
)
func average2(a, b uint32) uint32 {
return (((a ^ b) & 0xfefefefe) >> 1) + (a & b)
}
func abs32(v int32) int32 {
if v < 0 {
return -v
}
return v
}
func sub3(a, b, c uint32) int32 {
pb := int32(b) - int32(c)
pa := int32(a) - int32(c)
return abs32(pb) - abs32(pa)
}
// selectPred implements predictor 11 (a = top, b = left, c = top-left).
func selectPred(a, b, c uint32) uint32 {
d := sub3(a>>24, b>>24, c>>24) +
sub3((a>>16)&0xff, (b>>16)&0xff, (c>>16)&0xff) +
sub3((a>>8)&0xff, (b>>8)&0xff, (c>>8)&0xff) +
sub3(a&0xff, b&0xff, c&0xff)
if d <= 0 {
return a
}
return b
}
func clip255(v int32) uint32 {
if uint32(v) < 256 {
return uint32(v)
}
if v < 0 {
return 0
}
return 255
}
func clampedAddSubtractFull(c0, c1, c2 uint32) uint32 {
a := clip255(int32(c0>>24) + int32(c1>>24) - int32(c2>>24))
r := clip255(int32((c0>>16)&0xff) + int32((c1>>16)&0xff) - int32((c2>>16)&0xff))
g := clip255(int32((c0>>8)&0xff) + int32((c1>>8)&0xff) - int32((c2>>8)&0xff))
b := clip255(int32(c0&0xff) + int32(c1&0xff) - int32(c2&0xff))
return a<<24 | r<<16 | g<<8 | b
}
func addSubHalf(a, b int32) uint32 { return clip255(a + (a-b)/2) }
func clampedAddSubtractHalf(c0, c1, c2 uint32) uint32 {
ave := average2(c0, c1)
a := addSubHalf(int32(ave>>24), int32(c2>>24))
r := addSubHalf(int32((ave>>16)&0xff), int32((c2>>16)&0xff))
g := addSubHalf(int32((ave>>8)&0xff), int32((c2>>8)&0xff))
b := addSubHalf(int32(ave&0xff), int32(c2&0xff))
return a<<24 | r<<16 | g<<8 | b
}
// predictRowGo writes residuals for x in [x0,x1) of a row with y >= 1 and
// x0 >= 1. cur is the current row, up the row above extended by one pixel
// (up[width] is the first pixel of cur). out must not overlap cur or up.
// It is the Go reference of predictRow (dsp_amd64.go, dsp_arm64.go,
// dsp_generic.go).
func predictRowGo(mode int, cur, up []uint32, x0, x1 int, out []uint32) {
_ = up[x1]
_ = cur[x1-1]
out = out[:x1-x0]
switch mode {
case 0:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], argbBlack)
}
case 1:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], cur[x-1])
}
case 2:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], up[x])
}
case 3:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], up[x+1])
}
case 4:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], up[x-1])
}
case 5:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], average2(average2(cur[x-1], up[x+1]), up[x]))
}
case 6:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], average2(cur[x-1], up[x-1]))
}
case 7:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], average2(cur[x-1], up[x]))
}
case 8:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], average2(up[x-1], up[x]))
}
case 9:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], average2(up[x], up[x+1]))
}
case 10:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], average2(average2(cur[x-1], up[x-1]), average2(up[x], up[x+1])))
}
case 11:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], selectPred(up[x], cur[x-1], up[x-1]))
}
case 12:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], clampedAddSubtractFull(cur[x-1], up[x], up[x-1]))
}
case 13:
for x := x0; x < x1; x++ {
out[x-x0] = subPixels(cur[x], clampedAddSubtractHalf(cur[x-1], up[x], up[x-1]))
}
}
}
// residualRow computes the residuals of row y for x in [x0,x1), handling the
// image borders (first row predicts from the left, first column from the top).
func residualRow(mode int, cur, up []uint32, y, x0, x1 int, out []uint32) {
if y == 0 {
for x := x0; x < x1; x++ {
if x == 0 {
out[x-x0] = subPixels(cur[0], argbBlack)
} else {
out[x-x0] = subPixels(cur[x], cur[x-1])
}
}
return
}
xs := x0
if xs == 0 {
out[0] = subPixels(cur[0], up[0])
xs = 1
}
if xs < x1 {
predictRow(mode, cur, up, xs, x1, out[xs-x0:])
}
}
// predictPixel returns the prediction of mode for pixel x (x >= 1, y >= 1).
func predictPixel(mode int, cur, up []uint32, x int) uint32 {
switch mode {
case 0:
return argbBlack
case 1:
return cur[x-1]
case 2:
return up[x]
case 3:
return up[x+1]
case 4:
return up[x-1]
case 5:
return average2(average2(cur[x-1], up[x+1]), up[x])
case 6:
return average2(cur[x-1], up[x-1])
case 7:
return average2(cur[x-1], up[x])
case 8:
return average2(up[x-1], up[x])
case 9:
return average2(up[x], up[x+1])
case 10:
return average2(average2(cur[x-1], up[x-1]), average2(up[x], up[x+1]))
case 11:
return selectPred(up[x], cur[x-1], up[x-1])
case 12:
return clampedAddSubtractFull(cur[x-1], up[x], up[x-1])
default:
return clampedAddSubtractHalf(cur[x-1], up[x], up[x-1])
}
}
// residualRowNL is residualRow with near-lossless quantization (maxQuant >
// 1) and/or the exact=0 handling of transparent pixels (clean), like
// libwebp's GetResidual. It updates cur with the reconstructed pixels (and
// up[width] when the first pixel of the row changes). md holds the max
// diffs of the row (only used with near-lossless).
func residualRowNL(mode int, cur, up []uint32, y, width, height, x0, x1 int, md []uint8,
maxQuant int, usedSubGreen, clean bool, out []uint32) {
for x := x0; x < x1; x++ {
var pred uint32
switch {
case y == 0:
if x == 0 {
pred = argbBlack
} else {
pred = cur[x-1]
}
case x == 0:
pred = up[0]
default:
pred = predictPixel(mode, cur, up, x)
}
var res uint32
if maxQuant <= 1 || mode == 0 || y == 0 || y == height-1 || x == 0 || x == width-1 {
res = subPixels(cur[x], pred)
} else {
res = nearLosslessResidual(cur[x], pred, maxQuant, int(md[x]), usedSubGreen)
cur[x] = addPixels(pred, res)
}
if clean && cur[x] < 0x01000000 {
// Alpha is 0: the RGB of the residual can be chosen freely;
// make it 0 and update the source accordingly. The prediction
// of alpha itself must be kept.
res &= 0xff000000
cur[x] = pred & 0x00ffffff
if x == 0 && y != 0 {
// The rightmost pixel of a row uses the leftmost pixel of
// the same row as its top-right context.
up[width] = cur[0]
}
}
out[x-x0] = res
}
}
// cleanFastPath enables cleanMask (a variable for the tests).
var cleanFastPath = true
// cleanMask sets mask[i] to 1 for the pixels of argb whose residual
// depends on libwebp's exact=0 cleaning (residualRowNL with clean and no
// near-lossless), and to 0 for the others: with clean, only the fully
// transparent pixels are changed (to their prediction), so the residual of
// a pixel only differs from residualRow's when the pixel or one of its
// prediction neighbors (left, top-left, top, top-right) is fully
// transparent. The top-right neighbor of the last column is the first
// pixel of the row (up[width]).
func cleanMask(argb []uint32, width, height int, mask []uint8) {
// mask first receives the transparency of the pixels, then is
// dilated in place row by row from the bottom (row y-1 is still the
// plain transparency when row y is dilated).
for i, p := range argb[:width*height] {
mask[i] = b2u8(p < 0x01000000)
}
for y := height - 1; y >= 0; y-- {
row := mask[y*width : (y+1)*width]
first := row[0]
// Left neighbor (in place, right to left).
for x := width - 1; x >= 1; x-- {
row[x] |= row[x-1]
}
if y == 0 {
break
}
up := mask[(y-1)*width : y*width]
row[0] |= up[0]
if width > 1 {
row[0] |= up[1]
}
for x := 1; x < width-1; x++ {
row[x] |= up[x-1] | up[x] | up[x+1]
}
if width > 1 {
row[width-1] |= up[width-2] | up[width-1] | first
} else {
row[0] |= first
}
}
}
func b2u8(b bool) uint8 {
if b {
return 1
}
return 0
}
// residualRowClean is residualRowNL with clean and no near-lossless
// (maxQuant 1): the pixels whose mask is 0 (see cleanMask) take the fast
// residualRow path, in runs. The pixels are processed in order, so the
// cleaned pixels the slow runs depend on are up to date.
func residualRowClean(mode int, cur, up []uint32, y, width, height, x0, x1 int, mask []uint8, out []uint32) {
mask = mask[:x1]
for x := x0; x < x1; {
s := x
for x < x1 && mask[x] != 0 {
x++
}
if x > s {
residualRowNL(mode, cur, up, y, width, height, s, x, nil, 1, false, true, out[s-x0:x-x0])
}
s = x
for x < x1 && mask[x] == 0 {
x++
}
if x > s {
residualRow(mode, cur, up, y, s, x, out[s-x0:x-x0])
}
}
}
type histo4 [4][256]int32
func (h *histo4) add(p uint32) {
h[0][p>>24]++
h[1][(p>>16)&0xff]++
h[2][(p>>8)&0xff]++
h[3][p&0xff]++
}
func predictionCostSpatial(counts *[256]int32, weight0 int, expVal float64) float64 {
const significant = 256 >> 4
const decay = 0.6
bits := float64(weight0) * float64(counts[0])
for i := 1; i < significant; i++ {
bits += expVal * float64(counts[i]+counts[256-i])
expVal *= decay
}
return -0.1 * bits
}
func predictionCostSpatialHistogram(acc, tile *histo4, ae *[4]accEntropy) float64 {
var r float64
for i := 0; i < 4; i++ {
r += predictionCostSpatial(&tile[i], 1, 0.94)
r += combinedShannonEntropy(&tile[i], &acc[i], &ae[i])
}
return r
}
// predictorImage selects the predictor modes and replaces argb by the
// prediction residuals. Like libwebp 1.6 (VP8LResidualImage), the modes are
// searched for tiles of every size from 1<<minBits to 1<<maxBits pixels and
// the sampling with the lowest estimated cost is kept, then reduced further
// when the chosen mode image is made of uniform squares
// (VP8LOptimizeSampling). It returns the transform bits; modes (which must
// hold one entry per tile of 1<<minBits pixels) receives the mode image as
// ARGB pixels. maxQuant > 1 enables near-lossless quantization of the
// residuals.
//
// clean enables libwebp's exact=0 handling of fully transparent pixels
// (ignored with lowEffort, as in libwebp). opaque tells that every pixel of
// argb has alpha 0xff: the predictions and (near-lossless) reconstructions
// are then opaque too, so the alpha residuals are all 0 and the mode search
// skips their histogram.
//
// With helpers > 0, the single-sampling mode search (minBits == maxBits)
// is spread over helper goroutines (see predSearch.runPar).
func predictorImage(width, height, minBits, maxBits int, lowEffort bool, maxQuant int, usedSubGreen, clean, opaque bool,
argb []uint32, modes []uint32, sc *scratch, helpers int) int {
n := width * height
var md []uint8
nl := maxQuant > 1 && !lowEffort && height >= 3 && width >= 3
if !nl {
maxQuant = 1
}
clean = clean && !lowEffort
// slow selects the per-pixel GetResidual path working on row copies.
slow := nl || clean
if nl {
md = sc.maxDiffs(n)
computeMaxDiffs(width, height, argb, usedSubGreen, md)
}
// Without near-lossless, the clean path only changes the pixels next to
// fully transparent ones: the others take the fast path (cleanMask). The
// mask uses the buffer of the max diffs (only used with near-lossless).
var mask []uint8
if clean && !nl && cleanFastPath {
mask = sc.maxDiffs(n)
cleanMask(argb[:n], width, height, mask)
}
var bits int
if lowEffort {
bits = maxBits
for i := range modes[:subSampleSize(width, bits)*subSampleSize(height, bits)] {
modes[i] = argbBlack | predLowEffort<<8
}
} else {
ps := predSearch{width: width, height: height, minBits: minBits, maxBits: maxBits,
maxQuant: maxQuant, md: md, mask: mask, usedSubGreen: usedSubGreen, clean: clean, slow: slow, opaque: opaque,
argb: argb, sc: sc}
if helpers > 0 && minBits == maxBits {
bits = ps.runPar(modes, helpers)
} else {
bits = ps.run(modes)
}
if sc.interrupted() { // the modes may be incomplete
return bits
}
}
// Replace the image by residuals, row by row, keeping the original (or,
// with near-lossless, reconstructed) previous row.
tilesX := subSampleSize(width, bits)
prev := sc.rowA(width + 1)
curCopy := sc.rowB(width + 1)
out := sc.residBuf(width)
tile := 1 << uint(bits)
for y := 0; y < height; y++ {
row := argb[y*width : (y+1)*width]
copy(curCopy, row)
if y > 0 {
prev[width] = curCopy[0]
}
mrow := modes[(y>>uint(bits))*tilesX:]
for x := 0; x < width; x += tile {
x1 := min(x+tile, width)
mode := int(mrow[x>>uint(bits)]>>8) & 0xff
switch {
case mask != nil:
residualRowClean(mode, curCopy, prev, y, width, height, x, x1, mask[y*width:(y+1)*width], out[x:x1])
case slow:
var mdRow []uint8
if nl {
mdRow = md[y*width : (y+1)*width]
}
residualRowNL(mode, curCopy, prev, y, width, height, x, x1, mdRow, maxQuant, usedSubGreen, clean, out[x:x1])
default:
residualRow(mode, curCopy, prev, y, x, x1, out[x:x1])
}
}
copy(row, out[:width])
prev, curCopy = curCopy, prev
}
return bits
}
// predSearch is libwebp's GetBestPredictorsAndSubSampling: the best mode of
// every tile is searched at every sampling from minBits to maxBits at once.
//
// Tiles of 1<<minBits pixels are visited in Z order within each max-tile
// (of 1<<maxBits pixels) so that super-tiles are completed as soon as
// possible:
//
// 1 2| 5 6
// 3 4| 7 8
// -----------
// 9 10| 13 14
// 11 12| 15 16
//
// The residual histograms of a tile (for each mode) are added to those of
// its enclosing super-tiles; when a super-tile is complete its best mode is
// chosen like for a tile, with its own accumulated histogram.
type predSearch struct {
width, height int
minBits, maxBits int
maxQuant int
md []uint8
mask []uint8 // see cleanMask (nil: every pixel takes the slow path)
usedSubGreen bool
clean, slow bool
opaque bool // every alpha residual is 0 (see predictorImage)
argb []uint32
sc *scratch
hist []histo4 // [level][mode] residual histograms of the current (super-)tiles
acc []histo4 // [level] accumulated histograms of the chosen modes
levelMode [][]uint32
predHisto [(maxTransformBits - minTransformBits + 1) * numPredModes]int32
}
// setup prepares the mode images and the accumulated histograms of every
// sampling level.
func (ps *predSearch) setup() {
width, height, minBits := ps.width, ps.height, ps.minBits
levels := ps.maxBits - minBits + 1
total := 0
for l := 0; l < levels; l++ {
total += subSampleSize(width, minBits+l) * subSampleSize(height, minBits+l)
}
all := ps.sc.predModeBuf(total)
if cap(ps.levelMode) < levels {
ps.levelMode = make([][]uint32, levels)
}
ps.levelMode = ps.levelMode[:levels]
off := 0
for l := 0; l < levels; l++ {
sz := subSampleSize(width, minBits+l) * subSampleSize(height, minBits+l)
ps.levelMode[l] = all[off : off+sz]
off += sz
}
ps.acc = ps.sc.predAcc(levels)
}
func (ps *predSearch) run(modes []uint32) int {
width, height := ps.width, ps.height
minBits := ps.minBits
sc := ps.sc
tilesPerRow := subSampleSize(width, minBits)
tilesPerCol := subSampleSize(height, minBits)
maxSub := ps.maxBits - minBits
// Residuals are added directly to the histograms of the super-tiles up
// to updateUpTo (cheaper for small tiles); larger super-tiles add the
// histograms of the finished smaller ones.
updateUpTo := max(min(4, ps.maxBits), minBits) - minBits
levels := maxSub + 1
ps.setup()
ps.hist = sc.predHistos(levels * numPredModes)
tile := 1 << uint(minBits)
resid := sc.residBuf(tile * tile)
rowCur, rowUp := sc.rowA(width+1), sc.rowB(width+1)
maxTileSize := 1 << uint(maxSub) // in tiles
var localX, localY, maxTileX, maxTileY, tileX, tileY int
for tileY < tilesPerCol {
// Residuals of the tile for every mode.
sx, sy := tileX<<uint(minBits), tileY<<uint(minBits)
maxX := min(tile, width-sx)
maxY := min(tile, height-sy)
slow := ps.tileSlow(sx, sy, maxX, maxY)
for mode := 0; mode < numPredModes; mode++ {
r := resid[:maxX*maxY]
ps.tileResiduals(mode, sx, sy, maxX, maxY, slow, r, rowCur, rowUp)
for l := 0; l <= updateUpTo; l++ {
ps.addResiduals(&ps.hist[l*numPredModes+mode], r)
}
}
// Update all the super-tiles that are complete.
sub := 0
for {
ps.bestForTile(sub, tileX>>uint(sub), tileY>>uint(sub), subSampleSize(width, minBits+sub))
if sub == maxSub {
break
}
sub++
if sub > updateUpTo {
dst := ps.hist[sub*numPredModes : (sub+1)*numPredModes]
src := ps.hist[(sub-1)*numPredModes : sub*numPredModes]
for m := range dst {
addHisto4(&dst[m], &src[m])
}
}
if !((tileX == tilesPerRow-1 || (localX+1)%(1<<uint(sub)) == 0) &&
(tileY == tilesPerCol-1 || (localY+1)%(1<<uint(sub)) == 0)) {
sub-- // index of the last finished super-tile
break
}
}
// Reset the histograms of the finished (super-)tiles.
clear(ps.hist[:(sub+1)*numPredModes])
if sub == maxSub {
// Start a new max-tile.
if tileX == tilesPerRow-1 {
maxTileX = 0
maxTileY++
if sc.interrupted() {
break
}
} else {
maxTileX++
}
localX, localY = 0, 0
} else {
// Proceed with the Z traversal.
cx := localX >> uint(sub)
cy := localY >> uint(sub)
switch {
case tileX == tilesPerRow-1 && cx%2 == 0:
cy++
case cx%2 == 0:
cx++
default:
cy++
cx--
}
localX = cx << uint(sub)
localY = cy << uint(sub)
}
tileX = maxTileX*maxTileSize + localX
tileY = maxTileY*maxTileSize + localY
}
return ps.finish(modes)
}
// finish picks the sampling with the lowest cost (entropy of the mode image
// plus entropy of the residuals), copies its mode image into modes and
// returns its (optimized) bits.
func (ps *predSearch) finish(modes []uint32) int {
width, height, minBits := ps.width, ps.height, ps.minBits
levels := ps.maxBits - minBits + 1
bestCost := math.Inf(1)
best := 0
for l := 0; l < levels; l++ {
cost := shannonEntropy(ps.predHisto[l*numPredModes : (l+1)*numPredModes])
for c := 0; c < 4; c++ {
cost += shannonEntropy(ps.acc[l][c][:])
}
if cost < bestCost {
bestCost = cost
best = l
}
}
bits := minBits + best
copy(modes, ps.levelMode[best])
return optimizeSampling(modes, width, height, bits, maxTransformBits)
}
// predWorker holds the working buffers of one goroutine of runPar.
type predWorker struct {
resid, rowCur, rowUp []uint32
}
// runPar is run for a single sampling (minBits == maxBits), with the
// residual histograms of the tiles (for every mode) computed by the caller
// and up to helpers helper goroutines, a batch of tiles at a time, while
// the caller chooses the modes of the previous batch in raster order (the
// choice of a tile depends on the choices before it). The histograms are
// pure functions of the tiles, so the modes are those of run.
func (ps *predSearch) runPar(modes []uint32, helpers int) int {
width, height, bits := ps.width, ps.height, ps.minBits
sc := ps.sc
tilesX := subSampleSize(width, bits)
nt := tilesX * subSampleSize(height, bits)
ps.setup()
tile := 1 << uint(bits)
// Batches of about 32K pixels (at least 16 tiles), double-buffered:
// their histograms take 56 KB per tile.
batch := min(max(32768/(tile*tile), 16), 64)
nb := (nt + batch - 1) / batch
bufs := sc.predBatchBufs(2 * batch * numPredModes)
work := sc.predWorkers(helpers+1, tile*tile, width+1)
compute := func(b, worker int, claim func() (int, bool)) {
w := &work[worker]
buf := bufs[(b&1)*batch*numPredModes:]
for {
k, ok := claim()
if !ok {
return
}
t := b*batch + k
sx, sy := (t%tilesX)<<uint(bits), (t/tilesX)<<uint(bits)
maxX, maxY := min(tile, width-sx), min(tile, height-sy)
hs := buf[k*numPredModes : (k+1)*numPredModes]
clear(hs)
r := w.resid[:maxX*maxY]
slow := ps.tileSlow(sx, sy, maxX, maxY)
for mode := range hs {
ps.tileResiduals(mode, sx, sy, maxX, maxY, slow, r, w.rowCur, w.rowUp)
ps.addResiduals(&hs[mode], r)
}
}
}
consume := func(b int) {
buf := bufs[(b&1)*batch*numPredModes:]
for t := b * batch; t < min((b+1)*batch, nt); t++ {
k := t - b*batch
ps.hist = buf[k*numPredModes : (k+1)*numPredModes]
ps.bestForTile(0, t%tilesX, t/tilesX, tilesX)
}
}
batchTiles := func(b int) int { return min(batch, nt-b*batch) }
// The caller chooses the modes of batch cur-1 (if any) while the
// helpers compute batch cur (into the other buffer), then joins them.
// (One closure for all the batches: the stages run on the crew of the
// scratch.)
cur := 0
stage := func(worker int, claim func() (int, bool)) {
if worker == 0 && cur > 0 {
consume(cur - 1)
}
compute(cur, worker, claim)
}
sc.crew.run(batchTiles(0), helpers, stage)
for b := 0; b < nb; b++ {
if sc.interrupted() {
break // the caller reports the interruption (modes are incomplete)
}
if b+1 == nb {
consume(b)
break
}
cur = b + 1
sc.crew.run(batchTiles(cur), helpers, stage)
}
sc.crew.stop() // (no helpers held through the sequential stages that follow)
return ps.finish(modes)
}
// addResiduals adds the residuals r to h. For an opaque image, their alpha
// is 0 (see predictorImage): it is counted at once.
func (ps *predSearch) addResiduals(h *histo4, r []uint32) {
if !ps.opaque {
for _, p := range r {
h.add(p)
}
return
}
h[0][0] += int32(len(r))
for _, p := range r {
h[1][(p>>16)&0xff]++
h[2][(p>>8)&0xff]++
h[3][p&0xff]++
}
}
// bestForTile chooses the mode of the (super-)tile (tx, ty) at level sub
// (libwebp GetBestPredictorForTile).
func (ps *predSearch) bestForTile(sub, tx, ty, perRow int) {
modes := ps.levelMode[sub]
acc := &ps.acc[sub]
leftMode, aboveMode := -1, -1
if tx > 0 {
leftMode = int(modes[ty*perRow+tx-1]>>8) & 0xff
}
if ty > 0 {
aboveMode = int(modes[(ty-1)*perRow+tx]>>8) & 0xff
}
var ae [4]accEntropy
for i := range ae {
ae[i].init(&acc[i])
}
hs := ps.hist[sub*numPredModes : (sub+1)*numPredModes]
bestDiff := math.Inf(1)
bestMode := 0
for mode := range hs {
d := predictionCostSpatialHistogram(acc, &hs[mode], &ae)
if mode == leftMode {
d -= spatialPredictorBias
}
if mode == aboveMode {
d -= spatialPredictorBias
}
if d < bestDiff {
bestDiff = d
bestMode = mode
}
}
addHisto4(acc, &hs[bestMode])
modes[ty*perRow+tx] = argbBlack | uint32(bestMode)<<8
ps.predHisto[sub*numPredModes+bestMode]++
}
func addHisto4(dst, src *histo4) {
for i := range dst {
d, s := &dst[i], &src[i]
for j := range d {
d[j] += s[j]
}
}
}
// shannonEntropy returns sum(X)*log2(sum(X)) - sum(x*log2(x)) (libwebp
// VP8LShannonEntropy).
func shannonEntropy(x []int32) float64 {
var r float64
var sum uint32
for _, v := range x {
if v != 0 {
sum += uint32(v)
r -= slog2(uint32(v))
}
}
return r + slog2(sum)
}
// tileSlow reports whether the residuals of a tile need the slow path
// (residualRowNL): with near-lossless, or with clean when a pixel of the
// tile depends on a fully transparent one (see cleanMask).
func (ps *predSearch) tileSlow(sx, sy, maxX, maxY int) bool {
if !ps.slow || ps.mask == nil {
return ps.slow
}
var acc uint8
for y := sy; y < sy+maxY; y++ {
for _, m := range ps.mask[y*ps.width+sx : y*ps.width+sx+maxX] {
acc |= m
}
}
return acc != 0
}
// tileResiduals computes into out the residuals of one tile for mode. slow
// is tileSlow of the tile. cur and up (width+1 entries each) are working
// rows (for the slow path).
func (ps *predSearch) tileResiduals(mode, sx, sy, maxX, maxY int, slow bool, out, cur, up []uint32) {
width := ps.width
argb := ps.argb
if !slow {
for ry := 0; ry < maxY; ry++ {
y := sy + ry
row := argb[y*width : (y+1)*width]
var up []uint32
if y > 0 {
up = argb[(y-1)*width : y*width+1]
}
residualRow(mode, row, up, y, sx, sx+maxX, out[ry*maxX:(ry+1)*maxX])
}
return
}
// Row copies, so that predictions use the reconstructed (near-lossless)
// or cleaned (transparent) pixels.
lo := sx
if lo > 0 {
lo--
}
hi := sx + maxX + 1 // one pixel past the tile (top-right context)
n := width * ps.height
for ry := 0; ry < maxY; ry++ {
y := sy + ry
if ry == 0 {
if y > 0 {
e := min((y-1)*width+hi, n)
copy(up[lo:], argb[(y-1)*width+lo:e])
}
} else {
up, cur = cur, up
}
e := min(y*width+hi, n)
copy(cur[lo:], argb[y*width+lo:e])
if ps.mask != nil {
residualRowClean(mode, cur, up, y, width, ps.height, sx, sx+maxX, ps.mask[y*width:(y+1)*width], out[ry*maxX:(ry+1)*maxX])
continue
}
var mdRow []uint8
if ps.md != nil {
mdRow = ps.md[y*width : (y+1)*width]
}
residualRowNL(mode, cur, up, y, width, ps.height, sx, sx+maxX, mdRow, ps.maxQuant, ps.usedSubGreen, ps.clean,
out[ry*maxX:(ry+1)*maxX])
}
}
// optimizeSampling checks whether image (a sub-image of a fullWidth x
// fullHeight image sampled with bits) is made of uniform squares of a larger
// power of 2 and, if so, subsamples it in place. It returns the new bits
// (at most maxBits). Port of libwebp's VP8LOptimizeSampling.
func optimizeSampling[T uint16 | uint32](image []T, fullWidth, fullHeight, bits, maxBits int) int {
width := subSampleSize(fullWidth, bits)
height := subSampleSize(fullHeight, bits)
bestBits := bits
// Check rows first.
for bestBits < maxBits {
newSquare := 1 << uint(bestBits+1-bits)
square := 1 << uint(bestBits-bits)
good := true
for y := 0; y+square < height; y += newSquare {
a := image[y*width : (y+1)*width]
b := image[(y+square)*width : (y+square+1)*width]
if !equalSlice(a, b) {
good = false
break
}
}
if !good {
break
}
bestBits++
}
if bestBits == bits {
return bits
}
// Check columns.
for bestBits > bits {
square := 1 << uint(bestBits-bits)
good := true
rows:
for y := 0; y < height; y++ {
row := image[y*width : (y+1)*width]
for x := 0; x < width; x += square {
for i := x + 1; i < min(x+square, width); i++ {
if row[i] != row[x] {
good = false
break rows
}
}
}
}
if good {
break
}
bestBits--
}
if bestBits == bits {
return bits
}
// Subsample the image.
oldWidth := width
square := 1 << uint(bestBits-bits)
width = subSampleSize(fullWidth, bestBits)
height = subSampleSize(fullHeight, bestBits)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
image[y*width+x] = image[square*(y*oldWidth+x)]
}
}
return bestBits
}
func equalSlice[T uint16 | uint32](a, b []T) bool {
b = b[:len(a)]
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package vp8lenc
import "sync"
// scratch holds all reusable buffers of one encoding goroutine.
type scratch struct {
hc hashChain
hcBox hashChain // matches of the box LZ77 parse
counts []uint16 // pixel repetition counts (box LZ77)
refs [4][]pixOrCopy
cm costModel
costMgr costManager
tmpSet histoSet
clus clusterer
out histoSet
huff huffScratch
lens []uint8
codes []uint16
hcodes []huffCode
costRing *[costRing]int64 // trace backwards costs
ccost []int64
u16buf []uint16
cache []uint32
u32abuf []uint32
resid []uint32
curbuf []uint32 // working copy of the image (encodeStream)
rowa []uint32
rowb []uint32
idxRow []uint8
md []uint8 // near-lossless max diffs, or cleanMask
predMode []uint32 // mode images of all the samplings (predSearch)
predHist []histo4 // per sampling and mode residual histograms
predAccH []histo4 // per sampling accumulated histograms
tile tilePixels
bwTmp [2]bitWriter
// ThreadLevel only.
crew crew // helpers of the parallel stages (stopped by the encode)
predBatch []histo4 // per tile and mode histograms (predSearch.runPar)
predWork []predWorker // per goroutine buffers (predSearch.runPar)
hcChain []uint32 // hash chain kept apart from the results (fillStripes)
hcMarks []uint64 // positions searched by the stripes
hcExits []int // last position searched by each stripe
sub *scratch // for sub-images encoded while the main buffers are in use
// pixels is the largest image (in pixels) this scratch has served; its
// buffers are sized accordingly.
pixels int
// interrupt is Config.Interrupt of the encode the scratch serves: long
// loops poll it to stop early.
interrupt func() bool
}
func (s *scratch) interrupted() bool { return s.interrupt != nil && s.interrupt() }
// maxPooledPixels bounds the image size whose scratch is kept in the
// sync.Pool when the free list (see freelist.go), which has a budget, does
// not take it: the buffers of a large encode (hundreds of MB for 12 MP) are
// left to the garbage collector instead of being retained until the next
// collections.
const maxPooledPixels = 2 << 20
// minScratchFit is the image size (in pixels) up to which a scratch from
// the free list serves an image of any size.
const minScratchFit = 1 << 20
var scratchPool = sync.Pool{New: func() any { return new(scratch) }}
// getScratch returns a scratch for an image of n pixels: the most recently
// returned one of the free list not sized for an image more than 4 times
// larger (whose buffers an encode of that size could reuse), else one from
// the pool.
func getScratch(n int) *scratch {
if s, ok := scratchFree.Get(func(s *scratch) bool { return s.pixels <= max(4*n, minScratchFit) }); ok {
return s
}
return scratchPool.Get().(*scratch)
}
// putScratch returns s to the free list if the budget allows, else to the
// pool unless it served an image larger than maxPooledPixels (dropping it
// bounds the memory retained by the pool).
func putScratch(s *scratch) {
s.interrupt = nil // do not retain the caller's closures in the free list or pool
s.crew.gate = nil
if scratchFree.Put(s, s.bytes()) || s.pixels > maxPooledPixels {
return
}
scratchPool.Put(s)
}
// noteSize records that s is used for an image of n pixels.
func (s *scratch) noteSize(n int) {
s.pixels = max(s.pixels, n)
}
func (s *scratch) child() *scratch {
if s.sub == nil {
s.sub = new(scratch)
}
return s.sub
}
func (s *scratch) u16(n int) []uint16 {
if cap(s.u16buf) < n {
s.u16buf = make([]uint16, n)
}
return s.u16buf[:n]
}
func (s *scratch) u32a(n int) []uint32 {
if cap(s.u32abuf) < n {
s.u32abuf = make([]uint32, n)
}
return s.u32abuf[:n]
}
// cacheBuf returns a zeroed buffer of n entries.
func (s *scratch) cacheBuf(n int) []uint32 {
if cap(s.cache) < n {
s.cache = make([]uint32, n)
}
c := s.cache[:n]
for i := range c {
c[i] = 0
}
return c
}
// curBuf returns the working image buffer of n entries (contents
// unspecified).
func (s *scratch) curBuf(n int) []uint32 {
if cap(s.curbuf) < n {
s.curbuf = make([]uint32, n)
}
return s.curbuf[:n]
}
func (s *scratch) residBuf(n int) []uint32 {
if cap(s.resid) < n {
s.resid = make([]uint32, n)
}
return s.resid[:n]
}
func (s *scratch) rowA(n int) []uint32 {
if cap(s.rowa) < n {
s.rowa = make([]uint32, n)
}
return s.rowa[:n]
}
func (s *scratch) rowB(n int) []uint32 {
if cap(s.rowb) < n {
s.rowb = make([]uint32, n)
}
return s.rowb[:n]
}
func (s *scratch) idx(n int) []uint8 {
if cap(s.idxRow) < n {
s.idxRow = make([]uint8, n)
}
return s.idxRow[:n]
}
// tmpHisto returns a cleared single histogram with the given cache bits.
func (s *scratch) tmpHisto(cacheBits int) *histo {
s.tmpSet.init(1, cacheBits)
return &s.tmpSet.h[0]
}
// refsBuf returns refs buffer i with capacity for at least n entries.
func (s *scratch) refsBuf(i, n int) []pixOrCopy {
if cap(s.refs[i]) < n {
s.refs[i] = make([]pixOrCopy, 0, n)
}
return s.refs[i][:0]
}
func (s *scratch) maxDiffs(n int) []uint8 {
if cap(s.md) < n {
s.md = make([]uint8, n)
}
return s.md[:n]
}
func (s *scratch) predModeBuf(n int) []uint32 {
if cap(s.predMode) < n {
s.predMode = make([]uint32, n)
}
return s.predMode[:n]
}
// predHistos returns n cleared histograms.
func (s *scratch) predHistos(n int) []histo4 {
if cap(s.predHist) < n {
s.predHist = make([]histo4, n)
}
h := s.predHist[:n]
clear(h)
return h
}
// predAcc returns n cleared histograms.
func (s *scratch) predAcc(n int) []histo4 {
if cap(s.predAccH) < n {
s.predAccH = make([]histo4, n)
}
h := s.predAccH[:n]
clear(h)
return h
}
// predBatchBufs returns n histograms (contents unspecified).
func (s *scratch) predBatchBufs(n int) []histo4 {
if cap(s.predBatch) < n {
s.predBatch = make([]histo4, n)
}
return s.predBatch[:n]
}
// predWorkers returns the buffers of n goroutines of predSearch.runPar.
func (s *scratch) predWorkers(n, resid, row int) []predWorker {
if len(s.predWork) < n {
s.predWork = append(s.predWork, make([]predWorker, n-len(s.predWork))...)
}
w := s.predWork[:n]
for i := range w {
if cap(w[i].resid) < resid {
w[i].resid = make([]uint32, resid)
}
if cap(w[i].rowCur) < row {
w[i].rowCur = make([]uint32, row)
w[i].rowUp = make([]uint32, row)
}
w[i].resid, w[i].rowCur, w[i].rowUp = w[i].resid[:resid], w[i].rowCur[:row], w[i].rowUp[:row]
}
return w
}
// hcChainBuf returns a buffer of n entries (contents unspecified).
func (s *scratch) hcChainBuf(n int) []uint32 {
if cap(s.hcChain) < n {
s.hcChain = make([]uint32, n)
}
return s.hcChain[:n]
}
// hcMarkBuf returns n cleared words.
func (s *scratch) hcMarkBuf(n int) []uint64 {
if cap(s.hcMarks) < n {
s.hcMarks = make([]uint64, n)
}
m := s.hcMarks[:n]
clear(m)
return m
}
func (s *scratch) hcExitBuf(n int) []int {
if cap(s.hcExits) < n {
s.hcExits = make([]int, n)
}
return s.hcExits[:n]
}
func (s *scratch) cacheCosts(n int) []int64 {
if cap(s.ccost) < n {
s.ccost = make([]int64, n)
}
return s.ccost[:n]
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package workers is the process-wide budget for the helper goroutines the
// codec starts on its own (decoder.Options.UseThreads, encoder ThreadLevel).
//
// Every helper goroutine must be started through Spawn. The budget is
// GOMAXPROCS-1 helpers in total across all concurrent Encode/Decode calls
// (GOMAXPROCS is re-read on every call), so a server that already runs one
// request per core does not get oversubscribed: when no slot is free, Spawn
// returns nil and the caller must do the work itself, on its own goroutine
// (every parallel code path therefore keeps a sequential fallback).
//
// A panic in a helper is recovered, so that it cannot crash the process from
// a goroutine the caller cannot recover in; Task.Wait re-raises it on the
// caller's goroutine as a *PanicError, the same place a panic of the
// sequential code path would surface.
package workers
import (
"errors"
"fmt"
"runtime"
"runtime/debug"
"sync/atomic"
)
var (
inUse atomic.Int64
// limit overrides the budget when > 0 (tests).
limit atomic.Int64
)
// Limit returns the current budget: the number of helper goroutines that may
// run at the same time in the whole process.
func Limit() int {
if l := limit.Load(); l > 0 {
return int(l)
}
return runtime.GOMAXPROCS(0) - 1
}
// SetLimitForTest overrides the budget (n > 0) or restores the default
// (n <= 0) and returns the previous override. Tests only.
func SetLimitForTest(n int) int {
if n < 0 {
n = 0
}
return int(limit.Swap(int64(n)))
}
// InUse returns the number of helper goroutines currently running.
func InUse() int { return int(inUse.Load()) }
// handing counts the calls in progress whose goroutines wake each other up
// while they keep working (see SpareProcs).
var handing atomic.Int64
// BeginHandOffs registers a call whose goroutines hand work to each other
// (a pipeline of stages), until EndHandOffs.
func BeginHandOffs() { handing.Add(1) }
// EndHandOffs ends a call registered by BeginHandOffs.
func EndHandOffs() { handing.Add(-1) }
// SpareProcs reports whether the process probably has idle processors:
// calls registered by BeginHandOffs occupy at most half of procs (the
// GOMAXPROCS the caller read when it started). A goroutine that wakes up
// another one and keeps working may then yield its processor
// (runtime.Gosched), so that the woken goroutine starts at once instead of
// after the scheduler's back-off while the waker moves to an idle
// processor; on a busy process that yield would only add a context switch
// to every hand-off.
func SpareProcs(procs int) bool { return 2*handing.Load() <= int64(procs) }
// HandOffs returns the number of calls registered by BeginHandOffs that
// are in progress (tests).
func HandOffs() int { return int(handing.Load()) }
// TryAcquire reserves one helper slot if the budget allows. A successful call
// must be paired with Release. Prefer Spawn, which pairs them and recovers
// panics.
func TryAcquire() bool {
max := int64(Limit())
for {
n := inUse.Load()
if n >= max {
return false
}
if inUse.CompareAndSwap(n, n+1) {
return true
}
}
}
// Release returns a slot obtained with TryAcquire.
func Release() { inUse.Add(-1) }
// PanicError carries a panic recovered in a helper goroutine.
type PanicError struct {
Value any
Stack []byte
}
func (e *PanicError) Error() string {
return fmt.Sprintf("webp: panic in helper goroutine: %v\n%s", e.Value, e.Stack)
}
// Unwrap returns the panic value when it is an error.
func (e *PanicError) Unwrap() error {
err, _ := e.Value.(error)
return err
}
// Task is a helper goroutine started by Spawn.
type Task struct {
done chan struct{}
err error
pe *PanicError
}
// Spawn starts f on a new helper goroutine when the budget has a free slot
// and returns its Task; otherwise it returns nil without running f, and the
// caller must do the work itself.
//
// The slot is released when f returns or panics. The caller must call Wait
// (typically deferred) before returning, so no helper outlives the
// Encode/Decode call that started it.
func Spawn(f func() error) *Task {
if !TryAcquire() {
return nil
}
t := &Task{done: make(chan struct{})}
go t.run(f)
return t
}
// ErrGoexit is the PanicError value of a helper that called runtime.Goexit
// (for example testing.T.FailNow in a callback such as a sink): its work is
// incomplete, so Wait must not report it as a success.
var ErrGoexit = errors.New("runtime.Goexit called in a helper goroutine")
func (t *Task) run(f func() error) {
defer close(t.done)
defer Release()
returned := false
defer func() {
if r := recover(); r != nil {
t.pe = &PanicError{Value: r, Stack: debug.Stack()}
} else if !returned {
t.pe = &PanicError{Value: ErrGoexit, Stack: debug.Stack()}
}
}()
t.err = f()
returned = true
}
// Done is closed when the helper has returned (normally or by panicking).
// Producers blocked on sending to a helper should also select on Done, so
// that a failed helper cannot deadlock them.
func (t *Task) Done() <-chan struct{} { return t.done }
// Wait blocks until the helper has returned and returns f's error. If f
// panicked, or exited through runtime.Goexit (PanicError.Value ErrGoexit),
// Wait panics with the *PanicError on the calling goroutine.
func (t *Task) Wait() error {
<-t.done
if t.pe != nil {
panic(t.pe)
}
return t.err
}
// Panicked reports, after Done is closed, whether f panicked or called
// runtime.Goexit (without re-raising it). It lets deferred cleanup run
// before Wait re-panics.
func (t *Task) Panicked() bool {
<-t.done
return t.pe != nil
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package utils
// noinspection GoUnusedConst
const (
Vp8StatusOk VP8StatusCode = iota
Vp8StatusOutOfMemory
Vp8StatusInvalidParam
Vp8StatusBitstreamError
Vp8StatusUnsupportedFeature
Vp8StatusSuspended
Vp8StatusUserAbort
Vp8StatusNotEnoughData
)
type VP8StatusCode int
func (c VP8StatusCode) String() (label string) {
switch c {
case Vp8StatusOk:
label = "VP8_STATUS_OK"
case Vp8StatusOutOfMemory:
label = "VP8_STATUS_OUT_OF_MEMORY"
case Vp8StatusInvalidParam:
label = "VP8_STATUS_INVALID_PARAM"
case Vp8StatusBitstreamError:
label = "VP8_STATUS_BITSTREAM_ERROR"
case Vp8StatusUnsupportedFeature:
label = "VP8_STATUS_UNSUPPORTED_FEATURE"
case Vp8StatusSuspended:
label = "VP8_STATUS_SUSPENDED"
case Vp8StatusUserAbort:
label = "VP8_STATUS_USER_ABORT"
case Vp8StatusNotEnoughData:
label = "VP8_STATUS_NOT_ENOUGH_DATA"
default:
label = "VP8 undefined status code"
}
return
}
const (
Vp8EncOk Vp8EncStatus = iota
Vp8EncErrorOutOfMemory
Vp8EncErrorBitstreamOutOfMemory
Vp8EncErrorNullParameter
Vp8EncErrorInvalidConfiguration
Vp8EncErrorBadDimension
Vp8EncErrorPartition0Overflow
Vp8EncErrorPartitionOverflow
Vp8EncErrorBadWrite
Vp8EncErrorFileTooBig
Vp8EncErrorUserAbort
Vp8EncErrorLast
)
type Vp8EncStatus int
func (c Vp8EncStatus) String() (label string) {
switch c {
case Vp8EncOk:
label = "VP8_ENC_OK"
case Vp8EncErrorOutOfMemory:
label = "VP8_ENC_ERROR_OUT_OF_MEMORY"
case Vp8EncErrorBitstreamOutOfMemory:
label = "VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY"
case Vp8EncErrorNullParameter:
label = "VP8_ENC_ERROR_NULL_PARAMETER"
case Vp8EncErrorInvalidConfiguration:
label = "VP8_ENC_ERROR_INVALID_CONFIGURATION"
case Vp8EncErrorBadDimension:
label = "VP8_ENC_ERROR_BAD_DIMENSION"
case Vp8EncErrorPartition0Overflow:
label = "VP8_ENC_ERROR_PARTITION0_OVERFLOW"
case Vp8EncErrorPartitionOverflow:
label = "VP8_ENC_ERROR_PARTITION_OVERFLOW"
case Vp8EncErrorBadWrite:
label = "VP8_ENC_ERROR_BAD_WRITE"
case Vp8EncErrorFileTooBig:
label = "VP8_ENC_ERROR_FILE_TOO_BIG"
case Vp8EncErrorUserAbort:
label = "VP8_ENC_ERROR_USER_ABORT"
case Vp8EncErrorLast:
label = "VP8_ENC_ERROR_LAST"
default:
label = "VP8 undefined status code"
}
return
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package webp
import (
"context"
"image"
"io"
"github.com/kolesa-team/go-webp/v2/decoder"
"github.com/kolesa-team/go-webp/v2/internal/ctxio"
)
// DecodeInto decodes a picture from r into dst, reusing the memory of
// dst.Pix when it is large enough, and returns dst (a new image when dst is
// nil). See decoder.Decoder.DecodeInto for the exact semantics. r is read
// by decoder.NewDecoder, which copies an input already in memory: to
// decode a []byte without that copy, use decoder.NewDecoderBytes and its
// DecodeInto method.
func DecodeInto(r io.Reader, dst *image.NRGBA, options *decoder.Options) (*image.NRGBA, error) {
dec, err := decoder.NewDecoder(r, options)
if err != nil {
return nil, err
}
return dec.DecodeInto(dst)
}
// DecodeIntoContext is DecodeInto with cancellation, as DecodeContext is
// Decode with cancellation. It returns ctx.Err() itself when ctx is already
// done. Then ctx is checked before each Read of r and between batches of
// output rows: once it is done, DecodeIntoContext returns the error of a
// cancelled decode, without reading r any further. The fields of dst are
// then unchanged, as after every error of DecodeInto. A Read already
// blocked in r is not interrupted: see DecodeContext for how to bound it.
func DecodeIntoContext(ctx context.Context, r io.Reader, dst *image.NRGBA, options *decoder.Options) (*image.NRGBA, error) {
dec, err := newDecoderContext(ctx, r, options)
if err != nil {
return nil, err
}
return dec.DecodeIntoContext(ctx, dst)
}
// DecodeContext is Decode with cancellation. It returns ctx.Err() itself
// when ctx is already done. Then ctx is checked before each Read of r and
// between batches of output rows: once it is done, DecodeContext returns
// the error of a cancelled decode (see decoder.Decoder.DecodeContext),
// without reading r any further.
//
// A Read already blocked in r is not interrupted: with a client that stops
// sending, DecodeContext returns only when that Read does. Bound the read at
// its source too, for example with http.ResponseController.SetReadDeadline
// for a request body in an http.Handler, or with a request made with ctx
// (http.NewRequestWithContext) for a response body.
func DecodeContext(ctx context.Context, r io.Reader, options *decoder.Options) (image.Image, error) {
dec, err := newDecoderContext(ctx, r, options)
if err != nil {
return nil, err
}
return dec.DecodeContext(ctx)
}
// newDecoderContext is decoder.NewDecoder reading r under ctx, for
// DecodeContext and DecodeIntoContext.
func newDecoderContext(ctx context.Context, r io.Reader, options *decoder.Options) (*decoder.Decoder, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if ctx.Done() != nil {
r = &ctxio.Reader{Ctx: ctx, R: r}
}
return decoder.NewDecoder(r, options)
}
// The MIT License (MIT)
//
// Copyright (c) 2019 Amangeldy Kadyl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package webp encodes and decodes WebP images with a pure Go implementation
// of libwebp's codecs (no cgo). Importing it registers the "webp" format with
// the standard image package.
package webp
import (
"context"
"errors"
"image"
"image/color"
"io"
"github.com/kolesa-team/go-webp/v2/decoder"
"github.com/kolesa-team/go-webp/v2/encoder"
"github.com/kolesa-team/go-webp/v2/internal/container"
"github.com/kolesa-team/go-webp/v2/internal/oneshot"
"github.com/kolesa-team/go-webp/v2/internal/status"
"github.com/kolesa-team/go-webp/v2/utils"
)
func init() {
image.RegisterFormat("webp", "RIFF????WEBPVP8", quickDecode, quickDecodeConfig)
}
func quickDecode(r io.Reader) (image.Image, error) {
return Decode(r, &decoder.Options{})
}
func quickDecodeConfig(r io.Reader) (image.Config, error) {
return DecodeConfig(r, &decoder.Options{})
}
// Decode reads a picture from r (see decoder.NewDecoder) and decodes it
// into a new *image.NRGBA. To decode many pictures, use DecodeInto with one
// image for all of them: the output is nearly all of a decode's memory (4
// bytes per pixel), and reusing it removes most of the garbage collector's
// work.
func Decode(r io.Reader, options *decoder.Options) (image.Image, error) {
dec, err := decoder.NewDecoder(r, options)
if err != nil {
return nil, err
}
return dec.Decode()
}
// DecodeConfig returns the dimensions of a WebP picture without decoding its
// pixels. Only the headers up to the VP8/VP8L frame header are read from r;
// they are validated like decoder.NewDecoder does.
//
// For compatibility with v1 the reported ColorModel is color.RGBAModel,
// although Decode returns an *image.NRGBA.
func DecodeConfig(r io.Reader, options *decoder.Options) (image.Config, error) {
if _, err := options.GetConfig(); err != nil {
return image.Config{}, err
}
f, err := readFeatures(r)
if err != nil {
return image.Config{}, err
}
return image.Config{
ColorModel: color.RGBAModel,
Width: f.Width,
Height: f.Height,
}, nil
}
// GetFeatures returns the features of a WebP picture (dimensions, alpha,
// animation, lossy/lossless) reading only its headers from r.
func GetFeatures(r io.Reader) (utils.BitstreamFeatures, error) {
f, err := readFeatures(r)
if err != nil {
return utils.BitstreamFeatures{}, err
}
return utils.BitstreamFeatures{
Width: f.Width,
Height: f.Height,
HasAlpha: f.HasAlpha,
HasAnimation: f.HasAnimation,
Format: f.Format,
}, nil
}
// featuresError formats like decoder.NewDecoder's errors and unwraps to the
// underlying *status.Error.
type featuresError struct{ err error }
func (e *featuresError) Error() string {
return "cannot fetch features: " + status.CodeOf(e.err).String()
}
func (e *featuresError) Unwrap() error { return e.err }
// readFeatures reads a growing prefix of r until the WebP headers up to the
// VP8/VP8L frame header can be parsed (or r ends), and returns the same
// features and errors as container.GetFeatures on the whole file, which is
// what decoder.NewDecoder (and libwebp's WebPGetFeatures) report.
func readFeatures(r io.Reader) (container.Features, error) {
buf := make([]byte, 0, 64)
eof := false
for {
for !eof && len(buf) < cap(buf) {
n, err := r.Read(buf[len(buf):cap(buf)])
buf = buf[:len(buf)+n]
if err == io.EOF {
eof = true
} else if err != nil {
return container.Features{}, err
}
}
if len(buf) == 0 {
return container.Features{}, errors.New("data is empty")
}
f, done, err := container.GetFeaturesPrefix(buf)
if !done && eof {
f, err = container.GetFeatures(buf)
done = true
}
if done {
if err != nil {
return container.Features{}, &featuresError{err: err}
}
return f, nil
}
nb := make([]byte, len(buf), 2*cap(buf))
copy(nb, buf)
buf = nb
}
}
// Encode picture and write to io.Writer
func Encode(w io.Writer, src image.Image, options *encoder.Options) error {
enc, err := encoder.NewEncoder(oneShot(src, options), options)
if err != nil {
return err
}
// One shot: the snapshot of src, if any, goes back to the pools right
// away.
defer enc.Release()
return enc.Encode(w)
}
// oneShot returns src marked as the source of a one-shot encode (see
// oneshot.Source) for a lossless encode of a picture that NewEncoder would
// otherwise copy: the encoder then converts it straight into its working
// image, without the copy (4 bytes per pixel). The mark, a struct in an
// interface, takes an allocation of 16 bytes, which a lossy encode and an
// *image.NRGBA source, that would gain nothing from it, are spared.
func oneShot(src image.Image, options *encoder.Options) image.Image {
if _, ok := src.(*image.NRGBA); ok || options == nil || !options.Lossless {
return src
}
return oneshot.Source{Image: src}
}
// EncodeContext is Encode, but gives up when ctx is done and then returns
// ctx.Err(), writing nothing to w (see encoder.Encoder.EncodeContext). A
// lossless encode of a picture other than an *image.NRGBA, which converts
// it while it encodes instead of in encoder.NewEncoder, also checks ctx
// every 16 rows of that conversion.
func EncodeContext(ctx context.Context, w io.Writer, src image.Image, options *encoder.Options) error {
if err := ctx.Err(); err != nil {
return err
}
enc, err := encoder.NewEncoder(oneShot(src, options), options)
if err != nil {
return err
}
defer enc.Release()
return enc.EncodeContext(ctx, w)
}