Files
ziran/std/resample.zi
T
waozi cef1a98d95 std/resample: NEON and SIMD128 kernels in std/simd
The ARMv7, AArch64 and WebAssembly row kernels move from #asm to std/simd,
making the same bytes. Each tap's bytes widen to 32 bits and take its whole
weight; the horizontal kernel takes four taps a step and walks pointers with
32-bit counts, which ARMv7 and wasm32 keep in one register.

On a Cortex-A53 (ARMv7) resizes run 3 to 10% faster than the assembly, and
under wasmtime about twice as fast.

ziran_simd.h: Clang's ARMv7 backend copied an unaligned 8-byte load that it
merged into a widening through the stack; Simd.LoadLow now keeps it one
vld1.

tests/lanczos_isa_bitexact.sh runs the WebAssembly modules standalone with
WASI_RUN (such as wasmtime run), without JavaScript.
2026-11-07 07:20:21 -03:00

810 lines
35 KiB
Ziran

// Pillow's separable resampling of 8-bit RGBA as allocation-free row
// kernels, with std/simd versions for x86-64 (SSE2 to AVX2), NEON (AArch64
// and ARMv7) and WebAssembly SIMD128 that make the same bytes.
//
// axis: ResampleAxis
// ResampleAxisInto(*axis, 640, 853, RESAMPLE_LANCZOS) // weights once
// ResampleRowHorizontal(*axis, source_row, target_row) // then every row
//
// ResamplePlan resizes a whole premultiplied picture in two passes with
// scratch it owns, so resizing again to the same size never allocates; its
// passes split into row ranges for worker threads.
//
// Weights are Pillow's 22-bit fixed point, each pass rounds to bytes and
// the arithmetic is on the stored (premultiplied) bytes, not linear light,
// as in Pillow. The scalar loops are the reference; the fastest kernels
// this CPU has are chosen once. An axis whose sums could leave 32 bits,
// which Pillow's filters never produce, uses the scalar loops. Pointer
// kernels need a native target; std/image keeps the portable resizes.
using Vectors :: #import "vec"
#import "math"
Simd :: #import "simd"
RESAMPLE_BOX :: 0
RESAMPLE_LANCZOS :: 1
RESAMPLE_BICUBIC :: 2
RESAMPLE_SCALAR :: 0
RESAMPLE_SSE2 :: 1
RESAMPLE_AVX2 :: 2
RESAMPLE_NEON :: 3
RESAMPLE_SIMD128 :: 4
// Weights from INPUT source positions to OUTPUT positions along one axis.
ResampleAxis :: struct {
input: s32
output: s32
// Weights kept per output position, and u32 words per packed entry.
size: s32
entry: s32
// Every partial sum fits in 32 bits, so the vector kernels are exact.
exact: bool
// First source position and tap count of each output position.
bounds: Vec(s32)
weights: Vec(s32)
// Each output: first position, count, then per pair of taps the 16-bit
// low halves of both weights and their high halves.
packed: Vec(u32)
scratch: Vec(float64)
}
// Both passes of one resize and the rows between them.
ResamplePlan :: struct {
horizontal: ResampleAxis
vertical: ResampleAxis
source_width: s32
source_height: s32
width: s32
height: s32
horizontal_pass: bool
vertical_pass: bool
// Source rows the horizontal pass makes, from first_row.
first_row: s32
rows: s32
// The horizontal pass's rows when the vertical pass reads them.
intermediate: Vec(u8)
}
#scope_file
ROUND :: 2097152
LIMIT :: 1069547520
resample_forced: s32 = -1;
Truncate :: (value: float64) -> s32 { return cast(s32)value }
Sinc :: (x: float64) -> float64 {
if x == 0.0 { return 1.0 }
angle := x * 3.14159265358979323846
return Sin(angle) / angle
}
// std/image's filters, evaluated in the same order.
Filter :: (filter: s32, x: float64) -> float64 {
if filter == RESAMPLE_LANCZOS {
if x >= -3.0 && x < 3.0 { return Sinc(x) * Sinc(x / 3.0) }
return 0.0
}
if filter == RESAMPLE_BICUBIC {
distance := ifx x < 0.0 then -x else x
if distance < 1.0 { return ((1.5 * distance - 2.5) * distance) * distance + 1.0 }
if distance < 2.0 { return (((distance - 5.0) * distance + 8.0) * distance - 4.0) * -0.5 }
return 0.0
}
if x > -0.5 && x <= 0.5 { return 1.0 }
return 0.0
}
Clip32 :: (value: s32) -> u8 {
if value >= LIMIT { return 255 }
if value <= 0 { return 0 }
return cast(u8)(value >> 22)
}
Clip64 :: (value: s64) -> u8 {
if value >= cast(s64)LIMIT { return 255 }
if value <= 0 { return 0 }
return cast(u8)(value >> 22)
}
// The low 16 bits of WEIGHT as a signed half; the rest is the high half.
LowHalf :: (weight: s32) -> s32 {
bits := weight & 65535
return ifx bits >= 32768 then bits - 65536 else bits
}
HighHalf :: (weight: s32) -> s32 { return (weight - LowHalf(weight)) / 65536 }
PackHalves :: (first: s32, second: s32) -> u32 {
return cast(u32)(first & 65535) | (cast(u32)(second & 65535) << 16)
}
// Reference loops. Partial sums of an exact axis stay inside 32 bits.
HorizontalScalar :: (axis: *ResampleAxis, source: *u8, target: *u8) {
size := cast(s64)axis.size
bounds := *axis.bounds[0]
weights := *axis.weights[0]
for x: cast(s64)0..cast(s64)axis.output - 1 {
low := cast(s64)bounds[x * 2]
count := cast(s64)bounds[x * 2 + 1]
row := x * size
at := low * 4
to := x * 4
if axis.exact {
r: s32 = ROUND; g: s32 = ROUND; b: s32 = ROUND; a: s32 = ROUND
for k: cast(s64)0..count - 1 {
w := weights[row + k]
r += cast(s32)source[at] * w
g += cast(s32)source[at + 1] * w
b += cast(s32)source[at + 2] * w
a += cast(s32)source[at + 3] * w
at += 4
}
target[to] = Clip32(r); target[to + 1] = Clip32(g)
target[to + 2] = Clip32(b); target[to + 3] = Clip32(a)
} else {
r: s64 = ROUND; g: s64 = ROUND; b: s64 = ROUND; a: s64 = ROUND
for k: cast(s64)0..count - 1 {
w := cast(s64)weights[row + k]
r += cast(s64)source[at] * w
g += cast(s64)source[at + 1] * w
b += cast(s64)source[at + 2] * w
a += cast(s64)source[at + 3] * w
at += 4
}
target[to] = Clip64(r); target[to + 1] = Clip64(g)
target[to + 2] = Clip64(b); target[to + 3] = Clip64(a)
}
}
}
// Bytes [START, END) of one output row from COUNT rows STRIDE bytes apart,
// in blocks so each source row is read in order.
VerticalScalar :: (rows: *u8, stride: s64, weights: *s32, count: s64, exact: bool,
target: *u8, start: s64, end: s64) {
if !exact {
for i: start..end - 1 {
sum: s64 = ROUND
at := i
for k: cast(s64)0..count - 1 {
sum += cast(s64)rows[at] * cast(s64)weights[k]
at += stride
}
target[i] = Clip64(sum)
}
return
}
sums: [64]s32
block := start
while block < end {
n := end - block
if n > 64 { n = 64 }
for i: cast(s64)0..n - 1 { sums[i] = ROUND }
for k: cast(s64)0..count - 1 {
w := weights[k]
at := k * stride + block
for i: cast(s64)0..n - 1 { sums[i] += cast(s32)rows[at + i] * w }
}
for i: cast(s64)0..n - 1 { target[block + i] = Clip32(sums[i]) }
block += n
}
}
// The kernels below each implement their scalar body. A horizontal kernel
// makes a whole row; a vertical kernel makes BYTES bytes, a multiple of its
// width. Packed entries hold 16-bit weight halves for pmaddwd, whose two
// products per lane combine as low + (high << 16), exactly, modulo 2^32.
HasAvx2 :: () -> s32 #asm("x86_64+avx2", "movl $1, %[out]", "=r", "", "", "") { return 0 }
HasSse2 :: () -> s32 #asm("x86_64", "movl $1, %[out]", "=r", "", "", "") { return 0 }
HasNeon :: () -> s32 #asm("aarch64", "mov %w[out], #1", "=r", "", "", "") { return 0 }
HasArmNeon :: () -> s32 #asm("arm+neon", "mov %[out], #1", "=r", "", "", "") { return 0 }
// SIMD128 is a build option, not a CPU check: true only in a module built
// with -msimd128, which a host loads where WebAssembly.validate accepts SIMD.
HasSimd128 :: () -> s32 #asm("wasm32+simd128", "i32.const 1
local.set %[out]", "=r", "", "", "") { return 0 }
// The x86-64 kernels, in std/simd: #target builds SSE2, SSSE3, SSE4.1 and
// AVX2 copies of each and calls the best one the CPU runs. RESAMPLE_AVX2
// takes the 256-bit kernels, which are slow without AVX2.
// Two taps of one output pixel from SOURCE + PIXEL: each 32-bit lane holds
// one channel of both taps for MulAddPairs.
HorizontalStep :: (source: *u8, pixel: s64, packed: *u32, w: s64, low: *s32x4, high: *s32x4) #inline {
words := Simd.Reinterpret(s16x8, Simd.WidenLow(Simd.LoadLow(u8x16, source, pixel)))
taps := Simd.InterleaveLow(words, Simd.Reinterpret(s16x8, Simd.Shuffle(Simd.Reinterpret(s32x4, words), 2, 3, 0, 1)))
low.* = Simd.Add(low.*, Simd.MulAddPairs(taps, Simd.Reinterpret(s16x8, Simd.Splat(u32x4, packed[w]))))
high.* = Simd.Add(high.*, Simd.MulAddPairs(taps, Simd.Reinterpret(s16x8, Simd.Splat(u32x4, packed[w + 1]))))
}
// The last tap of an odd count, its partner weight 0. After an earlier tap
// it is the high half of the 8 bytes ending there, which one load reads;
// a lone tap is read byte by byte, as nothing before it need exist.
HorizontalOdd :: (source: *u8, pixel: s64, packed: *u32, w: s64, alone: bool, low: *s32x4, high: *s32x4) #inline {
taps := Simd.Zero(s16x8)
if alone {
word := cast(u32)source[pixel] | (cast(u32)source[pixel + 1] << 8) |
(cast(u32)source[pixel + 2] << 16) | (cast(u32)source[pixel + 3] << 24)
words := Simd.Reinterpret(s16x8, Simd.WidenLow(Simd.Reinterpret(u8x16, Simd.WithLane(Simd.Zero(u32x4), 0, word))))
taps = Simd.InterleaveLow(words, Simd.Zero(s16x8))
} else {
words := Simd.Reinterpret(s16x8, Simd.WidenLow(Simd.LoadLow(u8x16, source, pixel - 4)))
taps = Simd.InterleaveHigh(words, Simd.Zero(s16x8))
}
low.* = Simd.Add(low.*, Simd.MulAddPairs(taps, Simd.Reinterpret(s16x8, Simd.Splat(u32x4, packed[w]))))
high.* = Simd.Add(high.*, Simd.MulAddPairs(taps, Simd.Reinterpret(s16x8, Simd.Splat(u32x4, packed[w + 1]))))
}
// One pixel's four channel sums, before the shift, as bytes of TARGET.
HorizontalStore :: (target: *u8, to: s64, sums: s32x4) #inline {
sum := Simd.ShiftRight(sums, 22)
halves := Simd.Narrow(s16x8, sum, sum)
out := Simd.Lane(Simd.Reinterpret(u32x4, Simd.Narrow(u8x16, halves, halves)), 0)
target[to] = cast(u8)out
target[to + 1] = cast(u8)(out >> 8)
target[to + 2] = cast(u8)(out >> 16)
target[to + 3] = cast(u8)(out >> 24)
}
// OUTPUT pixels of TARGET from the packed weights, ENTRY words apart:
// four taps a step, then two, then an odd last one.
HorizontalTyped :: (source: *u8, packed: *u32, entry: s64, output: s64, target: *u8) #target {
at: s64 = 0
x: s64 = 0
while x < output {
count := cast(s64)packed[at + 1]
pixel := cast(s64)cast(s32)packed[at] * 4
w := at + 2
low := Simd.Splat(s32x4, ROUND)
high := Simd.Zero(s32x4)
quads := count / 4
while quads > 0 {
// The taps in order 0 2 1 3, then their bytes interleaved so each
// 32-bit lane holds one channel of taps 0 and 1, or 2 and 3.
spread := Simd.Reinterpret(u8x16, Simd.Shuffle(Simd.Reinterpret(u32x4, Simd.Load(u8x16, source, pixel)), 0, 2, 1, 3))
bytes := Simd.InterleaveLow(spread, Simd.Reinterpret(u8x16, Simd.Shuffle(Simd.Reinterpret(u32x4, spread), 2, 3, 2, 3)))
first := Simd.Reinterpret(s16x8, Simd.InterleaveLow(bytes, Simd.Zero(u8x16)))
second := Simd.Reinterpret(s16x8, Simd.InterleaveHigh(bytes, Simd.Zero(u8x16)))
weights := Simd.Load(u32x4, packed, w)
low = Simd.Add(low, Simd.MulAddPairs(first, Simd.Reinterpret(s16x8, Simd.Shuffle(weights, 0, 0, 0, 0))))
high = Simd.Add(high, Simd.MulAddPairs(first, Simd.Reinterpret(s16x8, Simd.Shuffle(weights, 1, 1, 1, 1))))
low = Simd.Add(low, Simd.MulAddPairs(second, Simd.Reinterpret(s16x8, Simd.Shuffle(weights, 2, 2, 2, 2))))
high = Simd.Add(high, Simd.MulAddPairs(second, Simd.Reinterpret(s16x8, Simd.Shuffle(weights, 3, 3, 3, 3))))
pixel += 16
w += 4
quads -= 1
}
if (count & 2) != 0 {
HorizontalStep(source, pixel, packed, w, *low, *high)
pixel += 8
w += 2
}
if count % 2 == 1 { HorizontalOdd(source, pixel, packed, w, count == 1, *low, *high) }
HorizontalStore(target, x * 4, Simd.Add(low, Simd.ShiftLeft(high, 16)))
at += entry
x += 1
}
}
// HorizontalTyped with 256-bit vectors, eight or four taps a step, for
// AVX2. A step's byte shuffle gives each 32-bit lane one channel of two
// neighbouring taps; each 128-bit block takes the weights of its own pair.
HorizontalTypedWide :: (source: *u8, packed: *u32, entry: s64, output: s64, target: *u8) #target {
order := Simd.Make(u8x16, 0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15)
orders := Simd.Combine(order, order)
at: s64 = 0
x: s64 = 0
while x < output {
count := cast(s64)packed[at + 1]
pixel := cast(s64)cast(s32)packed[at] * 4
w := at + 2
low := Simd.Splat(s32x4, ROUND)
high := Simd.Zero(s32x4)
if count >= 4 {
// The rounding rides in the first half until the halves meet.
low8 := Simd.Combine(low, high)
high8 := Simd.Zero(s32x8)
octs := count / 8
while octs > 0 {
bytes := Simd.ByteShuffle(Simd.Load(u8x32, source, pixel), orders)
first := Simd.Reinterpret(s16x16, Simd.InterleaveLow(bytes, Simd.Zero(u8x32)))
second := Simd.Reinterpret(s16x16, Simd.InterleaveHigh(bytes, Simd.Zero(u8x32)))
weights := Simd.Load(u32x8, packed, w)
low8 = Simd.Add(low8, Simd.MulAddPairs(first, Simd.Reinterpret(s16x16, Simd.Shuffle(weights, 0, 0, 0, 0))))
high8 = Simd.Add(high8, Simd.MulAddPairs(first, Simd.Reinterpret(s16x16, Simd.Shuffle(weights, 1, 1, 1, 1))))
low8 = Simd.Add(low8, Simd.MulAddPairs(second, Simd.Reinterpret(s16x16, Simd.Shuffle(weights, 2, 2, 2, 2))))
high8 = Simd.Add(high8, Simd.MulAddPairs(second, Simd.Reinterpret(s16x16, Simd.Shuffle(weights, 3, 3, 3, 3))))
pixel += 32
w += 8
octs -= 1
}
if count % 8 >= 4 {
taps := Simd.Reinterpret(s16x16, Simd.Widen(Simd.ByteShuffle(Simd.Load(u8x16, source, pixel), order)))
weights := Simd.Reinterpret(u32x8, Simd.Widen(Simd.Load(u32x4, packed, w)))
low8 = Simd.Add(low8, Simd.MulAddPairs(taps, Simd.Reinterpret(s16x16, Simd.Shuffle(weights, 0, 0, 0, 0))))
high8 = Simd.Add(high8, Simd.MulAddPairs(taps, Simd.Reinterpret(s16x16, Simd.Shuffle(weights, 2, 2, 2, 2))))
pixel += 16
w += 4
}
low = Simd.Add(Simd.Low(low8), Simd.High(low8))
high = Simd.Add(Simd.Low(high8), Simd.High(high8))
}
if (count & 2) != 0 {
HorizontalStep(source, pixel, packed, w, *low, *high)
pixel += 8
w += 2
}
if count % 2 == 1 { HorizontalOdd(source, pixel, packed, w, count == 1, *low, *high) }
HorizontalStore(target, x * 4, Simd.Add(low, Simd.ShiftLeft(high, 16)))
at += entry
x += 1
}
}
// BYTES bytes of one output row, a multiple of 16, two source rows a step;
// WIDE takes 32 bytes at a time first, for AVX2. An odd COUNT's last step
// reads its row twice, the second time with weight 0.
VerticalTyped :: (rows: *u8, stride: s64, pairs: *u32, count: s64, target: *u8, bytes: s64, wide: bool) #target {
steps := (count + 1) / 2
last := ifx count % 2 == 1 then cast(s64)0 else stride
i: s64 = 0
if wide {
while i + 32 <= bytes {
a0 := Simd.Splat(s32x8, ROUND)
a1 := a0
a2 := a0
a3 := a0
h0 := Simd.Zero(s32x8)
h1 := h0
h2 := h0
h3 := h0
at := i
step: s64 = 0
while step < steps {
next := ifx step == steps - 1 then last else stride
x := Simd.Load(u8x32, rows, at)
y := Simd.Load(u8x32, rows, at + next)
lo := Simd.InterleaveLow(x, y)
hi := Simd.InterleaveHigh(x, y)
wl := Simd.Reinterpret(s16x16, Simd.Splat(u32x8, pairs[step * 2]))
wh := Simd.Reinterpret(s16x16, Simd.Splat(u32x8, pairs[step * 2 + 1]))
v := Simd.Reinterpret(s16x16, Simd.WidenLow(lo))
a0 = Simd.Add(a0, Simd.MulAddPairs(v, wl))
h0 = Simd.Add(h0, Simd.MulAddPairs(v, wh))
v = Simd.Reinterpret(s16x16, Simd.WidenHigh(lo))
a1 = Simd.Add(a1, Simd.MulAddPairs(v, wl))
h1 = Simd.Add(h1, Simd.MulAddPairs(v, wh))
v = Simd.Reinterpret(s16x16, Simd.WidenLow(hi))
a2 = Simd.Add(a2, Simd.MulAddPairs(v, wl))
h2 = Simd.Add(h2, Simd.MulAddPairs(v, wh))
v = Simd.Reinterpret(s16x16, Simd.WidenHigh(hi))
a3 = Simd.Add(a3, Simd.MulAddPairs(v, wl))
h3 = Simd.Add(h3, Simd.MulAddPairs(v, wh))
at += stride * 2
step += 1
}
r0 := Simd.ShiftRight(Simd.Add(a0, Simd.ShiftLeft(h0, 16)), 22)
r1 := Simd.ShiftRight(Simd.Add(a1, Simd.ShiftLeft(h1, 16)), 22)
r2 := Simd.ShiftRight(Simd.Add(a2, Simd.ShiftLeft(h2, 16)), 22)
r3 := Simd.ShiftRight(Simd.Add(a3, Simd.ShiftLeft(h3, 16)), 22)
Simd.Store(target, i, Simd.Narrow(u8x32, Simd.Narrow(s16x16, r0, r1), Simd.Narrow(s16x16, r2, r3)))
i += 32
}
}
while i + 16 <= bytes {
a0 := Simd.Splat(s32x4, ROUND)
a1 := a0
a2 := a0
a3 := a0
h0 := Simd.Zero(s32x4)
h1 := h0
h2 := h0
h3 := h0
at := i
step: s64 = 0
while step < steps {
next := ifx step == steps - 1 then last else stride
x := Simd.Load(u8x16, rows, at)
y := Simd.Load(u8x16, rows, at + next)
lo := Simd.InterleaveLow(x, y)
hi := Simd.InterleaveHigh(x, y)
wl := Simd.Reinterpret(s16x8, Simd.Splat(u32x4, pairs[step * 2]))
wh := Simd.Reinterpret(s16x8, Simd.Splat(u32x4, pairs[step * 2 + 1]))
v := Simd.Reinterpret(s16x8, Simd.WidenLow(lo))
a0 = Simd.Add(a0, Simd.MulAddPairs(v, wl))
h0 = Simd.Add(h0, Simd.MulAddPairs(v, wh))
v = Simd.Reinterpret(s16x8, Simd.WidenHigh(lo))
a1 = Simd.Add(a1, Simd.MulAddPairs(v, wl))
h1 = Simd.Add(h1, Simd.MulAddPairs(v, wh))
v = Simd.Reinterpret(s16x8, Simd.WidenLow(hi))
a2 = Simd.Add(a2, Simd.MulAddPairs(v, wl))
h2 = Simd.Add(h2, Simd.MulAddPairs(v, wh))
v = Simd.Reinterpret(s16x8, Simd.WidenHigh(hi))
a3 = Simd.Add(a3, Simd.MulAddPairs(v, wl))
h3 = Simd.Add(h3, Simd.MulAddPairs(v, wh))
at += stride * 2
step += 1
}
r0 := Simd.ShiftRight(Simd.Add(a0, Simd.ShiftLeft(h0, 16)), 22)
r1 := Simd.ShiftRight(Simd.Add(a1, Simd.ShiftLeft(h1, 16)), 22)
r2 := Simd.ShiftRight(Simd.Add(a2, Simd.ShiftLeft(h2, 16)), 22)
r3 := Simd.ShiftRight(Simd.Add(a3, Simd.ShiftLeft(h3, 16)), 22)
Simd.Store(target, i, Simd.Narrow(u8x16, Simd.Narrow(s16x8, r0, r1), Simd.Narrow(s16x8, r2, r3)))
i += 16
}
}
// The NEON and SIMD128 kernels, in std/simd. These instruction sets multiply
// 32-bit lanes in one step, so each tap's bytes widen to 32 bits and take
// its whole weight, rather than MulAddPairs' 16-bit halves. On ARMv7 they
// are fast in builds with NEON, as Android's armeabi-v7a is.
// OUTPUT pixels of TARGET, from the weights SIZE apart per output position:
// four taps a step, then two, then an odd last one.
// The loops walk pointers with 32-bit counts, which ARMv7 and wasm32, whose
// registers are 32-bit, keep in one register each.
HorizontalLanes :: (source: *u8, bounds: *s32, weights: *s32, size: s32, output: s32, target: *u8) {
bound := bounds
row := weights
to := target
left := output
while left > 0 {
at := *source[cast(s64)bound[0] * 4]
count := bound[1]
weight := row
even := Simd.Splat(s32x4, ROUND)
odd := Simd.Zero(s32x4)
quads := count / 4
while quads > 0 {
pixels := Simd.Load(u8x16, at, 0)
four := Simd.Load(s32x4, weight, 0)
low := Simd.WidenLow(pixels)
high := Simd.WidenHigh(pixels)
even = Simd.Add(even, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenLow(low)), Simd.Shuffle(four, 0, 0, 0, 0)))
odd = Simd.Add(odd, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenHigh(low)), Simd.Shuffle(four, 1, 1, 1, 1)))
even = Simd.Add(even, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenLow(high)), Simd.Shuffle(four, 2, 2, 2, 2)))
odd = Simd.Add(odd, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenHigh(high)), Simd.Shuffle(four, 3, 3, 3, 3)))
at = *at[16]
weight = *weight[4]
quads -= 1
}
if (count & 2) != 0 {
taps := Simd.WidenLow(Simd.LoadLow(u8x16, at, 0))
both := Simd.LoadLow(s32x4, weight, 0)
even = Simd.Add(even, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenLow(taps)), Simd.Shuffle(both, 0, 0, 0, 0)))
odd = Simd.Add(odd, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenHigh(taps)), Simd.Shuffle(both, 1, 1, 1, 1)))
at = *at[8]
weight = *weight[2]
}
if (count & 1) != 0 {
// Four byte reads, which compilers merge into one 32-bit load.
word := cast(u32)at[0] | (cast(u32)at[1] << 8) | (cast(u32)at[2] << 16) | (cast(u32)at[3] << 24)
tap := Simd.WidenLow(Simd.WidenLow(Simd.Reinterpret(u8x16, Simd.WithLane(Simd.Zero(u32x4), 0, word))))
even = Simd.Add(even, Simd.Mul(Simd.Reinterpret(s32x4, tap), Simd.Splat(s32x4, weight[0])))
}
HorizontalStore(to, 0, Simd.Add(even, odd))
bound = *bound[2]
row = *row[size]
to = *to[4]
left -= 1
}
}
// BYTES bytes of one output row, a multiple of 16, from COUNT source rows
// STRIDE bytes apart, one row a step.
VerticalLanes :: (rows: *u8, stride: s64, weights: *s32, count: s64, target: *u8, bytes: s64) {
taps := cast(s32)count
i: s64 = 0
while i + 16 <= bytes {
a0 := Simd.Splat(s32x4, ROUND)
a1 := a0
a2 := a0
a3 := a0
at := *rows[i]
weight := weights
left := taps
while left > 0 {
factor := Simd.Splat(s32x4, weight[0])
pixels := Simd.Load(u8x16, at, 0)
low := Simd.WidenLow(pixels)
high := Simd.WidenHigh(pixels)
a0 = Simd.Add(a0, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenLow(low)), factor))
a1 = Simd.Add(a1, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenHigh(low)), factor))
a2 = Simd.Add(a2, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenLow(high)), factor))
a3 = Simd.Add(a3, Simd.Mul(Simd.Reinterpret(s32x4, Simd.WidenHigh(high)), factor))
at = *at[stride]
weight = *weight[1]
left -= 1
}
r0 := Simd.ShiftRight(a0, 22)
r1 := Simd.ShiftRight(a1, 22)
r2 := Simd.ShiftRight(a2, 22)
r3 := Simd.ShiftRight(a3, 22)
Simd.Store(target, i, Simd.Narrow(u8x16, Simd.Narrow(s16x8, r0, r1), Simd.Narrow(s16x8, r2, r3)))
i += 16
}
}
Level :: () -> s32 {
if resample_forced >= 0 { return resample_forced }
return ResampleKernels()
}
#scope_export
// The fastest kernels this program and CPU have: RESAMPLE_AVX2,
// RESAMPLE_SSE2, RESAMPLE_NEON (AArch64, or ARMv7 with NEON),
// RESAMPLE_SIMD128 (a WebAssembly module built with -msimd128) or
// RESAMPLE_SCALAR. A build with ZIRAN_NO_ASM, a compiler without GNU
// assembly and .zx use the scalar ones.
ResampleKernels :: () -> s32 {
if HasAvx2() != 0 { return RESAMPLE_AVX2 }
if HasSse2() != 0 { return RESAMPLE_SSE2 }
if HasNeon() != 0 || HasArmNeon() != 0 { return RESAMPLE_NEON }
if HasSimd128() != 0 { return RESAMPLE_SIMD128 }
return RESAMPLE_SCALAR
}
// For tests and benchmarks, before any rows run: use LEVEL's kernels from
// now on, or the fastest again for -1. False, changing nothing, when this
// CPU lacks them.
ResampleUseKernels :: (level: s32) -> bool {
if level < 0 { resample_forced = -1; return true }
available := level == RESAMPLE_SCALAR ||
(level == RESAMPLE_SSE2 && HasSse2() != 0) ||
(level == RESAMPLE_AVX2 && HasAvx2() != 0) ||
(level == RESAMPLE_NEON && (HasNeon() != 0 || HasArmNeon() != 0)) ||
(level == RESAMPLE_SIMD128 && HasSimd128() != 0)
if available { resample_forced = level }
return available
}
// Pillow's weights for scaling the source span [START, END) of INPUT
// positions to OUTPUT positions, as Image.resize's box does; positions
// outside the source are left out and the rest renormalized. Reusing an
// axis reuses its storage. False leaves the axis empty.
ResampleAxisBoxInto :: (axis: *ResampleAxis, input: s32, start: float64, end: float64,
output: s32, filter: s32) -> bool {
axis.input = 0; axis.output = 0
if input <= 0 || output <= 0 || !(start >= 0.0) || !(end <= cast(float64)input) || !(end > start) {
return false
}
scale := (end - start) / cast(float64)output
filter_scale := ifx scale < 1.0 then 1.0 else scale
inverse_scale := 1.0 / filter_scale
support := (ifx filter == RESAMPLE_LANCZOS then 3.0 else
(ifx filter == RESAMPLE_BICUBIC then 2.0 else 0.5)) * filter_scale
if support > 1073741822.0 { return false }
whole := Truncate(support)
if cast(float64)whole < support { whole += 1 }
size := whole * 2 + 1
pairs := (size + 1) / 2
entry := 2 + pairs * 2
count := cast(s64)output * size
if count > 2305843009213693951 / 4 || cast(s64)output * entry > 2305843009213693951 / 4 { return false }
if !VecResize(axis.weights, count) || !VecResize(axis.bounds, cast(s64)output * 2) ||
!VecResize(axis.packed, cast(s64)output * entry) || !VecResize(axis.scratch, cast(s64)size) {
return false
}
exact := true
for out: 0..output - 1 {
center := start + (cast(float64)out + 0.5) * scale
lower := center - support + 0.5
upper := center + support + 0.5
low := ifx lower < 0.0 then 0 else Truncate(lower)
high := ifx upper > cast(float64)input then input else Truncate(upper)
high -= low
total := 0.0
for at: 0..size - 1 {
weight := 0.0
if at < high {
distance := cast(float64)(at + low) - center + 0.5
weight = Filter(filter, ifx filter == RESAMPLE_BICUBIC then distance * inverse_scale else distance / filter_scale)
}
axis.scratch[at] = weight
total += weight
}
row := cast(s64)out * size
positive: s64 = 0
negative: s64 = 0
for at: 0..size - 1 {
weight := axis.scratch[at]
if at < high && total != 0.0 { weight = weight / total }
scaled := weight * 4194304.0
fixed := ifx scaled < 0.0 then Truncate(scaled - 0.5) else Truncate(scaled + 0.5)
axis.weights[row + at] = fixed
if fixed > 0 { positive += fixed } else { negative -= fixed }
}
// A span with no taps adds nothing, as in Pillow, through one
// zero-weight tap the kernels can read.
if high < 1 {
low = ifx low < 0 then 0 else (ifx low >= input then input - 1 else low)
high = 1
}
if cast(s64)ROUND + 255 * positive > 2147483647 || cast(s64)ROUND - 255 * negative < -2147483648 {
exact = false
}
axis.bounds[cast(s64)out * 2] = low
axis.bounds[cast(s64)out * 2 + 1] = high
at := cast(s64)out * entry
axis.packed[at] = cast(u32)low
axis.packed[at + 1] = cast(u32)high
for pair: 0..pairs - 1 {
first := ifx pair * 2 < size then axis.weights[row + pair * 2] else 0
second := ifx pair * 2 + 1 < size then axis.weights[row + pair * 2 + 1] else 0
axis.packed[at + 2 + pair * 2] = PackHalves(LowHalf(first), LowHalf(second))
axis.packed[at + 3 + pair * 2] = PackHalves(HighHalf(first), HighHalf(second))
}
}
axis.input = input; axis.output = output
axis.size = size; axis.entry = entry; axis.exact = exact
return true
}
// Pillow's weights for scaling all INPUT positions to OUTPUT positions.
ResampleAxisInto :: (axis: *ResampleAxis, input: s32, output: s32, filter: s32) -> bool {
return ResampleAxisBoxInto(axis, input, 0.0, cast(float64)input, output, filter)
}
// AXIS.output pixels of TARGET from AXIS.input pixels of SOURCE.
ResampleRowHorizontal :: (axis: *ResampleAxis, source: *u8, target: *u8) {
if axis.output <= 0 || source == null || target == null { return }
level := Level()
if axis.exact && level == RESAMPLE_AVX2 {
HorizontalTypedWide(source, *axis.packed[0], cast(s64)axis.entry, cast(s64)axis.output, target)
} else if axis.exact && level == RESAMPLE_SSE2 {
HorizontalTyped(source, *axis.packed[0], cast(s64)axis.entry, cast(s64)axis.output, target)
} else if axis.exact && (level == RESAMPLE_NEON || level == RESAMPLE_SIMD128) {
HorizontalLanes(source, *axis.bounds[0], *axis.weights[0], axis.size, axis.output, target)
} else {
HorizontalScalar(axis, source, target)
}
}
// Output row ROW of a vertical AXIS: WIDTH pixels of TARGET from the
// source rows at SOURCE, STRIDE bytes apart.
ResampleRowVertical :: (axis: *ResampleAxis, row: s32, source: *u8, stride: s64, width: s32, target: *u8) {
if row < 0 || row >= axis.output || width <= 0 || source == null || target == null { return }
low := cast(s64)axis.bounds[cast(s64)row * 2]
count := cast(s64)axis.bounds[cast(s64)row * 2 + 1]
rows := *source[low * stride]
weights := *axis.weights[cast(s64)row * axis.size]
pairs := *axis.packed[cast(s64)row * axis.entry + 2]
bytes := cast(s64)width * 4
done: s64 = 0
if axis.exact {
level := Level()
if level == RESAMPLE_AVX2 || level == RESAMPLE_SSE2 {
done = bytes - bytes % 16
if done > 0 { VerticalTyped(rows, stride, pairs, count, target, done, level == RESAMPLE_AVX2) }
}
if level == RESAMPLE_NEON || level == RESAMPLE_SIMD128 {
done = bytes - bytes % 16
if done > 0 { VerticalLanes(rows, stride, weights, count, target, done) }
}
}
if done < bytes { VerticalScalar(rows, stride, weights, count, axis.exact, target, done, bytes) }
}
// Pillow's premultiplication of COUNT RGBA pixels in place, and its inverse.
ResamplePremultiply :: (pixels: *u8, count: s64) {
at: s64 = 0
end := count * 4
while at < end {
alpha := cast(u32)pixels[at + 3]
if alpha != 255 {
for channel: cast(s64)0..2 {
value := cast(u32)pixels[at + channel] * alpha + 128
pixels[at + channel] = cast(u8)(((value >> 8) + value) >> 8)
}
}
at += 4
}
}
ResampleUnpremultiply :: (pixels: *u8, count: s64) {
at: s64 = 0
end := count * 4
while at < end {
alpha := cast(u32)pixels[at + 3]
if alpha != 0 && alpha != 255 {
for channel: cast(s64)0..2 {
value := 255 * cast(u32)pixels[at + channel] / alpha
pixels[at + channel] = cast(u8)(ifx value > 255 then 255 else value)
}
}
at += 4
}
}
// Plans resizing the box (X, Y, BOX_WIDTH, BOX_HEIGHT) of a SOURCE_WIDTH by
// SOURCE_HEIGHT picture to WIDTH by HEIGHT, passes as Pillow chooses them.
// Reusing a plan reuses its storage. False leaves no pass to run.
ResamplePlanInto :: (plan: *ResamplePlan, source_width: s32, source_height: s32,
x: float64, y: float64, box_width: float64, box_height: float64,
width: s32, height: s32, filter: s32) -> bool {
plan.width = 0; plan.height = 0; plan.rows = 0
plan.horizontal_pass = false; plan.vertical_pass = false
if source_width <= 0 || source_height <= 0 || width <= 0 || height <= 0 ||
cast(s64)width * height > 1073741824 || cast(s64)source_width * source_height > 1073741824 ||
!(x >= 0.0) || !(y >= 0.0) || !(box_width > 0.0) || !(box_height > 0.0) ||
!(x + box_width <= cast(float64)source_width) || !(y + box_height <= cast(float64)source_height) {
return false
}
right := x + box_width
bottom := y + box_height
horizontal := width != source_width || x != 0.0 || right != cast(float64)width
vertical := height != source_height || y != 0.0 || bottom != cast(float64)height
if horizontal && !ResampleAxisBoxInto(*plan.horizontal, source_width, x, right, width, filter) { return false }
if vertical && !ResampleAxisBoxInto(*plan.vertical, source_height, y, bottom, height, filter) { return false }
plan.first_row = 0
plan.rows = height
if vertical {
last := cast(s64)height - 1
plan.first_row = plan.vertical.bounds[0]
plan.rows = plan.vertical.bounds[last * 2] + plan.vertical.bounds[last * 2 + 1] - plan.first_row
// The vertical pass reads the horizontal pass's rows from 0.
if horizontal {
for out: cast(s64)0..cast(s64)height - 1 {
plan.vertical.bounds[out * 2] -= plan.first_row
plan.vertical.packed[out * plan.vertical.entry] = cast(u32)plan.vertical.bounds[out * 2]
}
if !VecResize(plan.intermediate, cast(s64)width * plan.rows * 4) { return false }
}
}
plan.source_width = source_width; plan.source_height = source_height
plan.width = width; plan.height = height
plan.horizontal_pass = horizontal; plan.vertical_pass = vertical
return true
}
// Rows the first pass makes, then the second: ranges of these numbers can
// run on different threads, all first-pass rows before any second-pass row.
ResamplePlanFirstRows :: (plan: *ResamplePlan) -> s32 {
if plan.width <= 0 { return 0 }
if plan.horizontal_pass || !plan.vertical_pass { return plan.rows }
return 0
}
ResamplePlanSecondRows :: (plan: *ResamplePlan) -> s32 {
return ifx plan.width > 0 && plan.vertical_pass then plan.height else 0
}
// First-pass rows [FIRST, END) from premultiplied SOURCE (STRIDE bytes per
// row) into the plan, or into TARGET when there is no second pass.
ResamplePlanFirst :: (plan: *ResamplePlan, source: *u8, stride: s64,
target: *u8, target_stride: s64, first: s32, end: s32) {
limit := ResamplePlanFirstRows(plan)
if first < 0 { first = 0 }
if end > limit { end = limit }
if first >= end { return }
into := target
into_stride := target_stride
if plan.vertical_pass { into = *plan.intermediate[0]; into_stride = cast(s64)plan.width * 4 }
for row: first..end - 1 {
from := *source[(cast(s64)plan.first_row + row) * stride]
to := *into[cast(s64)row * into_stride]
if plan.horizontal_pass {
ResampleRowHorizontal(*plan.horizontal, from, to)
} else {
for at: cast(s64)0..cast(s64)plan.width * 4 - 1 { to[at] = from[at] }
}
}
}
// Second-pass rows [FIRST, END) of TARGET (TARGET_STRIDE bytes per row).
ResamplePlanSecond :: (plan: *ResamplePlan, source: *u8, stride: s64,
target: *u8, target_stride: s64, first: s32, end: s32) {
limit := ResamplePlanSecondRows(plan)
if first < 0 { first = 0 }
if end > limit { end = limit }
if first >= end { return }
from := source
from_stride := stride
if plan.horizontal_pass { from = *plan.intermediate[0]; from_stride = cast(s64)plan.width * 4 }
for row: first..end - 1 {
ResampleRowVertical(*plan.vertical, row, from, from_stride, plan.width, *target[cast(s64)row * target_stride])
}
}
// The whole resize on this thread: premultiplied SOURCE into TARGET.
ResamplePlanRun :: (plan: *ResamplePlan, source: *u8, stride: s64, target: *u8, target_stride: s64) {
ResamplePlanFirst(plan, source, stride, target, target_stride, 0, ResamplePlanFirstRows(plan))
ResamplePlanSecond(plan, source, stride, target, target_stride, 0, ResamplePlanSecondRows(plan))
}