repo_id
stringclasses 927
values | file_path
stringlengths 99
214
| content
stringlengths 2
4.15M
|
---|---|---|
vector | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vector/acc_test.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vector
import (
"bytes"
"fmt"
"math"
"math/rand"
"runtime"
"testing"
)
// TestDivideByFFFF tests that dividing by 0xffff is equivalent to multiplying
// and then shifting by magic constants. The Go compiler itself issues this
// multiply-and-shift for a division by the constant value 0xffff. This trick
// is used in the asm code as the GOARCH=amd64 SIMD instructions have parallel
// multiply but not parallel divide.
//
// There's undoubtedly a justification somewhere in Hacker's Delight chapter 10
// "Integer Division by Constants", but I don't have a more specific link.
//
// http://www.hackersdelight.org/divcMore.pdf and
// http://www.hackersdelight.org/magic.htm
func TestDivideByFFFF(t *testing.T) {
const mul, shift = 0x80008001, 47
rng := rand.New(rand.NewSource(1))
for i := 0; i < 20000; i++ {
u := rng.Uint32()
got := uint32((uint64(u) * mul) >> shift)
want := u / 0xffff
if got != want {
t.Fatalf("i=%d, u=%#08x: got %#08x, want %#08x", i, u, got, want)
}
}
}
// TestXxxSIMDUnaligned tests that unaligned SIMD loads/stores don't crash.
func TestFixedAccumulateSIMDUnaligned(t *testing.T) {
if !haveAccumulateSIMD {
t.Skip("No SIMD implemention")
}
dst := make([]uint8, 64)
src := make([]uint32, 64)
for d := 0; d < 16; d++ {
for s := 0; s < 16; s++ {
fixedAccumulateOpSrcSIMD(dst[d:d+32], src[s:s+32])
}
}
}
func TestFloatingAccumulateSIMDUnaligned(t *testing.T) {
if !haveAccumulateSIMD {
t.Skip("No SIMD implemention")
}
dst := make([]uint8, 64)
src := make([]float32, 64)
for d := 0; d < 16; d++ {
for s := 0; s < 16; s++ {
floatingAccumulateOpSrcSIMD(dst[d:d+32], src[s:s+32])
}
}
}
// TestXxxSIMDShortDst tests that the SIMD implementations don't write past the
// end of the dst buffer.
func TestFixedAccumulateSIMDShortDst(t *testing.T) {
if !haveAccumulateSIMD {
t.Skip("No SIMD implemention")
}
const oneQuarter = uint32(int2ϕ(fxOne*fxOne)) / 4
src := []uint32{oneQuarter, oneQuarter, oneQuarter, oneQuarter}
for i := 0; i < 4; i++ {
dst := make([]uint8, 4)
fixedAccumulateOpSrcSIMD(dst[:i], src[:i])
for j := range dst {
if j < i {
if got := dst[j]; got == 0 {
t.Errorf("i=%d, j=%d: got %#02x, want non-zero", i, j, got)
}
} else {
if got := dst[j]; got != 0 {
t.Errorf("i=%d, j=%d: got %#02x, want zero", i, j, got)
}
}
}
}
}
func TestFloatingAccumulateSIMDShortDst(t *testing.T) {
if !haveAccumulateSIMD {
t.Skip("No SIMD implemention")
}
const oneQuarter = 0.25
src := []float32{oneQuarter, oneQuarter, oneQuarter, oneQuarter}
for i := 0; i < 4; i++ {
dst := make([]uint8, 4)
floatingAccumulateOpSrcSIMD(dst[:i], src[:i])
for j := range dst {
if j < i {
if got := dst[j]; got == 0 {
t.Errorf("i=%d, j=%d: got %#02x, want non-zero", i, j, got)
}
} else {
if got := dst[j]; got != 0 {
t.Errorf("i=%d, j=%d: got %#02x, want zero", i, j, got)
}
}
}
}
}
func TestFixedAccumulateOpOverShort(t *testing.T) { testAcc(t, fxInShort, fxMaskShort, "over") }
func TestFixedAccumulateOpSrcShort(t *testing.T) { testAcc(t, fxInShort, fxMaskShort, "src") }
func TestFixedAccumulateMaskShort(t *testing.T) { testAcc(t, fxInShort, fxMaskShort, "mask") }
func TestFloatingAccumulateOpOverShort(t *testing.T) { testAcc(t, flInShort, flMaskShort, "over") }
func TestFloatingAccumulateOpSrcShort(t *testing.T) { testAcc(t, flInShort, flMaskShort, "src") }
func TestFloatingAccumulateMaskShort(t *testing.T) { testAcc(t, flInShort, flMaskShort, "mask") }
func TestFixedAccumulateOpOver16(t *testing.T) { testAcc(t, fxIn16, fxMask16, "over") }
func TestFixedAccumulateOpSrc16(t *testing.T) { testAcc(t, fxIn16, fxMask16, "src") }
func TestFixedAccumulateMask16(t *testing.T) { testAcc(t, fxIn16, fxMask16, "mask") }
func TestFloatingAccumulateOpOver16(t *testing.T) { testAcc(t, flIn16, flMask16, "over") }
func TestFloatingAccumulateOpSrc16(t *testing.T) { testAcc(t, flIn16, flMask16, "src") }
func TestFloatingAccumulateMask16(t *testing.T) { testAcc(t, flIn16, flMask16, "mask") }
func testAcc(t *testing.T, in interface{}, mask []uint32, op string) {
for _, simd := range []bool{false, true} {
maxN := 0
switch in := in.(type) {
case []uint32:
if simd && !haveAccumulateSIMD {
continue
}
maxN = len(in)
case []float32:
if simd && !haveAccumulateSIMD {
continue
}
maxN = len(in)
}
for _, n := range []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
33, 55, 79, 96, 120, 165, 256, maxN} {
if n > maxN {
continue
}
var (
got8, want8 []uint8
got32, want32 []uint32
)
switch op {
case "over":
const background = 0x40
got8 = make([]uint8, n)
for i := range got8 {
got8[i] = background
}
want8 = make([]uint8, n)
for i := range want8 {
dstA := uint32(background * 0x101)
maskA := mask[i]
outA := dstA*(0xffff-maskA)/0xffff + maskA
want8[i] = uint8(outA >> 8)
}
case "src":
got8 = make([]uint8, n)
want8 = make([]uint8, n)
for i := range want8 {
want8[i] = uint8(mask[i] >> 8)
}
case "mask":
got32 = make([]uint32, n)
want32 = mask[:n]
}
switch in := in.(type) {
case []uint32:
switch op {
case "over":
if simd {
fixedAccumulateOpOverSIMD(got8, in[:n])
} else {
fixedAccumulateOpOver(got8, in[:n])
}
case "src":
if simd {
fixedAccumulateOpSrcSIMD(got8, in[:n])
} else {
fixedAccumulateOpSrc(got8, in[:n])
}
case "mask":
copy(got32, in[:n])
if simd {
fixedAccumulateMaskSIMD(got32)
} else {
fixedAccumulateMask(got32)
}
}
case []float32:
switch op {
case "over":
if simd {
floatingAccumulateOpOverSIMD(got8, in[:n])
} else {
floatingAccumulateOpOver(got8, in[:n])
}
case "src":
if simd {
floatingAccumulateOpSrcSIMD(got8, in[:n])
} else {
floatingAccumulateOpSrc(got8, in[:n])
}
case "mask":
if simd {
floatingAccumulateMaskSIMD(got32, in[:n])
} else {
floatingAccumulateMask(got32, in[:n])
}
}
}
if op != "mask" {
if !bytes.Equal(got8, want8) {
t.Errorf("simd=%t, n=%d:\ngot: % x\nwant: % x", simd, n, got8, want8)
}
} else {
if !uint32sMatch(got32, want32) {
t.Errorf("simd=%t, n=%d:\ngot: % x\nwant: % x", simd, n, got32, want32)
}
}
}
}
}
// This package contains multiple implementations of the same algorithm, e.g.
// there are both SIMD and non-SIMD (vanilla) implementations on GOARCH=amd64.
// In general, the tests in this file check that the output is *exactly* the
// same, regardless of implementation.
//
// On GOARCH=wasm, float32 arithmetic is done with 64 bit precision. This is
// allowed by the Go specification: only explicit conversions to float32 have
// to round to 32 bit precision. However, the vanilla implementation therefore
// produces different output for GOARCH=wasm than on other GOARCHes.
//
// We therefore treat GOARCH=wasm as a special case, where the tests check that
// the output is only *approximately* the same (within a 0.1% tolerance).
//
// It's not that, on GOARCH=wasm, we produce the "wrong" answer. In fact, the
// computation is more, not less, accurate on GOARCH=wasm. It's that the golden
// output that the tests compare to were, for historical reasons, produced on
// GOARCH=amd64 and so done with less accuracy (where float32 arithmetic is
// performed entirely with 32 bits, not with 64 bits and then rounded back to
// 32 bits). Furthermore, on amd64, we still want to test that SIMD and
// non-SIMD produce exactly the same (albeit less accurate) output. The SIMD
// implementation in particular is limited by what the underlying hardware
// instructions provide, which often favors speed over accuracy.
// approxEquals returns whether got is within 0.1% of want.
func approxEquals(got, want float64) bool {
const tolerance = 0.001
return math.Abs(got-want) <= math.Abs(want)*tolerance
}
// sixteen is used by TestFloat32ArithmeticWithinTolerance, below. It needs to
// be a package-level variable so that the compiler does not replace the
// calculation with a single constant.
var sixteen float32 = 16
// TestFloat32ArithmeticWithinTolerance checks that approxEquals' tolerance is
// sufficiently high so that the results of two separate ways of computing the
// arbitrary fraction 16 / 1122 are deemed "approximately equal" even if they
// aren't "exactly equal".
//
// We're not testing whether the computation on amd64 or wasm is "right" or
// "wrong". We're testing that we cope with them being different.
//
// On GOARCH=amd64, printing x and y gives:
//
// 0.0142602495543672
// 0.014260249212384224
//
// On GOARCH=wasm, printing x and y gives:
//
// 0.0142602495543672
// 0.0142602495543672
//
// The infinitely precise (mathematical) answer is:
//
// 0.014260249554367201426024955436720142602495543672recurring...
//
// See https://play.golang.org/p/RxzKSdD_suE
//
// This test establishes a lower bound on approxEquals' tolerance constant.
// Passing this one test (on all of the various supported GOARCH's) is a
// necessary but not a sufficient condition on that value. Other tests in this
// package that call uint32sMatch or float32sMatch (such as TestMakeFxInXxx,
// TestMakeFlInXxx or anything calling testAcc) also require a sufficiently
// large tolerance. But those tests are more complicated, and if there is a
// problem with the tolerance constant, debugging this test can be simpler.
func TestFloat32ArithmeticWithinTolerance(t *testing.T) {
x := float64(sixteen) / 1122 // Always use 64-bit division.
y := float64(sixteen / 1122) // Use 32- or 64-bit division (GOARCH dependent).
if !approxEquals(x, y) {
t.Errorf("x and y were not approximately equal:\nx = %v\ny = %v", x, y)
}
}
func uint32sMatch(xs, ys []uint32) bool {
if len(xs) != len(ys) {
return false
}
if runtime.GOARCH == "wasm" {
for i := range xs {
if !approxEquals(float64(xs[i]), float64(ys[i])) {
return false
}
}
} else {
for i := range xs {
if xs[i] != ys[i] {
return false
}
}
}
return true
}
func float32sMatch(xs, ys []float32) bool {
if len(xs) != len(ys) {
return false
}
if runtime.GOARCH == "wasm" {
for i := range xs {
if !approxEquals(float64(xs[i]), float64(ys[i])) {
return false
}
}
} else {
for i := range xs {
if xs[i] != ys[i] {
return false
}
}
}
return true
}
func BenchmarkFixedAccumulateOpOver16(b *testing.B) { benchAcc(b, fxIn16, "over", false) }
func BenchmarkFixedAccumulateOpOverSIMD16(b *testing.B) { benchAcc(b, fxIn16, "over", true) }
func BenchmarkFixedAccumulateOpSrc16(b *testing.B) { benchAcc(b, fxIn16, "src", false) }
func BenchmarkFixedAccumulateOpSrcSIMD16(b *testing.B) { benchAcc(b, fxIn16, "src", true) }
func BenchmarkFixedAccumulateMask16(b *testing.B) { benchAcc(b, fxIn16, "mask", false) }
func BenchmarkFixedAccumulateMaskSIMD16(b *testing.B) { benchAcc(b, fxIn16, "mask", true) }
func BenchmarkFloatingAccumulateOpOver16(b *testing.B) { benchAcc(b, flIn16, "over", false) }
func BenchmarkFloatingAccumulateOpOverSIMD16(b *testing.B) { benchAcc(b, flIn16, "over", true) }
func BenchmarkFloatingAccumulateOpSrc16(b *testing.B) { benchAcc(b, flIn16, "src", false) }
func BenchmarkFloatingAccumulateOpSrcSIMD16(b *testing.B) { benchAcc(b, flIn16, "src", true) }
func BenchmarkFloatingAccumulateMask16(b *testing.B) { benchAcc(b, flIn16, "mask", false) }
func BenchmarkFloatingAccumulateMaskSIMD16(b *testing.B) { benchAcc(b, flIn16, "mask", true) }
func BenchmarkFixedAccumulateOpOver64(b *testing.B) { benchAcc(b, fxIn64, "over", false) }
func BenchmarkFixedAccumulateOpOverSIMD64(b *testing.B) { benchAcc(b, fxIn64, "over", true) }
func BenchmarkFixedAccumulateOpSrc64(b *testing.B) { benchAcc(b, fxIn64, "src", false) }
func BenchmarkFixedAccumulateOpSrcSIMD64(b *testing.B) { benchAcc(b, fxIn64, "src", true) }
func BenchmarkFixedAccumulateMask64(b *testing.B) { benchAcc(b, fxIn64, "mask", false) }
func BenchmarkFixedAccumulateMaskSIMD64(b *testing.B) { benchAcc(b, fxIn64, "mask", true) }
func BenchmarkFloatingAccumulateOpOver64(b *testing.B) { benchAcc(b, flIn64, "over", false) }
func BenchmarkFloatingAccumulateOpOverSIMD64(b *testing.B) { benchAcc(b, flIn64, "over", true) }
func BenchmarkFloatingAccumulateOpSrc64(b *testing.B) { benchAcc(b, flIn64, "src", false) }
func BenchmarkFloatingAccumulateOpSrcSIMD64(b *testing.B) { benchAcc(b, flIn64, "src", true) }
func BenchmarkFloatingAccumulateMask64(b *testing.B) { benchAcc(b, flIn64, "mask", false) }
func BenchmarkFloatingAccumulateMaskSIMD64(b *testing.B) { benchAcc(b, flIn64, "mask", true) }
func benchAcc(b *testing.B, in interface{}, op string, simd bool) {
var f func()
switch in := in.(type) {
case []uint32:
if simd && !haveAccumulateSIMD {
b.Skip("No SIMD implemention")
}
switch op {
case "over":
dst := make([]uint8, len(in))
if simd {
f = func() { fixedAccumulateOpOverSIMD(dst, in) }
} else {
f = func() { fixedAccumulateOpOver(dst, in) }
}
case "src":
dst := make([]uint8, len(in))
if simd {
f = func() { fixedAccumulateOpSrcSIMD(dst, in) }
} else {
f = func() { fixedAccumulateOpSrc(dst, in) }
}
case "mask":
buf := make([]uint32, len(in))
copy(buf, in)
if simd {
f = func() { fixedAccumulateMaskSIMD(buf) }
} else {
f = func() { fixedAccumulateMask(buf) }
}
}
case []float32:
if simd && !haveAccumulateSIMD {
b.Skip("No SIMD implemention")
}
switch op {
case "over":
dst := make([]uint8, len(in))
if simd {
f = func() { floatingAccumulateOpOverSIMD(dst, in) }
} else {
f = func() { floatingAccumulateOpOver(dst, in) }
}
case "src":
dst := make([]uint8, len(in))
if simd {
f = func() { floatingAccumulateOpSrcSIMD(dst, in) }
} else {
f = func() { floatingAccumulateOpSrc(dst, in) }
}
case "mask":
dst := make([]uint32, len(in))
if simd {
f = func() { floatingAccumulateMaskSIMD(dst, in) }
} else {
f = func() { floatingAccumulateMask(dst, in) }
}
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
f()
}
}
// itou exists because "uint32(int2ϕ(-1))" doesn't compile: constant -1
// overflows uint32.
func itou(i int2ϕ) uint32 {
return uint32(i)
}
var fxInShort = []uint32{
itou(+0x08000), // +0.125, // Running sum: +0.125
itou(-0x20000), // -0.500, // Running sum: -0.375
itou(+0x10000), // +0.250, // Running sum: -0.125
itou(+0x18000), // +0.375, // Running sum: +0.250
itou(+0x08000), // +0.125, // Running sum: +0.375
itou(+0x00000), // +0.000, // Running sum: +0.375
itou(-0x40000), // -1.000, // Running sum: -0.625
itou(-0x20000), // -0.500, // Running sum: -1.125
itou(+0x10000), // +0.250, // Running sum: -0.875
itou(+0x38000), // +0.875, // Running sum: +0.000
itou(+0x10000), // +0.250, // Running sum: +0.250
itou(+0x30000), // +0.750, // Running sum: +1.000
}
var flInShort = []float32{
+0.125, // Running sum: +0.125
-0.500, // Running sum: -0.375
+0.250, // Running sum: -0.125
+0.375, // Running sum: +0.250
+0.125, // Running sum: +0.375
+0.000, // Running sum: +0.375
-1.000, // Running sum: -0.625
-0.500, // Running sum: -1.125
+0.250, // Running sum: -0.875
+0.875, // Running sum: +0.000
+0.250, // Running sum: +0.250
+0.750, // Running sum: +1.000
}
// It's OK for fxMaskShort and flMaskShort to have slightly different values.
// Both the fixed and floating point implementations already have (different)
// rounding errors in the xxxLineTo methods before we get to accumulation. It's
// OK for 50% coverage (in ideal math) to be approximated by either 0x7fff or
// 0x8000. Both slices do contain checks that 0% and 100% map to 0x0000 and
// 0xffff, as does checkCornersCenter in vector_test.go.
//
// It is important, though, for the SIMD and non-SIMD fixed point
// implementations to give the exact same output, and likewise for the floating
// point implementations.
var fxMaskShort = []uint32{
0x2000,
0x6000,
0x2000,
0x4000,
0x6000,
0x6000,
0xa000,
0xffff,
0xe000,
0x0000,
0x4000,
0xffff,
}
var flMaskShort = []uint32{
0x1fff,
0x5fff,
0x1fff,
0x3fff,
0x5fff,
0x5fff,
0x9fff,
0xffff,
0xdfff,
0x0000,
0x3fff,
0xffff,
}
func TestMakeFxInXxx(t *testing.T) {
dump := func(us []uint32) string {
var b bytes.Buffer
for i, u := range us {
if i%8 == 0 {
b.WriteByte('\n')
}
fmt.Fprintf(&b, "%#08x, ", u)
}
return b.String()
}
if !uint32sMatch(fxIn16, hardCodedFxIn16) {
t.Errorf("height 16: got:%v\nwant:%v", dump(fxIn16), dump(hardCodedFxIn16))
}
}
func TestMakeFlInXxx(t *testing.T) {
dump := func(fs []float32) string {
var b bytes.Buffer
for i, f := range fs {
if i%8 == 0 {
b.WriteByte('\n')
}
fmt.Fprintf(&b, "%v, ", f)
}
return b.String()
}
if !float32sMatch(flIn16, hardCodedFlIn16) {
t.Errorf("height 16: got:%v\nwant:%v", dump(flIn16), dump(hardCodedFlIn16))
}
}
func makeInXxx(height int, useFloatingPointMath bool) *Rasterizer {
width, data := scaledBenchmarkGlyphData(height)
z := NewRasterizer(width, height)
z.setUseFloatingPointMath(useFloatingPointMath)
for _, d := range data {
switch d.n {
case 0:
z.MoveTo(d.px, d.py)
case 1:
z.LineTo(d.px, d.py)
case 2:
z.QuadTo(d.px, d.py, d.qx, d.qy)
}
}
return z
}
func makeFxInXxx(height int) []uint32 {
z := makeInXxx(height, false)
return z.bufU32
}
func makeFlInXxx(height int) []float32 {
z := makeInXxx(height, true)
return z.bufF32
}
// fxInXxx and flInXxx are the z.bufU32 and z.bufF32 inputs to the accumulate
// functions when rasterizing benchmarkGlyphData at a height of Xxx pixels.
//
// fxMaskXxx and flMaskXxx are the corresponding golden outputs of those
// accumulateMask functions.
//
// The hardCodedEtc versions are a sanity check for unexpected changes in the
// rasterization implementations up to but not including accumulation.
var (
fxIn16 = makeFxInXxx(16)
fxIn64 = makeFxInXxx(64)
flIn16 = makeFlInXxx(16)
flIn64 = makeFlInXxx(64)
)
var hardCodedFxIn16 = []uint32{
0x00000000, 0x00000000, 0xffffe91d, 0xfffe7c4a, 0xfffeaa9f, 0xffff4e33, 0xffffc1c5, 0x00007782,
0x00009619, 0x0001a857, 0x000129e9, 0x00000028, 0x00000000, 0x00000000, 0xffff6e70, 0xfffd3199,
0xffff5ff8, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00014b29,
0x0002acf3, 0x000007e2, 0xffffca5a, 0xfffcab73, 0xffff8a34, 0x00001b55, 0x0001b334, 0x0001449e,
0x0000434d, 0xffff62ec, 0xfffe1443, 0xffff325d, 0x00000000, 0x0002234a, 0x0001dcb6, 0xfffe2948,
0xfffdd6b8, 0x00000000, 0x00028cc0, 0x00017340, 0x00000000, 0x00000000, 0x00000000, 0xffffd2d6,
0xfffcadd0, 0xffff7f5c, 0x00007400, 0x00038c00, 0xfffe9260, 0xffff2da0, 0x0000023a, 0x0002259b,
0x0000182a, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xfffdc600, 0xfffe3a00, 0x00000059,
0x0003a44d, 0x00005b59, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0xfffe33f3, 0xfffdcc0d, 0x00000000, 0x00033c02, 0x0000c3fe, 0x00000000,
0x00000000, 0xffffa13d, 0xfffeeec8, 0xffff8c02, 0xffff8c48, 0xffffc7b5, 0x00000000, 0xffff5b68,
0xffff3498, 0x00000000, 0x00033c00, 0x0000c400, 0xffff9bc4, 0xfffdf4a3, 0xfffe8df3, 0xffffe1a8,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00033c00,
0x000092c7, 0xfffcf373, 0xffff3dc7, 0x00000fcc, 0x00011ae7, 0x000130c3, 0x0000680d, 0x00004a59,
0x00000a20, 0xfffe9dc4, 0xfffe4a3c, 0x00000000, 0x00033c00, 0xfffe87ef, 0xfffe3c11, 0x0000105e,
0x0002b9c4, 0x000135dc, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xfffe3600, 0xfffdca00,
0x00000000, 0x00033c00, 0xfffd9000, 0xffff3400, 0x0000e400, 0x00031c00, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0xfffe3600, 0xfffdca00, 0x00000000, 0x00033c00, 0xfffcf9a5,
0xffffca5b, 0x000120e6, 0x0002df1a, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xfffdb195, 0xfffe4e6b, 0x00000000, 0x00033c00, 0xfffd9e00, 0xffff2600, 0x00002f0e, 0x00033ea3,
0x0000924d, 0x00000000, 0x00000000, 0x00000000, 0xfffe83b3, 0xfffd881d, 0xfffff431, 0x00000000,
0x00031f60, 0xffff297a, 0xfffdb726, 0x00000000, 0x000053a7, 0x0001b506, 0x0000a24b, 0xffffa32d,
0xfffead9b, 0xffff0479, 0xffffffc9, 0x00000000, 0x00000000, 0x0002d800, 0x0001249d, 0xfffd67bb,
0xfffe9baa, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x0000ac03, 0x0001448b,
0xfffe0f70, 0x00000000, 0x000229ea, 0x0001d616, 0xffffff8c, 0xfffebf76, 0xfffe54d9, 0xffff5d9e,
0xffffd3eb, 0x0000c65e, 0x0000fc15, 0x0001d491, 0xffffb566, 0xfffd9433, 0x00000000, 0x0000e4ec,
}
var hardCodedFlIn16 = []float32{
0, 0, -0.022306755, -0.3782405, -0.33334962, -0.1741521, -0.0607556, 0.11660573,
0.14664596, 0.41462868, 0.2907673, 0.0001568835, 0, 0, -0.14239307, -0.7012868,
-0.15632017, 0, 0, 0, 0, 0, 0, 0.3230303,
0.6690931, 0.007876594, -0.05189419, -0.832786, -0.11531975, 0.026225802, 0.42518616, 0.3154636,
0.06598757, -0.15304244, -0.47969276, -0.20012794, 0, 0.5327272, 0.46727282, -0.45950258,
-0.5404974, 0, 0.63484025, 0.36515975, 0, 0, 0, -0.04351709,
-0.8293345, -0.12714837, 0.11087036, 0.88912964, -0.35792422, -0.2053554, 0.0022513224, 0.5374398,
0.023588525, 0, 0, 0, 0, -0.55346966, -0.44653034, 0.0002531938,
0.9088273, 0.090919495, 0, 0, 0, 0, 0, 0,
0, 0, -0.44745448, -0.5525455, 0, 0.80748945, 0.19251058, 0,
0, -0.092476256, -0.2661464, -0.11322958, -0.11298219, -0.055094406, 0, -0.16045958,
-0.1996116, 0, 0.80748653, 0.19251347, -0.09804727, -0.51129663, -0.3610403, -0.029615778,
0, 0, 0, 0, 0, 0, 0, 0.80748653,
0.14411622, -0.76251525, -0.1890875, 0.01527351, 0.27528667, 0.29730347, 0.101477206, 0.07259522,
0.009900213, -0.34395567, -0.42788061, 0, 0.80748653, -0.3648737, -0.44261283, 0.015778137,
0.6826565, 0.30156538, 0, 0, 0, 0, -0.44563293, -0.55436707,
0, 0.80748653, -0.60703933, -0.20044717, 0.22371745, 0.77628255, 0, 0,
0, 0, 0, -0.44563293, -0.55436707, 0, 0.80748653, -0.7550391,
-0.05244744, 0.2797074, 0.72029257, 0, 0, 0, 0, 0,
-0.57440215, -0.42559785, 0, 0.80748653, -0.59273535, -0.21475118, 0.04544862, 0.81148535,
0.14306602, 0, 0, 0, -0.369642, -0.61841226, -0.011945802, 0,
0.7791623, -0.20691396, -0.57224834, 0, 0.08218567, 0.42637306, 0.1586175, -0.089709565,
-0.32935485, -0.24788953, -0.00022224105, 0, 0, 0.7085409, 0.28821066, -0.64765793,
-0.34909368, 0, 0, 0, 0, 0, 0.16679136, 0.31914657,
-0.48593786, 0, 0.537915, 0.462085, -0.00041967133, -0.3120329, -0.41914812, -0.15886839,
-0.042683028, 0.19370951, 0.24624406, 0.45803425, -0.07049577, -0.6091341, 0, 0.22253075,
}
var fxMask16 = []uint32{
0x0000, 0x0000, 0x05b8, 0x66a6, 0xbbfe, 0xe871, 0xf800, 0xda20, 0xb499, 0x4a84, 0x0009, 0x0000, 0x0000,
0x0000, 0x2463, 0xd7fd, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xad35, 0x01f8, 0x0000,
0x0d69, 0xe28c, 0xffff, 0xf92a, 0x8c5d, 0x3b36, 0x2a62, 0x51a7, 0xcc97, 0xffff, 0xffff, 0x772d, 0x0000,
0x75ad, 0xffff, 0xffff, 0x5ccf, 0x0000, 0x0000, 0x0000, 0x0000, 0x0b4a, 0xdfd6, 0xffff, 0xe2ff, 0x0000,
0x5b67, 0x8fff, 0x8f70, 0x060a, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x8e7f, 0xffff, 0xffe9, 0x16d6,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7303, 0xffff, 0xffff, 0x30ff,
0x0000, 0x0000, 0x0000, 0x17b0, 0x5bfe, 0x78fe, 0x95ec, 0xa3fe, 0xa3fe, 0xcd24, 0xfffe, 0xfffe, 0x30fe,
0x0001, 0x190d, 0x9be5, 0xf868, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0x30fe,
0x0c4c, 0xcf6f, 0xfffe, 0xfc0b, 0xb551, 0x6920, 0x4f1d, 0x3c87, 0x39ff, 0x928e, 0xffff, 0xffff, 0x30ff,
0x8f03, 0xffff, 0xfbe7, 0x4d76, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x727f, 0xffff, 0xffff, 0x30ff,
0xccff, 0xffff, 0xc6ff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x727f, 0xffff, 0xffff, 0x30ff,
0xf296, 0xffff, 0xb7c6, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x939a, 0xffff, 0xffff, 0x30ff,
0xc97f, 0xffff, 0xf43c, 0x2493, 0x0000, 0x0000, 0x0000, 0x0000, 0x5f13, 0xfd0c, 0xffff, 0xffff, 0x3827,
0x6dc9, 0xffff, 0xffff, 0xeb16, 0x7dd4, 0x5541, 0x6c76, 0xc10f, 0xfff1, 0xffff, 0xffff, 0xffff, 0x49ff,
0x00d8, 0xa6e9, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xfffe, 0xd4fe, 0x83db, 0xffff, 0xffff, 0x7584,
0x0000, 0x001c, 0x503e, 0xbb08, 0xe3a1, 0xeea6, 0xbd0e, 0x7e09, 0x08e5, 0x1b8b, 0xb67f, 0xb67f, 0x7d44,
}
var flMask16 = []uint32{
0x0000, 0x0000, 0x05b5, 0x668a, 0xbbe0, 0xe875, 0xf803, 0xda29, 0xb49f, 0x4a7a, 0x000a, 0x0000, 0x0000,
0x0000, 0x2473, 0xd7fb, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xad4d, 0x0204, 0x0000,
0x0d48, 0xe27a, 0xffff, 0xf949, 0x8c70, 0x3bae, 0x2ac9, 0x51f7, 0xccc4, 0xffff, 0xffff, 0x779f, 0x0000,
0x75a1, 0xffff, 0xffff, 0x5d7b, 0x0000, 0x0000, 0x0000, 0x0000, 0x0b23, 0xdf73, 0xffff, 0xe39d, 0x0000,
0x5ba0, 0x9033, 0x8f9f, 0x0609, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x8db0, 0xffff, 0xffef, 0x1746,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x728c, 0xffff, 0xffff, 0x3148,
0x0000, 0x0000, 0x0000, 0x17ac, 0x5bce, 0x78cb, 0x95b7, 0xa3d2, 0xa3d2, 0xcce6, 0xffff, 0xffff, 0x3148,
0x0000, 0x1919, 0x9bfd, 0xf86b, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x3148,
0x0c63, 0xcf97, 0xffff, 0xfc17, 0xb59d, 0x6981, 0x4f87, 0x3cf1, 0x3a68, 0x9276, 0xffff, 0xffff, 0x3148,
0x8eb0, 0xffff, 0xfbf5, 0x4d33, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7214, 0xffff, 0xffff, 0x3148,
0xccaf, 0xffff, 0xc6ba, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7214, 0xffff, 0xffff, 0x3148,
0xf292, 0xffff, 0xb865, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x930c, 0xffff, 0xffff, 0x3148,
0xc906, 0xffff, 0xf45d, 0x249f, 0x0000, 0x0000, 0x0000, 0x0000, 0x5ea0, 0xfcf1, 0xffff, 0xffff, 0x3888,
0x6d81, 0xffff, 0xffff, 0xeaf5, 0x7dcf, 0x5533, 0x6c2b, 0xc07b, 0xfff1, 0xffff, 0xffff, 0xffff, 0x4a9d,
0x00d4, 0xa6a1, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xd54d, 0x8399, 0xffff, 0xffff, 0x764b,
0x0000, 0x001b, 0x4ffc, 0xbb4a, 0xe3f5, 0xeee3, 0xbd4c, 0x7e42, 0x0900, 0x1b0c, 0xb6fc, 0xb6fc, 0x7e04,
}
// TestFixedFloatingCloseness compares the closeness of the fixed point and
// floating point rasterizer.
func TestFixedFloatingCloseness(t *testing.T) {
if len(fxMask16) != len(flMask16) {
t.Fatalf("len(fxMask16) != len(flMask16)")
}
total := uint32(0)
for i := range fxMask16 {
a := fxMask16[i]
b := flMask16[i]
if a > b {
total += a - b
} else {
total += b - a
}
}
n := len(fxMask16)
// This log message is useful when changing the fixed point rasterizer
// implementation, such as by changing ϕ. Assuming that the floating point
// rasterizer is accurate, the average difference is a measure of how
// inaccurate the (faster) fixed point rasterizer is.
//
// Smaller is better.
percent := float64(total*100) / float64(n*65535)
t.Logf("Comparing closeness of the fixed point and floating point rasterizer.\n"+
"Specifically, the elements of fxMask16 and flMask16.\n"+
"Total diff = %d, n = %d, avg = %.5f out of 65535, or %.5f%%.\n",
total, n, float64(total)/float64(n), percent)
const thresholdPercent = 1.0
if percent > thresholdPercent {
t.Errorf("average difference: got %.5f%%, want <= %.5f%%", percent, thresholdPercent)
}
}
|
vector | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vector/vector_test.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vector
// TODO: add tests for NaN and Inf coordinates.
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"math/rand"
"os"
"path/filepath"
"testing"
)
// encodePNG is useful for manually debugging the tests.
func encodePNG(dstFilename string, src image.Image) error {
f, err := os.Create(dstFilename)
if err != nil {
return err
}
encErr := png.Encode(f, src)
closeErr := f.Close()
if encErr != nil {
return encErr
}
return closeErr
}
func pointOnCircle(center, radius, index, number int) (x, y float32) {
c := float64(center)
r := float64(radius)
i := float64(index)
n := float64(number)
return float32(c + r*(math.Cos(2*math.Pi*i/n))),
float32(c + r*(math.Sin(2*math.Pi*i/n)))
}
func TestRasterizeOutOfBounds(t *testing.T) {
// Set this to a non-empty string such as "/tmp" to manually inspect the
// rasterization.
//
// If empty, this test simply checks that calling LineTo with points out of
// the rasterizer's bounds doesn't panic.
const tmpDir = ""
const center, radius, n = 16, 20, 16
var z Rasterizer
for i := 0; i < n; i++ {
for j := 1; j < n/2; j++ {
z.Reset(2*center, 2*center)
z.MoveTo(1*center, 1*center)
z.LineTo(pointOnCircle(center, radius, i+0, n))
z.LineTo(pointOnCircle(center, radius, i+j, n))
z.ClosePath()
z.MoveTo(0*center, 0*center)
z.LineTo(0*center, 2*center)
z.LineTo(2*center, 2*center)
z.LineTo(2*center, 0*center)
z.ClosePath()
dst := image.NewAlpha(z.Bounds())
z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{})
if tmpDir == "" {
continue
}
filename := filepath.Join(tmpDir, fmt.Sprintf("out-%02d-%02d.png", i, j))
if err := encodePNG(filename, dst); err != nil {
t.Error(err)
}
t.Logf("wrote %s", filename)
}
}
}
func TestRasterizePolygon(t *testing.T) {
var z Rasterizer
for radius := 4; radius <= 256; radius *= 2 {
for n := 3; n <= 19; n += 4 {
z.Reset(2*radius, 2*radius)
z.MoveTo(float32(2*radius), float32(1*radius))
for i := 1; i < n; i++ {
z.LineTo(pointOnCircle(radius, radius, i, n))
}
z.ClosePath()
dst := image.NewAlpha(z.Bounds())
z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{})
if err := checkCornersCenter(dst); err != nil {
t.Errorf("radius=%d, n=%d: %v", radius, n, err)
}
}
}
}
func TestRasterizeAlmostAxisAligned(t *testing.T) {
z := NewRasterizer(8, 8)
z.MoveTo(2, 2)
z.LineTo(6, math.Nextafter32(2, 0))
z.LineTo(6, 6)
z.LineTo(math.Nextafter32(2, 0), 6)
z.ClosePath()
dst := image.NewAlpha(z.Bounds())
z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{})
if err := checkCornersCenter(dst); err != nil {
t.Error(err)
}
}
func TestRasterizeWideAlmostHorizontalLines(t *testing.T) {
var z Rasterizer
for i := uint(3); i < 16; i++ {
x := float32(int(1 << i))
z.Reset(8, 8)
z.MoveTo(-x, 3)
z.LineTo(+x, 4)
z.LineTo(+x, 6)
z.LineTo(-x, 6)
z.ClosePath()
dst := image.NewAlpha(z.Bounds())
z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{})
if err := checkCornersCenter(dst); err != nil {
t.Errorf("i=%d: %v", i, err)
}
}
}
func TestRasterize30Degrees(t *testing.T) {
z := NewRasterizer(8, 8)
z.MoveTo(4, 4)
z.LineTo(8, 4)
z.LineTo(4, 6)
z.ClosePath()
dst := image.NewAlpha(z.Bounds())
z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{})
if err := checkCornersCenter(dst); err != nil {
t.Error(err)
}
}
func TestRasterizeRandomLineTos(t *testing.T) {
var z Rasterizer
for i := 5; i < 50; i++ {
n, rng := 0, rand.New(rand.NewSource(int64(i)))
z.Reset(i+2, i+2)
z.MoveTo(float32(i/2), float32(i/2))
for ; rng.Intn(16) != 0; n++ {
x := 1 + rng.Intn(i)
y := 1 + rng.Intn(i)
z.LineTo(float32(x), float32(y))
}
z.ClosePath()
dst := image.NewAlpha(z.Bounds())
z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{})
if err := checkCorners(dst); err != nil {
t.Errorf("i=%d (%d nodes): %v", i, n, err)
}
}
}
// checkCornersCenter checks that the corners of the image are all 0x00 and the
// center is 0xff.
func checkCornersCenter(m *image.Alpha) error {
if err := checkCorners(m); err != nil {
return err
}
size := m.Bounds().Size()
center := m.Pix[(size.Y/2)*m.Stride+(size.X/2)]
if center != 0xff {
return fmt.Errorf("center: got %#02x, want 0xff", center)
}
return nil
}
// checkCorners checks that the corners of the image are all 0x00.
func checkCorners(m *image.Alpha) error {
size := m.Bounds().Size()
corners := [4]uint8{
m.Pix[(0*size.Y+0)*m.Stride+(0*size.X+0)],
m.Pix[(0*size.Y+0)*m.Stride+(1*size.X-1)],
m.Pix[(1*size.Y-1)*m.Stride+(0*size.X+0)],
m.Pix[(1*size.Y-1)*m.Stride+(1*size.X-1)],
}
if corners != [4]uint8{} {
return fmt.Errorf("corners were not all zero: %v", corners)
}
return nil
}
var basicMask = []byte{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xaa, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x5f, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x24, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa1, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x14, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x4a, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0x00, 0x00,
0x00, 0x00, 0x66, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xe4, 0xff, 0xff, 0xff, 0xb6, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xf2, 0xff, 0xff, 0xfe, 0x9e, 0x15, 0x00, 0x15, 0x96, 0xff, 0xce, 0x00, 0x00,
0x00, 0x00, 0x00, 0x88, 0xfc, 0xe3, 0x43, 0x00, 0x00, 0x00, 0x00, 0x06, 0xcd, 0xdc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0xde, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}
func testBasicPath(t *testing.T, prefix string, dst draw.Image, src image.Image, op draw.Op, want []byte) {
z := NewRasterizer(16, 16)
z.MoveTo(2, 2)
z.LineTo(8, 2)
z.QuadTo(14, 2, 14, 14)
z.CubeTo(8, 2, 5, 20, 2, 8)
z.ClosePath()
z.DrawOp = op
z.Draw(dst, z.Bounds(), src, image.Point{})
var got []byte
switch dst := dst.(type) {
case *image.Alpha:
got = dst.Pix
case *image.RGBA:
got = dst.Pix
default:
t.Errorf("%s: unrecognized dst image type %T", prefix, dst)
}
if len(got) != len(want) {
t.Errorf("%s: len(got)=%d and len(want)=%d differ", prefix, len(got), len(want))
return
}
for i := range got {
delta := int(got[i]) - int(want[i])
// The +/- 2 allows different implementations to give different
// rounding errors.
if delta < -2 || +2 < delta {
t.Errorf("%s: i=%d: got %#02x, want %#02x", prefix, i, got[i], want[i])
return
}
}
}
func TestBasicPathDstAlpha(t *testing.T) {
for _, background := range []uint8{0x00, 0x80} {
for _, op := range []draw.Op{draw.Over, draw.Src} {
for _, xPadding := range []int{0, 7} {
bounds := image.Rect(0, 0, 16+xPadding, 16)
dst := image.NewAlpha(bounds)
for i := range dst.Pix {
dst.Pix[i] = background
}
want := make([]byte, len(dst.Pix))
copy(want, dst.Pix)
if op == draw.Over && background == 0x80 {
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
ma := basicMask[16*y+x]
i := dst.PixOffset(x, y)
want[i] = 0xff - (0xff-ma)/2
}
}
} else {
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
ma := basicMask[16*y+x]
i := dst.PixOffset(x, y)
want[i] = ma
}
}
}
prefix := fmt.Sprintf("background=%#02x, op=%v, xPadding=%d", background, op, xPadding)
testBasicPath(t, prefix, dst, image.Opaque, op, want)
}
}
}
}
func TestBasicPathDstRGBA(t *testing.T) {
blue := image.NewUniform(color.RGBA{0x00, 0x00, 0xff, 0xff})
for _, op := range []draw.Op{draw.Over, draw.Src} {
for _, xPadding := range []int{0, 7} {
bounds := image.Rect(0, 0, 16+xPadding, 16)
dst := image.NewRGBA(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
dst.SetRGBA(x, y, color.RGBA{
R: uint8(y * 0x07),
G: uint8(x * 0x05),
B: 0x00,
A: 0x80,
})
}
}
want := make([]byte, len(dst.Pix))
copy(want, dst.Pix)
if op == draw.Over {
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
ma := basicMask[16*y+x]
i := dst.PixOffset(x, y)
want[i+0] = uint8((uint32(0xff-ma) * uint32(y*0x07)) / 0xff)
want[i+1] = uint8((uint32(0xff-ma) * uint32(x*0x05)) / 0xff)
want[i+2] = ma
want[i+3] = ma/2 + 0x80
}
}
} else {
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
ma := basicMask[16*y+x]
i := dst.PixOffset(x, y)
want[i+0] = 0x00
want[i+1] = 0x00
want[i+2] = ma
want[i+3] = ma
}
}
}
prefix := fmt.Sprintf("op=%v, xPadding=%d", op, xPadding)
testBasicPath(t, prefix, dst, blue, op, want)
}
}
}
const (
benchmarkGlyphWidth = 893
benchmarkGlyphHeight = 1122
)
type benchmarkGlyphDatum struct {
// n being 0, 1 or 2 means moveTo, lineTo or quadTo.
n uint32
px float32
py float32
qx float32
qy float32
}
// benchmarkGlyphData is the 'a' glyph from the Roboto Regular font, translated
// so that its top left corner is (0, 0).
var benchmarkGlyphData = []benchmarkGlyphDatum{
{0, 699, 1102, 0, 0},
{2, 683, 1070, 673, 988},
{2, 544, 1122, 365, 1122},
{2, 205, 1122, 102.5, 1031.5},
{2, 0, 941, 0, 802},
{2, 0, 633, 128.5, 539.5},
{2, 257, 446, 490, 446},
{1, 670, 446, 0, 0},
{1, 670, 361, 0, 0},
{2, 670, 264, 612, 206.5},
{2, 554, 149, 441, 149},
{2, 342, 149, 275, 199},
{2, 208, 249, 208, 320},
{1, 22, 320, 0, 0},
{2, 22, 239, 79.5, 163.5},
{2, 137, 88, 235.5, 44},
{2, 334, 0, 452, 0},
{2, 639, 0, 745, 93.5},
{2, 851, 187, 855, 351},
{1, 855, 849, 0, 0},
{2, 855, 998, 893, 1086},
{1, 893, 1102, 0, 0},
{1, 699, 1102, 0, 0},
{0, 392, 961, 0, 0},
{2, 479, 961, 557, 916},
{2, 635, 871, 670, 799},
{1, 670, 577, 0, 0},
{1, 525, 577, 0, 0},
{2, 185, 577, 185, 776},
{2, 185, 863, 243, 912},
{2, 301, 961, 392, 961},
}
func scaledBenchmarkGlyphData(height int) (width int, data []benchmarkGlyphDatum) {
scale := float32(height) / benchmarkGlyphHeight
// Clone the benchmarkGlyphData slice and scale its coordinates.
data = append(data, benchmarkGlyphData...)
for i := range data {
data[i].px *= scale
data[i].py *= scale
data[i].qx *= scale
data[i].qy *= scale
}
return int(math.Ceil(float64(benchmarkGlyphWidth * scale))), data
}
// benchGlyph benchmarks rasterizing a TrueType glyph.
//
// Note that, compared to the github.com/google/font-go prototype, the height
// here is the height of the bounding box, not the pixels per em used to scale
// a glyph's vectors. A height of 64 corresponds to a ppem greater than 64.
func benchGlyph(b *testing.B, colorModel byte, loose bool, height int, op draw.Op) {
width, data := scaledBenchmarkGlyphData(height)
z := NewRasterizer(width, height)
bounds := z.Bounds()
if loose {
bounds.Max.X++
}
dst, src := draw.Image(nil), image.Image(nil)
switch colorModel {
case 'A':
dst = image.NewAlpha(bounds)
src = image.Opaque
case 'N':
dst = image.NewNRGBA(bounds)
src = image.NewUniform(color.NRGBA{0x40, 0x80, 0xc0, 0xff})
case 'R':
dst = image.NewRGBA(bounds)
src = image.NewUniform(color.RGBA{0x40, 0x80, 0xc0, 0xff})
default:
b.Fatal("unsupported color model")
}
bounds = z.Bounds()
b.ResetTimer()
for i := 0; i < b.N; i++ {
z.Reset(width, height)
z.DrawOp = op
for _, d := range data {
switch d.n {
case 0:
z.MoveTo(d.px, d.py)
case 1:
z.LineTo(d.px, d.py)
case 2:
z.QuadTo(d.px, d.py, d.qx, d.qy)
}
}
z.Draw(dst, bounds, src, image.Point{})
}
}
// The heights 16, 32, 64, 128, 256, 1024 include numbers both above and below
// the floatingPointMathThreshold constant (512).
func BenchmarkGlyphAlpha16Over(b *testing.B) { benchGlyph(b, 'A', false, 16, draw.Over) }
func BenchmarkGlyphAlpha16Src(b *testing.B) { benchGlyph(b, 'A', false, 16, draw.Src) }
func BenchmarkGlyphAlpha32Over(b *testing.B) { benchGlyph(b, 'A', false, 32, draw.Over) }
func BenchmarkGlyphAlpha32Src(b *testing.B) { benchGlyph(b, 'A', false, 32, draw.Src) }
func BenchmarkGlyphAlpha64Over(b *testing.B) { benchGlyph(b, 'A', false, 64, draw.Over) }
func BenchmarkGlyphAlpha64Src(b *testing.B) { benchGlyph(b, 'A', false, 64, draw.Src) }
func BenchmarkGlyphAlpha128Over(b *testing.B) { benchGlyph(b, 'A', false, 128, draw.Over) }
func BenchmarkGlyphAlpha128Src(b *testing.B) { benchGlyph(b, 'A', false, 128, draw.Src) }
func BenchmarkGlyphAlpha256Over(b *testing.B) { benchGlyph(b, 'A', false, 256, draw.Over) }
func BenchmarkGlyphAlpha256Src(b *testing.B) { benchGlyph(b, 'A', false, 256, draw.Src) }
func BenchmarkGlyphAlpha1024Over(b *testing.B) { benchGlyph(b, 'A', false, 1024, draw.Over) }
func BenchmarkGlyphAlpha1024Src(b *testing.B) { benchGlyph(b, 'A', false, 1024, draw.Src) }
func BenchmarkGlyphAlphaLoose16Over(b *testing.B) { benchGlyph(b, 'A', true, 16, draw.Over) }
func BenchmarkGlyphAlphaLoose16Src(b *testing.B) { benchGlyph(b, 'A', true, 16, draw.Src) }
func BenchmarkGlyphAlphaLoose32Over(b *testing.B) { benchGlyph(b, 'A', true, 32, draw.Over) }
func BenchmarkGlyphAlphaLoose32Src(b *testing.B) { benchGlyph(b, 'A', true, 32, draw.Src) }
func BenchmarkGlyphAlphaLoose64Over(b *testing.B) { benchGlyph(b, 'A', true, 64, draw.Over) }
func BenchmarkGlyphAlphaLoose64Src(b *testing.B) { benchGlyph(b, 'A', true, 64, draw.Src) }
func BenchmarkGlyphAlphaLoose128Over(b *testing.B) { benchGlyph(b, 'A', true, 128, draw.Over) }
func BenchmarkGlyphAlphaLoose128Src(b *testing.B) { benchGlyph(b, 'A', true, 128, draw.Src) }
func BenchmarkGlyphAlphaLoose256Over(b *testing.B) { benchGlyph(b, 'A', true, 256, draw.Over) }
func BenchmarkGlyphAlphaLoose256Src(b *testing.B) { benchGlyph(b, 'A', true, 256, draw.Src) }
func BenchmarkGlyphAlphaLoose1024Over(b *testing.B) { benchGlyph(b, 'A', true, 1024, draw.Over) }
func BenchmarkGlyphAlphaLoose1024Src(b *testing.B) { benchGlyph(b, 'A', true, 1024, draw.Src) }
func BenchmarkGlyphRGBA16Over(b *testing.B) { benchGlyph(b, 'R', false, 16, draw.Over) }
func BenchmarkGlyphRGBA16Src(b *testing.B) { benchGlyph(b, 'R', false, 16, draw.Src) }
func BenchmarkGlyphRGBA32Over(b *testing.B) { benchGlyph(b, 'R', false, 32, draw.Over) }
func BenchmarkGlyphRGBA32Src(b *testing.B) { benchGlyph(b, 'R', false, 32, draw.Src) }
func BenchmarkGlyphRGBA64Over(b *testing.B) { benchGlyph(b, 'R', false, 64, draw.Over) }
func BenchmarkGlyphRGBA64Src(b *testing.B) { benchGlyph(b, 'R', false, 64, draw.Src) }
func BenchmarkGlyphRGBA128Over(b *testing.B) { benchGlyph(b, 'R', false, 128, draw.Over) }
func BenchmarkGlyphRGBA128Src(b *testing.B) { benchGlyph(b, 'R', false, 128, draw.Src) }
func BenchmarkGlyphRGBA256Over(b *testing.B) { benchGlyph(b, 'R', false, 256, draw.Over) }
func BenchmarkGlyphRGBA256Src(b *testing.B) { benchGlyph(b, 'R', false, 256, draw.Src) }
func BenchmarkGlyphRGBA1024Over(b *testing.B) { benchGlyph(b, 'R', false, 1024, draw.Over) }
func BenchmarkGlyphRGBA1024Src(b *testing.B) { benchGlyph(b, 'R', false, 1024, draw.Src) }
func BenchmarkGlyphNRGBA16Over(b *testing.B) { benchGlyph(b, 'N', false, 16, draw.Over) }
func BenchmarkGlyphNRGBA16Src(b *testing.B) { benchGlyph(b, 'N', false, 16, draw.Src) }
func BenchmarkGlyphNRGBA32Over(b *testing.B) { benchGlyph(b, 'N', false, 32, draw.Over) }
func BenchmarkGlyphNRGBA32Src(b *testing.B) { benchGlyph(b, 'N', false, 32, draw.Src) }
func BenchmarkGlyphNRGBA64Over(b *testing.B) { benchGlyph(b, 'N', false, 64, draw.Over) }
func BenchmarkGlyphNRGBA64Src(b *testing.B) { benchGlyph(b, 'N', false, 64, draw.Src) }
func BenchmarkGlyphNRGBA128Over(b *testing.B) { benchGlyph(b, 'N', false, 128, draw.Over) }
func BenchmarkGlyphNRGBA128Src(b *testing.B) { benchGlyph(b, 'N', false, 128, draw.Src) }
func BenchmarkGlyphNRGBA256Over(b *testing.B) { benchGlyph(b, 'N', false, 256, draw.Over) }
func BenchmarkGlyphNRGBA256Src(b *testing.B) { benchGlyph(b, 'N', false, 256, draw.Src) }
func BenchmarkGlyphNRGBA1024Over(b *testing.B) { benchGlyph(b, 'N', false, 1024, draw.Over) }
func BenchmarkGlyphNRGBA1024Src(b *testing.B) { benchGlyph(b, 'N', false, 1024, draw.Src) }
|
vector | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vector/gen.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"io/ioutil"
"log"
"strings"
"text/template"
)
const (
copyright = "" +
"// Copyright 2016 The Go Authors. All rights reserved.\n" +
"// Use of this source code is governed by a BSD-style\n" +
"// license that can be found in the LICENSE file.\n"
doNotEdit = "// generated by go run gen.go; DO NOT EDIT\n"
dashDashDash = "// --------"
)
func main() {
tmpl, err := ioutil.ReadFile("gen_acc_amd64.s.tmpl")
if err != nil {
log.Fatalf("ReadFile: %v", err)
}
if !bytes.HasPrefix(tmpl, []byte(copyright)) {
log.Fatal("source template did not start with the copyright header")
}
tmpl = tmpl[len(copyright):]
preamble := []byte(nil)
if i := bytes.Index(tmpl, []byte(dashDashDash)); i < 0 {
log.Fatalf("source template did not contain %q", dashDashDash)
} else {
preamble, tmpl = tmpl[:i], tmpl[i:]
}
t, err := template.New("").Parse(string(tmpl))
if err != nil {
log.Fatalf("Parse: %v", err)
}
out := bytes.NewBuffer(nil)
out.WriteString(doNotEdit)
out.Write(preamble)
for i, v := range instances {
if i != 0 {
out.WriteString("\n")
}
if strings.Contains(v.LoadArgs, "{{.ShortName}}") {
v.LoadArgs = strings.Replace(v.LoadArgs, "{{.ShortName}}", v.ShortName, -1)
}
if err := t.Execute(out, v); err != nil {
log.Fatalf("Execute(%q): %v", v.ShortName, err)
}
}
if err := ioutil.WriteFile("acc_amd64.s", out.Bytes(), 0666); err != nil {
log.Fatalf("WriteFile: %v", err)
}
}
var instances = []struct {
LongName string
ShortName string
FrameSize string
ArgsSize string
Args string
DstElemSize1 int
DstElemSize4 int
XMM3 string
XMM4 string
XMM5 string
XMM6 string
XMM8 string
XMM9 string
XMM10 string
LoadArgs string
Setup string
LoadXMMRegs string
Add string
ClampAndScale string
ConvertToInt32 string
Store4 string
Store1 string
}{{
LongName: "fixedAccumulateOpOver",
ShortName: "fxAccOpOver",
FrameSize: fxFrameSize,
ArgsSize: twoArgArgsSize,
Args: "dst []uint8, src []uint32",
DstElemSize1: 1 * sizeOfUint8,
DstElemSize4: 4 * sizeOfUint8,
XMM3: fxXMM3,
XMM4: fxXMM4,
XMM5: fxXMM5,
XMM6: opOverXMM6,
XMM8: opOverXMM8,
XMM9: opOverXMM9,
XMM10: opOverXMM10,
LoadArgs: twoArgLoadArgs,
Setup: fxSetup,
LoadXMMRegs: fxLoadXMMRegs + "\n" + opOverLoadXMMRegs,
Add: fxAdd,
ClampAndScale: fxClampAndScale,
ConvertToInt32: fxConvertToInt32,
Store4: opOverStore4,
Store1: opOverStore1,
}, {
LongName: "fixedAccumulateOpSrc",
ShortName: "fxAccOpSrc",
FrameSize: fxFrameSize,
ArgsSize: twoArgArgsSize,
Args: "dst []uint8, src []uint32",
DstElemSize1: 1 * sizeOfUint8,
DstElemSize4: 4 * sizeOfUint8,
XMM3: fxXMM3,
XMM4: fxXMM4,
XMM5: fxXMM5,
XMM6: opSrcXMM6,
XMM8: opSrcXMM8,
XMM9: opSrcXMM9,
XMM10: opSrcXMM10,
LoadArgs: twoArgLoadArgs,
Setup: fxSetup,
LoadXMMRegs: fxLoadXMMRegs + "\n" + opSrcLoadXMMRegs,
Add: fxAdd,
ClampAndScale: fxClampAndScale,
ConvertToInt32: fxConvertToInt32,
Store4: opSrcStore4,
Store1: opSrcStore1,
}, {
LongName: "fixedAccumulateMask",
ShortName: "fxAccMask",
FrameSize: fxFrameSize,
ArgsSize: oneArgArgsSize,
Args: "buf []uint32",
DstElemSize1: 1 * sizeOfUint32,
DstElemSize4: 4 * sizeOfUint32,
XMM3: fxXMM3,
XMM4: fxXMM4,
XMM5: fxXMM5,
XMM6: maskXMM6,
XMM8: maskXMM8,
XMM9: maskXMM9,
XMM10: maskXMM10,
LoadArgs: oneArgLoadArgs,
Setup: fxSetup,
LoadXMMRegs: fxLoadXMMRegs + "\n" + maskLoadXMMRegs,
Add: fxAdd,
ClampAndScale: fxClampAndScale,
ConvertToInt32: fxConvertToInt32,
Store4: maskStore4,
Store1: maskStore1,
}, {
LongName: "floatingAccumulateOpOver",
ShortName: "flAccOpOver",
FrameSize: flFrameSize,
ArgsSize: twoArgArgsSize,
Args: "dst []uint8, src []float32",
DstElemSize1: 1 * sizeOfUint8,
DstElemSize4: 4 * sizeOfUint8,
XMM3: flXMM3,
XMM4: flXMM4,
XMM5: flXMM5,
XMM6: opOverXMM6,
XMM8: opOverXMM8,
XMM9: opOverXMM9,
XMM10: opOverXMM10,
LoadArgs: twoArgLoadArgs,
Setup: flSetup,
LoadXMMRegs: flLoadXMMRegs + "\n" + opOverLoadXMMRegs,
Add: flAdd,
ClampAndScale: flClampAndScale,
ConvertToInt32: flConvertToInt32,
Store4: opOverStore4,
Store1: opOverStore1,
}, {
LongName: "floatingAccumulateOpSrc",
ShortName: "flAccOpSrc",
FrameSize: flFrameSize,
ArgsSize: twoArgArgsSize,
Args: "dst []uint8, src []float32",
DstElemSize1: 1 * sizeOfUint8,
DstElemSize4: 4 * sizeOfUint8,
XMM3: flXMM3,
XMM4: flXMM4,
XMM5: flXMM5,
XMM6: opSrcXMM6,
XMM8: opSrcXMM8,
XMM9: opSrcXMM9,
XMM10: opSrcXMM10,
LoadArgs: twoArgLoadArgs,
Setup: flSetup,
LoadXMMRegs: flLoadXMMRegs + "\n" + opSrcLoadXMMRegs,
Add: flAdd,
ClampAndScale: flClampAndScale,
ConvertToInt32: flConvertToInt32,
Store4: opSrcStore4,
Store1: opSrcStore1,
}, {
LongName: "floatingAccumulateMask",
ShortName: "flAccMask",
FrameSize: flFrameSize,
ArgsSize: twoArgArgsSize,
Args: "dst []uint32, src []float32",
DstElemSize1: 1 * sizeOfUint32,
DstElemSize4: 4 * sizeOfUint32,
XMM3: flXMM3,
XMM4: flXMM4,
XMM5: flXMM5,
XMM6: maskXMM6,
XMM8: maskXMM8,
XMM9: maskXMM9,
XMM10: maskXMM10,
LoadArgs: twoArgLoadArgs,
Setup: flSetup,
LoadXMMRegs: flLoadXMMRegs + "\n" + maskLoadXMMRegs,
Add: flAdd,
ClampAndScale: flClampAndScale,
ConvertToInt32: flConvertToInt32,
Store4: maskStore4,
Store1: maskStore1,
}}
const (
fxFrameSize = `0`
flFrameSize = `8`
oneArgArgsSize = `24`
twoArgArgsSize = `48`
sizeOfUint8 = 1
sizeOfUint32 = 4
fxXMM3 = `-`
flXMM3 = `flSignMask`
fxXMM4 = `-`
flXMM4 = `flOne`
fxXMM5 = `fxAlmost65536`
flXMM5 = `flAlmost65536`
oneArgLoadArgs = `
MOVQ buf_base+0(FP), DI
MOVQ buf_len+8(FP), BX
MOVQ buf_base+0(FP), SI
MOVQ buf_len+8(FP), R10
`
twoArgLoadArgs = `
MOVQ dst_base+0(FP), DI
MOVQ dst_len+8(FP), BX
MOVQ src_base+24(FP), SI
MOVQ src_len+32(FP), R10
// Sanity check that len(dst) >= len(src).
CMPQ BX, R10
JLT {{.ShortName}}End
`
fxSetup = ``
flSetup = `
// Prepare to set MXCSR bits 13 and 14, so that the CVTPS2PL below is
// "Round To Zero".
STMXCSR mxcsrOrig-8(SP)
MOVL mxcsrOrig-8(SP), AX
ORL $0x6000, AX
MOVL AX, mxcsrNew-4(SP)
`
fxLoadXMMRegs = `
// fxAlmost65536 := XMM(0x0000ffff repeated four times) // Maximum of an uint16.
MOVOU fxAlmost65536<>(SB), X5
`
flLoadXMMRegs = `
// flSignMask := XMM(0x7fffffff repeated four times) // All but the sign bit of a float32.
// flOne := XMM(0x3f800000 repeated four times) // 1 as a float32.
// flAlmost65536 := XMM(0x477fffff repeated four times) // 255.99998 * 256 as a float32.
MOVOU flSignMask<>(SB), X3
MOVOU flOne<>(SB), X4
MOVOU flAlmost65536<>(SB), X5
`
fxAdd = `PADDD`
flAdd = `ADDPS`
fxClampAndScale = `
// y = abs(x)
// y >>= 2 // Shift by 2*ϕ - 16.
// y = min(y, fxAlmost65536)
PABSD X1, X2
PSRLL $2, X2
PMINUD X5, X2
`
flClampAndScale = `
// y = x & flSignMask
// y = min(y, flOne)
// y = mul(y, flAlmost65536)
MOVOU X3, X2
ANDPS X1, X2
MINPS X4, X2
MULPS X5, X2
`
fxConvertToInt32 = `
// z = convertToInt32(y)
// No-op.
`
flConvertToInt32 = `
// z = convertToInt32(y)
LDMXCSR mxcsrNew-4(SP)
CVTPS2PL X2, X2
LDMXCSR mxcsrOrig-8(SP)
`
opOverStore4 = `
// Blend over the dst's prior value. SIMD for i in 0..3:
//
// dstA := uint32(dst[i]) * 0x101
// maskA := z@i
// outA := dstA*(0xffff-maskA)/0xffff + maskA
// dst[i] = uint8(outA >> 8)
//
// First, set X0 to dstA*(0xfff-maskA).
MOVL (DI), X0
PSHUFB X8, X0
MOVOU X9, X11
PSUBL X2, X11
PMULLD X11, X0
// We implement uint32 division by 0xffff as multiplication by a magic
// constant (0x800080001) and then a shift by a magic constant (47).
// See TestDivideByFFFF for a justification.
//
// That multiplication widens from uint32 to uint64, so we have to
// duplicate and shift our four uint32s from one XMM register (X0) to
// two XMM registers (X0 and X11).
//
// Move the second and fourth uint32s in X0 to be the first and third
// uint32s in X11.
MOVOU X0, X11
PSRLQ $32, X11
// Multiply by magic, shift by magic.
PMULULQ X10, X0
PMULULQ X10, X11
PSRLQ $47, X0
PSRLQ $47, X11
// Merge the two registers back to one, X11, and add maskA.
PSLLQ $32, X11
XORPS X0, X11
PADDD X11, X2
// As per opSrcStore4, shuffle and copy the 4 second-lowest bytes.
PSHUFB X6, X2
MOVL X2, (DI)
`
opSrcStore4 = `
// z = shuffleTheSecondLowestBytesOfEach4ByteElement(z)
// copy(dst[:4], low4BytesOf(z))
PSHUFB X6, X2
MOVL X2, (DI)
`
maskStore4 = `
// copy(dst[:4], z)
MOVOU X2, (DI)
`
opOverStore1 = `
// Blend over the dst's prior value.
//
// dstA := uint32(dst[0]) * 0x101
// maskA := z
// outA := dstA*(0xffff-maskA)/0xffff + maskA
// dst[0] = uint8(outA >> 8)
MOVBLZX (DI), R12
IMULL $0x101, R12
MOVL X2, R13
MOVL $0xffff, AX
SUBL R13, AX
MULL R12 // MULL's implicit arg is AX, and the result is stored in DX:AX.
MOVL $0x80008001, BX // Divide by 0xffff is to first multiply by a magic constant...
MULL BX // MULL's implicit arg is AX, and the result is stored in DX:AX.
SHRL $15, DX // ...and then shift by another magic constant (47 - 32 = 15).
ADDL DX, R13
SHRL $8, R13
MOVB R13, (DI)
`
opSrcStore1 = `
// dst[0] = uint8(z>>8)
MOVL X2, BX
SHRL $8, BX
MOVB BX, (DI)
`
maskStore1 = `
// dst[0] = uint32(z)
MOVL X2, (DI)
`
opOverXMM6 = `gather`
opSrcXMM6 = `gather`
maskXMM6 = `-`
opOverXMM8 = `scatterAndMulBy0x101`
opSrcXMM8 = `-`
maskXMM8 = `-`
opOverXMM9 = `fxAlmost65536`
opSrcXMM9 = `-`
maskXMM9 = `-`
opOverXMM10 = `inverseFFFF`
opSrcXMM10 = `-`
maskXMM10 = `-`
opOverLoadXMMRegs = `
// gather := XMM(see above) // PSHUFB shuffle mask.
// scatterAndMulBy0x101 := XMM(see above) // PSHUFB shuffle mask.
// fxAlmost65536 := XMM(0x0000ffff repeated four times) // 0xffff.
// inverseFFFF := XMM(0x80008001 repeated four times) // Magic constant for dividing by 0xffff.
MOVOU gather<>(SB), X6
MOVOU scatterAndMulBy0x101<>(SB), X8
MOVOU fxAlmost65536<>(SB), X9
MOVOU inverseFFFF<>(SB), X10
`
opSrcLoadXMMRegs = `
// gather := XMM(see above) // PSHUFB shuffle mask.
MOVOU gather<>(SB), X6
`
maskLoadXMMRegs = ``
)
|
webp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/webp/decode.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package webp
import (
"bytes"
"errors"
"image"
"image/color"
"io"
"golang.org/x/image/riff"
"golang.org/x/image/vp8"
"golang.org/x/image/vp8l"
)
var errInvalidFormat = errors.New("webp: invalid format")
var (
fccALPH = riff.FourCC{'A', 'L', 'P', 'H'}
fccVP8 = riff.FourCC{'V', 'P', '8', ' '}
fccVP8L = riff.FourCC{'V', 'P', '8', 'L'}
fccVP8X = riff.FourCC{'V', 'P', '8', 'X'}
fccWEBP = riff.FourCC{'W', 'E', 'B', 'P'}
)
func decode(r io.Reader, configOnly bool) (image.Image, image.Config, error) {
formType, riffReader, err := riff.NewReader(r)
if err != nil {
return nil, image.Config{}, err
}
if formType != fccWEBP {
return nil, image.Config{}, errInvalidFormat
}
var (
alpha []byte
alphaStride int
wantAlpha bool
seenVP8X bool
widthMinusOne uint32
heightMinusOne uint32
buf [10]byte
)
for {
chunkID, chunkLen, chunkData, err := riffReader.Next()
if err == io.EOF {
err = errInvalidFormat
}
if err != nil {
return nil, image.Config{}, err
}
switch chunkID {
case fccALPH:
if !wantAlpha {
return nil, image.Config{}, errInvalidFormat
}
wantAlpha = false
// Read the Pre-processing | Filter | Compression byte.
if _, err := io.ReadFull(chunkData, buf[:1]); err != nil {
if err == io.EOF {
err = errInvalidFormat
}
return nil, image.Config{}, err
}
alpha, alphaStride, err = readAlpha(chunkData, widthMinusOne, heightMinusOne, buf[0]&0x03)
if err != nil {
return nil, image.Config{}, err
}
unfilterAlpha(alpha, alphaStride, (buf[0]>>2)&0x03)
case fccVP8:
if wantAlpha || int32(chunkLen) < 0 {
return nil, image.Config{}, errInvalidFormat
}
d := vp8.NewDecoder()
d.Init(chunkData, int(chunkLen))
fh, err := d.DecodeFrameHeader()
if err != nil {
return nil, image.Config{}, err
}
if configOnly {
return nil, image.Config{
ColorModel: color.YCbCrModel,
Width: fh.Width,
Height: fh.Height,
}, nil
}
m, err := d.DecodeFrame()
if err != nil {
return nil, image.Config{}, err
}
if alpha != nil {
return &image.NYCbCrA{
YCbCr: *m,
A: alpha,
AStride: alphaStride,
}, image.Config{}, nil
}
return m, image.Config{}, nil
case fccVP8L:
if wantAlpha || alpha != nil {
return nil, image.Config{}, errInvalidFormat
}
if configOnly {
c, err := vp8l.DecodeConfig(chunkData)
return nil, c, err
}
m, err := vp8l.Decode(chunkData)
return m, image.Config{}, err
case fccVP8X:
if seenVP8X {
return nil, image.Config{}, errInvalidFormat
}
seenVP8X = true
if chunkLen != 10 {
return nil, image.Config{}, errInvalidFormat
}
if _, err := io.ReadFull(chunkData, buf[:10]); err != nil {
return nil, image.Config{}, err
}
const (
animationBit = 1 << 1
xmpMetadataBit = 1 << 2
exifMetadataBit = 1 << 3
alphaBit = 1 << 4
iccProfileBit = 1 << 5
)
wantAlpha = (buf[0] & alphaBit) != 0
widthMinusOne = uint32(buf[4]) | uint32(buf[5])<<8 | uint32(buf[6])<<16
heightMinusOne = uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16
if configOnly {
if wantAlpha {
return nil, image.Config{
ColorModel: color.NYCbCrAModel,
Width: int(widthMinusOne) + 1,
Height: int(heightMinusOne) + 1,
}, nil
}
return nil, image.Config{
ColorModel: color.YCbCrModel,
Width: int(widthMinusOne) + 1,
Height: int(heightMinusOne) + 1,
}, nil
}
}
}
}
func readAlpha(chunkData io.Reader, widthMinusOne, heightMinusOne uint32, compression byte) (
alpha []byte, alphaStride int, err error) {
switch compression {
case 0:
w := int(widthMinusOne) + 1
h := int(heightMinusOne) + 1
alpha = make([]byte, w*h)
if _, err := io.ReadFull(chunkData, alpha); err != nil {
return nil, 0, err
}
return alpha, w, nil
case 1:
// Read the VP8L-compressed alpha values. First, synthesize a 5-byte VP8L header:
// a 1-byte magic number, a 14-bit widthMinusOne, a 14-bit heightMinusOne,
// a 1-bit (ignored, zero) alphaIsUsed and a 3-bit (zero) version.
// TODO(nigeltao): be more efficient than decoding an *image.NRGBA just to
// extract the green values to a separately allocated []byte. Fixing this
// will require changes to the vp8l package's API.
if widthMinusOne > 0x3fff || heightMinusOne > 0x3fff {
return nil, 0, errors.New("webp: invalid format")
}
alphaImage, err := vp8l.Decode(io.MultiReader(
bytes.NewReader([]byte{
0x2f, // VP8L magic number.
uint8(widthMinusOne),
uint8(widthMinusOne>>8) | uint8(heightMinusOne<<6),
uint8(heightMinusOne >> 2),
uint8(heightMinusOne >> 10),
}),
chunkData,
))
if err != nil {
return nil, 0, err
}
// The green values of the inner NRGBA image are the alpha values of the
// outer NYCbCrA image.
pix := alphaImage.(*image.NRGBA).Pix
alpha = make([]byte, len(pix)/4)
for i := range alpha {
alpha[i] = pix[4*i+1]
}
return alpha, int(widthMinusOne) + 1, nil
}
return nil, 0, errInvalidFormat
}
func unfilterAlpha(alpha []byte, alphaStride int, filter byte) {
if len(alpha) == 0 || alphaStride == 0 {
return
}
switch filter {
case 1: // Horizontal filter.
for i := 1; i < alphaStride; i++ {
alpha[i] += alpha[i-1]
}
for i := alphaStride; i < len(alpha); i += alphaStride {
// The first column is equivalent to the vertical filter.
alpha[i] += alpha[i-alphaStride]
for j := 1; j < alphaStride; j++ {
alpha[i+j] += alpha[i+j-1]
}
}
case 2: // Vertical filter.
// The first row is equivalent to the horizontal filter.
for i := 1; i < alphaStride; i++ {
alpha[i] += alpha[i-1]
}
for i := alphaStride; i < len(alpha); i++ {
alpha[i] += alpha[i-alphaStride]
}
case 3: // Gradient filter.
// The first row is equivalent to the horizontal filter.
for i := 1; i < alphaStride; i++ {
alpha[i] += alpha[i-1]
}
for i := alphaStride; i < len(alpha); i += alphaStride {
// The first column is equivalent to the vertical filter.
alpha[i] += alpha[i-alphaStride]
// The interior is predicted on the three top/left pixels.
for j := 1; j < alphaStride; j++ {
c := int(alpha[i+j-alphaStride-1])
b := int(alpha[i+j-alphaStride])
a := int(alpha[i+j-1])
x := a + b - c
if x < 0 {
x = 0
} else if x > 255 {
x = 255
}
alpha[i+j] += uint8(x)
}
}
}
}
// Decode reads a WEBP image from r and returns it as an image.Image.
func Decode(r io.Reader) (image.Image, error) {
m, _, err := decode(r, false)
if err != nil {
return nil, err
}
return m, err
}
// DecodeConfig returns the color model and dimensions of a WEBP image without
// decoding the entire image.
func DecodeConfig(r io.Reader) (image.Config, error) {
_, c, err := decode(r, true)
return c, err
}
func init() {
image.RegisterFormat("webp", "RIFF????WEBPVP8", Decode, DecodeConfig)
}
|
webp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/webp/doc.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package webp implements a decoder for WEBP images.
//
// WEBP is defined at:
// https://developers.google.com/speed/webp/docs/riff_container
package webp // import "golang.org/x/image/webp"
|
webp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/webp/decode_test.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package webp
import (
"bytes"
"fmt"
"image"
"image/png"
"io/ioutil"
"os"
"strings"
"testing"
)
// hex is like fmt.Sprintf("% x", x) but also inserts dots every 16 bytes, to
// delineate VP8 macroblock boundaries.
func hex(x []byte) string {
buf := new(bytes.Buffer)
for len(x) > 0 {
n := len(x)
if n > 16 {
n = 16
}
fmt.Fprintf(buf, " . % x", x[:n])
x = x[n:]
}
return buf.String()
}
func testDecodeLossy(t *testing.T, tc string, withAlpha bool) {
webpFilename := "../testdata/" + tc + ".lossy.webp"
pngFilename := webpFilename + ".ycbcr.png"
if withAlpha {
webpFilename = "../testdata/" + tc + ".lossy-with-alpha.webp"
pngFilename = webpFilename + ".nycbcra.png"
}
f0, err := os.Open(webpFilename)
if err != nil {
t.Errorf("%s: Open WEBP: %v", tc, err)
return
}
defer f0.Close()
img0, err := Decode(f0)
if err != nil {
t.Errorf("%s: Decode WEBP: %v", tc, err)
return
}
var (
m0 *image.YCbCr
a0 *image.NYCbCrA
ok bool
)
if withAlpha {
a0, ok = img0.(*image.NYCbCrA)
if ok {
m0 = &a0.YCbCr
}
} else {
m0, ok = img0.(*image.YCbCr)
}
if !ok || m0.SubsampleRatio != image.YCbCrSubsampleRatio420 {
t.Errorf("%s: decoded WEBP image is not a 4:2:0 YCbCr or 4:2:0 NYCbCrA", tc)
return
}
// w2 and h2 are the half-width and half-height, rounded up.
w, h := m0.Bounds().Dx(), m0.Bounds().Dy()
w2, h2 := int((w+1)/2), int((h+1)/2)
f1, err := os.Open(pngFilename)
if err != nil {
t.Errorf("%s: Open PNG: %v", tc, err)
return
}
defer f1.Close()
img1, err := png.Decode(f1)
if err != nil {
t.Errorf("%s: Open PNG: %v", tc, err)
return
}
// The split-into-YCbCr-planes golden image is a 2*w2 wide and h+h2 high
// (or 2*h+h2 high, if with Alpha) gray image arranged in IMC4 format:
// YYYY
// YYYY
// BBRR
// AAAA
// See http://www.fourcc.org/yuv.php#IMC4
pngW, pngH := 2*w2, h+h2
if withAlpha {
pngH += h
}
if got, want := img1.Bounds(), image.Rect(0, 0, pngW, pngH); got != want {
t.Errorf("%s: bounds0: got %v, want %v", tc, got, want)
return
}
m1, ok := img1.(*image.Gray)
if !ok {
t.Errorf("%s: decoded PNG image is not a Gray", tc)
return
}
type plane struct {
name string
m0Pix []uint8
m0Stride int
m1Rect image.Rectangle
}
planes := []plane{
{"Y", m0.Y, m0.YStride, image.Rect(0, 0, w, h)},
{"Cb", m0.Cb, m0.CStride, image.Rect(0*w2, h, 1*w2, h+h2)},
{"Cr", m0.Cr, m0.CStride, image.Rect(1*w2, h, 2*w2, h+h2)},
}
if withAlpha {
planes = append(planes, plane{
"A", a0.A, a0.AStride, image.Rect(0, h+h2, w, 2*h+h2),
})
}
for _, plane := range planes {
dx := plane.m1Rect.Dx()
nDiff, diff := 0, make([]byte, dx)
for j, y := 0, plane.m1Rect.Min.Y; y < plane.m1Rect.Max.Y; j, y = j+1, y+1 {
got := plane.m0Pix[j*plane.m0Stride:][:dx]
want := m1.Pix[y*m1.Stride+plane.m1Rect.Min.X:][:dx]
if bytes.Equal(got, want) {
continue
}
nDiff++
if nDiff > 10 {
t.Errorf("%s: %s plane: more rows differ", tc, plane.name)
break
}
for i := range got {
diff[i] = got[i] - want[i]
}
t.Errorf("%s: %s plane: m0 row %d, m1 row %d\ngot %s\nwant%s\ndiff%s",
tc, plane.name, j, y, hex(got), hex(want), hex(diff))
}
}
}
func TestDecodeVP8(t *testing.T) {
testCases := []string{
"blue-purple-pink",
"blue-purple-pink-large.no-filter",
"blue-purple-pink-large.simple-filter",
"blue-purple-pink-large.normal-filter",
"video-001",
"yellow_rose",
}
for _, tc := range testCases {
testDecodeLossy(t, tc, false)
}
}
func TestDecodeVP8XAlpha(t *testing.T) {
testCases := []string{
"yellow_rose",
}
for _, tc := range testCases {
testDecodeLossy(t, tc, true)
}
}
func TestDecodeVP8L(t *testing.T) {
testCases := []string{
"blue-purple-pink",
"blue-purple-pink-large",
"gopher-doc.1bpp",
"gopher-doc.2bpp",
"gopher-doc.4bpp",
"gopher-doc.8bpp",
"tux",
"yellow_rose",
}
loop:
for _, tc := range testCases {
f0, err := os.Open("../testdata/" + tc + ".lossless.webp")
if err != nil {
t.Errorf("%s: Open WEBP: %v", tc, err)
continue
}
defer f0.Close()
img0, err := Decode(f0)
if err != nil {
t.Errorf("%s: Decode WEBP: %v", tc, err)
continue
}
m0, ok := img0.(*image.NRGBA)
if !ok {
t.Errorf("%s: WEBP image is %T, want *image.NRGBA", tc, img0)
continue
}
f1, err := os.Open("../testdata/" + tc + ".png")
if err != nil {
t.Errorf("%s: Open PNG: %v", tc, err)
continue
}
defer f1.Close()
img1, err := png.Decode(f1)
if err != nil {
t.Errorf("%s: Decode PNG: %v", tc, err)
continue
}
m1, ok := img1.(*image.NRGBA)
if !ok {
rgba1, ok := img1.(*image.RGBA)
if !ok {
t.Fatalf("%s: PNG image is %T, want *image.NRGBA", tc, img1)
continue
}
if !rgba1.Opaque() {
t.Fatalf("%s: PNG image is non-opaque *image.RGBA, want *image.NRGBA", tc)
continue
}
// The image is fully opaque, so we can re-interpret the RGBA pixels
// as NRGBA pixels.
m1 = &image.NRGBA{
Pix: rgba1.Pix,
Stride: rgba1.Stride,
Rect: rgba1.Rect,
}
}
b0, b1 := m0.Bounds(), m1.Bounds()
if b0 != b1 {
t.Errorf("%s: bounds: got %v, want %v", tc, b0, b1)
continue
}
for i := range m0.Pix {
if m0.Pix[i] != m1.Pix[i] {
y := i / m0.Stride
x := (i - y*m0.Stride) / 4
i = 4 * (y*m0.Stride + x)
t.Errorf("%s: at (%d, %d):\ngot %02x %02x %02x %02x\nwant %02x %02x %02x %02x",
tc, x, y,
m0.Pix[i+0], m0.Pix[i+1], m0.Pix[i+2], m0.Pix[i+3],
m1.Pix[i+0], m1.Pix[i+1], m1.Pix[i+2], m1.Pix[i+3],
)
continue loop
}
}
}
}
// TestDecodePartitionTooLarge tests that decoding a malformed WEBP image
// doesn't try to allocate an unreasonable amount of memory. This WEBP image
// claims a RIFF chunk length of 0x12345678 bytes (291 MiB) compressed,
// independent of the actual image size (0 pixels wide * 0 pixels high).
//
// This is based on golang.org/issue/10790.
func TestDecodePartitionTooLarge(t *testing.T) {
data := "RIFF\xff\xff\xff\x7fWEBPVP8 " +
"\x78\x56\x34\x12" + // RIFF chunk length.
"\xbd\x01\x00\x14\x00\x00\xb2\x34\x0a\x9d\x01\x2a\x96\x00\x67\x00"
_, err := Decode(strings.NewReader(data))
if err == nil {
t.Fatal("got nil error, want non-nil")
}
if got, want := err.Error(), "too much data"; !strings.Contains(got, want) {
t.Fatalf("got error %q, want something containing %q", got, want)
}
}
func TestDuplicateVP8X(t *testing.T) {
data := []byte{'R', 'I', 'F', 'F', 49, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', 'X', 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'V', 'P', '8', 'X', 10, 0, 0, 0, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0}
_, err := Decode(bytes.NewReader(data))
if err != errInvalidFormat {
t.Fatalf("unexpected error: want %q, got %q", errInvalidFormat, err)
}
}
func benchmarkDecode(b *testing.B, filename string) {
data, err := ioutil.ReadFile("../testdata/blue-purple-pink-large." + filename + ".webp")
if err != nil {
b.Fatal(err)
}
s := string(data)
cfg, err := DecodeConfig(strings.NewReader(s))
if err != nil {
b.Fatal(err)
}
b.SetBytes(int64(cfg.Width * cfg.Height * 4))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Decode(strings.NewReader(s))
}
}
func BenchmarkDecodeVP8NoFilter(b *testing.B) { benchmarkDecode(b, "no-filter.lossy") }
func BenchmarkDecodeVP8SimpleFilter(b *testing.B) { benchmarkDecode(b, "simple-filter.lossy") }
func BenchmarkDecodeVP8NormalFilter(b *testing.B) { benchmarkDecode(b, "normal-filter.lossy") }
func BenchmarkDecodeVP8L(b *testing.B) { benchmarkDecode(b, "lossless") }
|
f32 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/math/f32/f32.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package f32 implements float32 vector and matrix types.
package f32 // import "golang.org/x/image/math/f32"
// Vec2 is a 2-element vector.
type Vec2 [2]float32
// Vec3 is a 3-element vector.
type Vec3 [3]float32
// Vec4 is a 4-element vector.
type Vec4 [4]float32
// Mat3 is a 3x3 matrix in row major order.
//
// m[3*r + c] is the element in the r'th row and c'th column.
type Mat3 [9]float32
// Mat4 is a 4x4 matrix in row major order.
//
// m[4*r + c] is the element in the r'th row and c'th column.
type Mat4 [16]float32
// Aff3 is a 3x3 affine transformation matrix in row major order, where the
// bottom row is implicitly [0 0 1].
//
// m[3*r + c] is the element in the r'th row and c'th column.
type Aff3 [6]float32
// Aff4 is a 4x4 affine transformation matrix in row major order, where the
// bottom row is implicitly [0 0 0 1].
//
// m[4*r + c] is the element in the r'th row and c'th column.
type Aff4 [12]float32
|
fixed | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/math/fixed/fixed_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fixed
import (
"math"
"math/rand"
"testing"
)
var testCases = []struct {
x float64
s26_6 string
s52_12 string
floor int
round int
ceil int
}{{
x: 0,
s26_6: "0:00",
s52_12: "0:0000",
floor: 0,
round: 0,
ceil: 0,
}, {
x: 1,
s26_6: "1:00",
s52_12: "1:0000",
floor: 1,
round: 1,
ceil: 1,
}, {
x: 1.25,
s26_6: "1:16",
s52_12: "1:1024",
floor: 1,
round: 1,
ceil: 2,
}, {
x: 2.5,
s26_6: "2:32",
s52_12: "2:2048",
floor: 2,
round: 3,
ceil: 3,
}, {
x: 63 / 64.0,
s26_6: "0:63",
s52_12: "0:4032",
floor: 0,
round: 1,
ceil: 1,
}, {
x: -0.5,
s26_6: "-0:32",
s52_12: "-0:2048",
floor: -1,
round: +0,
ceil: +0,
}, {
x: -4.125,
s26_6: "-4:08",
s52_12: "-4:0512",
floor: -5,
round: -4,
ceil: -4,
}, {
x: -7.75,
s26_6: "-7:48",
s52_12: "-7:3072",
floor: -8,
round: -8,
ceil: -7,
}}
func TestInt26_6(t *testing.T) {
const one = Int26_6(1 << 6)
for _, tc := range testCases {
x := Int26_6(tc.x * (1 << 6))
if got, want := x.String(), tc.s26_6; got != want {
t.Errorf("tc.x=%v: String: got %q, want %q", tc.x, got, want)
}
if got, want := x.Floor(), tc.floor; got != want {
t.Errorf("tc.x=%v: Floor: got %v, want %v", tc.x, got, want)
}
if got, want := x.Round(), tc.round; got != want {
t.Errorf("tc.x=%v: Round: got %v, want %v", tc.x, got, want)
}
if got, want := x.Ceil(), tc.ceil; got != want {
t.Errorf("tc.x=%v: Ceil: got %v, want %v", tc.x, got, want)
}
if got, want := x.Mul(one), x; got != want {
t.Errorf("tc.x=%v: Mul by one: got %v, want %v", tc.x, got, want)
}
if got, want := x.mul(one), x; got != want {
t.Errorf("tc.x=%v: mul by one: got %v, want %v", tc.x, got, want)
}
}
}
func TestInt52_12(t *testing.T) {
const one = Int52_12(1 << 12)
for _, tc := range testCases {
x := Int52_12(tc.x * (1 << 12))
if got, want := x.String(), tc.s52_12; got != want {
t.Errorf("tc.x=%v: String: got %q, want %q", tc.x, got, want)
}
if got, want := x.Floor(), tc.floor; got != want {
t.Errorf("tc.x=%v: Floor: got %v, want %v", tc.x, got, want)
}
if got, want := x.Round(), tc.round; got != want {
t.Errorf("tc.x=%v: Round: got %v, want %v", tc.x, got, want)
}
if got, want := x.Ceil(), tc.ceil; got != want {
t.Errorf("tc.x=%v: Ceil: got %v, want %v", tc.x, got, want)
}
if got, want := x.Mul(one), x; got != want {
t.Errorf("tc.x=%v: Mul by one: got %v, want %v", tc.x, got, want)
}
}
}
var mulTestCases = []struct {
x float64
y float64
z26_6 float64 // Equals truncate26_6(x)*truncate26_6(y).
z52_12 float64 // Equals truncate52_12(x)*truncate52_12(y).
s26_6 string
s52_12 string
}{{
x: 0,
y: 1.5,
z26_6: 0,
z52_12: 0,
s26_6: "0:00",
s52_12: "0:0000",
}, {
x: +1.25,
y: +4,
z26_6: +5,
z52_12: +5,
s26_6: "5:00",
s52_12: "5:0000",
}, {
x: +1.25,
y: -4,
z26_6: -5,
z52_12: -5,
s26_6: "-5:00",
s52_12: "-5:0000",
}, {
x: -1.25,
y: +4,
z26_6: -5,
z52_12: -5,
s26_6: "-5:00",
s52_12: "-5:0000",
}, {
x: -1.25,
y: -4,
z26_6: +5,
z52_12: +5,
s26_6: "5:00",
s52_12: "5:0000",
}, {
x: 1.25,
y: 1.5,
z26_6: 1.875,
z52_12: 1.875,
s26_6: "1:56",
s52_12: "1:3584",
}, {
x: 1234.5,
y: -8888.875,
z26_6: -10973316.1875,
z52_12: -10973316.1875,
s26_6: "-10973316:12",
s52_12: "-10973316:0768",
}, {
x: 1.515625, // 1 + 33/64 = 97/64
y: 1.531250, // 1 + 34/64 = 98/64
z26_6: 2.32080078125, // 2 + 1314/4096 = 9506/4096
z52_12: 2.32080078125, // 2 + 1314/4096 = 9506/4096
s26_6: "2:21", // 2.32812500000, which is closer than 2:20 (in decimal, 2.3125)
s52_12: "2:1314", // 2.32080078125
}, {
x: 0.500244140625, // 2049/4096, approximately 32/64
y: 0.500732421875, // 2051/4096, approximately 32/64
z26_6: 0.25, // 4194304/16777216, or 1024/4096
z52_12: 0.2504884600639343, // 4202499/16777216
s26_6: "0:16", // 0.25000000000
s52_12: "0:1026", // 0.25048828125, which is closer than 0:1027 (in decimal, 0.250732421875)
}, {
x: 0.015625, // 1/64
y: 0.000244140625, // 1/4096, approximately 0/64
z26_6: 0.0, // 0
z52_12: 0.000003814697265625, // 1/262144
s26_6: "0:00", // 0
s52_12: "0:0000", // 0, which is closer than 0:0001 (in decimal, 0.000244140625)
}, {
// Round the Int52_12 calculation down.
x: 1.44140625, // 1 + 1808/4096 = 5904/4096, approximately 92/64
y: 1.44140625, // 1 + 1808/4096 = 5904/4096, approximately 92/64
z26_6: 2.06640625, // 2 + 272/4096 = 8464/4096
z52_12: 2.0776519775390625, // 2 + 318/4096 + 256/16777216 = 34857216/16777216
s26_6: "2:04", // 2.06250000000, which is closer than 2:05 (in decimal, 2.078125000000)
s52_12: "2:0318", // 2.07763671875, which is closer than 2:0319 (in decimal, 2.077880859375)
}, {
// Round the Int52_12 calculation up.
x: 1.44140625, // 1 + 1808/4096 = 5904/4096, approximately 92/64
y: 1.441650390625, // 1 + 1809/4096 = 5905/4096, approximately 92/64
z26_6: 2.06640625, // 2 + 272/4096 = 8464/4096
z52_12: 2.0780038833618164, // 2 + 319/4096 + 2064/16777216 = 34863120/16777216
s26_6: "2:04", // 2.06250000000, which is closer than 2:05 (in decimal, 2.078125000000)
s52_12: "2:0320", // 2.07812500000, which is closer than 2:0319 (in decimal, 2.077880859375)
}}
func TestInt26_6Mul(t *testing.T) {
for _, tc := range mulTestCases {
x := Int26_6(tc.x * (1 << 6))
y := Int26_6(tc.y * (1 << 6))
if z := float64(x) * float64(y) / (1 << 12); z != tc.z26_6 {
t.Errorf("tc.x=%v, tc.y=%v: z: got %v, want %v", tc.x, tc.y, z, tc.z26_6)
continue
}
if got, want := x.Mul(y).String(), tc.s26_6; got != want {
t.Errorf("tc.x=%v: Mul: got %q, want %q", tc.x, got, want)
}
}
}
func TestInt52_12Mul(t *testing.T) {
for _, tc := range mulTestCases {
x := Int52_12(tc.x * (1 << 12))
y := Int52_12(tc.y * (1 << 12))
if z := float64(x) * float64(y) / (1 << 24); z != tc.z52_12 {
t.Errorf("tc.x=%v, tc.y=%v: z: got %v, want %v", tc.x, tc.y, z, tc.z52_12)
continue
}
if got, want := x.Mul(y).String(), tc.s52_12; got != want {
t.Errorf("tc.x=%v: Mul: got %q, want %q", tc.x, got, want)
}
}
}
func TestInt26_6MulByOneMinusIota(t *testing.T) {
const (
totalBits = 32
fracBits = 6
oneMinusIota = Int26_6(1<<fracBits) - 1
oneMinusIotaF = float64(oneMinusIota) / (1 << fracBits)
)
for _, neg := range []bool{false, true} {
for i := uint(0); i < totalBits; i++ {
x := Int26_6(1 << i)
if neg {
x = -x
} else if i == totalBits-1 {
// A signed int32 can't represent 1<<31.
continue
}
// want equals x * oneMinusIota, rounded to nearest.
want := Int26_6(0)
if -1<<fracBits < x && x < 1<<fracBits {
// (x * oneMinusIota) isn't exactly representable as an
// Int26_6. Calculate the rounded value using float64 math.
xF := float64(x) / (1 << fracBits)
wantF := xF * oneMinusIotaF * (1 << fracBits)
want = Int26_6(math.Floor(wantF + 0.5))
} else {
// (x * oneMinusIota) is exactly representable.
want = oneMinusIota << (i - fracBits)
if neg {
want = -want
}
}
if got := x.Mul(oneMinusIota); got != want {
t.Errorf("neg=%t, i=%d, x=%v, Mul: got %v, want %v", neg, i, x, got, want)
}
if got := x.mul(oneMinusIota); got != want {
t.Errorf("neg=%t, i=%d, x=%v, mul: got %v, want %v", neg, i, x, got, want)
}
}
}
}
func TestInt52_12MulByOneMinusIota(t *testing.T) {
const (
totalBits = 64
fracBits = 12
oneMinusIota = Int52_12(1<<fracBits) - 1
oneMinusIotaF = float64(oneMinusIota) / (1 << fracBits)
)
for _, neg := range []bool{false, true} {
for i := uint(0); i < totalBits; i++ {
x := Int52_12(1 << i)
if neg {
x = -x
} else if i == totalBits-1 {
// A signed int64 can't represent 1<<63.
continue
}
// want equals x * oneMinusIota, rounded to nearest.
want := Int52_12(0)
if -1<<fracBits < x && x < 1<<fracBits {
// (x * oneMinusIota) isn't exactly representable as an
// Int52_12. Calculate the rounded value using float64 math.
xF := float64(x) / (1 << fracBits)
wantF := xF * oneMinusIotaF * (1 << fracBits)
want = Int52_12(math.Floor(wantF + 0.5))
} else {
// (x * oneMinusIota) is exactly representable.
want = oneMinusIota << (i - fracBits)
if neg {
want = -want
}
}
if got := x.Mul(oneMinusIota); got != want {
t.Errorf("neg=%t, i=%d, x=%v, Mul: got %v, want %v", neg, i, x, got, want)
}
}
}
}
func TestInt26_6MulVsMul(t *testing.T) {
rng := rand.New(rand.NewSource(1))
for i := 0; i < 10000; i++ {
u := Int26_6(rng.Uint32())
v := Int26_6(rng.Uint32())
Mul := u.Mul(v)
mul := u.mul(v)
if Mul != mul {
t.Errorf("u=%#08x, v=%#08x: Mul=%#08x and mul=%#08x differ",
uint32(u), uint32(v), uint32(Mul), uint32(mul))
}
}
}
func TestMuli32(t *testing.T) {
rng := rand.New(rand.NewSource(2))
for i := 0; i < 10000; i++ {
u := int32(rng.Uint32())
v := int32(rng.Uint32())
lo, hi := muli32(u, v)
got := uint64(lo) | uint64(hi)<<32
want := uint64(int64(u) * int64(v))
if got != want {
t.Errorf("u=%#08x, v=%#08x: got %#016x, want %#016x", uint32(u), uint32(v), got, want)
}
}
}
func TestMulu32(t *testing.T) {
rng := rand.New(rand.NewSource(3))
for i := 0; i < 10000; i++ {
u := rng.Uint32()
v := rng.Uint32()
lo, hi := mulu32(u, v)
got := uint64(lo) | uint64(hi)<<32
want := uint64(u) * uint64(v)
if got != want {
t.Errorf("u=%#08x, v=%#08x: got %#016x, want %#016x", u, v, got, want)
}
}
}
// mul (with a lower case 'm') is an alternative implementation of Int26_6.Mul
// (with an upper case 'M'). It has the same structure as the Int52_12.Mul
// implementation, but Int26_6.mul is easier to test since Go has built-in
// 64-bit integers.
func (x Int26_6) mul(y Int26_6) Int26_6 {
const M, N = 26, 6
lo, hi := muli32(int32(x), int32(y))
ret := Int26_6(hi<<M | lo>>N)
ret += Int26_6((lo >> (N - 1)) & 1) // Round to nearest, instead of rounding down.
return ret
}
// muli32 multiplies two int32 values, returning the 64-bit signed integer
// result as two uint32 values.
//
// muli32 isn't used directly by this package, but it has the same structure as
// muli64, and muli32 is easier to test since Go has built-in 64-bit integers.
func muli32(u, v int32) (lo, hi uint32) {
const (
s = 16
mask = 1<<s - 1
)
u1 := uint32(u >> s)
u0 := uint32(u & mask)
v1 := uint32(v >> s)
v0 := uint32(v & mask)
w0 := u0 * v0
t := u1*v0 + w0>>s
w1 := t & mask
w2 := uint32(int32(t) >> s)
w1 += u0 * v1
return uint32(u) * uint32(v), u1*v1 + w2 + uint32(int32(w1)>>s)
}
// mulu32 is like muli32, except that it multiplies unsigned instead of signed
// values.
//
// This implementation comes from $GOROOT/src/runtime/softfloat64.go's mullu
// function, which is in turn adapted from Hacker's Delight.
//
// mulu32 (and its corresponding test, TestMulu32) isn't used directly by this
// package. It is provided in this test file as a reference point to compare
// the muli32 (and TestMuli32) implementations against.
func mulu32(u, v uint32) (lo, hi uint32) {
const (
s = 16
mask = 1<<s - 1
)
u0 := u & mask
u1 := u >> s
v0 := v & mask
v1 := v >> s
w0 := u0 * v0
t := u1*v0 + w0>>s
w1 := t & mask
w2 := t >> s
w1 += u0 * v1
return u * v, u1*v1 + w2 + w1>>s
}
|
fixed | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/math/fixed/fixed.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package fixed implements fixed-point integer types.
package fixed // import "golang.org/x/image/math/fixed"
import (
"fmt"
)
// TODO: implement fmt.Formatter for %f and %g.
// I returns the integer value i as an Int26_6.
//
// For example, passing the integer value 2 yields Int26_6(128).
func I(i int) Int26_6 {
return Int26_6(i << 6)
}
// Int26_6 is a signed 26.6 fixed-point number.
//
// The integer part ranges from -33554432 to 33554431, inclusive. The
// fractional part has 6 bits of precision.
//
// For example, the number one-and-a-quarter is Int26_6(1<<6 + 1<<4).
type Int26_6 int32
// String returns a human-readable representation of a 26.6 fixed-point number.
//
// For example, the number one-and-a-quarter becomes "1:16".
func (x Int26_6) String() string {
const shift, mask = 6, 1<<6 - 1
if x >= 0 {
return fmt.Sprintf("%d:%02d", int32(x>>shift), int32(x&mask))
}
x = -x
if x >= 0 {
return fmt.Sprintf("-%d:%02d", int32(x>>shift), int32(x&mask))
}
return "-33554432:00" // The minimum value is -(1<<25).
}
// Floor returns the greatest integer value less than or equal to x.
//
// Its return type is int, not Int26_6.
func (x Int26_6) Floor() int { return int((x + 0x00) >> 6) }
// Round returns the nearest integer value to x. Ties are rounded up.
//
// Its return type is int, not Int26_6.
func (x Int26_6) Round() int { return int((x + 0x20) >> 6) }
// Ceil returns the least integer value greater than or equal to x.
//
// Its return type is int, not Int26_6.
func (x Int26_6) Ceil() int { return int((x + 0x3f) >> 6) }
// Mul returns x*y in 26.6 fixed-point arithmetic.
func (x Int26_6) Mul(y Int26_6) Int26_6 {
return Int26_6((int64(x)*int64(y) + 1<<5) >> 6)
}
// Int52_12 is a signed 52.12 fixed-point number.
//
// The integer part ranges from -2251799813685248 to 2251799813685247,
// inclusive. The fractional part has 12 bits of precision.
//
// For example, the number one-and-a-quarter is Int52_12(1<<12 + 1<<10).
type Int52_12 int64
// String returns a human-readable representation of a 52.12 fixed-point
// number.
//
// For example, the number one-and-a-quarter becomes "1:1024".
func (x Int52_12) String() string {
const shift, mask = 12, 1<<12 - 1
if x >= 0 {
return fmt.Sprintf("%d:%04d", int64(x>>shift), int64(x&mask))
}
x = -x
if x >= 0 {
return fmt.Sprintf("-%d:%04d", int64(x>>shift), int64(x&mask))
}
return "-2251799813685248:0000" // The minimum value is -(1<<51).
}
// Floor returns the greatest integer value less than or equal to x.
//
// Its return type is int, not Int52_12.
func (x Int52_12) Floor() int { return int((x + 0x000) >> 12) }
// Round returns the nearest integer value to x. Ties are rounded up.
//
// Its return type is int, not Int52_12.
func (x Int52_12) Round() int { return int((x + 0x800) >> 12) }
// Ceil returns the least integer value greater than or equal to x.
//
// Its return type is int, not Int52_12.
func (x Int52_12) Ceil() int { return int((x + 0xfff) >> 12) }
// Mul returns x*y in 52.12 fixed-point arithmetic.
func (x Int52_12) Mul(y Int52_12) Int52_12 {
const M, N = 52, 12
lo, hi := muli64(int64(x), int64(y))
ret := Int52_12(hi<<M | lo>>N)
ret += Int52_12((lo >> (N - 1)) & 1) // Round to nearest, instead of rounding down.
return ret
}
// muli64 multiplies two int64 values, returning the 128-bit signed integer
// result as two uint64 values.
//
// This implementation is similar to $GOROOT/src/runtime/softfloat64.go's mullu
// function, which is in turn adapted from Hacker's Delight.
func muli64(u, v int64) (lo, hi uint64) {
const (
s = 32
mask = 1<<s - 1
)
u1 := uint64(u >> s)
u0 := uint64(u & mask)
v1 := uint64(v >> s)
v0 := uint64(v & mask)
w0 := u0 * v0
t := u1*v0 + w0>>s
w1 := t & mask
w2 := uint64(int64(t) >> s)
w1 += u0 * v1
return uint64(u) * uint64(v), u1*v1 + w2 + uint64(int64(w1)>>s)
}
// P returns the integer values x and y as a Point26_6.
//
// For example, passing the integer values (2, -3) yields Point26_6{128, -192}.
func P(x, y int) Point26_6 {
return Point26_6{Int26_6(x << 6), Int26_6(y << 6)}
}
// Point26_6 is a 26.6 fixed-point coordinate pair.
//
// It is analogous to the image.Point type in the standard library.
type Point26_6 struct {
X, Y Int26_6
}
// Add returns the vector p+q.
func (p Point26_6) Add(q Point26_6) Point26_6 {
return Point26_6{p.X + q.X, p.Y + q.Y}
}
// Sub returns the vector p-q.
func (p Point26_6) Sub(q Point26_6) Point26_6 {
return Point26_6{p.X - q.X, p.Y - q.Y}
}
// Mul returns the vector p*k.
func (p Point26_6) Mul(k Int26_6) Point26_6 {
return Point26_6{p.X * k / 64, p.Y * k / 64}
}
// Div returns the vector p/k.
func (p Point26_6) Div(k Int26_6) Point26_6 {
return Point26_6{p.X * 64 / k, p.Y * 64 / k}
}
// In returns whether p is in r.
func (p Point26_6) In(r Rectangle26_6) bool {
return r.Min.X <= p.X && p.X < r.Max.X && r.Min.Y <= p.Y && p.Y < r.Max.Y
}
// Point52_12 is a 52.12 fixed-point coordinate pair.
//
// It is analogous to the image.Point type in the standard library.
type Point52_12 struct {
X, Y Int52_12
}
// Add returns the vector p+q.
func (p Point52_12) Add(q Point52_12) Point52_12 {
return Point52_12{p.X + q.X, p.Y + q.Y}
}
// Sub returns the vector p-q.
func (p Point52_12) Sub(q Point52_12) Point52_12 {
return Point52_12{p.X - q.X, p.Y - q.Y}
}
// Mul returns the vector p*k.
func (p Point52_12) Mul(k Int52_12) Point52_12 {
return Point52_12{p.X * k / 4096, p.Y * k / 4096}
}
// Div returns the vector p/k.
func (p Point52_12) Div(k Int52_12) Point52_12 {
return Point52_12{p.X * 4096 / k, p.Y * 4096 / k}
}
// In returns whether p is in r.
func (p Point52_12) In(r Rectangle52_12) bool {
return r.Min.X <= p.X && p.X < r.Max.X && r.Min.Y <= p.Y && p.Y < r.Max.Y
}
// R returns the integer values minX, minY, maxX, maxY as a Rectangle26_6.
//
// For example, passing the integer values (0, 1, 2, 3) yields
// Rectangle26_6{Point26_6{0, 64}, Point26_6{128, 192}}.
//
// Like the image.Rect function in the standard library, the returned rectangle
// has minimum and maximum coordinates swapped if necessary so that it is
// well-formed.
func R(minX, minY, maxX, maxY int) Rectangle26_6 {
if minX > maxX {
minX, maxX = maxX, minX
}
if minY > maxY {
minY, maxY = maxY, minY
}
return Rectangle26_6{
Point26_6{
Int26_6(minX << 6),
Int26_6(minY << 6),
},
Point26_6{
Int26_6(maxX << 6),
Int26_6(maxY << 6),
},
}
}
// Rectangle26_6 is a 26.6 fixed-point coordinate rectangle. The Min bound is
// inclusive and the Max bound is exclusive. It is well-formed if Min.X <=
// Max.X and likewise for Y.
//
// It is analogous to the image.Rectangle type in the standard library.
type Rectangle26_6 struct {
Min, Max Point26_6
}
// Add returns the rectangle r translated by p.
func (r Rectangle26_6) Add(p Point26_6) Rectangle26_6 {
return Rectangle26_6{
Point26_6{r.Min.X + p.X, r.Min.Y + p.Y},
Point26_6{r.Max.X + p.X, r.Max.Y + p.Y},
}
}
// Sub returns the rectangle r translated by -p.
func (r Rectangle26_6) Sub(p Point26_6) Rectangle26_6 {
return Rectangle26_6{
Point26_6{r.Min.X - p.X, r.Min.Y - p.Y},
Point26_6{r.Max.X - p.X, r.Max.Y - p.Y},
}
}
// Intersect returns the largest rectangle contained by both r and s. If the
// two rectangles do not overlap then the zero rectangle will be returned.
func (r Rectangle26_6) Intersect(s Rectangle26_6) Rectangle26_6 {
if r.Min.X < s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y < s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X > s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y > s.Max.Y {
r.Max.Y = s.Max.Y
}
// Letting r0 and s0 be the values of r and s at the time that the method
// is called, this next line is equivalent to:
//
// if max(r0.Min.X, s0.Min.X) >= min(r0.Max.X, s0.Max.X) || likewiseForY { etc }
if r.Empty() {
return Rectangle26_6{}
}
return r
}
// Union returns the smallest rectangle that contains both r and s.
func (r Rectangle26_6) Union(s Rectangle26_6) Rectangle26_6 {
if r.Empty() {
return s
}
if s.Empty() {
return r
}
if r.Min.X > s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y > s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X < s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y < s.Max.Y {
r.Max.Y = s.Max.Y
}
return r
}
// Empty returns whether the rectangle contains no points.
func (r Rectangle26_6) Empty() bool {
return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y
}
// In returns whether every point in r is in s.
func (r Rectangle26_6) In(s Rectangle26_6) bool {
if r.Empty() {
return true
}
// Note that r.Max is an exclusive bound for r, so that r.In(s)
// does not require that r.Max.In(s).
return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X &&
s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y
}
// Rectangle52_12 is a 52.12 fixed-point coordinate rectangle. The Min bound is
// inclusive and the Max bound is exclusive. It is well-formed if Min.X <=
// Max.X and likewise for Y.
//
// It is analogous to the image.Rectangle type in the standard library.
type Rectangle52_12 struct {
Min, Max Point52_12
}
// Add returns the rectangle r translated by p.
func (r Rectangle52_12) Add(p Point52_12) Rectangle52_12 {
return Rectangle52_12{
Point52_12{r.Min.X + p.X, r.Min.Y + p.Y},
Point52_12{r.Max.X + p.X, r.Max.Y + p.Y},
}
}
// Sub returns the rectangle r translated by -p.
func (r Rectangle52_12) Sub(p Point52_12) Rectangle52_12 {
return Rectangle52_12{
Point52_12{r.Min.X - p.X, r.Min.Y - p.Y},
Point52_12{r.Max.X - p.X, r.Max.Y - p.Y},
}
}
// Intersect returns the largest rectangle contained by both r and s. If the
// two rectangles do not overlap then the zero rectangle will be returned.
func (r Rectangle52_12) Intersect(s Rectangle52_12) Rectangle52_12 {
if r.Min.X < s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y < s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X > s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y > s.Max.Y {
r.Max.Y = s.Max.Y
}
// Letting r0 and s0 be the values of r and s at the time that the method
// is called, this next line is equivalent to:
//
// if max(r0.Min.X, s0.Min.X) >= min(r0.Max.X, s0.Max.X) || likewiseForY { etc }
if r.Empty() {
return Rectangle52_12{}
}
return r
}
// Union returns the smallest rectangle that contains both r and s.
func (r Rectangle52_12) Union(s Rectangle52_12) Rectangle52_12 {
if r.Empty() {
return s
}
if s.Empty() {
return r
}
if r.Min.X > s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y > s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X < s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y < s.Max.Y {
r.Max.Y = s.Max.Y
}
return r
}
// Empty returns whether the rectangle contains no points.
func (r Rectangle52_12) Empty() bool {
return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y
}
// In returns whether every point in r is in s.
func (r Rectangle52_12) In(s Rectangle52_12) bool {
if r.Empty() {
return true
}
// Note that r.Max is an exclusive bound for r, so that r.In(s)
// does not require that r.Max.In(s).
return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X &&
s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y
}
|
f64 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/math/f64/f64.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package f64 implements float64 vector and matrix types.
package f64 // import "golang.org/x/image/math/f64"
// Vec2 is a 2-element vector.
type Vec2 [2]float64
// Vec3 is a 3-element vector.
type Vec3 [3]float64
// Vec4 is a 4-element vector.
type Vec4 [4]float64
// Mat3 is a 3x3 matrix in row major order.
//
// m[3*r + c] is the element in the r'th row and c'th column.
type Mat3 [9]float64
// Mat4 is a 4x4 matrix in row major order.
//
// m[4*r + c] is the element in the r'th row and c'th column.
type Mat4 [16]float64
// Aff3 is a 3x3 affine transformation matrix in row major order, where the
// bottom row is implicitly [0 0 1].
//
// m[3*r + c] is the element in the r'th row and c'th column.
type Aff3 [6]float64
// Aff4 is a 4x4 affine transformation matrix in row major order, where the
// bottom row is implicitly [0 0 0 1].
//
// m[4*r + c] is the element in the r'th row and c'th column.
type Aff4 [12]float64
|
colornames | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/colornames/colornames.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run gen.go
// Package colornames provides named colors as defined in the SVG 1.1 spec.
//
// See http://www.w3.org/TR/SVG/types.html#ColorKeywords
package colornames
|
colornames | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/colornames/colornames_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colornames
import (
"image/color"
"testing"
)
func TestColornames(t *testing.T) {
if len(Map) != len(Names) {
t.Fatalf("Map and Names have different length: %d vs %d", len(Map), len(Names))
}
for name, want := range testCases {
got, ok := Map[name]
if !ok {
t.Errorf("Did not find %s", name)
continue
}
if got != want {
t.Errorf("%s:\ngot %v\nwant %v", name, got, want)
}
}
}
var testCases = map[string]color.RGBA{
"aliceblue": color.RGBA{240, 248, 255, 255},
"crimson": color.RGBA{220, 20, 60, 255},
"darkorange": color.RGBA{255, 140, 0, 255},
"deepskyblue": color.RGBA{0, 191, 255, 255},
"greenyellow": color.RGBA{173, 255, 47, 255},
"lightgrey": color.RGBA{211, 211, 211, 255},
"lightpink": color.RGBA{255, 182, 193, 255},
"mediumseagreen": color.RGBA{60, 179, 113, 255},
"olivedrab": color.RGBA{107, 142, 35, 255},
"purple": color.RGBA{128, 0, 128, 255},
"slategrey": color.RGBA{112, 128, 144, 255},
"yellowgreen": color.RGBA{154, 205, 50, 255},
}
|
colornames | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/colornames/table.go | // generated by go generate; DO NOT EDIT.
package colornames
import "image/color"
// Map contains named colors defined in the SVG 1.1 spec.
var Map = map[string]color.RGBA{
"aliceblue": color.RGBA{0xf0, 0xf8, 0xff, 0xff}, // rgb(240, 248, 255)
"antiquewhite": color.RGBA{0xfa, 0xeb, 0xd7, 0xff}, // rgb(250, 235, 215)
"aqua": color.RGBA{0x00, 0xff, 0xff, 0xff}, // rgb(0, 255, 255)
"aquamarine": color.RGBA{0x7f, 0xff, 0xd4, 0xff}, // rgb(127, 255, 212)
"azure": color.RGBA{0xf0, 0xff, 0xff, 0xff}, // rgb(240, 255, 255)
"beige": color.RGBA{0xf5, 0xf5, 0xdc, 0xff}, // rgb(245, 245, 220)
"bisque": color.RGBA{0xff, 0xe4, 0xc4, 0xff}, // rgb(255, 228, 196)
"black": color.RGBA{0x00, 0x00, 0x00, 0xff}, // rgb(0, 0, 0)
"blanchedalmond": color.RGBA{0xff, 0xeb, 0xcd, 0xff}, // rgb(255, 235, 205)
"blue": color.RGBA{0x00, 0x00, 0xff, 0xff}, // rgb(0, 0, 255)
"blueviolet": color.RGBA{0x8a, 0x2b, 0xe2, 0xff}, // rgb(138, 43, 226)
"brown": color.RGBA{0xa5, 0x2a, 0x2a, 0xff}, // rgb(165, 42, 42)
"burlywood": color.RGBA{0xde, 0xb8, 0x87, 0xff}, // rgb(222, 184, 135)
"cadetblue": color.RGBA{0x5f, 0x9e, 0xa0, 0xff}, // rgb(95, 158, 160)
"chartreuse": color.RGBA{0x7f, 0xff, 0x00, 0xff}, // rgb(127, 255, 0)
"chocolate": color.RGBA{0xd2, 0x69, 0x1e, 0xff}, // rgb(210, 105, 30)
"coral": color.RGBA{0xff, 0x7f, 0x50, 0xff}, // rgb(255, 127, 80)
"cornflowerblue": color.RGBA{0x64, 0x95, 0xed, 0xff}, // rgb(100, 149, 237)
"cornsilk": color.RGBA{0xff, 0xf8, 0xdc, 0xff}, // rgb(255, 248, 220)
"crimson": color.RGBA{0xdc, 0x14, 0x3c, 0xff}, // rgb(220, 20, 60)
"cyan": color.RGBA{0x00, 0xff, 0xff, 0xff}, // rgb(0, 255, 255)
"darkblue": color.RGBA{0x00, 0x00, 0x8b, 0xff}, // rgb(0, 0, 139)
"darkcyan": color.RGBA{0x00, 0x8b, 0x8b, 0xff}, // rgb(0, 139, 139)
"darkgoldenrod": color.RGBA{0xb8, 0x86, 0x0b, 0xff}, // rgb(184, 134, 11)
"darkgray": color.RGBA{0xa9, 0xa9, 0xa9, 0xff}, // rgb(169, 169, 169)
"darkgreen": color.RGBA{0x00, 0x64, 0x00, 0xff}, // rgb(0, 100, 0)
"darkgrey": color.RGBA{0xa9, 0xa9, 0xa9, 0xff}, // rgb(169, 169, 169)
"darkkhaki": color.RGBA{0xbd, 0xb7, 0x6b, 0xff}, // rgb(189, 183, 107)
"darkmagenta": color.RGBA{0x8b, 0x00, 0x8b, 0xff}, // rgb(139, 0, 139)
"darkolivegreen": color.RGBA{0x55, 0x6b, 0x2f, 0xff}, // rgb(85, 107, 47)
"darkorange": color.RGBA{0xff, 0x8c, 0x00, 0xff}, // rgb(255, 140, 0)
"darkorchid": color.RGBA{0x99, 0x32, 0xcc, 0xff}, // rgb(153, 50, 204)
"darkred": color.RGBA{0x8b, 0x00, 0x00, 0xff}, // rgb(139, 0, 0)
"darksalmon": color.RGBA{0xe9, 0x96, 0x7a, 0xff}, // rgb(233, 150, 122)
"darkseagreen": color.RGBA{0x8f, 0xbc, 0x8f, 0xff}, // rgb(143, 188, 143)
"darkslateblue": color.RGBA{0x48, 0x3d, 0x8b, 0xff}, // rgb(72, 61, 139)
"darkslategray": color.RGBA{0x2f, 0x4f, 0x4f, 0xff}, // rgb(47, 79, 79)
"darkslategrey": color.RGBA{0x2f, 0x4f, 0x4f, 0xff}, // rgb(47, 79, 79)
"darkturquoise": color.RGBA{0x00, 0xce, 0xd1, 0xff}, // rgb(0, 206, 209)
"darkviolet": color.RGBA{0x94, 0x00, 0xd3, 0xff}, // rgb(148, 0, 211)
"deeppink": color.RGBA{0xff, 0x14, 0x93, 0xff}, // rgb(255, 20, 147)
"deepskyblue": color.RGBA{0x00, 0xbf, 0xff, 0xff}, // rgb(0, 191, 255)
"dimgray": color.RGBA{0x69, 0x69, 0x69, 0xff}, // rgb(105, 105, 105)
"dimgrey": color.RGBA{0x69, 0x69, 0x69, 0xff}, // rgb(105, 105, 105)
"dodgerblue": color.RGBA{0x1e, 0x90, 0xff, 0xff}, // rgb(30, 144, 255)
"firebrick": color.RGBA{0xb2, 0x22, 0x22, 0xff}, // rgb(178, 34, 34)
"floralwhite": color.RGBA{0xff, 0xfa, 0xf0, 0xff}, // rgb(255, 250, 240)
"forestgreen": color.RGBA{0x22, 0x8b, 0x22, 0xff}, // rgb(34, 139, 34)
"fuchsia": color.RGBA{0xff, 0x00, 0xff, 0xff}, // rgb(255, 0, 255)
"gainsboro": color.RGBA{0xdc, 0xdc, 0xdc, 0xff}, // rgb(220, 220, 220)
"ghostwhite": color.RGBA{0xf8, 0xf8, 0xff, 0xff}, // rgb(248, 248, 255)
"gold": color.RGBA{0xff, 0xd7, 0x00, 0xff}, // rgb(255, 215, 0)
"goldenrod": color.RGBA{0xda, 0xa5, 0x20, 0xff}, // rgb(218, 165, 32)
"gray": color.RGBA{0x80, 0x80, 0x80, 0xff}, // rgb(128, 128, 128)
"green": color.RGBA{0x00, 0x80, 0x00, 0xff}, // rgb(0, 128, 0)
"greenyellow": color.RGBA{0xad, 0xff, 0x2f, 0xff}, // rgb(173, 255, 47)
"grey": color.RGBA{0x80, 0x80, 0x80, 0xff}, // rgb(128, 128, 128)
"honeydew": color.RGBA{0xf0, 0xff, 0xf0, 0xff}, // rgb(240, 255, 240)
"hotpink": color.RGBA{0xff, 0x69, 0xb4, 0xff}, // rgb(255, 105, 180)
"indianred": color.RGBA{0xcd, 0x5c, 0x5c, 0xff}, // rgb(205, 92, 92)
"indigo": color.RGBA{0x4b, 0x00, 0x82, 0xff}, // rgb(75, 0, 130)
"ivory": color.RGBA{0xff, 0xff, 0xf0, 0xff}, // rgb(255, 255, 240)
"khaki": color.RGBA{0xf0, 0xe6, 0x8c, 0xff}, // rgb(240, 230, 140)
"lavender": color.RGBA{0xe6, 0xe6, 0xfa, 0xff}, // rgb(230, 230, 250)
"lavenderblush": color.RGBA{0xff, 0xf0, 0xf5, 0xff}, // rgb(255, 240, 245)
"lawngreen": color.RGBA{0x7c, 0xfc, 0x00, 0xff}, // rgb(124, 252, 0)
"lemonchiffon": color.RGBA{0xff, 0xfa, 0xcd, 0xff}, // rgb(255, 250, 205)
"lightblue": color.RGBA{0xad, 0xd8, 0xe6, 0xff}, // rgb(173, 216, 230)
"lightcoral": color.RGBA{0xf0, 0x80, 0x80, 0xff}, // rgb(240, 128, 128)
"lightcyan": color.RGBA{0xe0, 0xff, 0xff, 0xff}, // rgb(224, 255, 255)
"lightgoldenrodyellow": color.RGBA{0xfa, 0xfa, 0xd2, 0xff}, // rgb(250, 250, 210)
"lightgray": color.RGBA{0xd3, 0xd3, 0xd3, 0xff}, // rgb(211, 211, 211)
"lightgreen": color.RGBA{0x90, 0xee, 0x90, 0xff}, // rgb(144, 238, 144)
"lightgrey": color.RGBA{0xd3, 0xd3, 0xd3, 0xff}, // rgb(211, 211, 211)
"lightpink": color.RGBA{0xff, 0xb6, 0xc1, 0xff}, // rgb(255, 182, 193)
"lightsalmon": color.RGBA{0xff, 0xa0, 0x7a, 0xff}, // rgb(255, 160, 122)
"lightseagreen": color.RGBA{0x20, 0xb2, 0xaa, 0xff}, // rgb(32, 178, 170)
"lightskyblue": color.RGBA{0x87, 0xce, 0xfa, 0xff}, // rgb(135, 206, 250)
"lightslategray": color.RGBA{0x77, 0x88, 0x99, 0xff}, // rgb(119, 136, 153)
"lightslategrey": color.RGBA{0x77, 0x88, 0x99, 0xff}, // rgb(119, 136, 153)
"lightsteelblue": color.RGBA{0xb0, 0xc4, 0xde, 0xff}, // rgb(176, 196, 222)
"lightyellow": color.RGBA{0xff, 0xff, 0xe0, 0xff}, // rgb(255, 255, 224)
"lime": color.RGBA{0x00, 0xff, 0x00, 0xff}, // rgb(0, 255, 0)
"limegreen": color.RGBA{0x32, 0xcd, 0x32, 0xff}, // rgb(50, 205, 50)
"linen": color.RGBA{0xfa, 0xf0, 0xe6, 0xff}, // rgb(250, 240, 230)
"magenta": color.RGBA{0xff, 0x00, 0xff, 0xff}, // rgb(255, 0, 255)
"maroon": color.RGBA{0x80, 0x00, 0x00, 0xff}, // rgb(128, 0, 0)
"mediumaquamarine": color.RGBA{0x66, 0xcd, 0xaa, 0xff}, // rgb(102, 205, 170)
"mediumblue": color.RGBA{0x00, 0x00, 0xcd, 0xff}, // rgb(0, 0, 205)
"mediumorchid": color.RGBA{0xba, 0x55, 0xd3, 0xff}, // rgb(186, 85, 211)
"mediumpurple": color.RGBA{0x93, 0x70, 0xdb, 0xff}, // rgb(147, 112, 219)
"mediumseagreen": color.RGBA{0x3c, 0xb3, 0x71, 0xff}, // rgb(60, 179, 113)
"mediumslateblue": color.RGBA{0x7b, 0x68, 0xee, 0xff}, // rgb(123, 104, 238)
"mediumspringgreen": color.RGBA{0x00, 0xfa, 0x9a, 0xff}, // rgb(0, 250, 154)
"mediumturquoise": color.RGBA{0x48, 0xd1, 0xcc, 0xff}, // rgb(72, 209, 204)
"mediumvioletred": color.RGBA{0xc7, 0x15, 0x85, 0xff}, // rgb(199, 21, 133)
"midnightblue": color.RGBA{0x19, 0x19, 0x70, 0xff}, // rgb(25, 25, 112)
"mintcream": color.RGBA{0xf5, 0xff, 0xfa, 0xff}, // rgb(245, 255, 250)
"mistyrose": color.RGBA{0xff, 0xe4, 0xe1, 0xff}, // rgb(255, 228, 225)
"moccasin": color.RGBA{0xff, 0xe4, 0xb5, 0xff}, // rgb(255, 228, 181)
"navajowhite": color.RGBA{0xff, 0xde, 0xad, 0xff}, // rgb(255, 222, 173)
"navy": color.RGBA{0x00, 0x00, 0x80, 0xff}, // rgb(0, 0, 128)
"oldlace": color.RGBA{0xfd, 0xf5, 0xe6, 0xff}, // rgb(253, 245, 230)
"olive": color.RGBA{0x80, 0x80, 0x00, 0xff}, // rgb(128, 128, 0)
"olivedrab": color.RGBA{0x6b, 0x8e, 0x23, 0xff}, // rgb(107, 142, 35)
"orange": color.RGBA{0xff, 0xa5, 0x00, 0xff}, // rgb(255, 165, 0)
"orangered": color.RGBA{0xff, 0x45, 0x00, 0xff}, // rgb(255, 69, 0)
"orchid": color.RGBA{0xda, 0x70, 0xd6, 0xff}, // rgb(218, 112, 214)
"palegoldenrod": color.RGBA{0xee, 0xe8, 0xaa, 0xff}, // rgb(238, 232, 170)
"palegreen": color.RGBA{0x98, 0xfb, 0x98, 0xff}, // rgb(152, 251, 152)
"paleturquoise": color.RGBA{0xaf, 0xee, 0xee, 0xff}, // rgb(175, 238, 238)
"palevioletred": color.RGBA{0xdb, 0x70, 0x93, 0xff}, // rgb(219, 112, 147)
"papayawhip": color.RGBA{0xff, 0xef, 0xd5, 0xff}, // rgb(255, 239, 213)
"peachpuff": color.RGBA{0xff, 0xda, 0xb9, 0xff}, // rgb(255, 218, 185)
"peru": color.RGBA{0xcd, 0x85, 0x3f, 0xff}, // rgb(205, 133, 63)
"pink": color.RGBA{0xff, 0xc0, 0xcb, 0xff}, // rgb(255, 192, 203)
"plum": color.RGBA{0xdd, 0xa0, 0xdd, 0xff}, // rgb(221, 160, 221)
"powderblue": color.RGBA{0xb0, 0xe0, 0xe6, 0xff}, // rgb(176, 224, 230)
"purple": color.RGBA{0x80, 0x00, 0x80, 0xff}, // rgb(128, 0, 128)
"red": color.RGBA{0xff, 0x00, 0x00, 0xff}, // rgb(255, 0, 0)
"rosybrown": color.RGBA{0xbc, 0x8f, 0x8f, 0xff}, // rgb(188, 143, 143)
"royalblue": color.RGBA{0x41, 0x69, 0xe1, 0xff}, // rgb(65, 105, 225)
"saddlebrown": color.RGBA{0x8b, 0x45, 0x13, 0xff}, // rgb(139, 69, 19)
"salmon": color.RGBA{0xfa, 0x80, 0x72, 0xff}, // rgb(250, 128, 114)
"sandybrown": color.RGBA{0xf4, 0xa4, 0x60, 0xff}, // rgb(244, 164, 96)
"seagreen": color.RGBA{0x2e, 0x8b, 0x57, 0xff}, // rgb(46, 139, 87)
"seashell": color.RGBA{0xff, 0xf5, 0xee, 0xff}, // rgb(255, 245, 238)
"sienna": color.RGBA{0xa0, 0x52, 0x2d, 0xff}, // rgb(160, 82, 45)
"silver": color.RGBA{0xc0, 0xc0, 0xc0, 0xff}, // rgb(192, 192, 192)
"skyblue": color.RGBA{0x87, 0xce, 0xeb, 0xff}, // rgb(135, 206, 235)
"slateblue": color.RGBA{0x6a, 0x5a, 0xcd, 0xff}, // rgb(106, 90, 205)
"slategray": color.RGBA{0x70, 0x80, 0x90, 0xff}, // rgb(112, 128, 144)
"slategrey": color.RGBA{0x70, 0x80, 0x90, 0xff}, // rgb(112, 128, 144)
"snow": color.RGBA{0xff, 0xfa, 0xfa, 0xff}, // rgb(255, 250, 250)
"springgreen": color.RGBA{0x00, 0xff, 0x7f, 0xff}, // rgb(0, 255, 127)
"steelblue": color.RGBA{0x46, 0x82, 0xb4, 0xff}, // rgb(70, 130, 180)
"tan": color.RGBA{0xd2, 0xb4, 0x8c, 0xff}, // rgb(210, 180, 140)
"teal": color.RGBA{0x00, 0x80, 0x80, 0xff}, // rgb(0, 128, 128)
"thistle": color.RGBA{0xd8, 0xbf, 0xd8, 0xff}, // rgb(216, 191, 216)
"tomato": color.RGBA{0xff, 0x63, 0x47, 0xff}, // rgb(255, 99, 71)
"turquoise": color.RGBA{0x40, 0xe0, 0xd0, 0xff}, // rgb(64, 224, 208)
"violet": color.RGBA{0xee, 0x82, 0xee, 0xff}, // rgb(238, 130, 238)
"wheat": color.RGBA{0xf5, 0xde, 0xb3, 0xff}, // rgb(245, 222, 179)
"white": color.RGBA{0xff, 0xff, 0xff, 0xff}, // rgb(255, 255, 255)
"whitesmoke": color.RGBA{0xf5, 0xf5, 0xf5, 0xff}, // rgb(245, 245, 245)
"yellow": color.RGBA{0xff, 0xff, 0x00, 0xff}, // rgb(255, 255, 0)
"yellowgreen": color.RGBA{0x9a, 0xcd, 0x32, 0xff}, // rgb(154, 205, 50)
}
// Names contains the color names defined in the SVG 1.1 spec.
var Names = []string{
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen",
}
var (
Aliceblue = color.RGBA{0xf0, 0xf8, 0xff, 0xff} // rgb(240, 248, 255)
Antiquewhite = color.RGBA{0xfa, 0xeb, 0xd7, 0xff} // rgb(250, 235, 215)
Aqua = color.RGBA{0x00, 0xff, 0xff, 0xff} // rgb(0, 255, 255)
Aquamarine = color.RGBA{0x7f, 0xff, 0xd4, 0xff} // rgb(127, 255, 212)
Azure = color.RGBA{0xf0, 0xff, 0xff, 0xff} // rgb(240, 255, 255)
Beige = color.RGBA{0xf5, 0xf5, 0xdc, 0xff} // rgb(245, 245, 220)
Bisque = color.RGBA{0xff, 0xe4, 0xc4, 0xff} // rgb(255, 228, 196)
Black = color.RGBA{0x00, 0x00, 0x00, 0xff} // rgb(0, 0, 0)
Blanchedalmond = color.RGBA{0xff, 0xeb, 0xcd, 0xff} // rgb(255, 235, 205)
Blue = color.RGBA{0x00, 0x00, 0xff, 0xff} // rgb(0, 0, 255)
Blueviolet = color.RGBA{0x8a, 0x2b, 0xe2, 0xff} // rgb(138, 43, 226)
Brown = color.RGBA{0xa5, 0x2a, 0x2a, 0xff} // rgb(165, 42, 42)
Burlywood = color.RGBA{0xde, 0xb8, 0x87, 0xff} // rgb(222, 184, 135)
Cadetblue = color.RGBA{0x5f, 0x9e, 0xa0, 0xff} // rgb(95, 158, 160)
Chartreuse = color.RGBA{0x7f, 0xff, 0x00, 0xff} // rgb(127, 255, 0)
Chocolate = color.RGBA{0xd2, 0x69, 0x1e, 0xff} // rgb(210, 105, 30)
Coral = color.RGBA{0xff, 0x7f, 0x50, 0xff} // rgb(255, 127, 80)
Cornflowerblue = color.RGBA{0x64, 0x95, 0xed, 0xff} // rgb(100, 149, 237)
Cornsilk = color.RGBA{0xff, 0xf8, 0xdc, 0xff} // rgb(255, 248, 220)
Crimson = color.RGBA{0xdc, 0x14, 0x3c, 0xff} // rgb(220, 20, 60)
Cyan = color.RGBA{0x00, 0xff, 0xff, 0xff} // rgb(0, 255, 255)
Darkblue = color.RGBA{0x00, 0x00, 0x8b, 0xff} // rgb(0, 0, 139)
Darkcyan = color.RGBA{0x00, 0x8b, 0x8b, 0xff} // rgb(0, 139, 139)
Darkgoldenrod = color.RGBA{0xb8, 0x86, 0x0b, 0xff} // rgb(184, 134, 11)
Darkgray = color.RGBA{0xa9, 0xa9, 0xa9, 0xff} // rgb(169, 169, 169)
Darkgreen = color.RGBA{0x00, 0x64, 0x00, 0xff} // rgb(0, 100, 0)
Darkgrey = color.RGBA{0xa9, 0xa9, 0xa9, 0xff} // rgb(169, 169, 169)
Darkkhaki = color.RGBA{0xbd, 0xb7, 0x6b, 0xff} // rgb(189, 183, 107)
Darkmagenta = color.RGBA{0x8b, 0x00, 0x8b, 0xff} // rgb(139, 0, 139)
Darkolivegreen = color.RGBA{0x55, 0x6b, 0x2f, 0xff} // rgb(85, 107, 47)
Darkorange = color.RGBA{0xff, 0x8c, 0x00, 0xff} // rgb(255, 140, 0)
Darkorchid = color.RGBA{0x99, 0x32, 0xcc, 0xff} // rgb(153, 50, 204)
Darkred = color.RGBA{0x8b, 0x00, 0x00, 0xff} // rgb(139, 0, 0)
Darksalmon = color.RGBA{0xe9, 0x96, 0x7a, 0xff} // rgb(233, 150, 122)
Darkseagreen = color.RGBA{0x8f, 0xbc, 0x8f, 0xff} // rgb(143, 188, 143)
Darkslateblue = color.RGBA{0x48, 0x3d, 0x8b, 0xff} // rgb(72, 61, 139)
Darkslategray = color.RGBA{0x2f, 0x4f, 0x4f, 0xff} // rgb(47, 79, 79)
Darkslategrey = color.RGBA{0x2f, 0x4f, 0x4f, 0xff} // rgb(47, 79, 79)
Darkturquoise = color.RGBA{0x00, 0xce, 0xd1, 0xff} // rgb(0, 206, 209)
Darkviolet = color.RGBA{0x94, 0x00, 0xd3, 0xff} // rgb(148, 0, 211)
Deeppink = color.RGBA{0xff, 0x14, 0x93, 0xff} // rgb(255, 20, 147)
Deepskyblue = color.RGBA{0x00, 0xbf, 0xff, 0xff} // rgb(0, 191, 255)
Dimgray = color.RGBA{0x69, 0x69, 0x69, 0xff} // rgb(105, 105, 105)
Dimgrey = color.RGBA{0x69, 0x69, 0x69, 0xff} // rgb(105, 105, 105)
Dodgerblue = color.RGBA{0x1e, 0x90, 0xff, 0xff} // rgb(30, 144, 255)
Firebrick = color.RGBA{0xb2, 0x22, 0x22, 0xff} // rgb(178, 34, 34)
Floralwhite = color.RGBA{0xff, 0xfa, 0xf0, 0xff} // rgb(255, 250, 240)
Forestgreen = color.RGBA{0x22, 0x8b, 0x22, 0xff} // rgb(34, 139, 34)
Fuchsia = color.RGBA{0xff, 0x00, 0xff, 0xff} // rgb(255, 0, 255)
Gainsboro = color.RGBA{0xdc, 0xdc, 0xdc, 0xff} // rgb(220, 220, 220)
Ghostwhite = color.RGBA{0xf8, 0xf8, 0xff, 0xff} // rgb(248, 248, 255)
Gold = color.RGBA{0xff, 0xd7, 0x00, 0xff} // rgb(255, 215, 0)
Goldenrod = color.RGBA{0xda, 0xa5, 0x20, 0xff} // rgb(218, 165, 32)
Gray = color.RGBA{0x80, 0x80, 0x80, 0xff} // rgb(128, 128, 128)
Green = color.RGBA{0x00, 0x80, 0x00, 0xff} // rgb(0, 128, 0)
Greenyellow = color.RGBA{0xad, 0xff, 0x2f, 0xff} // rgb(173, 255, 47)
Grey = color.RGBA{0x80, 0x80, 0x80, 0xff} // rgb(128, 128, 128)
Honeydew = color.RGBA{0xf0, 0xff, 0xf0, 0xff} // rgb(240, 255, 240)
Hotpink = color.RGBA{0xff, 0x69, 0xb4, 0xff} // rgb(255, 105, 180)
Indianred = color.RGBA{0xcd, 0x5c, 0x5c, 0xff} // rgb(205, 92, 92)
Indigo = color.RGBA{0x4b, 0x00, 0x82, 0xff} // rgb(75, 0, 130)
Ivory = color.RGBA{0xff, 0xff, 0xf0, 0xff} // rgb(255, 255, 240)
Khaki = color.RGBA{0xf0, 0xe6, 0x8c, 0xff} // rgb(240, 230, 140)
Lavender = color.RGBA{0xe6, 0xe6, 0xfa, 0xff} // rgb(230, 230, 250)
Lavenderblush = color.RGBA{0xff, 0xf0, 0xf5, 0xff} // rgb(255, 240, 245)
Lawngreen = color.RGBA{0x7c, 0xfc, 0x00, 0xff} // rgb(124, 252, 0)
Lemonchiffon = color.RGBA{0xff, 0xfa, 0xcd, 0xff} // rgb(255, 250, 205)
Lightblue = color.RGBA{0xad, 0xd8, 0xe6, 0xff} // rgb(173, 216, 230)
Lightcoral = color.RGBA{0xf0, 0x80, 0x80, 0xff} // rgb(240, 128, 128)
Lightcyan = color.RGBA{0xe0, 0xff, 0xff, 0xff} // rgb(224, 255, 255)
Lightgoldenrodyellow = color.RGBA{0xfa, 0xfa, 0xd2, 0xff} // rgb(250, 250, 210)
Lightgray = color.RGBA{0xd3, 0xd3, 0xd3, 0xff} // rgb(211, 211, 211)
Lightgreen = color.RGBA{0x90, 0xee, 0x90, 0xff} // rgb(144, 238, 144)
Lightgrey = color.RGBA{0xd3, 0xd3, 0xd3, 0xff} // rgb(211, 211, 211)
Lightpink = color.RGBA{0xff, 0xb6, 0xc1, 0xff} // rgb(255, 182, 193)
Lightsalmon = color.RGBA{0xff, 0xa0, 0x7a, 0xff} // rgb(255, 160, 122)
Lightseagreen = color.RGBA{0x20, 0xb2, 0xaa, 0xff} // rgb(32, 178, 170)
Lightskyblue = color.RGBA{0x87, 0xce, 0xfa, 0xff} // rgb(135, 206, 250)
Lightslategray = color.RGBA{0x77, 0x88, 0x99, 0xff} // rgb(119, 136, 153)
Lightslategrey = color.RGBA{0x77, 0x88, 0x99, 0xff} // rgb(119, 136, 153)
Lightsteelblue = color.RGBA{0xb0, 0xc4, 0xde, 0xff} // rgb(176, 196, 222)
Lightyellow = color.RGBA{0xff, 0xff, 0xe0, 0xff} // rgb(255, 255, 224)
Lime = color.RGBA{0x00, 0xff, 0x00, 0xff} // rgb(0, 255, 0)
Limegreen = color.RGBA{0x32, 0xcd, 0x32, 0xff} // rgb(50, 205, 50)
Linen = color.RGBA{0xfa, 0xf0, 0xe6, 0xff} // rgb(250, 240, 230)
Magenta = color.RGBA{0xff, 0x00, 0xff, 0xff} // rgb(255, 0, 255)
Maroon = color.RGBA{0x80, 0x00, 0x00, 0xff} // rgb(128, 0, 0)
Mediumaquamarine = color.RGBA{0x66, 0xcd, 0xaa, 0xff} // rgb(102, 205, 170)
Mediumblue = color.RGBA{0x00, 0x00, 0xcd, 0xff} // rgb(0, 0, 205)
Mediumorchid = color.RGBA{0xba, 0x55, 0xd3, 0xff} // rgb(186, 85, 211)
Mediumpurple = color.RGBA{0x93, 0x70, 0xdb, 0xff} // rgb(147, 112, 219)
Mediumseagreen = color.RGBA{0x3c, 0xb3, 0x71, 0xff} // rgb(60, 179, 113)
Mediumslateblue = color.RGBA{0x7b, 0x68, 0xee, 0xff} // rgb(123, 104, 238)
Mediumspringgreen = color.RGBA{0x00, 0xfa, 0x9a, 0xff} // rgb(0, 250, 154)
Mediumturquoise = color.RGBA{0x48, 0xd1, 0xcc, 0xff} // rgb(72, 209, 204)
Mediumvioletred = color.RGBA{0xc7, 0x15, 0x85, 0xff} // rgb(199, 21, 133)
Midnightblue = color.RGBA{0x19, 0x19, 0x70, 0xff} // rgb(25, 25, 112)
Mintcream = color.RGBA{0xf5, 0xff, 0xfa, 0xff} // rgb(245, 255, 250)
Mistyrose = color.RGBA{0xff, 0xe4, 0xe1, 0xff} // rgb(255, 228, 225)
Moccasin = color.RGBA{0xff, 0xe4, 0xb5, 0xff} // rgb(255, 228, 181)
Navajowhite = color.RGBA{0xff, 0xde, 0xad, 0xff} // rgb(255, 222, 173)
Navy = color.RGBA{0x00, 0x00, 0x80, 0xff} // rgb(0, 0, 128)
Oldlace = color.RGBA{0xfd, 0xf5, 0xe6, 0xff} // rgb(253, 245, 230)
Olive = color.RGBA{0x80, 0x80, 0x00, 0xff} // rgb(128, 128, 0)
Olivedrab = color.RGBA{0x6b, 0x8e, 0x23, 0xff} // rgb(107, 142, 35)
Orange = color.RGBA{0xff, 0xa5, 0x00, 0xff} // rgb(255, 165, 0)
Orangered = color.RGBA{0xff, 0x45, 0x00, 0xff} // rgb(255, 69, 0)
Orchid = color.RGBA{0xda, 0x70, 0xd6, 0xff} // rgb(218, 112, 214)
Palegoldenrod = color.RGBA{0xee, 0xe8, 0xaa, 0xff} // rgb(238, 232, 170)
Palegreen = color.RGBA{0x98, 0xfb, 0x98, 0xff} // rgb(152, 251, 152)
Paleturquoise = color.RGBA{0xaf, 0xee, 0xee, 0xff} // rgb(175, 238, 238)
Palevioletred = color.RGBA{0xdb, 0x70, 0x93, 0xff} // rgb(219, 112, 147)
Papayawhip = color.RGBA{0xff, 0xef, 0xd5, 0xff} // rgb(255, 239, 213)
Peachpuff = color.RGBA{0xff, 0xda, 0xb9, 0xff} // rgb(255, 218, 185)
Peru = color.RGBA{0xcd, 0x85, 0x3f, 0xff} // rgb(205, 133, 63)
Pink = color.RGBA{0xff, 0xc0, 0xcb, 0xff} // rgb(255, 192, 203)
Plum = color.RGBA{0xdd, 0xa0, 0xdd, 0xff} // rgb(221, 160, 221)
Powderblue = color.RGBA{0xb0, 0xe0, 0xe6, 0xff} // rgb(176, 224, 230)
Purple = color.RGBA{0x80, 0x00, 0x80, 0xff} // rgb(128, 0, 128)
Red = color.RGBA{0xff, 0x00, 0x00, 0xff} // rgb(255, 0, 0)
Rosybrown = color.RGBA{0xbc, 0x8f, 0x8f, 0xff} // rgb(188, 143, 143)
Royalblue = color.RGBA{0x41, 0x69, 0xe1, 0xff} // rgb(65, 105, 225)
Saddlebrown = color.RGBA{0x8b, 0x45, 0x13, 0xff} // rgb(139, 69, 19)
Salmon = color.RGBA{0xfa, 0x80, 0x72, 0xff} // rgb(250, 128, 114)
Sandybrown = color.RGBA{0xf4, 0xa4, 0x60, 0xff} // rgb(244, 164, 96)
Seagreen = color.RGBA{0x2e, 0x8b, 0x57, 0xff} // rgb(46, 139, 87)
Seashell = color.RGBA{0xff, 0xf5, 0xee, 0xff} // rgb(255, 245, 238)
Sienna = color.RGBA{0xa0, 0x52, 0x2d, 0xff} // rgb(160, 82, 45)
Silver = color.RGBA{0xc0, 0xc0, 0xc0, 0xff} // rgb(192, 192, 192)
Skyblue = color.RGBA{0x87, 0xce, 0xeb, 0xff} // rgb(135, 206, 235)
Slateblue = color.RGBA{0x6a, 0x5a, 0xcd, 0xff} // rgb(106, 90, 205)
Slategray = color.RGBA{0x70, 0x80, 0x90, 0xff} // rgb(112, 128, 144)
Slategrey = color.RGBA{0x70, 0x80, 0x90, 0xff} // rgb(112, 128, 144)
Snow = color.RGBA{0xff, 0xfa, 0xfa, 0xff} // rgb(255, 250, 250)
Springgreen = color.RGBA{0x00, 0xff, 0x7f, 0xff} // rgb(0, 255, 127)
Steelblue = color.RGBA{0x46, 0x82, 0xb4, 0xff} // rgb(70, 130, 180)
Tan = color.RGBA{0xd2, 0xb4, 0x8c, 0xff} // rgb(210, 180, 140)
Teal = color.RGBA{0x00, 0x80, 0x80, 0xff} // rgb(0, 128, 128)
Thistle = color.RGBA{0xd8, 0xbf, 0xd8, 0xff} // rgb(216, 191, 216)
Tomato = color.RGBA{0xff, 0x63, 0x47, 0xff} // rgb(255, 99, 71)
Turquoise = color.RGBA{0x40, 0xe0, 0xd0, 0xff} // rgb(64, 224, 208)
Violet = color.RGBA{0xee, 0x82, 0xee, 0xff} // rgb(238, 130, 238)
Wheat = color.RGBA{0xf5, 0xde, 0xb3, 0xff} // rgb(245, 222, 179)
White = color.RGBA{0xff, 0xff, 0xff, 0xff} // rgb(255, 255, 255)
Whitesmoke = color.RGBA{0xf5, 0xf5, 0xf5, 0xff} // rgb(245, 245, 245)
Yellow = color.RGBA{0xff, 0xff, 0x00, 0xff} // rgb(255, 255, 0)
Yellowgreen = color.RGBA{0x9a, 0xcd, 0x32, 0xff} // rgb(154, 205, 50)
)
|
colornames | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/colornames/gen.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
// This program generates table.go from
// https://www.w3.org/TR/SVG11/types.html#ColorKeywords
package main
import (
"bytes"
"fmt"
"go/format"
"image/color"
"io"
"io/ioutil"
"log"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// matchFunc matches HTML nodes.
type matchFunc func(*html.Node) bool
// appendAll recursively traverses the parse tree rooted under the provided
// node and appends all nodes matched by the matchFunc to dst.
func appendAll(dst []*html.Node, n *html.Node, mf matchFunc) []*html.Node {
if mf(n) {
dst = append(dst, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
dst = appendAll(dst, c, mf)
}
return dst
}
// matchAtom returns a matchFunc that matches a Node with the specified Atom.
func matchAtom(a atom.Atom) matchFunc {
return func(n *html.Node) bool {
return n.DataAtom == a
}
}
// matchAtomAttr returns a matchFunc that matches a Node with the specified
// Atom and a html.Attribute's namespace, key and value.
func matchAtomAttr(a atom.Atom, namespace, key, value string) matchFunc {
return func(n *html.Node) bool {
return n.DataAtom == a && getAttr(n, namespace, key) == value
}
}
// getAttr fetches the value of a html.Attribute for a given namespace and key.
func getAttr(n *html.Node, namespace, key string) string {
for _, attr := range n.Attr {
if attr.Namespace == namespace && attr.Key == key {
return attr.Val
}
}
return ""
}
// re extracts RGB values from strings like "rgb( 0, 223, 128)".
var re = regexp.MustCompile(`rgb\(\s*([0-9]+),\s*([0-9]+),\s*([0-9]+)\)`)
// parseRGB parses a color from a string like "rgb( 0, 233, 128)". It sets
// the alpha value of the color to full opacity.
func parseRGB(s string) (color.RGBA, error) {
m := re.FindStringSubmatch(s)
if m == nil {
return color.RGBA{}, fmt.Errorf("malformed color: %q", s)
}
var rgb [3]uint8
for i, t := range m[1:] {
num, err := strconv.ParseUint(t, 10, 8)
if err != nil {
return color.RGBA{}, fmt.Errorf("malformed value %q in %q: %s", t, s, err)
}
rgb[i] = uint8(num)
}
return color.RGBA{rgb[0], rgb[1], rgb[2], 0xFF}, nil
}
// extractSVGColors extracts named colors from the parse tree of the SVG 1.1
// spec HTML document "Chapter 4: Basic data types and interfaces".
func extractSVGColors(tree *html.Node) (map[string]color.RGBA, error) {
ret := make(map[string]color.RGBA)
// Find the tables which store the color keywords in the parse tree.
colorTables := appendAll(nil, tree, func(n *html.Node) bool {
return n.DataAtom == atom.Table && strings.Contains(getAttr(n, "", "summary"), "color keywords part")
})
for _, table := range colorTables {
// Color names and values are stored in TextNodes within spans in each row.
for _, tr := range appendAll(nil, table, matchAtom(atom.Tr)) {
nameSpan := appendAll(nil, tr, matchAtomAttr(atom.Span, "", "class", "prop-value"))
valueSpan := appendAll(nil, tr, matchAtomAttr(atom.Span, "", "class", "color-keyword-value"))
// Since SVG 1.1 defines an odd number of colors, the last row
// in the second table does not have contents. We skip it.
if len(nameSpan) != 1 || len(valueSpan) != 1 {
continue
}
n, v := nameSpan[0].FirstChild, valueSpan[0].FirstChild
// This sanity checks for the existence of TextNodes under spans.
if n == nil || n.Type != html.TextNode || v == nil || v.Type != html.TextNode {
return nil, fmt.Errorf("extractSVGColors: couldn't find name/value text nodes")
}
val, err := parseRGB(v.Data)
if err != nil {
return nil, fmt.Errorf("extractSVGColors: couldn't parse name/value %q/%q: %s", n.Data, v.Data, err)
}
ret[n.Data] = val
}
}
return ret, nil
}
const preamble = `// generated by go generate; DO NOT EDIT.
package colornames
import "image/color"
`
// WriteColorNames writes table.go.
func writeColorNames(w io.Writer, m map[string]color.RGBA) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Fprintln(w, preamble)
fmt.Fprintln(w, "// Map contains named colors defined in the SVG 1.1 spec.")
fmt.Fprintln(w, "var Map = map[string]color.RGBA{")
for _, k := range keys {
c := m[k]
fmt.Fprintf(w, "%q:color.RGBA{%#02x, %#02x, %#02x, %#02x}, // rgb(%d, %d, %d)\n",
k, c.R, c.G, c.B, c.A, c.R, c.G, c.B)
}
fmt.Fprintln(w, "}\n")
fmt.Fprintln(w, "// Names contains the color names defined in the SVG 1.1 spec.")
fmt.Fprintln(w, "var Names = []string{")
for _, k := range keys {
fmt.Fprintf(w, "%q,\n", k)
}
fmt.Fprintln(w, "}\n")
fmt.Fprintln(w, "var (")
for _, k := range keys {
c := m[k]
// Make the upper case version of k: "Darkred" instead of "darkred".
k = string(k[0]-0x20) + k[1:]
fmt.Fprintf(w, "%s=color.RGBA{%#02x, %#02x, %#02x, %#02x} // rgb(%d, %d, %d)\n",
k, c.R, c.G, c.B, c.A, c.R, c.G, c.B)
}
fmt.Fprintln(w, ")")
}
const url = "https://www.w3.org/TR/SVG11/types.html"
func main() {
res, err := http.Get(url)
if err != nil {
log.Fatalf("Couldn't read from %s: %s\n", url, err)
}
defer res.Body.Close()
tree, err := html.Parse(res.Body)
if err != nil {
log.Fatalf("Couldn't parse %s: %s\n", url, err)
}
colors, err := extractSVGColors(tree)
if err != nil {
log.Fatalf("Couldn't extract colors: %s\n", err)
}
buf := &bytes.Buffer{}
writeColorNames(buf, colors)
fmted, err := format.Source(buf.Bytes())
if err != nil {
log.Fatalf("Error while formatting code: %s\n", err)
}
if err := ioutil.WriteFile("table.go", fmted, 0644); err != nil {
log.Fatalf("Error writing table.go: %s\n", err)
}
}
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/writer.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ccitt
import (
"encoding/binary"
"io"
)
type bitWriter struct {
w io.Writer
// order is whether to process w's bytes LSB first or MSB first.
order Order
// The high nBits bits of the bits field hold encoded bits to be written to w.
bits uint64
nBits uint32
// bytes[:bw] holds encoded bytes not yet written to w.
// Overflow protection is ensured by using a multiple of 8 as bytes length.
bw uint32
bytes [1024]uint8
}
// flushBits copies 64 bits from b.bits to b.bytes. If b.bytes is then full, it
// is written to b.w.
func (b *bitWriter) flushBits() error {
binary.BigEndian.PutUint64(b.bytes[b.bw:], b.bits)
b.bits = 0
b.nBits = 0
b.bw += 8
if b.bw < uint32(len(b.bytes)) {
return nil
}
b.bw = 0
if b.order != MSB {
reverseBitsWithinBytes(b.bytes[:])
}
_, err := b.w.Write(b.bytes[:])
return err
}
// close finalizes a bitcode stream by writing any
// pending bits to bitWriter's underlying io.Writer.
func (b *bitWriter) close() error {
// Write any encoded bits to bytes.
if b.nBits > 0 {
binary.BigEndian.PutUint64(b.bytes[b.bw:], b.bits)
b.bw += (b.nBits + 7) >> 3
}
if b.order != MSB {
reverseBitsWithinBytes(b.bytes[:b.bw])
}
// Write b.bw bytes to b.w.
_, err := b.w.Write(b.bytes[:b.bw])
return err
}
// alignToByteBoundary rounds b.nBits up to a multiple of 8.
// If all 64 bits are used, flush them to bitWriter's bytes.
func (b *bitWriter) alignToByteBoundary() error {
if b.nBits = (b.nBits + 7) &^ 7; b.nBits == 64 {
return b.flushBits()
}
return nil
}
// writeCode writes a variable length bitcode to b's underlying io.Writer.
func (b *bitWriter) writeCode(bs bitString) error {
bits := bs.bits
nBits := bs.nBits
if 64-b.nBits >= nBits {
// b.bits has sufficient room for storing nBits bits.
b.bits |= uint64(bits) << (64 - nBits - b.nBits)
b.nBits += nBits
if b.nBits == 64 {
return b.flushBits()
}
return nil
}
// Number of leading bits that fill b.bits.
i := 64 - b.nBits
// Fill b.bits then flush and write remaining bits.
b.bits |= uint64(bits) >> (nBits - i)
b.nBits = 64
if err := b.flushBits(); err != nil {
return err
}
nBits -= i
b.bits = uint64(bits) << (64 - nBits)
b.nBits = nBits
return nil
}
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/reader_test.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ccitt
import (
"bytes"
"fmt"
"image"
"image/png"
"io"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"unsafe"
)
func compareImages(t *testing.T, img0 image.Image, img1 image.Image) {
t.Helper()
b0 := img0.Bounds()
b1 := img1.Bounds()
if b0 != b1 {
t.Fatalf("bounds differ: %v vs %v", b0, b1)
}
for y := b0.Min.Y; y < b0.Max.Y; y++ {
for x := b0.Min.X; x < b0.Max.X; x++ {
c0 := img0.At(x, y)
c1 := img1.At(x, y)
if c0 != c1 {
t.Fatalf("pixel at (%d, %d) differs: %v vs %v", x, y, c0, c1)
}
}
}
}
func decodePNG(fileName string) (image.Image, error) {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
return png.Decode(f)
}
// simpleHB is a simple implementation of highBits.
func simpleHB(dst []byte, src []byte, invert bool) (d int, s int) {
for d < len(dst) {
numToPack := len(src) - s
if numToPack <= 0 {
break
} else if numToPack > 8 {
numToPack = 8
}
byteValue := byte(0)
if invert {
byteValue = 0xFF >> uint(numToPack)
}
for n := 0; n < numToPack; n++ {
byteValue |= (src[s] & 0x80) >> uint(n)
s++
}
dst[d] = byteValue
d++
}
return d, s
}
func TestHighBits(t *testing.T) {
rng := rand.New(rand.NewSource(1))
dst0 := make([]byte, 3)
dst1 := make([]byte, 3)
src := make([]byte, 20)
for r := 0; r < 1000; r++ {
numDst := rng.Intn(len(dst0) + 1)
randomByte := byte(rng.Intn(256))
for i := 0; i < numDst; i++ {
dst0[i] = randomByte
dst1[i] = randomByte
}
numSrc := rng.Intn(len(src) + 1)
for i := 0; i < numSrc; i++ {
src[i] = byte(rng.Intn(256))
}
invert := rng.Intn(2) == 0
d0, s0 := highBits(dst0[:numDst], src[:numSrc], invert)
d1, s1 := simpleHB(dst1[:numDst], src[:numSrc], invert)
if (d0 != d1) || (s0 != s1) || !bytes.Equal(dst0[:numDst], dst1[:numDst]) {
srcHighBits := make([]byte, numSrc)
for i := range srcHighBits {
srcHighBits[i] = src[i] >> 7
}
t.Fatalf("r=%d, numDst=%d, numSrc=%d, invert=%t:\nsrcHighBits=%d\n"+
"got d=%d, s=%d, bytes=[% 02X]\n"+
"want d=%d, s=%d, bytes=[% 02X]",
r, numDst, numSrc, invert, srcHighBits,
d0, s0, dst0[:numDst],
d1, s1, dst1[:numDst],
)
}
}
}
func BenchmarkHighBits(b *testing.B) {
rng := rand.New(rand.NewSource(1))
dst := make([]byte, 1024)
src := make([]byte, 7777)
for i := range src {
src[i] = uint8(rng.Intn(256))
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
highBits(dst, src, false)
highBits(dst, src, true)
}
}
func TestMaxCodeLength(t *testing.T) {
br := bitReader{}
size := unsafe.Sizeof(br.bits)
size *= 8 // Convert from bytes to bits.
// Check that the size of the bitReader.bits field is large enough to hold
// nextBitMaxNBits bits.
if size < nextBitMaxNBits {
t.Fatalf("size: got %d, want >= %d", size, nextBitMaxNBits)
}
// Check that bitReader.nextBit will always leave enough spare bits in the
// bitReader.bits field such that the decode function can unread up to
// maxCodeLength bits.
if want := size - nextBitMaxNBits; maxCodeLength > want {
t.Fatalf("maxCodeLength: got %d, want <= %d", maxCodeLength, want)
}
// The decode function also assumes that, when saving bits to possibly
// unread later, those bits fit inside a uint32.
if maxCodeLength > 32 {
t.Fatalf("maxCodeLength: got %d, want <= %d", maxCodeLength, 32)
}
}
func testDecodeTable(t *testing.T, decodeTable [][2]int16, codes []code, values []uint32) {
// Build a map from values to codes.
m := map[uint32]string{}
for _, code := range codes {
m[code.val] = code.str
}
// Build the encoded form of those values in MSB order.
enc := []byte(nil)
bits := uint8(0)
nBits := uint32(0)
for _, v := range values {
code := m[v]
if code == "" {
panic("unmapped code")
}
for _, c := range code {
bits |= uint8(c&1) << (7 - nBits)
nBits++
if nBits == 8 {
enc = append(enc, bits)
bits = 0
nBits = 0
continue
}
}
}
if nBits > 0 {
enc = append(enc, bits)
}
// Decode that encoded form.
got := []uint32(nil)
r := &bitReader{
r: bytes.NewReader(enc),
order: MSB,
}
finalValue := values[len(values)-1]
for {
v, err := decode(r, decodeTable)
if err != nil {
t.Fatalf("after got=%d: %v", got, err)
}
got = append(got, v)
if v == finalValue {
break
}
}
// Check that the round-tripped values were unchanged.
if !reflect.DeepEqual(got, values) {
t.Fatalf("\ngot: %v\nwant: %v", got, values)
}
}
func TestModeDecodeTable(t *testing.T) {
testDecodeTable(t, modeDecodeTable[:], modeCodes, []uint32{
modePass,
modeV0,
modeV0,
modeVL1,
modeVR3,
modeVL2,
modeExt,
modeVL1,
modeH,
modeVL1,
modeVL1,
// The exact value of this final slice element doesn't really matter,
// except that testDecodeTable assumes that it (the finalValue) is
// different from every previous element.
modeVL3,
})
}
func TestWhiteDecodeTable(t *testing.T) {
testDecodeTable(t, whiteDecodeTable[:], whiteCodes, []uint32{
0, 1, 256, 7, 128, 3, 2560,
})
}
func TestBlackDecodeTable(t *testing.T) {
testDecodeTable(t, blackDecodeTable[:], blackCodes, []uint32{
63, 64, 63, 64, 64, 63, 22, 1088, 2048, 7, 6, 5, 4, 3, 2, 1, 0,
})
}
func TestDecodeInvalidCode(t *testing.T) {
// The bit stream is:
// 1 010 000000011011
// Packing that LSB-first gives:
// 0b_1101_1000_0000_0101
src := []byte{0x05, 0xD8}
decodeTable := modeDecodeTable[:]
r := &bitReader{
r: bytes.NewReader(src),
}
// "1" decodes to the value 2.
if v, err := decode(r, decodeTable); v != 2 || err != nil {
t.Fatalf("decode #0: got (%v, %v), want (2, nil)", v, err)
}
// "010" decodes to the value 6.
if v, err := decode(r, decodeTable); v != 6 || err != nil {
t.Fatalf("decode #0: got (%v, %v), want (6, nil)", v, err)
}
// "00000001" is an invalid code.
if v, err := decode(r, decodeTable); v != 0 || err != errInvalidCode {
t.Fatalf("decode #0: got (%v, %v), want (0, %v)", v, err, errInvalidCode)
}
// The bitReader should not have advanced after encountering an invalid
// code. The remaining bits should be "000000011011".
remaining := []byte(nil)
for {
bit, err := r.nextBit()
if err == io.EOF {
break
} else if err != nil {
t.Fatalf("nextBit: %v", err)
}
remaining = append(remaining, uint8('0'+bit))
}
if got, want := string(remaining), "000000011011"; got != want {
t.Fatalf("remaining bits: got %q, want %q", got, want)
}
}
func testRead(t *testing.T, fileName string, sf SubFormat, align, invert, truncated bool) {
t.Helper()
const width, height = 153, 55
opts := &Options{
Align: align,
Invert: invert,
}
got := ""
{
f, err := os.Open(fileName)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
gotBytes, err := ioutil.ReadAll(NewReader(f, MSB, sf, width, height, opts))
if err != nil {
t.Fatalf("ReadAll: %v", err)
}
got = string(gotBytes)
}
want := ""
{
img, err := decodePNG("testdata/bw-gopher.png")
if err != nil {
t.Fatalf("decodePNG: %v", err)
}
gray, ok := img.(*image.Gray)
if !ok {
t.Fatalf("decodePNG: got %T, want *image.Gray", img)
}
bounds := gray.Bounds()
if w := bounds.Dx(); w != width {
t.Fatalf("width: got %d, want %d", w, width)
}
if h := bounds.Dy(); h != height {
t.Fatalf("height: got %d, want %d", h, height)
}
// Prepare to extend each row's width to a multiple of 8, to simplify
// packing from 1 byte per pixel to 1 bit per pixel.
extended := make([]byte, (width+7)&^7)
wantBytes := []byte(nil)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
rowPix := gray.Pix[(y-bounds.Min.Y)*gray.Stride:]
rowPix = rowPix[:width]
copy(extended, rowPix)
// Pack from 1 byte per pixel to 1 bit per pixel, MSB first.
byteValue := uint8(0)
for x, pixel := range extended {
byteValue |= (pixel & 0x80) >> uint(x&7)
if (x & 7) == 7 {
wantBytes = append(wantBytes, byteValue)
byteValue = 0
}
}
}
want = string(wantBytes)
}
// We expect a width of 153 pixels, which is 20 bytes per row (at 1 bit per
// pixel, plus 7 final bits of padding). Check that want is 20 * height
// bytes long, and if got != want, format them to split at every 20 bytes.
if n := len(want); n != 20*height {
t.Fatalf("len(want): got %d, want %d", n, 20*height)
}
format := func(s string) string {
b := []byte(nil)
for row := 0; len(s) >= 20; row++ {
b = append(b, fmt.Sprintf("row%02d: %02X\n", row, s[:20])...)
s = s[20:]
}
if len(s) > 0 {
b = append(b, fmt.Sprintf("%02X\n", s)...)
}
return string(b)
}
if got != want {
t.Fatalf("got:\n%s\nwant:\n%s", format(got), format(want))
}
// Passing AutoDetectHeight should produce the same output, provided that
// the input hasn't truncated the trailing sequence of consecutive EOL's
// that marks the end of the image.
if !truncated {
f, err := os.Open(fileName)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
adhBytes, err := ioutil.ReadAll(NewReader(f, MSB, sf, width, AutoDetectHeight, opts))
if err != nil {
t.Fatalf("ReadAll: %v", err)
}
if s := string(adhBytes); s != want {
t.Fatalf("AutoDetectHeight produced different output.\n"+
"height=%d:\n%s\nheight=%d:\n%s",
AutoDetectHeight, format(s), height, format(want))
}
}
}
func TestRead(t *testing.T) {
for _, fileName := range []string{
"testdata/bw-gopher.ccitt_group3",
"testdata/bw-gopher-aligned.ccitt_group3",
"testdata/bw-gopher-inverted.ccitt_group3",
"testdata/bw-gopher-inverted-aligned.ccitt_group3",
"testdata/bw-gopher.ccitt_group4",
"testdata/bw-gopher-aligned.ccitt_group4",
"testdata/bw-gopher-inverted.ccitt_group4",
"testdata/bw-gopher-inverted-aligned.ccitt_group4",
"testdata/bw-gopher-truncated0.ccitt_group3",
"testdata/bw-gopher-truncated0.ccitt_group4",
"testdata/bw-gopher-truncated1.ccitt_group3",
"testdata/bw-gopher-truncated1.ccitt_group4",
} {
subFormat := Group3
if strings.HasSuffix(fileName, "group4") {
subFormat = Group4
}
align := strings.Contains(fileName, "aligned")
invert := strings.Contains(fileName, "inverted")
truncated := strings.Contains(fileName, "truncated")
testRead(t, fileName, subFormat, align, invert, truncated)
}
}
func TestDecodeIntoGray(t *testing.T) {
for _, tt := range []struct {
fileName string
sf SubFormat
w, h int
}{
{"testdata/bw-gopher.ccitt_group3", Group3, 153, 55},
{"testdata/bw-gopher.ccitt_group4", Group4, 153, 55},
{"testdata/bw-gopher-truncated0.ccitt_group3", Group3, 153, 55},
{"testdata/bw-gopher-truncated0.ccitt_group4", Group4, 153, 55},
{"testdata/bw-gopher-truncated1.ccitt_group3", Group3, 153, 55},
{"testdata/bw-gopher-truncated1.ccitt_group4", Group4, 153, 55},
} {
t.Run(tt.fileName, func(t *testing.T) {
testDecodeIntoGray(t, tt.fileName, MSB, tt.sf, tt.w, tt.h, nil)
})
}
}
func testDecodeIntoGray(t *testing.T, fileName string, order Order, sf SubFormat, width int, height int, opts *Options) {
t.Helper()
f, err := os.Open(filepath.FromSlash(fileName))
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
got := image.NewGray(image.Rect(0, 0, width, height))
if err := DecodeIntoGray(got, f, order, sf, opts); err != nil {
t.Fatalf("DecodeIntoGray: %v", err)
}
want, err := decodePNG("testdata/bw-gopher.png")
if err != nil {
t.Fatal(err)
}
compareImages(t, got, want)
}
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/writer_test.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ccitt
import (
"bytes"
"reflect"
"testing"
)
func testEncode(t *testing.T, o Order) {
t.Helper()
values := []uint32{0, 1, 256, 7, 128, 3, 2560, 2240, 2368, 2048}
decTable := whiteDecodeTable[:]
encTableSmall := whiteEncodeTable2[:]
encTableBig := whiteEncodeTable3[:]
// Encode values to bit stream.
var bb bytes.Buffer
w := &bitWriter{w: &bb, order: o}
for _, v := range values {
encTable := encTableSmall
if v < 64 {
// No-op.
} else if v&63 != 0 {
t.Fatalf("writeCode: cannot encode %d: large but not a multiple of 64", v)
} else {
encTable = encTableBig
v = v/64 - 1
}
if err := w.writeCode(encTable[v]); err != nil {
t.Fatalf("writeCode: %v", err)
}
}
if err := w.close(); err != nil {
t.Fatalf("close: %v", err)
}
// Decode bit stream to values.
got := []uint32(nil)
r := &bitReader{
r: bytes.NewReader(bb.Bytes()),
order: o,
}
finalValue := values[len(values)-1]
for {
v, err := decode(r, decTable)
if err != nil {
t.Fatalf("after got=%d: %v", got, err)
}
got = append(got, v)
if v == finalValue {
break
}
}
// Check that the round-tripped values were unchanged.
if !reflect.DeepEqual(got, values) {
t.Fatalf("\ngot: %v\nwant: %v", got, values)
}
}
func TestEncodeLSB(t *testing.T) { testEncode(t, LSB) }
func TestEncodeMSB(t *testing.T) { testEncode(t, MSB) }
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/table.go | // generated by "go run gen.go". DO NOT EDIT.
package ccitt
// Each decodeTable is represented by an array of [2]int16's: a binary tree.
// Each array element (other than element 0, which means invalid) is a branch
// node in that tree. The root node is always element 1 (the second element).
//
// To walk the tree, look at the next bit in the bit stream, using it to select
// the first or second element of the [2]int16. If that int16 is 0, we have an
// invalid code. If it is positive, go to that branch node. If it is negative,
// then we have a leaf node, whose value is the bitwise complement (the ^
// operator) of that int16.
//
// Comments above each decodeTable also show the same structure visually. The
// "b123" lines show the 123'rd branch node. The "=XXXXX" lines show an invalid
// code. The "=v1234" lines show a leaf node with value 1234. When reading the
// bit stream, a 0 or 1 bit means to go up or down, as you move left to right.
//
// For example, in modeDecodeTable, branch node b005 is three steps up from the
// root node, meaning that we have already seen "000". If the next bit is "0"
// then we move to branch node b006. Otherwise, the next bit is "1", and we
// move to the leaf node v0000 (also known as the modePass constant). Indeed,
// the bits that encode modePass are "0001".
//
// Tables 1, 2 and 3 come from the "ITU-T Recommendation T.6: FACSIMILE CODING
// SCHEMES AND CODING CONTROL FUNCTIONS FOR GROUP 4 FACSIMILE APPARATUS"
// specification:
//
// https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.6-198811-I!!PDF-E&type=items
// modeDecodeTable represents Table 1 and the End-of-Line code.
//
// +=XXXXX
// b009 +-+
// | +=v0009
// b007 +-+
// | | +=v0008
// b010 | +-+
// | +=v0005
// b006 +-+
// | | +=v0007
// b008 | +-+
// | +=v0004
// b005 +-+
// | +=v0000
// b003 +-+
// | +=v0001
// b002 +-+
// | | +=v0006
// b004 | +-+
// | +=v0003
// b001 +-+
// +=v0002
var modeDecodeTable = [...][2]int16{
0: {0, 0},
1: {2, ^2},
2: {3, 4},
3: {5, ^1},
4: {^6, ^3},
5: {6, ^0},
6: {7, 8},
7: {9, 10},
8: {^7, ^4},
9: {0, ^9},
10: {^8, ^5},
}
// whiteDecodeTable represents Tables 2 and 3 for a white run.
//
// +=XXXXX
// b059 +-+
// | | +=v1792
// b096 | | +-+
// | | | | +=v1984
// b100 | | | +-+
// | | | +=v2048
// b094 | | +-+
// | | | | +=v2112
// b101 | | | | +-+
// | | | | | +=v2176
// b097 | | | +-+
// | | | | +=v2240
// b102 | | | +-+
// | | | +=v2304
// b085 | +-+
// | | +=v1856
// b098 | | +-+
// | | | +=v1920
// b095 | +-+
// | | +=v2368
// b103 | | +-+
// | | | +=v2432
// b099 | +-+
// | | +=v2496
// b104 | +-+
// | +=v2560
// b040 +-+
// | | +=v0029
// b060 | +-+
// | +=v0030
// b026 +-+
// | | +=v0045
// b061 | | +-+
// | | | +=v0046
// b041 | +-+
// | +=v0022
// b016 +-+
// | | +=v0023
// b042 | | +-+
// | | | | +=v0047
// b062 | | | +-+
// | | | +=v0048
// b027 | +-+
// | +=v0013
// b008 +-+
// | | +=v0020
// b043 | | +-+
// | | | | +=v0033
// b063 | | | +-+
// | | | +=v0034
// b028 | | +-+
// | | | | +=v0035
// b064 | | | | +-+
// | | | | | +=v0036
// b044 | | | +-+
// | | | | +=v0037
// b065 | | | +-+
// | | | +=v0038
// b017 | +-+
// | | +=v0019
// b045 | | +-+
// | | | | +=v0031
// b066 | | | +-+
// | | | +=v0032
// b029 | +-+
// | +=v0001
// b004 +-+
// | | +=v0012
// b030 | | +-+
// | | | | +=v0053
// b067 | | | | +-+
// | | | | | +=v0054
// b046 | | | +-+
// | | | +=v0026
// b018 | | +-+
// | | | | +=v0039
// b068 | | | | +-+
// | | | | | +=v0040
// b047 | | | | +-+
// | | | | | | +=v0041
// b069 | | | | | +-+
// | | | | | +=v0042
// b031 | | | +-+
// | | | | +=v0043
// b070 | | | | +-+
// | | | | | +=v0044
// b048 | | | +-+
// | | | +=v0021
// b009 | +-+
// | | +=v0028
// b049 | | +-+
// | | | | +=v0061
// b071 | | | +-+
// | | | +=v0062
// b032 | | +-+
// | | | | +=v0063
// b072 | | | | +-+
// | | | | | +=v0000
// b050 | | | +-+
// | | | | +=v0320
// b073 | | | +-+
// | | | +=v0384
// b019 | +-+
// | +=v0010
// b002 +-+
// | | +=v0011
// b020 | | +-+
// | | | | +=v0027
// b051 | | | | +-+
// | | | | | | +=v0059
// b074 | | | | | +-+
// | | | | | +=v0060
// b033 | | | +-+
// | | | | +=v1472
// b086 | | | | +-+
// | | | | | +=v1536
// b075 | | | | +-+
// | | | | | | +=v1600
// b087 | | | | | +-+
// | | | | | +=v1728
// b052 | | | +-+
// | | | +=v0018
// b010 | | +-+
// | | | | +=v0024
// b053 | | | | +-+
// | | | | | | +=v0049
// b076 | | | | | +-+
// | | | | | +=v0050
// b034 | | | | +-+
// | | | | | | +=v0051
// b077 | | | | | | +-+
// | | | | | | | +=v0052
// b054 | | | | | +-+
// | | | | | +=v0025
// b021 | | | +-+
// | | | | +=v0055
// b078 | | | | +-+
// | | | | | +=v0056
// b055 | | | | +-+
// | | | | | | +=v0057
// b079 | | | | | +-+
// | | | | | +=v0058
// b035 | | | +-+
// | | | +=v0192
// b005 | +-+
// | | +=v1664
// b036 | | +-+
// | | | | +=v0448
// b080 | | | | +-+
// | | | | | +=v0512
// b056 | | | +-+
// | | | | +=v0704
// b088 | | | | +-+
// | | | | | +=v0768
// b081 | | | +-+
// | | | +=v0640
// b022 | | +-+
// | | | | +=v0576
// b082 | | | | +-+
// | | | | | | +=v0832
// b089 | | | | | +-+
// | | | | | +=v0896
// b057 | | | | +-+
// | | | | | | +=v0960
// b090 | | | | | | +-+
// | | | | | | | +=v1024
// b083 | | | | | +-+
// | | | | | | +=v1088
// b091 | | | | | +-+
// | | | | | +=v1152
// b037 | | | +-+
// | | | | +=v1216
// b092 | | | | +-+
// | | | | | +=v1280
// b084 | | | | +-+
// | | | | | | +=v1344
// b093 | | | | | +-+
// | | | | | +=v1408
// b058 | | | +-+
// | | | +=v0256
// b011 | +-+
// | +=v0002
// b001 +-+
// | +=v0003
// b012 | +-+
// | | | +=v0128
// b023 | | +-+
// | | +=v0008
// b006 | +-+
// | | | +=v0009
// b024 | | | +-+
// | | | | | +=v0016
// b038 | | | | +-+
// | | | | +=v0017
// b013 | | +-+
// | | +=v0004
// b003 +-+
// | +=v0005
// b014 | +-+
// | | | +=v0014
// b039 | | | +-+
// | | | | +=v0015
// b025 | | +-+
// | | +=v0064
// b007 +-+
// | +=v0006
// b015 +-+
// +=v0007
var whiteDecodeTable = [...][2]int16{
0: {0, 0},
1: {2, 3},
2: {4, 5},
3: {6, 7},
4: {8, 9},
5: {10, 11},
6: {12, 13},
7: {14, 15},
8: {16, 17},
9: {18, 19},
10: {20, 21},
11: {22, ^2},
12: {^3, 23},
13: {24, ^4},
14: {^5, 25},
15: {^6, ^7},
16: {26, 27},
17: {28, 29},
18: {30, 31},
19: {32, ^10},
20: {^11, 33},
21: {34, 35},
22: {36, 37},
23: {^128, ^8},
24: {^9, 38},
25: {39, ^64},
26: {40, 41},
27: {42, ^13},
28: {43, 44},
29: {45, ^1},
30: {^12, 46},
31: {47, 48},
32: {49, 50},
33: {51, 52},
34: {53, 54},
35: {55, ^192},
36: {^1664, 56},
37: {57, 58},
38: {^16, ^17},
39: {^14, ^15},
40: {59, 60},
41: {61, ^22},
42: {^23, 62},
43: {^20, 63},
44: {64, 65},
45: {^19, 66},
46: {67, ^26},
47: {68, 69},
48: {70, ^21},
49: {^28, 71},
50: {72, 73},
51: {^27, 74},
52: {75, ^18},
53: {^24, 76},
54: {77, ^25},
55: {78, 79},
56: {80, 81},
57: {82, 83},
58: {84, ^256},
59: {0, 85},
60: {^29, ^30},
61: {^45, ^46},
62: {^47, ^48},
63: {^33, ^34},
64: {^35, ^36},
65: {^37, ^38},
66: {^31, ^32},
67: {^53, ^54},
68: {^39, ^40},
69: {^41, ^42},
70: {^43, ^44},
71: {^61, ^62},
72: {^63, ^0},
73: {^320, ^384},
74: {^59, ^60},
75: {86, 87},
76: {^49, ^50},
77: {^51, ^52},
78: {^55, ^56},
79: {^57, ^58},
80: {^448, ^512},
81: {88, ^640},
82: {^576, 89},
83: {90, 91},
84: {92, 93},
85: {94, 95},
86: {^1472, ^1536},
87: {^1600, ^1728},
88: {^704, ^768},
89: {^832, ^896},
90: {^960, ^1024},
91: {^1088, ^1152},
92: {^1216, ^1280},
93: {^1344, ^1408},
94: {96, 97},
95: {98, 99},
96: {^1792, 100},
97: {101, 102},
98: {^1856, ^1920},
99: {103, 104},
100: {^1984, ^2048},
101: {^2112, ^2176},
102: {^2240, ^2304},
103: {^2368, ^2432},
104: {^2496, ^2560},
}
// blackDecodeTable represents Tables 2 and 3 for a black run.
//
// +=XXXXX
// b017 +-+
// | | +=v1792
// b042 | | +-+
// | | | | +=v1984
// b063 | | | +-+
// | | | +=v2048
// b029 | | +-+
// | | | | +=v2112
// b064 | | | | +-+
// | | | | | +=v2176
// b043 | | | +-+
// | | | | +=v2240
// b065 | | | +-+
// | | | +=v2304
// b022 | +-+
// | | +=v1856
// b044 | | +-+
// | | | +=v1920
// b030 | +-+
// | | +=v2368
// b066 | | +-+
// | | | +=v2432
// b045 | +-+
// | | +=v2496
// b067 | +-+
// | +=v2560
// b013 +-+
// | | +=v0018
// b031 | | +-+
// | | | | +=v0052
// b068 | | | | +-+
// | | | | | | +=v0640
// b095 | | | | | +-+
// | | | | | +=v0704
// b046 | | | +-+
// | | | | +=v0768
// b096 | | | | +-+
// | | | | | +=v0832
// b069 | | | +-+
// | | | +=v0055
// b023 | | +-+
// | | | | +=v0056
// b070 | | | | +-+
// | | | | | | +=v1280
// b097 | | | | | +-+
// | | | | | +=v1344
// b047 | | | | +-+
// | | | | | | +=v1408
// b098 | | | | | | +-+
// | | | | | | | +=v1472
// b071 | | | | | +-+
// | | | | | +=v0059
// b032 | | | +-+
// | | | | +=v0060
// b072 | | | | +-+
// | | | | | | +=v1536
// b099 | | | | | +-+
// | | | | | +=v1600
// b048 | | | +-+
// | | | +=v0024
// b018 | +-+
// | | +=v0025
// b049 | | +-+
// | | | | +=v1664
// b100 | | | | +-+
// | | | | | +=v1728
// b073 | | | +-+
// | | | +=v0320
// b033 | | +-+
// | | | | +=v0384
// b074 | | | | +-+
// | | | | | +=v0448
// b050 | | | +-+
// | | | | +=v0512
// b101 | | | | +-+
// | | | | | +=v0576
// b075 | | | +-+
// | | | +=v0053
// b024 | +-+
// | | +=v0054
// b076 | | +-+
// | | | | +=v0896
// b102 | | | +-+
// | | | +=v0960
// b051 | | +-+
// | | | | +=v1024
// b103 | | | | +-+
// | | | | | +=v1088
// b077 | | | +-+
// | | | | +=v1152
// b104 | | | +-+
// | | | +=v1216
// b034 | +-+
// | +=v0064
// b010 +-+
// | | +=v0013
// b019 | | +-+
// | | | | +=v0023
// b052 | | | | +-+
// | | | | | | +=v0050
// b078 | | | | | +-+
// | | | | | +=v0051
// b035 | | | | +-+
// | | | | | | +=v0044
// b079 | | | | | | +-+
// | | | | | | | +=v0045
// b053 | | | | | +-+
// | | | | | | +=v0046
// b080 | | | | | +-+
// | | | | | +=v0047
// b025 | | | +-+
// | | | | +=v0057
// b081 | | | | +-+
// | | | | | +=v0058
// b054 | | | | +-+
// | | | | | | +=v0061
// b082 | | | | | +-+
// | | | | | +=v0256
// b036 | | | +-+
// | | | +=v0016
// b014 | +-+
// | | +=v0017
// b037 | | +-+
// | | | | +=v0048
// b083 | | | | +-+
// | | | | | +=v0049
// b055 | | | +-+
// | | | | +=v0062
// b084 | | | +-+
// | | | +=v0063
// b026 | | +-+
// | | | | +=v0030
// b085 | | | | +-+
// | | | | | +=v0031
// b056 | | | | +-+
// | | | | | | +=v0032
// b086 | | | | | +-+
// | | | | | +=v0033
// b038 | | | +-+
// | | | | +=v0040
// b087 | | | | +-+
// | | | | | +=v0041
// b057 | | | +-+
// | | | +=v0022
// b020 | +-+
// | +=v0014
// b008 +-+
// | | +=v0010
// b015 | | +-+
// | | | +=v0011
// b011 | +-+
// | | +=v0015
// b027 | | +-+
// | | | | +=v0128
// b088 | | | | +-+
// | | | | | +=v0192
// b058 | | | | +-+
// | | | | | | +=v0026
// b089 | | | | | +-+
// | | | | | +=v0027
// b039 | | | +-+
// | | | | +=v0028
// b090 | | | | +-+
// | | | | | +=v0029
// b059 | | | +-+
// | | | +=v0019
// b021 | | +-+
// | | | | +=v0020
// b060 | | | | +-+
// | | | | | | +=v0034
// b091 | | | | | +-+
// | | | | | +=v0035
// b040 | | | | +-+
// | | | | | | +=v0036
// b092 | | | | | | +-+
// | | | | | | | +=v0037
// b061 | | | | | +-+
// | | | | | | +=v0038
// b093 | | | | | +-+
// | | | | | +=v0039
// b028 | | | +-+
// | | | | +=v0021
// b062 | | | | +-+
// | | | | | | +=v0042
// b094 | | | | | +-+
// | | | | | +=v0043
// b041 | | | +-+
// | | | +=v0000
// b016 | +-+
// | +=v0012
// b006 +-+
// | | +=v0009
// b012 | | +-+
// | | | +=v0008
// b009 | +-+
// | +=v0007
// b004 +-+
// | | +=v0006
// b007 | +-+
// | +=v0005
// b002 +-+
// | | +=v0001
// b005 | +-+
// | +=v0004
// b001 +-+
// | +=v0003
// b003 +-+
// +=v0002
var blackDecodeTable = [...][2]int16{
0: {0, 0},
1: {2, 3},
2: {4, 5},
3: {^3, ^2},
4: {6, 7},
5: {^1, ^4},
6: {8, 9},
7: {^6, ^5},
8: {10, 11},
9: {12, ^7},
10: {13, 14},
11: {15, 16},
12: {^9, ^8},
13: {17, 18},
14: {19, 20},
15: {^10, ^11},
16: {21, ^12},
17: {0, 22},
18: {23, 24},
19: {^13, 25},
20: {26, ^14},
21: {27, 28},
22: {29, 30},
23: {31, 32},
24: {33, 34},
25: {35, 36},
26: {37, 38},
27: {^15, 39},
28: {40, 41},
29: {42, 43},
30: {44, 45},
31: {^18, 46},
32: {47, 48},
33: {49, 50},
34: {51, ^64},
35: {52, 53},
36: {54, ^16},
37: {^17, 55},
38: {56, 57},
39: {58, 59},
40: {60, 61},
41: {62, ^0},
42: {^1792, 63},
43: {64, 65},
44: {^1856, ^1920},
45: {66, 67},
46: {68, 69},
47: {70, 71},
48: {72, ^24},
49: {^25, 73},
50: {74, 75},
51: {76, 77},
52: {^23, 78},
53: {79, 80},
54: {81, 82},
55: {83, 84},
56: {85, 86},
57: {87, ^22},
58: {88, 89},
59: {90, ^19},
60: {^20, 91},
61: {92, 93},
62: {^21, 94},
63: {^1984, ^2048},
64: {^2112, ^2176},
65: {^2240, ^2304},
66: {^2368, ^2432},
67: {^2496, ^2560},
68: {^52, 95},
69: {96, ^55},
70: {^56, 97},
71: {98, ^59},
72: {^60, 99},
73: {100, ^320},
74: {^384, ^448},
75: {101, ^53},
76: {^54, 102},
77: {103, 104},
78: {^50, ^51},
79: {^44, ^45},
80: {^46, ^47},
81: {^57, ^58},
82: {^61, ^256},
83: {^48, ^49},
84: {^62, ^63},
85: {^30, ^31},
86: {^32, ^33},
87: {^40, ^41},
88: {^128, ^192},
89: {^26, ^27},
90: {^28, ^29},
91: {^34, ^35},
92: {^36, ^37},
93: {^38, ^39},
94: {^42, ^43},
95: {^640, ^704},
96: {^768, ^832},
97: {^1280, ^1344},
98: {^1408, ^1472},
99: {^1536, ^1600},
100: {^1664, ^1728},
101: {^512, ^576},
102: {^896, ^960},
103: {^1024, ^1088},
104: {^1152, ^1216},
}
const maxCodeLength = 13
// Each encodeTable is represented by an array of bitStrings.
// bitString is a pair of uint32 values representing a bit code.
// The nBits low bits of bits make up the actual bit code.
// Eg. bitString{0x0004, 8} represents the bitcode "00000100".
type bitString struct {
bits uint32
nBits uint32
}
// modeEncodeTable represents Table 1 and the End-of-Line code.
var modeEncodeTable = [...]bitString{
0: {0x0001, 4}, // "0001"
1: {0x0001, 3}, // "001"
2: {0x0001, 1}, // "1"
3: {0x0003, 3}, // "011"
4: {0x0003, 6}, // "000011"
5: {0x0003, 7}, // "0000011"
6: {0x0002, 3}, // "010"
7: {0x0002, 6}, // "000010"
8: {0x0002, 7}, // "0000010"
9: {0x0001, 7}, // "0000001"
}
// whiteEncodeTable2 represents Table 2 for a white run.
var whiteEncodeTable2 = [...]bitString{
0: {0x0035, 8}, // "00110101"
1: {0x0007, 6}, // "000111"
2: {0x0007, 4}, // "0111"
3: {0x0008, 4}, // "1000"
4: {0x000b, 4}, // "1011"
5: {0x000c, 4}, // "1100"
6: {0x000e, 4}, // "1110"
7: {0x000f, 4}, // "1111"
8: {0x0013, 5}, // "10011"
9: {0x0014, 5}, // "10100"
10: {0x0007, 5}, // "00111"
11: {0x0008, 5}, // "01000"
12: {0x0008, 6}, // "001000"
13: {0x0003, 6}, // "000011"
14: {0x0034, 6}, // "110100"
15: {0x0035, 6}, // "110101"
16: {0x002a, 6}, // "101010"
17: {0x002b, 6}, // "101011"
18: {0x0027, 7}, // "0100111"
19: {0x000c, 7}, // "0001100"
20: {0x0008, 7}, // "0001000"
21: {0x0017, 7}, // "0010111"
22: {0x0003, 7}, // "0000011"
23: {0x0004, 7}, // "0000100"
24: {0x0028, 7}, // "0101000"
25: {0x002b, 7}, // "0101011"
26: {0x0013, 7}, // "0010011"
27: {0x0024, 7}, // "0100100"
28: {0x0018, 7}, // "0011000"
29: {0x0002, 8}, // "00000010"
30: {0x0003, 8}, // "00000011"
31: {0x001a, 8}, // "00011010"
32: {0x001b, 8}, // "00011011"
33: {0x0012, 8}, // "00010010"
34: {0x0013, 8}, // "00010011"
35: {0x0014, 8}, // "00010100"
36: {0x0015, 8}, // "00010101"
37: {0x0016, 8}, // "00010110"
38: {0x0017, 8}, // "00010111"
39: {0x0028, 8}, // "00101000"
40: {0x0029, 8}, // "00101001"
41: {0x002a, 8}, // "00101010"
42: {0x002b, 8}, // "00101011"
43: {0x002c, 8}, // "00101100"
44: {0x002d, 8}, // "00101101"
45: {0x0004, 8}, // "00000100"
46: {0x0005, 8}, // "00000101"
47: {0x000a, 8}, // "00001010"
48: {0x000b, 8}, // "00001011"
49: {0x0052, 8}, // "01010010"
50: {0x0053, 8}, // "01010011"
51: {0x0054, 8}, // "01010100"
52: {0x0055, 8}, // "01010101"
53: {0x0024, 8}, // "00100100"
54: {0x0025, 8}, // "00100101"
55: {0x0058, 8}, // "01011000"
56: {0x0059, 8}, // "01011001"
57: {0x005a, 8}, // "01011010"
58: {0x005b, 8}, // "01011011"
59: {0x004a, 8}, // "01001010"
60: {0x004b, 8}, // "01001011"
61: {0x0032, 8}, // "00110010"
62: {0x0033, 8}, // "00110011"
63: {0x0034, 8}, // "00110100"
}
// whiteEncodeTable3 represents Table 3 for a white run.
var whiteEncodeTable3 = [...]bitString{
0: {0x001b, 5}, // "11011"
1: {0x0012, 5}, // "10010"
2: {0x0017, 6}, // "010111"
3: {0x0037, 7}, // "0110111"
4: {0x0036, 8}, // "00110110"
5: {0x0037, 8}, // "00110111"
6: {0x0064, 8}, // "01100100"
7: {0x0065, 8}, // "01100101"
8: {0x0068, 8}, // "01101000"
9: {0x0067, 8}, // "01100111"
10: {0x00cc, 9}, // "011001100"
11: {0x00cd, 9}, // "011001101"
12: {0x00d2, 9}, // "011010010"
13: {0x00d3, 9}, // "011010011"
14: {0x00d4, 9}, // "011010100"
15: {0x00d5, 9}, // "011010101"
16: {0x00d6, 9}, // "011010110"
17: {0x00d7, 9}, // "011010111"
18: {0x00d8, 9}, // "011011000"
19: {0x00d9, 9}, // "011011001"
20: {0x00da, 9}, // "011011010"
21: {0x00db, 9}, // "011011011"
22: {0x0098, 9}, // "010011000"
23: {0x0099, 9}, // "010011001"
24: {0x009a, 9}, // "010011010"
25: {0x0018, 6}, // "011000"
26: {0x009b, 9}, // "010011011"
27: {0x0008, 11}, // "00000001000"
28: {0x000c, 11}, // "00000001100"
29: {0x000d, 11}, // "00000001101"
30: {0x0012, 12}, // "000000010010"
31: {0x0013, 12}, // "000000010011"
32: {0x0014, 12}, // "000000010100"
33: {0x0015, 12}, // "000000010101"
34: {0x0016, 12}, // "000000010110"
35: {0x0017, 12}, // "000000010111"
36: {0x001c, 12}, // "000000011100"
37: {0x001d, 12}, // "000000011101"
38: {0x001e, 12}, // "000000011110"
39: {0x001f, 12}, // "000000011111"
}
// blackEncodeTable2 represents Table 2 for a black run.
var blackEncodeTable2 = [...]bitString{
0: {0x0037, 10}, // "0000110111"
1: {0x0002, 3}, // "010"
2: {0x0003, 2}, // "11"
3: {0x0002, 2}, // "10"
4: {0x0003, 3}, // "011"
5: {0x0003, 4}, // "0011"
6: {0x0002, 4}, // "0010"
7: {0x0003, 5}, // "00011"
8: {0x0005, 6}, // "000101"
9: {0x0004, 6}, // "000100"
10: {0x0004, 7}, // "0000100"
11: {0x0005, 7}, // "0000101"
12: {0x0007, 7}, // "0000111"
13: {0x0004, 8}, // "00000100"
14: {0x0007, 8}, // "00000111"
15: {0x0018, 9}, // "000011000"
16: {0x0017, 10}, // "0000010111"
17: {0x0018, 10}, // "0000011000"
18: {0x0008, 10}, // "0000001000"
19: {0x0067, 11}, // "00001100111"
20: {0x0068, 11}, // "00001101000"
21: {0x006c, 11}, // "00001101100"
22: {0x0037, 11}, // "00000110111"
23: {0x0028, 11}, // "00000101000"
24: {0x0017, 11}, // "00000010111"
25: {0x0018, 11}, // "00000011000"
26: {0x00ca, 12}, // "000011001010"
27: {0x00cb, 12}, // "000011001011"
28: {0x00cc, 12}, // "000011001100"
29: {0x00cd, 12}, // "000011001101"
30: {0x0068, 12}, // "000001101000"
31: {0x0069, 12}, // "000001101001"
32: {0x006a, 12}, // "000001101010"
33: {0x006b, 12}, // "000001101011"
34: {0x00d2, 12}, // "000011010010"
35: {0x00d3, 12}, // "000011010011"
36: {0x00d4, 12}, // "000011010100"
37: {0x00d5, 12}, // "000011010101"
38: {0x00d6, 12}, // "000011010110"
39: {0x00d7, 12}, // "000011010111"
40: {0x006c, 12}, // "000001101100"
41: {0x006d, 12}, // "000001101101"
42: {0x00da, 12}, // "000011011010"
43: {0x00db, 12}, // "000011011011"
44: {0x0054, 12}, // "000001010100"
45: {0x0055, 12}, // "000001010101"
46: {0x0056, 12}, // "000001010110"
47: {0x0057, 12}, // "000001010111"
48: {0x0064, 12}, // "000001100100"
49: {0x0065, 12}, // "000001100101"
50: {0x0052, 12}, // "000001010010"
51: {0x0053, 12}, // "000001010011"
52: {0x0024, 12}, // "000000100100"
53: {0x0037, 12}, // "000000110111"
54: {0x0038, 12}, // "000000111000"
55: {0x0027, 12}, // "000000100111"
56: {0x0028, 12}, // "000000101000"
57: {0x0058, 12}, // "000001011000"
58: {0x0059, 12}, // "000001011001"
59: {0x002b, 12}, // "000000101011"
60: {0x002c, 12}, // "000000101100"
61: {0x005a, 12}, // "000001011010"
62: {0x0066, 12}, // "000001100110"
63: {0x0067, 12}, // "000001100111"
}
// blackEncodeTable3 represents Table 3 for a black run.
var blackEncodeTable3 = [...]bitString{
0: {0x000f, 10}, // "0000001111"
1: {0x00c8, 12}, // "000011001000"
2: {0x00c9, 12}, // "000011001001"
3: {0x005b, 12}, // "000001011011"
4: {0x0033, 12}, // "000000110011"
5: {0x0034, 12}, // "000000110100"
6: {0x0035, 12}, // "000000110101"
7: {0x006c, 13}, // "0000001101100"
8: {0x006d, 13}, // "0000001101101"
9: {0x004a, 13}, // "0000001001010"
10: {0x004b, 13}, // "0000001001011"
11: {0x004c, 13}, // "0000001001100"
12: {0x004d, 13}, // "0000001001101"
13: {0x0072, 13}, // "0000001110010"
14: {0x0073, 13}, // "0000001110011"
15: {0x0074, 13}, // "0000001110100"
16: {0x0075, 13}, // "0000001110101"
17: {0x0076, 13}, // "0000001110110"
18: {0x0077, 13}, // "0000001110111"
19: {0x0052, 13}, // "0000001010010"
20: {0x0053, 13}, // "0000001010011"
21: {0x0054, 13}, // "0000001010100"
22: {0x0055, 13}, // "0000001010101"
23: {0x005a, 13}, // "0000001011010"
24: {0x005b, 13}, // "0000001011011"
25: {0x0064, 13}, // "0000001100100"
26: {0x0065, 13}, // "0000001100101"
27: {0x0008, 11}, // "00000001000"
28: {0x000c, 11}, // "00000001100"
29: {0x000d, 11}, // "00000001101"
30: {0x0012, 12}, // "000000010010"
31: {0x0013, 12}, // "000000010011"
32: {0x0014, 12}, // "000000010100"
33: {0x0015, 12}, // "000000010101"
34: {0x0016, 12}, // "000000010110"
35: {0x0017, 12}, // "000000010111"
36: {0x001c, 12}, // "000000011100"
37: {0x001d, 12}, // "000000011101"
38: {0x001e, 12}, // "000000011110"
39: {0x001f, 12}, // "000000011111"
}
// COPY PASTE table.go BEGIN
const (
modePass = iota // Pass
modeH // Horizontal
modeV0 // Vertical-0
modeVR1 // Vertical-Right-1
modeVR2 // Vertical-Right-2
modeVR3 // Vertical-Right-3
modeVL1 // Vertical-Left-1
modeVL2 // Vertical-Left-2
modeVL3 // Vertical-Left-3
modeExt // Extension
)
// COPY PASTE table.go END
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/reader.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run gen.go
// Package ccitt implements a CCITT (fax) image decoder.
package ccitt
import (
"encoding/binary"
"errors"
"image"
"io"
"math/bits"
)
var (
errIncompleteCode = errors.New("ccitt: incomplete code")
errInvalidBounds = errors.New("ccitt: invalid bounds")
errInvalidCode = errors.New("ccitt: invalid code")
errInvalidMode = errors.New("ccitt: invalid mode")
errInvalidOffset = errors.New("ccitt: invalid offset")
errMissingEOL = errors.New("ccitt: missing End-of-Line")
errRunLengthOverflowsWidth = errors.New("ccitt: run length overflows width")
errRunLengthTooLong = errors.New("ccitt: run length too long")
errUnsupportedMode = errors.New("ccitt: unsupported mode")
errUnsupportedSubFormat = errors.New("ccitt: unsupported sub-format")
errUnsupportedWidth = errors.New("ccitt: unsupported width")
)
// Order specifies the bit ordering in a CCITT data stream.
type Order uint32
const (
// LSB means Least Significant Bits first.
LSB Order = iota
// MSB means Most Significant Bits first.
MSB
)
// SubFormat represents that the CCITT format consists of a number of
// sub-formats. Decoding or encoding a CCITT data stream requires knowing the
// sub-format context. It is not represented in the data stream per se.
type SubFormat uint32
const (
Group3 SubFormat = iota
Group4
)
// AutoDetectHeight is passed as the height argument to NewReader to indicate
// that the image height (the number of rows) is not known in advance.
const AutoDetectHeight = -1
// Options are optional parameters.
type Options struct {
// Align means that some variable-bit-width codes are byte-aligned.
Align bool
// Invert means that black is the 1 bit or 0xFF byte, and white is 0.
Invert bool
}
// maxWidth is the maximum (inclusive) supported width. This is a limitation of
// this implementation, to guard against integer overflow, and not anything
// inherent to the CCITT format.
const maxWidth = 1 << 20
func invertBytes(b []byte) {
for i, c := range b {
b[i] = ^c
}
}
func reverseBitsWithinBytes(b []byte) {
for i, c := range b {
b[i] = bits.Reverse8(c)
}
}
// highBits writes to dst (1 bit per pixel, most significant bit first) the
// high (0x80) bits from src (1 byte per pixel). It returns the number of bytes
// written and read such that dst[:d] is the packed form of src[:s].
//
// For example, if src starts with the 8 bytes [0x7D, 0x7E, 0x7F, 0x80, 0x81,
// 0x82, 0x00, 0xFF] then 0x1D will be written to dst[0].
//
// If src has (8 * len(dst)) or more bytes then only len(dst) bytes are
// written, (8 * len(dst)) bytes are read, and invert is ignored.
//
// Otherwise, if len(src) is not a multiple of 8 then the final byte written to
// dst is padded with 1 bits (if invert is true) or 0 bits. If inverted, the 1s
// are typically temporary, e.g. they will be flipped back to 0s by an
// invertBytes call in the highBits caller, reader.Read.
func highBits(dst []byte, src []byte, invert bool) (d int, s int) {
// Pack as many complete groups of 8 src bytes as we can.
n := len(src) / 8
if n > len(dst) {
n = len(dst)
}
dstN := dst[:n]
for i := range dstN {
src8 := src[i*8 : i*8+8]
dstN[i] = ((src8[0] & 0x80) >> 0) |
((src8[1] & 0x80) >> 1) |
((src8[2] & 0x80) >> 2) |
((src8[3] & 0x80) >> 3) |
((src8[4] & 0x80) >> 4) |
((src8[5] & 0x80) >> 5) |
((src8[6] & 0x80) >> 6) |
((src8[7] & 0x80) >> 7)
}
d, s = n, 8*n
dst, src = dst[d:], src[s:]
// Pack up to 7 remaining src bytes, if there's room in dst.
if (len(dst) > 0) && (len(src) > 0) {
dstByte := byte(0)
if invert {
dstByte = 0xFF >> uint(len(src))
}
for n, srcByte := range src {
dstByte |= (srcByte & 0x80) >> uint(n)
}
dst[0] = dstByte
d, s = d+1, s+len(src)
}
return d, s
}
type bitReader struct {
r io.Reader
// readErr is the error returned from the most recent r.Read call. As the
// io.Reader documentation says, when r.Read returns (n, err), "always
// process the n > 0 bytes returned before considering the error err".
readErr error
// order is whether to process r's bytes LSB first or MSB first.
order Order
// The high nBits bits of the bits field hold upcoming bits in MSB order.
bits uint64
nBits uint32
// bytes[br:bw] holds bytes read from r but not yet loaded into bits.
br uint32
bw uint32
bytes [1024]uint8
}
func (b *bitReader) alignToByteBoundary() {
n := b.nBits & 7
b.bits <<= n
b.nBits -= n
}
// nextBitMaxNBits is the maximum possible value of bitReader.nBits after a
// bitReader.nextBit call, provided that bitReader.nBits was not more than this
// value before that call.
//
// Note that the decode function can unread bits, which can temporarily set the
// bitReader.nBits value above nextBitMaxNBits.
const nextBitMaxNBits = 31
func (b *bitReader) nextBit() (uint64, error) {
for {
if b.nBits > 0 {
bit := b.bits >> 63
b.bits <<= 1
b.nBits--
return bit, nil
}
if available := b.bw - b.br; available >= 4 {
// Read 32 bits, even though b.bits is a uint64, since the decode
// function may need to unread up to maxCodeLength bits, putting
// them back in the remaining (64 - 32) bits. TestMaxCodeLength
// checks that the generated maxCodeLength constant fits.
//
// If changing the Uint32 call, also change nextBitMaxNBits.
b.bits = uint64(binary.BigEndian.Uint32(b.bytes[b.br:])) << 32
b.br += 4
b.nBits = 32
continue
} else if available > 0 {
b.bits = uint64(b.bytes[b.br]) << (7 * 8)
b.br++
b.nBits = 8
continue
}
if b.readErr != nil {
return 0, b.readErr
}
n, err := b.r.Read(b.bytes[:])
b.br = 0
b.bw = uint32(n)
b.readErr = err
if b.order != MSB {
reverseBitsWithinBytes(b.bytes[:b.bw])
}
}
}
func decode(b *bitReader, decodeTable [][2]int16) (uint32, error) {
nBitsRead, bitsRead, state := uint32(0), uint64(0), int32(1)
for {
bit, err := b.nextBit()
if err != nil {
if err == io.EOF {
err = errIncompleteCode
}
return 0, err
}
bitsRead |= bit << (63 - nBitsRead)
nBitsRead++
// The "&1" is redundant, but can eliminate a bounds check.
state = int32(decodeTable[state][bit&1])
if state < 0 {
return uint32(^state), nil
} else if state == 0 {
// Unread the bits we've read, then return errInvalidCode.
b.bits = (b.bits >> nBitsRead) | bitsRead
b.nBits += nBitsRead
return 0, errInvalidCode
}
}
}
// decodeEOL decodes the 12-bit EOL code 0000_0000_0001.
func decodeEOL(b *bitReader) error {
nBitsRead, bitsRead := uint32(0), uint64(0)
for {
bit, err := b.nextBit()
if err != nil {
if err == io.EOF {
err = errMissingEOL
}
return err
}
bitsRead |= bit << (63 - nBitsRead)
nBitsRead++
if nBitsRead < 12 {
if bit&1 == 0 {
continue
}
} else if bit&1 != 0 {
return nil
}
// Unread the bits we've read, then return errMissingEOL.
b.bits = (b.bits >> nBitsRead) | bitsRead
b.nBits += nBitsRead
return errMissingEOL
}
}
type reader struct {
br bitReader
subFormat SubFormat
// width is the image width in pixels.
width int
// rowsRemaining starts at the image height in pixels, when the reader is
// driven through the io.Reader interface, and decrements to zero as rows
// are decoded. Alternatively, it may be negative if the image height is
// not known in advance at the time of the NewReader call.
//
// When driven through DecodeIntoGray, this field is unused.
rowsRemaining int
// curr and prev hold the current and previous rows. Each element is either
// 0x00 (black) or 0xFF (white).
//
// prev may be nil, when processing the first row.
curr []byte
prev []byte
// ri is the read index. curr[:ri] are those bytes of curr that have been
// passed along via the Read method.
//
// When the reader is driven through DecodeIntoGray, instead of through the
// io.Reader interface, this field is unused.
ri int
// wi is the write index. curr[:wi] are those bytes of curr that have
// already been decoded via the decodeRow method.
//
// What this implementation calls wi is roughly equivalent to what the spec
// calls the a0 index.
wi int
// These fields are copied from the *Options (which may be nil).
align bool
invert bool
// atStartOfRow is whether we have just started the row. Some parts of the
// spec say to treat this situation as if "wi = -1".
atStartOfRow bool
// penColorIsWhite is whether the next run is black or white.
penColorIsWhite bool
// seenStartOfImage is whether we've called the startDecode method.
seenStartOfImage bool
// truncated is whether the input is missing the final 6 consecutive EOL's
// (for Group3) or 2 consecutive EOL's (for Group4). Omitting that trailer
// (but otherwise padding to a byte boundary, with either all 0 bits or all
// 1 bits) is invalid according to the spec, but happens in practice when
// exporting from Adobe Acrobat to TIFF + CCITT. This package silently
// ignores the format error for CCITT input that has been truncated in that
// fashion, returning the full decoded image.
//
// Detecting trailer truncation (just after the final row of pixels)
// requires knowing which row is the final row, and therefore does not
// trigger if the image height is not known in advance.
truncated bool
// readErr is a sticky error for the Read method.
readErr error
}
func (z *reader) Read(p []byte) (int, error) {
if z.readErr != nil {
return 0, z.readErr
}
originalP := p
for len(p) > 0 {
// Allocate buffers (and decode any start-of-image codes), if
// processing the first or second row.
if z.curr == nil {
if !z.seenStartOfImage {
if z.readErr = z.startDecode(); z.readErr != nil {
break
}
z.atStartOfRow = true
}
z.curr = make([]byte, z.width)
}
// Decode the next row, if necessary.
if z.atStartOfRow {
if z.rowsRemaining < 0 {
// We do not know the image height in advance. See if the next
// code is an EOL. If it is, it is consumed. If it isn't, the
// bitReader shouldn't advance along the bit stream, and we
// simply decode another row of pixel data.
//
// For the Group4 subFormat, we may need to align to a byte
// boundary. For the Group3 subFormat, the previous z.decodeRow
// call (or z.startDecode call) has already consumed one of the
// 6 consecutive EOL's. The next EOL is actually the second of
// 6, in the middle, and we shouldn't align at that point.
if z.align && (z.subFormat == Group4) {
z.br.alignToByteBoundary()
}
if err := z.decodeEOL(); err == errMissingEOL {
// No-op. It's another row of pixel data.
} else if err != nil {
z.readErr = err
break
} else {
if z.readErr = z.finishDecode(true); z.readErr != nil {
break
}
z.readErr = io.EOF
break
}
} else if z.rowsRemaining == 0 {
// We do know the image height in advance, and we have already
// decoded exactly that many rows.
if z.readErr = z.finishDecode(false); z.readErr != nil {
break
}
z.readErr = io.EOF
break
} else {
z.rowsRemaining--
}
if z.readErr = z.decodeRow(z.rowsRemaining == 0); z.readErr != nil {
break
}
}
// Pack from z.curr (1 byte per pixel) to p (1 bit per pixel).
packD, packS := highBits(p, z.curr[z.ri:], z.invert)
p = p[packD:]
z.ri += packS
// Prepare to decode the next row, if necessary.
if z.ri == len(z.curr) {
z.ri, z.curr, z.prev = 0, z.prev, z.curr
z.atStartOfRow = true
}
}
n := len(originalP) - len(p)
if z.invert {
invertBytes(originalP[:n])
}
return n, z.readErr
}
func (z *reader) penColor() byte {
if z.penColorIsWhite {
return 0xFF
}
return 0x00
}
func (z *reader) startDecode() error {
switch z.subFormat {
case Group3:
if err := z.decodeEOL(); err != nil {
return err
}
case Group4:
// No-op.
default:
return errUnsupportedSubFormat
}
z.seenStartOfImage = true
return nil
}
func (z *reader) finishDecode(alreadySeenEOL bool) error {
numberOfEOLs := 0
switch z.subFormat {
case Group3:
if z.truncated {
return nil
}
// The stream ends with a RTC (Return To Control) of 6 consecutive
// EOL's, but we should have already just seen an EOL, either in
// z.startDecode (for a zero-height image) or in z.decodeRow.
numberOfEOLs = 5
case Group4:
autoDetectHeight := z.rowsRemaining < 0
if autoDetectHeight {
// Aligning to a byte boundary was already handled by reader.Read.
} else if z.align {
z.br.alignToByteBoundary()
}
// The stream ends with two EOL's. If the first one is missing, and we
// had an explicit image height, we just assume that the trailing two
// EOL's were truncated and return a nil error.
if err := z.decodeEOL(); err != nil {
if (err == errMissingEOL) && !autoDetectHeight {
z.truncated = true
return nil
}
return err
}
numberOfEOLs = 1
default:
return errUnsupportedSubFormat
}
if alreadySeenEOL {
numberOfEOLs--
}
for ; numberOfEOLs > 0; numberOfEOLs-- {
if err := z.decodeEOL(); err != nil {
return err
}
}
return nil
}
func (z *reader) decodeEOL() error {
return decodeEOL(&z.br)
}
func (z *reader) decodeRow(finalRow bool) error {
z.wi = 0
z.atStartOfRow = true
z.penColorIsWhite = true
if z.align {
z.br.alignToByteBoundary()
}
switch z.subFormat {
case Group3:
for ; z.wi < len(z.curr); z.atStartOfRow = false {
if err := z.decodeRun(); err != nil {
return err
}
}
err := z.decodeEOL()
if finalRow && (err == errMissingEOL) {
z.truncated = true
return nil
}
return err
case Group4:
for ; z.wi < len(z.curr); z.atStartOfRow = false {
mode, err := decode(&z.br, modeDecodeTable[:])
if err != nil {
return err
}
rm := readerMode{}
if mode < uint32(len(readerModes)) {
rm = readerModes[mode]
}
if rm.function == nil {
return errInvalidMode
}
if err := rm.function(z, rm.arg); err != nil {
return err
}
}
return nil
}
return errUnsupportedSubFormat
}
func (z *reader) decodeRun() error {
table := blackDecodeTable[:]
if z.penColorIsWhite {
table = whiteDecodeTable[:]
}
total := 0
for {
n, err := decode(&z.br, table)
if err != nil {
return err
}
if n > maxWidth {
panic("unreachable")
}
total += int(n)
if total > maxWidth {
return errRunLengthTooLong
}
// Anything 0x3F or below is a terminal code.
if n <= 0x3F {
break
}
}
if total > (len(z.curr) - z.wi) {
return errRunLengthOverflowsWidth
}
dst := z.curr[z.wi : z.wi+total]
penColor := z.penColor()
for i := range dst {
dst[i] = penColor
}
z.wi += total
z.penColorIsWhite = !z.penColorIsWhite
return nil
}
// The various modes' semantics are based on determining a row of pixels'
// "changing elements": those pixels whose color differs from the one on its
// immediate left.
//
// The row above the first row is implicitly all white. Similarly, the column
// to the left of the first column is implicitly all white.
//
// For example, here's Figure 1 in "ITU-T Recommendation T.6", where the
// current and previous rows contain black (B) and white (w) pixels. The a?
// indexes point into curr, the b? indexes point into prev.
//
// b1 b2
// v v
// prev: BBBBBwwwwwBBBwwwww
// curr: BBBwwwwwBBBBBBwwww
// ^ ^ ^
// a0 a1 a2
//
// a0 is the "reference element" or current decoder position, roughly
// equivalent to what this implementation calls reader.wi.
//
// a1 is the next changing element to the right of a0, on the "coding line"
// (the current row).
//
// a2 is the next changing element to the right of a1, again on curr.
//
// b1 is the first changing element on the "reference line" (the previous row)
// to the right of a0 and of opposite color to a0.
//
// b2 is the next changing element to the right of b1, again on prev.
//
// The various modes calculate a1 (and a2, for modeH):
// - modePass calculates that a1 is at or to the right of b2.
// - modeH calculates a1 and a2 without considering b1 or b2.
// - modeV* calculates a1 to be b1 plus an adjustment (between -3 and +3).
const (
findB1 = false
findB2 = true
)
// findB finds either the b1 or b2 value.
func (z *reader) findB(whichB bool) int {
// The initial row is a special case. The previous row is implicitly all
// white, so that there are no changing pixel elements. We return b1 or b2
// to be at the end of the row.
if len(z.prev) != len(z.curr) {
return len(z.curr)
}
i := z.wi
if z.atStartOfRow {
// a0 is implicitly at -1, on a white pixel. b1 is the first black
// pixel in the previous row. b2 is the first white pixel after that.
for ; (i < len(z.prev)) && (z.prev[i] == 0xFF); i++ {
}
if whichB == findB2 {
for ; (i < len(z.prev)) && (z.prev[i] == 0x00); i++ {
}
}
return i
}
// As per figure 1 above, assume that the current pen color is white.
// First, walk past every contiguous black pixel in prev, starting at a0.
oppositeColor := ^z.penColor()
for ; (i < len(z.prev)) && (z.prev[i] == oppositeColor); i++ {
}
// Then walk past every contiguous white pixel.
penColor := ^oppositeColor
for ; (i < len(z.prev)) && (z.prev[i] == penColor); i++ {
}
// We're now at a black pixel (or at the end of the row). That's b1.
if whichB == findB2 {
// If we're looking for b2, walk past every contiguous black pixel
// again.
oppositeColor := ^penColor
for ; (i < len(z.prev)) && (z.prev[i] == oppositeColor); i++ {
}
}
return i
}
type readerMode struct {
function func(z *reader, arg int) error
arg int
}
var readerModes = [...]readerMode{
modePass: {function: readerModePass},
modeH: {function: readerModeH},
modeV0: {function: readerModeV, arg: +0},
modeVR1: {function: readerModeV, arg: +1},
modeVR2: {function: readerModeV, arg: +2},
modeVR3: {function: readerModeV, arg: +3},
modeVL1: {function: readerModeV, arg: -1},
modeVL2: {function: readerModeV, arg: -2},
modeVL3: {function: readerModeV, arg: -3},
modeExt: {function: readerModeExt},
}
func readerModePass(z *reader, arg int) error {
b2 := z.findB(findB2)
if (b2 < z.wi) || (len(z.curr) < b2) {
return errInvalidOffset
}
dst := z.curr[z.wi:b2]
penColor := z.penColor()
for i := range dst {
dst[i] = penColor
}
z.wi = b2
return nil
}
func readerModeH(z *reader, arg int) error {
// The first iteration finds a1. The second finds a2.
for i := 0; i < 2; i++ {
if err := z.decodeRun(); err != nil {
return err
}
}
return nil
}
func readerModeV(z *reader, arg int) error {
a1 := z.findB(findB1) + arg
if (a1 < z.wi) || (len(z.curr) < a1) {
return errInvalidOffset
}
dst := z.curr[z.wi:a1]
penColor := z.penColor()
for i := range dst {
dst[i] = penColor
}
z.wi = a1
z.penColorIsWhite = !z.penColorIsWhite
return nil
}
func readerModeExt(z *reader, arg int) error {
return errUnsupportedMode
}
// DecodeIntoGray decodes the CCITT-formatted data in r into dst.
//
// It returns an error if dst's width and height don't match the implied width
// and height of CCITT-formatted data.
func DecodeIntoGray(dst *image.Gray, r io.Reader, order Order, sf SubFormat, opts *Options) error {
bounds := dst.Bounds()
if (bounds.Dx() < 0) || (bounds.Dy() < 0) {
return errInvalidBounds
}
if bounds.Dx() > maxWidth {
return errUnsupportedWidth
}
z := reader{
br: bitReader{r: r, order: order},
subFormat: sf,
align: (opts != nil) && opts.Align,
invert: (opts != nil) && opts.Invert,
width: bounds.Dx(),
}
if err := z.startDecode(); err != nil {
return err
}
width := bounds.Dx()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
p := (y - bounds.Min.Y) * dst.Stride
z.curr = dst.Pix[p : p+width]
if err := z.decodeRow(y+1 == bounds.Max.Y); err != nil {
return err
}
z.curr, z.prev = nil, z.curr
}
if err := z.finishDecode(false); err != nil {
return err
}
if z.invert {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
p := (y - bounds.Min.Y) * dst.Stride
invertBytes(dst.Pix[p : p+width])
}
}
return nil
}
// NewReader returns an io.Reader that decodes the CCITT-formatted data in r.
// The resultant byte stream is one bit per pixel (MSB first), with 1 meaning
// white and 0 meaning black. Each row in the result is byte-aligned.
//
// A negative height, such as passing AutoDetectHeight, means that the image
// height is not known in advance. A negative width is invalid.
func NewReader(r io.Reader, order Order, sf SubFormat, width int, height int, opts *Options) io.Reader {
readErr := error(nil)
if width < 0 {
readErr = errInvalidBounds
} else if width > maxWidth {
readErr = errUnsupportedWidth
}
return &reader{
br: bitReader{r: r, order: order},
subFormat: sf,
align: (opts != nil) && opts.Align,
invert: (opts != nil) && opts.Invert,
width: width,
rowsRemaining: height,
readErr: readErr,
}
}
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/table_test.go | // generated by "go run gen.go". DO NOT EDIT.
package ccitt
// COPY PASTE table_test.go BEGIN
type code struct {
val uint32
str string
}
var modeCodes = []code{
{modePass, "0001"},
{modeH, "001"},
{modeV0, "1"},
{modeVR1, "011"},
{modeVR2, "000011"},
{modeVR3, "0000011"},
{modeVL1, "010"},
{modeVL2, "000010"},
{modeVL3, "0000010"},
{modeExt, "0000001"},
}
var whiteCodes = []code{
// Terminating codes (0-63).
{0x0000, "00110101"},
{0x0001, "000111"},
{0x0002, "0111"},
{0x0003, "1000"},
{0x0004, "1011"},
{0x0005, "1100"},
{0x0006, "1110"},
{0x0007, "1111"},
{0x0008, "10011"},
{0x0009, "10100"},
{0x000A, "00111"},
{0x000B, "01000"},
{0x000C, "001000"},
{0x000D, "000011"},
{0x000E, "110100"},
{0x000F, "110101"},
{0x0010, "101010"},
{0x0011, "101011"},
{0x0012, "0100111"},
{0x0013, "0001100"},
{0x0014, "0001000"},
{0x0015, "0010111"},
{0x0016, "0000011"},
{0x0017, "0000100"},
{0x0018, "0101000"},
{0x0019, "0101011"},
{0x001A, "0010011"},
{0x001B, "0100100"},
{0x001C, "0011000"},
{0x001D, "00000010"},
{0x001E, "00000011"},
{0x001F, "00011010"},
{0x0020, "00011011"},
{0x0021, "00010010"},
{0x0022, "00010011"},
{0x0023, "00010100"},
{0x0024, "00010101"},
{0x0025, "00010110"},
{0x0026, "00010111"},
{0x0027, "00101000"},
{0x0028, "00101001"},
{0x0029, "00101010"},
{0x002A, "00101011"},
{0x002B, "00101100"},
{0x002C, "00101101"},
{0x002D, "00000100"},
{0x002E, "00000101"},
{0x002F, "00001010"},
{0x0030, "00001011"},
{0x0031, "01010010"},
{0x0032, "01010011"},
{0x0033, "01010100"},
{0x0034, "01010101"},
{0x0035, "00100100"},
{0x0036, "00100101"},
{0x0037, "01011000"},
{0x0038, "01011001"},
{0x0039, "01011010"},
{0x003A, "01011011"},
{0x003B, "01001010"},
{0x003C, "01001011"},
{0x003D, "00110010"},
{0x003E, "00110011"},
{0x003F, "00110100"},
// Make-up codes between 64 and 1728.
{0x0040, "11011"},
{0x0080, "10010"},
{0x00C0, "010111"},
{0x0100, "0110111"},
{0x0140, "00110110"},
{0x0180, "00110111"},
{0x01C0, "01100100"},
{0x0200, "01100101"},
{0x0240, "01101000"},
{0x0280, "01100111"},
{0x02C0, "011001100"},
{0x0300, "011001101"},
{0x0340, "011010010"},
{0x0380, "011010011"},
{0x03C0, "011010100"},
{0x0400, "011010101"},
{0x0440, "011010110"},
{0x0480, "011010111"},
{0x04C0, "011011000"},
{0x0500, "011011001"},
{0x0540, "011011010"},
{0x0580, "011011011"},
{0x05C0, "010011000"},
{0x0600, "010011001"},
{0x0640, "010011010"},
{0x0680, "011000"},
{0x06C0, "010011011"},
// Make-up codes between 1792 and 2560.
{0x0700, "00000001000"},
{0x0740, "00000001100"},
{0x0780, "00000001101"},
{0x07C0, "000000010010"},
{0x0800, "000000010011"},
{0x0840, "000000010100"},
{0x0880, "000000010101"},
{0x08C0, "000000010110"},
{0x0900, "000000010111"},
{0x0940, "000000011100"},
{0x0980, "000000011101"},
{0x09C0, "000000011110"},
{0x0A00, "000000011111"},
}
var blackCodes = []code{
// Terminating codes (0-63).
{0x0000, "0000110111"},
{0x0001, "010"},
{0x0002, "11"},
{0x0003, "10"},
{0x0004, "011"},
{0x0005, "0011"},
{0x0006, "0010"},
{0x0007, "00011"},
{0x0008, "000101"},
{0x0009, "000100"},
{0x000A, "0000100"},
{0x000B, "0000101"},
{0x000C, "0000111"},
{0x000D, "00000100"},
{0x000E, "00000111"},
{0x000F, "000011000"},
{0x0010, "0000010111"},
{0x0011, "0000011000"},
{0x0012, "0000001000"},
{0x0013, "00001100111"},
{0x0014, "00001101000"},
{0x0015, "00001101100"},
{0x0016, "00000110111"},
{0x0017, "00000101000"},
{0x0018, "00000010111"},
{0x0019, "00000011000"},
{0x001A, "000011001010"},
{0x001B, "000011001011"},
{0x001C, "000011001100"},
{0x001D, "000011001101"},
{0x001E, "000001101000"},
{0x001F, "000001101001"},
{0x0020, "000001101010"},
{0x0021, "000001101011"},
{0x0022, "000011010010"},
{0x0023, "000011010011"},
{0x0024, "000011010100"},
{0x0025, "000011010101"},
{0x0026, "000011010110"},
{0x0027, "000011010111"},
{0x0028, "000001101100"},
{0x0029, "000001101101"},
{0x002A, "000011011010"},
{0x002B, "000011011011"},
{0x002C, "000001010100"},
{0x002D, "000001010101"},
{0x002E, "000001010110"},
{0x002F, "000001010111"},
{0x0030, "000001100100"},
{0x0031, "000001100101"},
{0x0032, "000001010010"},
{0x0033, "000001010011"},
{0x0034, "000000100100"},
{0x0035, "000000110111"},
{0x0036, "000000111000"},
{0x0037, "000000100111"},
{0x0038, "000000101000"},
{0x0039, "000001011000"},
{0x003A, "000001011001"},
{0x003B, "000000101011"},
{0x003C, "000000101100"},
{0x003D, "000001011010"},
{0x003E, "000001100110"},
{0x003F, "000001100111"},
// Make-up codes between 64 and 1728.
{0x0040, "0000001111"},
{0x0080, "000011001000"},
{0x00C0, "000011001001"},
{0x0100, "000001011011"},
{0x0140, "000000110011"},
{0x0180, "000000110100"},
{0x01C0, "000000110101"},
{0x0200, "0000001101100"},
{0x0240, "0000001101101"},
{0x0280, "0000001001010"},
{0x02C0, "0000001001011"},
{0x0300, "0000001001100"},
{0x0340, "0000001001101"},
{0x0380, "0000001110010"},
{0x03C0, "0000001110011"},
{0x0400, "0000001110100"},
{0x0440, "0000001110101"},
{0x0480, "0000001110110"},
{0x04C0, "0000001110111"},
{0x0500, "0000001010010"},
{0x0540, "0000001010011"},
{0x0580, "0000001010100"},
{0x05C0, "0000001010101"},
{0x0600, "0000001011010"},
{0x0640, "0000001011011"},
{0x0680, "0000001100100"},
{0x06C0, "0000001100101"},
// Make-up codes between 1792 and 2560.
{0x0700, "00000001000"},
{0x0740, "00000001100"},
{0x0780, "00000001101"},
{0x07C0, "000000010010"},
{0x0800, "000000010011"},
{0x0840, "000000010100"},
{0x0880, "000000010101"},
{0x08C0, "000000010110"},
{0x0900, "000000010111"},
{0x0940, "000000011100"},
{0x0980, "000000011101"},
{0x09C0, "000000011110"},
{0x0A00, "000000011111"},
}
// COPY PASTE table_test.go END
|
ccitt | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/ccitt/gen.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
)
var debug = flag.Bool("debug", false, "")
func main() {
flag.Parse()
// Generate table.go.
{
w := &bytes.Buffer{}
w.WriteString(header)
w.WriteString(decodeHeaderComment)
writeDecodeTable(w, build(modeCodes[:], 0), "modeDecodeTable",
"// modeDecodeTable represents Table 1 and the End-of-Line code.\n")
writeDecodeTable(w, build(whiteCodes[:], 0), "whiteDecodeTable",
"// whiteDecodeTable represents Tables 2 and 3 for a white run.\n")
writeDecodeTable(w, build(blackCodes[:], 0), "blackDecodeTable",
"// blackDecodeTable represents Tables 2 and 3 for a black run.\n")
writeMaxCodeLength(w, modeCodes[:], whiteCodes[:], blackCodes[:])
w.WriteString(encodeHeaderComment)
w.WriteString(bitStringTypeDef)
writeEncodeTable(w, modeCodes[:], "modeEncodeTable",
"// modeEncodeTable represents Table 1 and the End-of-Line code.\n")
writeEncodeTable(w, whiteCodes[:64], "whiteEncodeTable2",
"// whiteEncodeTable2 represents Table 2 for a white run.\n")
writeEncodeTable(w, whiteCodes[64:], "whiteEncodeTable3",
"// whiteEncodeTable3 represents Table 3 for a white run.\n")
writeEncodeTable(w, blackCodes[:64], "blackEncodeTable2",
"// blackEncodeTable2 represents Table 2 for a black run.\n")
writeEncodeTable(w, blackCodes[64:], "blackEncodeTable3",
"// blackEncodeTable3 represents Table 3 for a black run.\n")
finish(w, "table.go")
}
// Generate table_test.go.
{
w := &bytes.Buffer{}
w.WriteString(header)
finish(w, "table_test.go")
}
}
const header = `// generated by "go run gen.go". DO NOT EDIT.
package ccitt
`
const decodeHeaderComment = `
// Each decodeTable is represented by an array of [2]int16's: a binary tree.
// Each array element (other than element 0, which means invalid) is a branch
// node in that tree. The root node is always element 1 (the second element).
//
// To walk the tree, look at the next bit in the bit stream, using it to select
// the first or second element of the [2]int16. If that int16 is 0, we have an
// invalid code. If it is positive, go to that branch node. If it is negative,
// then we have a leaf node, whose value is the bitwise complement (the ^
// operator) of that int16.
//
// Comments above each decodeTable also show the same structure visually. The
// "b123" lines show the 123'rd branch node. The "=XXXXX" lines show an invalid
// code. The "=v1234" lines show a leaf node with value 1234. When reading the
// bit stream, a 0 or 1 bit means to go up or down, as you move left to right.
//
// For example, in modeDecodeTable, branch node b005 is three steps up from the
// root node, meaning that we have already seen "000". If the next bit is "0"
// then we move to branch node b006. Otherwise, the next bit is "1", and we
// move to the leaf node v0000 (also known as the modePass constant). Indeed,
// the bits that encode modePass are "0001".
//
// Tables 1, 2 and 3 come from the "ITU-T Recommendation T.6: FACSIMILE CODING
// SCHEMES AND CODING CONTROL FUNCTIONS FOR GROUP 4 FACSIMILE APPARATUS"
// specification:
//
// https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.6-198811-I!!PDF-E&type=items
`
const encodeHeaderComment = `
// Each encodeTable is represented by an array of bitStrings.
`
type node struct {
children [2]*node
val uint32
branchIndex int32
}
func (n *node) isBranch() bool {
return (n != nil) && ((n.children[0] != nil) || (n.children[1] != nil))
}
func (n *node) String() string {
if n == nil {
return "0"
}
if n.branchIndex > 0 {
return fmt.Sprintf("%d", n.branchIndex)
}
return fmt.Sprintf("^%d", n.val)
}
func build(codes []code, prefixLen int) *node {
if len(codes) == 0 {
return nil
}
if prefixLen == len(codes[0].str) {
if len(codes) != 1 {
panic("ambiguous codes")
}
return &node{
val: codes[0].val,
}
}
childrenCodes := [2][]code{}
for _, code := range codes {
bit := code.str[prefixLen] & 1
childrenCodes[bit] = append(childrenCodes[bit], code)
}
return &node{
children: [2]*node{
build(childrenCodes[0], prefixLen+1),
build(childrenCodes[1], prefixLen+1),
},
}
}
func writeDecodeTable(w *bytes.Buffer, root *node, varName, comment string) {
assignBranchIndexes(root)
w.WriteString(comment)
w.WriteString("//\n")
writeComment(w, root, " ", false)
fmt.Fprintf(w, "var %s = [...][2]int16{\n", varName)
fmt.Fprintf(w, "0: {0, 0},\n")
// Walk the tree in breadth-first order.
for queue := []*node{root}; len(queue) > 0; {
n := queue[0]
queue = queue[1:]
if n.isBranch() {
fmt.Fprintf(w, "%d: {%v, %v},\n", n.branchIndex, n.children[0], n.children[1])
queue = append(queue, n.children[0], n.children[1])
}
}
fmt.Fprintf(w, "}\n\n")
}
const bitStringTypeDef = `
// bitString is a pair of uint32 values representing a bit code.
// The nBits low bits of bits make up the actual bit code.
// Eg. bitString{0x0004, 8} represents the bitcode "00000100".
type bitString struct {
bits uint32
nBits uint32
}
`
func writeEncodeTable(w *bytes.Buffer, codes []code, varName, comment string) {
w.WriteString(comment)
fmt.Fprintf(w, "var %s = [...]bitString{\n", varName)
for i, code := range codes {
s := code.str
n := uint32(len(s))
c := uint32(0)
for j := uint32(0); j < n; j++ {
c |= uint32(s[j]&1) << (n - j - 1)
}
fmt.Fprintf(w, "%d: {0x%04x, %v}, // %q \n", i, c, n, s)
}
fmt.Fprintf(w, "}\n\n")
}
func assignBranchIndexes(root *node) {
// 0 is reserved for an invalid value.
branchIndex := int32(1)
// Walk the tree in breadth-first order.
for queue := []*node{root}; len(queue) > 0; {
n := queue[0]
queue = queue[1:]
if n.isBranch() {
n.branchIndex = branchIndex
branchIndex++
queue = append(queue, n.children[0], n.children[1])
}
}
}
func writeComment(w *bytes.Buffer, n *node, prefix string, down bool) {
if n.isBranch() {
prefixUp := prefix[:len(prefix)-2] + " | "
prefixDown := prefix + "| "
if down {
prefixUp, prefixDown = prefixDown, prefixUp
}
writeComment(w, n.children[0], prefixUp, false)
defer writeComment(w, n.children[1], prefixDown, true)
fmt.Fprintf(w, "//\tb%03d ", n.branchIndex)
} else {
fmt.Fprintf(w, "//\t ")
}
w.WriteString(prefix[:len(prefix)-2])
if n == nil {
fmt.Fprintf(w, "+=XXXXX\n")
return
}
if !n.isBranch() {
fmt.Fprintf(w, "+=v%04d\n", n.val)
return
}
w.WriteString("+-+\n")
}
func writeMaxCodeLength(w *bytes.Buffer, codesList ...[]code) {
maxCodeLength := 0
for _, codes := range codesList {
for _, code := range codes {
if n := len(code.str); maxCodeLength < n {
maxCodeLength = n
}
}
}
fmt.Fprintf(w, "const maxCodeLength = %d\n\n", maxCodeLength)
}
func finish(w *bytes.Buffer, filename string) {
copyPaste(w, filename)
if *debug {
os.Stdout.Write(w.Bytes())
return
}
out, err := format.Source(w.Bytes())
if err != nil {
log.Fatalf("format.Source: %v", err)
}
if err := ioutil.WriteFile(filename, out, 0660); err != nil {
log.Fatalf("ioutil.WriteFile: %v", err)
}
}
func copyPaste(w *bytes.Buffer, filename string) {
b, err := ioutil.ReadFile("gen.go")
if err != nil {
log.Fatalf("ioutil.ReadFile: %v", err)
}
begin := []byte("\n// COPY PASTE " + filename + " BEGIN\n\n")
end := []byte("\n// COPY PASTE " + filename + " END\n\n")
for len(b) > 0 {
i := bytes.Index(b, begin)
if i < 0 {
break
}
b = b[i:]
j := bytes.Index(b, end)
if j < 0 {
break
}
j += len(end)
w.Write(b[:j])
b = b[j:]
}
}
// COPY PASTE table.go BEGIN
const (
modePass = iota // Pass
modeH // Horizontal
modeV0 // Vertical-0
modeVR1 // Vertical-Right-1
modeVR2 // Vertical-Right-2
modeVR3 // Vertical-Right-3
modeVL1 // Vertical-Left-1
modeVL2 // Vertical-Left-2
modeVL3 // Vertical-Left-3
modeExt // Extension
)
// COPY PASTE table.go END
// The data that is the rest of this file is taken from Tables 1, 2 and 3 from
// the "ITU-T Recommendation T.6" spec.
// COPY PASTE table_test.go BEGIN
type code struct {
val uint32
str string
}
var modeCodes = []code{
{modePass, "0001"},
{modeH, "001"},
{modeV0, "1"},
{modeVR1, "011"},
{modeVR2, "000011"},
{modeVR3, "0000011"},
{modeVL1, "010"},
{modeVL2, "000010"},
{modeVL3, "0000010"},
{modeExt, "0000001"},
}
var whiteCodes = []code{
// Terminating codes (0-63).
{0x0000, "00110101"},
{0x0001, "000111"},
{0x0002, "0111"},
{0x0003, "1000"},
{0x0004, "1011"},
{0x0005, "1100"},
{0x0006, "1110"},
{0x0007, "1111"},
{0x0008, "10011"},
{0x0009, "10100"},
{0x000A, "00111"},
{0x000B, "01000"},
{0x000C, "001000"},
{0x000D, "000011"},
{0x000E, "110100"},
{0x000F, "110101"},
{0x0010, "101010"},
{0x0011, "101011"},
{0x0012, "0100111"},
{0x0013, "0001100"},
{0x0014, "0001000"},
{0x0015, "0010111"},
{0x0016, "0000011"},
{0x0017, "0000100"},
{0x0018, "0101000"},
{0x0019, "0101011"},
{0x001A, "0010011"},
{0x001B, "0100100"},
{0x001C, "0011000"},
{0x001D, "00000010"},
{0x001E, "00000011"},
{0x001F, "00011010"},
{0x0020, "00011011"},
{0x0021, "00010010"},
{0x0022, "00010011"},
{0x0023, "00010100"},
{0x0024, "00010101"},
{0x0025, "00010110"},
{0x0026, "00010111"},
{0x0027, "00101000"},
{0x0028, "00101001"},
{0x0029, "00101010"},
{0x002A, "00101011"},
{0x002B, "00101100"},
{0x002C, "00101101"},
{0x002D, "00000100"},
{0x002E, "00000101"},
{0x002F, "00001010"},
{0x0030, "00001011"},
{0x0031, "01010010"},
{0x0032, "01010011"},
{0x0033, "01010100"},
{0x0034, "01010101"},
{0x0035, "00100100"},
{0x0036, "00100101"},
{0x0037, "01011000"},
{0x0038, "01011001"},
{0x0039, "01011010"},
{0x003A, "01011011"},
{0x003B, "01001010"},
{0x003C, "01001011"},
{0x003D, "00110010"},
{0x003E, "00110011"},
{0x003F, "00110100"},
// Make-up codes between 64 and 1728.
{0x0040, "11011"},
{0x0080, "10010"},
{0x00C0, "010111"},
{0x0100, "0110111"},
{0x0140, "00110110"},
{0x0180, "00110111"},
{0x01C0, "01100100"},
{0x0200, "01100101"},
{0x0240, "01101000"},
{0x0280, "01100111"},
{0x02C0, "011001100"},
{0x0300, "011001101"},
{0x0340, "011010010"},
{0x0380, "011010011"},
{0x03C0, "011010100"},
{0x0400, "011010101"},
{0x0440, "011010110"},
{0x0480, "011010111"},
{0x04C0, "011011000"},
{0x0500, "011011001"},
{0x0540, "011011010"},
{0x0580, "011011011"},
{0x05C0, "010011000"},
{0x0600, "010011001"},
{0x0640, "010011010"},
{0x0680, "011000"},
{0x06C0, "010011011"},
// Make-up codes between 1792 and 2560.
{0x0700, "00000001000"},
{0x0740, "00000001100"},
{0x0780, "00000001101"},
{0x07C0, "000000010010"},
{0x0800, "000000010011"},
{0x0840, "000000010100"},
{0x0880, "000000010101"},
{0x08C0, "000000010110"},
{0x0900, "000000010111"},
{0x0940, "000000011100"},
{0x0980, "000000011101"},
{0x09C0, "000000011110"},
{0x0A00, "000000011111"},
}
var blackCodes = []code{
// Terminating codes (0-63).
{0x0000, "0000110111"},
{0x0001, "010"},
{0x0002, "11"},
{0x0003, "10"},
{0x0004, "011"},
{0x0005, "0011"},
{0x0006, "0010"},
{0x0007, "00011"},
{0x0008, "000101"},
{0x0009, "000100"},
{0x000A, "0000100"},
{0x000B, "0000101"},
{0x000C, "0000111"},
{0x000D, "00000100"},
{0x000E, "00000111"},
{0x000F, "000011000"},
{0x0010, "0000010111"},
{0x0011, "0000011000"},
{0x0012, "0000001000"},
{0x0013, "00001100111"},
{0x0014, "00001101000"},
{0x0015, "00001101100"},
{0x0016, "00000110111"},
{0x0017, "00000101000"},
{0x0018, "00000010111"},
{0x0019, "00000011000"},
{0x001A, "000011001010"},
{0x001B, "000011001011"},
{0x001C, "000011001100"},
{0x001D, "000011001101"},
{0x001E, "000001101000"},
{0x001F, "000001101001"},
{0x0020, "000001101010"},
{0x0021, "000001101011"},
{0x0022, "000011010010"},
{0x0023, "000011010011"},
{0x0024, "000011010100"},
{0x0025, "000011010101"},
{0x0026, "000011010110"},
{0x0027, "000011010111"},
{0x0028, "000001101100"},
{0x0029, "000001101101"},
{0x002A, "000011011010"},
{0x002B, "000011011011"},
{0x002C, "000001010100"},
{0x002D, "000001010101"},
{0x002E, "000001010110"},
{0x002F, "000001010111"},
{0x0030, "000001100100"},
{0x0031, "000001100101"},
{0x0032, "000001010010"},
{0x0033, "000001010011"},
{0x0034, "000000100100"},
{0x0035, "000000110111"},
{0x0036, "000000111000"},
{0x0037, "000000100111"},
{0x0038, "000000101000"},
{0x0039, "000001011000"},
{0x003A, "000001011001"},
{0x003B, "000000101011"},
{0x003C, "000000101100"},
{0x003D, "000001011010"},
{0x003E, "000001100110"},
{0x003F, "000001100111"},
// Make-up codes between 64 and 1728.
{0x0040, "0000001111"},
{0x0080, "000011001000"},
{0x00C0, "000011001001"},
{0x0100, "000001011011"},
{0x0140, "000000110011"},
{0x0180, "000000110100"},
{0x01C0, "000000110101"},
{0x0200, "0000001101100"},
{0x0240, "0000001101101"},
{0x0280, "0000001001010"},
{0x02C0, "0000001001011"},
{0x0300, "0000001001100"},
{0x0340, "0000001001101"},
{0x0380, "0000001110010"},
{0x03C0, "0000001110011"},
{0x0400, "0000001110100"},
{0x0440, "0000001110101"},
{0x0480, "0000001110110"},
{0x04C0, "0000001110111"},
{0x0500, "0000001010010"},
{0x0540, "0000001010011"},
{0x0580, "0000001010100"},
{0x05C0, "0000001010101"},
{0x0600, "0000001011010"},
{0x0640, "0000001011011"},
{0x0680, "0000001100100"},
{0x06C0, "0000001100101"},
// Make-up codes between 1792 and 2560.
{0x0700, "00000001000"},
{0x0740, "00000001100"},
{0x0780, "00000001101"},
{0x07C0, "000000010010"},
{0x0800, "000000010011"},
{0x0840, "000000010100"},
{0x0880, "000000010101"},
{0x08C0, "000000010110"},
{0x0900, "000000010111"},
{0x0940, "000000011100"},
{0x0980, "000000011101"},
{0x09C0, "000000011110"},
{0x0A00, "000000011111"},
}
// COPY PASTE table_test.go END
// This final comment makes the "END" above be followed by "\n\n".
|
vp8l | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8l/transform.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8l
// This file deals with image transforms, specified in section 3.
// nTiles returns the number of tiles needed to cover size pixels, where each
// tile's side is 1<<bits pixels long.
func nTiles(size int32, bits uint32) int32 {
return (size + 1<<bits - 1) >> bits
}
const (
transformTypePredictor = 0
transformTypeCrossColor = 1
transformTypeSubtractGreen = 2
transformTypeColorIndexing = 3
nTransformTypes = 4
)
// transform holds the parameters for an invertible transform.
type transform struct {
// transformType is the type of the transform.
transformType uint32
// oldWidth is the width of the image before transformation (or
// equivalently, after inverse transformation). The color-indexing
// transform can reduce the width. For example, a 50-pixel-wide
// image that only needs 4 bits (half a byte) per color index can
// be transformed into a 25-pixel-wide image.
oldWidth int32
// bits is the log-2 size of the transform's tiles, for the predictor
// and cross-color transforms. 8>>bits is the number of bits per
// color index, for the color-index transform.
bits uint32
// pix is the tile values, for the predictor and cross-color
// transforms, and the color palette, for the color-index transform.
pix []byte
}
var inverseTransforms = [nTransformTypes]func(*transform, []byte, int32) []byte{
transformTypePredictor: inversePredictor,
transformTypeCrossColor: inverseCrossColor,
transformTypeSubtractGreen: inverseSubtractGreen,
transformTypeColorIndexing: inverseColorIndexing,
}
func inversePredictor(t *transform, pix []byte, h int32) []byte {
if t.oldWidth == 0 || h == 0 {
return pix
}
// The first pixel's predictor is mode 0 (opaque black).
pix[3] += 0xff
p, mask := int32(4), int32(1)<<t.bits-1
for x := int32(1); x < t.oldWidth; x++ {
// The rest of the first row's predictor is mode 1 (L).
pix[p+0] += pix[p-4]
pix[p+1] += pix[p-3]
pix[p+2] += pix[p-2]
pix[p+3] += pix[p-1]
p += 4
}
top, tilesPerRow := 0, nTiles(t.oldWidth, t.bits)
for y := int32(1); y < h; y++ {
// The first column's predictor is mode 2 (T).
pix[p+0] += pix[top+0]
pix[p+1] += pix[top+1]
pix[p+2] += pix[top+2]
pix[p+3] += pix[top+3]
p, top = p+4, top+4
q := 4 * (y >> t.bits) * tilesPerRow
predictorMode := t.pix[q+1] & 0x0f
q += 4
for x := int32(1); x < t.oldWidth; x++ {
if x&mask == 0 {
predictorMode = t.pix[q+1] & 0x0f
q += 4
}
switch predictorMode {
case 0: // Opaque black.
pix[p+3] += 0xff
case 1: // L.
pix[p+0] += pix[p-4]
pix[p+1] += pix[p-3]
pix[p+2] += pix[p-2]
pix[p+3] += pix[p-1]
case 2: // T.
pix[p+0] += pix[top+0]
pix[p+1] += pix[top+1]
pix[p+2] += pix[top+2]
pix[p+3] += pix[top+3]
case 3: // TR.
pix[p+0] += pix[top+4]
pix[p+1] += pix[top+5]
pix[p+2] += pix[top+6]
pix[p+3] += pix[top+7]
case 4: // TL.
pix[p+0] += pix[top-4]
pix[p+1] += pix[top-3]
pix[p+2] += pix[top-2]
pix[p+3] += pix[top-1]
case 5: // Average2(Average2(L, TR), T).
pix[p+0] += avg2(avg2(pix[p-4], pix[top+4]), pix[top+0])
pix[p+1] += avg2(avg2(pix[p-3], pix[top+5]), pix[top+1])
pix[p+2] += avg2(avg2(pix[p-2], pix[top+6]), pix[top+2])
pix[p+3] += avg2(avg2(pix[p-1], pix[top+7]), pix[top+3])
case 6: // Average2(L, TL).
pix[p+0] += avg2(pix[p-4], pix[top-4])
pix[p+1] += avg2(pix[p-3], pix[top-3])
pix[p+2] += avg2(pix[p-2], pix[top-2])
pix[p+3] += avg2(pix[p-1], pix[top-1])
case 7: // Average2(L, T).
pix[p+0] += avg2(pix[p-4], pix[top+0])
pix[p+1] += avg2(pix[p-3], pix[top+1])
pix[p+2] += avg2(pix[p-2], pix[top+2])
pix[p+3] += avg2(pix[p-1], pix[top+3])
case 8: // Average2(TL, T).
pix[p+0] += avg2(pix[top-4], pix[top+0])
pix[p+1] += avg2(pix[top-3], pix[top+1])
pix[p+2] += avg2(pix[top-2], pix[top+2])
pix[p+3] += avg2(pix[top-1], pix[top+3])
case 9: // Average2(T, TR).
pix[p+0] += avg2(pix[top+0], pix[top+4])
pix[p+1] += avg2(pix[top+1], pix[top+5])
pix[p+2] += avg2(pix[top+2], pix[top+6])
pix[p+3] += avg2(pix[top+3], pix[top+7])
case 10: // Average2(Average2(L, TL), Average2(T, TR)).
pix[p+0] += avg2(avg2(pix[p-4], pix[top-4]), avg2(pix[top+0], pix[top+4]))
pix[p+1] += avg2(avg2(pix[p-3], pix[top-3]), avg2(pix[top+1], pix[top+5]))
pix[p+2] += avg2(avg2(pix[p-2], pix[top-2]), avg2(pix[top+2], pix[top+6]))
pix[p+3] += avg2(avg2(pix[p-1], pix[top-1]), avg2(pix[top+3], pix[top+7]))
case 11: // Select(L, T, TL).
l0 := int32(pix[p-4])
l1 := int32(pix[p-3])
l2 := int32(pix[p-2])
l3 := int32(pix[p-1])
c0 := int32(pix[top-4])
c1 := int32(pix[top-3])
c2 := int32(pix[top-2])
c3 := int32(pix[top-1])
t0 := int32(pix[top+0])
t1 := int32(pix[top+1])
t2 := int32(pix[top+2])
t3 := int32(pix[top+3])
l := abs(c0-t0) + abs(c1-t1) + abs(c2-t2) + abs(c3-t3)
t := abs(c0-l0) + abs(c1-l1) + abs(c2-l2) + abs(c3-l3)
if l < t {
pix[p+0] += uint8(l0)
pix[p+1] += uint8(l1)
pix[p+2] += uint8(l2)
pix[p+3] += uint8(l3)
} else {
pix[p+0] += uint8(t0)
pix[p+1] += uint8(t1)
pix[p+2] += uint8(t2)
pix[p+3] += uint8(t3)
}
case 12: // ClampAddSubtractFull(L, T, TL).
pix[p+0] += clampAddSubtractFull(pix[p-4], pix[top+0], pix[top-4])
pix[p+1] += clampAddSubtractFull(pix[p-3], pix[top+1], pix[top-3])
pix[p+2] += clampAddSubtractFull(pix[p-2], pix[top+2], pix[top-2])
pix[p+3] += clampAddSubtractFull(pix[p-1], pix[top+3], pix[top-1])
case 13: // ClampAddSubtractHalf(Average2(L, T), TL).
pix[p+0] += clampAddSubtractHalf(avg2(pix[p-4], pix[top+0]), pix[top-4])
pix[p+1] += clampAddSubtractHalf(avg2(pix[p-3], pix[top+1]), pix[top-3])
pix[p+2] += clampAddSubtractHalf(avg2(pix[p-2], pix[top+2]), pix[top-2])
pix[p+3] += clampAddSubtractHalf(avg2(pix[p-1], pix[top+3]), pix[top-1])
}
p, top = p+4, top+4
}
}
return pix
}
func inverseCrossColor(t *transform, pix []byte, h int32) []byte {
var greenToRed, greenToBlue, redToBlue int32
p, mask, tilesPerRow := int32(0), int32(1)<<t.bits-1, nTiles(t.oldWidth, t.bits)
for y := int32(0); y < h; y++ {
q := 4 * (y >> t.bits) * tilesPerRow
for x := int32(0); x < t.oldWidth; x++ {
if x&mask == 0 {
redToBlue = int32(int8(t.pix[q+0]))
greenToBlue = int32(int8(t.pix[q+1]))
greenToRed = int32(int8(t.pix[q+2]))
q += 4
}
red := pix[p+0]
green := pix[p+1]
blue := pix[p+2]
red += uint8(uint32(greenToRed*int32(int8(green))) >> 5)
blue += uint8(uint32(greenToBlue*int32(int8(green))) >> 5)
blue += uint8(uint32(redToBlue*int32(int8(red))) >> 5)
pix[p+0] = red
pix[p+2] = blue
p += 4
}
}
return pix
}
func inverseSubtractGreen(t *transform, pix []byte, h int32) []byte {
for p := 0; p < len(pix); p += 4 {
green := pix[p+1]
pix[p+0] += green
pix[p+2] += green
}
return pix
}
func inverseColorIndexing(t *transform, pix []byte, h int32) []byte {
if t.bits == 0 {
for p := 0; p < len(pix); p += 4 {
i := 4 * uint32(pix[p+1])
pix[p+0] = t.pix[i+0]
pix[p+1] = t.pix[i+1]
pix[p+2] = t.pix[i+2]
pix[p+3] = t.pix[i+3]
}
return pix
}
vMask, xMask, bitsPerPixel := uint32(0), int32(0), uint32(8>>t.bits)
switch t.bits {
case 1:
vMask, xMask = 0x0f, 0x01
case 2:
vMask, xMask = 0x03, 0x03
case 3:
vMask, xMask = 0x01, 0x07
}
d, p, v, dst := 0, 0, uint32(0), make([]byte, 4*t.oldWidth*h)
for y := int32(0); y < h; y++ {
for x := int32(0); x < t.oldWidth; x++ {
if x&xMask == 0 {
v = uint32(pix[p+1])
p += 4
}
i := 4 * (v & vMask)
dst[d+0] = t.pix[i+0]
dst[d+1] = t.pix[i+1]
dst[d+2] = t.pix[i+2]
dst[d+3] = t.pix[i+3]
d += 4
v >>= bitsPerPixel
}
}
return dst
}
func abs(x int32) int32 {
if x < 0 {
return -x
}
return x
}
func avg2(a, b uint8) uint8 {
return uint8((int32(a) + int32(b)) / 2)
}
func clampAddSubtractFull(a, b, c uint8) uint8 {
x := int32(a) + int32(b) - int32(c)
if x < 0 {
return 0
}
if x > 255 {
return 255
}
return uint8(x)
}
func clampAddSubtractHalf(a, b uint8) uint8 {
x := int32(a) + (int32(a)-int32(b))/2
if x < 0 {
return 0
}
if x > 255 {
return 255
}
return uint8(x)
}
|
vp8l | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8l/decode.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package vp8l implements a decoder for the VP8L lossless image format.
//
// The VP8L specification is at:
// https://developers.google.com/speed/webp/docs/riff_container
package vp8l // import "golang.org/x/image/vp8l"
import (
"bufio"
"errors"
"image"
"image/color"
"io"
)
var (
errInvalidCodeLengths = errors.New("vp8l: invalid code lengths")
errInvalidHuffmanTree = errors.New("vp8l: invalid Huffman tree")
)
// colorCacheMultiplier is the multiplier used for the color cache hash
// function, specified in section 4.2.3.
const colorCacheMultiplier = 0x1e35a7bd
// distanceMapTable is the look-up table for distanceMap.
var distanceMapTable = [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,
}
// distanceMap maps a LZ77 backwards reference distance to a two-dimensional
// pixel offset, specified in section 4.2.2.
func distanceMap(w int32, code uint32) int32 {
if int32(code) > int32(len(distanceMapTable)) {
return int32(code) - int32(len(distanceMapTable))
}
distCode := int32(distanceMapTable[code-1])
yOffset := distCode >> 4
xOffset := 8 - distCode&0xf
if d := yOffset*w + xOffset; d >= 1 {
return d
}
return 1
}
// decoder holds the bit-stream for a VP8L image.
type decoder struct {
r io.ByteReader
bits uint32
nBits uint32
}
// read reads the next n bits from the decoder's bit-stream.
func (d *decoder) read(n uint32) (uint32, error) {
for d.nBits < n {
c, err := d.r.ReadByte()
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return 0, err
}
d.bits |= uint32(c) << d.nBits
d.nBits += 8
}
u := d.bits & (1<<n - 1)
d.bits >>= n
d.nBits -= n
return u, nil
}
// decodeTransform decodes the next transform and the width of the image after
// transformation (or equivalently, before inverse transformation), specified
// in section 3.
func (d *decoder) decodeTransform(w int32, h int32) (t transform, newWidth int32, err error) {
t.oldWidth = w
t.transformType, err = d.read(2)
if err != nil {
return transform{}, 0, err
}
switch t.transformType {
case transformTypePredictor, transformTypeCrossColor:
t.bits, err = d.read(3)
if err != nil {
return transform{}, 0, err
}
t.bits += 2
t.pix, err = d.decodePix(nTiles(w, t.bits), nTiles(h, t.bits), 0, false)
if err != nil {
return transform{}, 0, err
}
case transformTypeSubtractGreen:
// No-op.
case transformTypeColorIndexing:
nColors, err := d.read(8)
if err != nil {
return transform{}, 0, err
}
nColors++
t.bits = 0
switch {
case nColors <= 2:
t.bits = 3
case nColors <= 4:
t.bits = 2
case nColors <= 16:
t.bits = 1
}
w = nTiles(w, t.bits)
pix, err := d.decodePix(int32(nColors), 1, 4*256, false)
if err != nil {
return transform{}, 0, err
}
for p := 4; p < len(pix); p += 4 {
pix[p+0] += pix[p-4]
pix[p+1] += pix[p-3]
pix[p+2] += pix[p-2]
pix[p+3] += pix[p-1]
}
// The spec says that "if the index is equal or larger than color_table_size,
// the argb color value should be set to 0x00000000 (transparent black)."
// We re-slice up to 256 4-byte pixels.
t.pix = pix[:4*256]
}
return t, w, nil
}
// repeatsCodeLength is the minimum code length for repeated codes.
const repeatsCodeLength = 16
// These magic numbers are specified at the end of section 5.2.2.
// The 3-length arrays apply to code lengths >= repeatsCodeLength.
var (
codeLengthCodeOrder = [19]uint8{
17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
}
repeatBits = [3]uint8{2, 3, 7}
repeatOffsets = [3]uint8{3, 3, 11}
)
// decodeCodeLengths decodes a Huffman tree's code lengths which are themselves
// encoded via a Huffman tree, specified in section 5.2.2.
func (d *decoder) decodeCodeLengths(dst []uint32, codeLengthCodeLengths []uint32) error {
h := hTree{}
if err := h.build(codeLengthCodeLengths); err != nil {
return err
}
maxSymbol := len(dst)
useLength, err := d.read(1)
if err != nil {
return err
}
if useLength != 0 {
n, err := d.read(3)
if err != nil {
return err
}
n = 2 + 2*n
ms, err := d.read(n)
if err != nil {
return err
}
maxSymbol = int(ms) + 2
if maxSymbol > len(dst) {
return errInvalidCodeLengths
}
}
// The spec says that "if code 16 [meaning repeat] is used before
// a non-zero value has been emitted, a value of 8 is repeated."
prevCodeLength := uint32(8)
for symbol := 0; symbol < len(dst); {
if maxSymbol == 0 {
break
}
maxSymbol--
codeLength, err := h.next(d)
if err != nil {
return err
}
if codeLength < repeatsCodeLength {
dst[symbol] = codeLength
symbol++
if codeLength != 0 {
prevCodeLength = codeLength
}
continue
}
repeat, err := d.read(uint32(repeatBits[codeLength-repeatsCodeLength]))
if err != nil {
return err
}
repeat += uint32(repeatOffsets[codeLength-repeatsCodeLength])
if symbol+int(repeat) > len(dst) {
return errInvalidCodeLengths
}
// A code length of 16 repeats the previous non-zero code.
// A code length of 17 or 18 repeats zeroes.
cl := uint32(0)
if codeLength == 16 {
cl = prevCodeLength
}
for ; repeat > 0; repeat-- {
dst[symbol] = cl
symbol++
}
}
return nil
}
// decodeHuffmanTree decodes a Huffman tree into h.
func (d *decoder) decodeHuffmanTree(h *hTree, alphabetSize uint32) error {
useSimple, err := d.read(1)
if err != nil {
return err
}
if useSimple != 0 {
nSymbols, err := d.read(1)
if err != nil {
return err
}
nSymbols++
firstSymbolLengthCode, err := d.read(1)
if err != nil {
return err
}
firstSymbolLengthCode = 7*firstSymbolLengthCode + 1
var symbols [2]uint32
symbols[0], err = d.read(firstSymbolLengthCode)
if err != nil {
return err
}
if nSymbols == 2 {
symbols[1], err = d.read(8)
if err != nil {
return err
}
}
return h.buildSimple(nSymbols, symbols, alphabetSize)
}
nCodes, err := d.read(4)
if err != nil {
return err
}
nCodes += 4
if int(nCodes) > len(codeLengthCodeOrder) {
return errInvalidHuffmanTree
}
codeLengthCodeLengths := [len(codeLengthCodeOrder)]uint32{}
for i := uint32(0); i < nCodes; i++ {
codeLengthCodeLengths[codeLengthCodeOrder[i]], err = d.read(3)
if err != nil {
return err
}
}
codeLengths := make([]uint32, alphabetSize)
if err = d.decodeCodeLengths(codeLengths, codeLengthCodeLengths[:]); err != nil {
return err
}
return h.build(codeLengths)
}
const (
huffGreen = 0
huffRed = 1
huffBlue = 2
huffAlpha = 3
huffDistance = 4
nHuff = 5
)
// hGroup is an array of 5 Huffman trees.
type hGroup [nHuff]hTree
// decodeHuffmanGroups decodes the one or more hGroups used to decode the pixel
// data. If one hGroup is used for the entire image, then hPix and hBits will
// be zero. If more than one hGroup is used, then hPix contains the meta-image
// that maps tiles to hGroup index, and hBits contains the log-2 tile size.
func (d *decoder) decodeHuffmanGroups(w int32, h int32, topLevel bool, ccBits uint32) (
hGroups []hGroup, hPix []byte, hBits uint32, err error) {
maxHGroupIndex := 0
if topLevel {
useMeta, err := d.read(1)
if err != nil {
return nil, nil, 0, err
}
if useMeta != 0 {
hBits, err = d.read(3)
if err != nil {
return nil, nil, 0, err
}
hBits += 2
hPix, err = d.decodePix(nTiles(w, hBits), nTiles(h, hBits), 0, false)
if err != nil {
return nil, nil, 0, err
}
for p := 0; p < len(hPix); p += 4 {
i := int(hPix[p])<<8 | int(hPix[p+1])
if maxHGroupIndex < i {
maxHGroupIndex = i
}
}
}
}
hGroups = make([]hGroup, maxHGroupIndex+1)
for i := range hGroups {
for j, alphabetSize := range alphabetSizes {
if j == 0 && ccBits > 0 {
alphabetSize += 1 << ccBits
}
if err := d.decodeHuffmanTree(&hGroups[i][j], alphabetSize); err != nil {
return nil, nil, 0, err
}
}
}
return hGroups, hPix, hBits, nil
}
const (
nLiteralCodes = 256
nLengthCodes = 24
nDistanceCodes = 40
)
var alphabetSizes = [nHuff]uint32{
nLiteralCodes + nLengthCodes,
nLiteralCodes,
nLiteralCodes,
nLiteralCodes,
nDistanceCodes,
}
// decodePix decodes pixel data, specified in section 5.2.2.
func (d *decoder) decodePix(w int32, h int32, minCap int32, topLevel bool) ([]byte, error) {
// Decode the color cache parameters.
ccBits, ccShift, ccEntries := uint32(0), uint32(0), ([]uint32)(nil)
useColorCache, err := d.read(1)
if err != nil {
return nil, err
}
if useColorCache != 0 {
ccBits, err = d.read(4)
if err != nil {
return nil, err
}
if ccBits < 1 || 11 < ccBits {
return nil, errors.New("vp8l: invalid color cache parameters")
}
ccShift = 32 - ccBits
ccEntries = make([]uint32, 1<<ccBits)
}
// Decode the Huffman groups.
hGroups, hPix, hBits, err := d.decodeHuffmanGroups(w, h, topLevel, ccBits)
if err != nil {
return nil, err
}
hMask, tilesPerRow := int32(0), int32(0)
if hBits != 0 {
hMask, tilesPerRow = 1<<hBits-1, nTiles(w, hBits)
}
// Decode the pixels.
if minCap < 4*w*h {
minCap = 4 * w * h
}
pix := make([]byte, 4*w*h, minCap)
p, cachedP := 0, 0
x, y := int32(0), int32(0)
hg, lookupHG := &hGroups[0], hMask != 0
for p < len(pix) {
if lookupHG {
i := 4 * (tilesPerRow*(y>>hBits) + (x >> hBits))
hg = &hGroups[uint32(hPix[i])<<8|uint32(hPix[i+1])]
}
green, err := hg[huffGreen].next(d)
if err != nil {
return nil, err
}
switch {
case green < nLiteralCodes:
// We have a literal pixel.
red, err := hg[huffRed].next(d)
if err != nil {
return nil, err
}
blue, err := hg[huffBlue].next(d)
if err != nil {
return nil, err
}
alpha, err := hg[huffAlpha].next(d)
if err != nil {
return nil, err
}
pix[p+0] = uint8(red)
pix[p+1] = uint8(green)
pix[p+2] = uint8(blue)
pix[p+3] = uint8(alpha)
p += 4
x++
if x == w {
x, y = 0, y+1
}
lookupHG = hMask != 0 && x&hMask == 0
case green < nLiteralCodes+nLengthCodes:
// We have a LZ77 backwards reference.
length, err := d.lz77Param(green - nLiteralCodes)
if err != nil {
return nil, err
}
distSym, err := hg[huffDistance].next(d)
if err != nil {
return nil, err
}
distCode, err := d.lz77Param(distSym)
if err != nil {
return nil, err
}
dist := distanceMap(w, distCode)
pEnd := p + 4*int(length)
q := p - 4*int(dist)
qEnd := pEnd - 4*int(dist)
if p < 0 || len(pix) < pEnd || q < 0 || len(pix) < qEnd {
return nil, errors.New("vp8l: invalid LZ77 parameters")
}
for ; p < pEnd; p, q = p+1, q+1 {
pix[p] = pix[q]
}
x += int32(length)
for x >= w {
x, y = x-w, y+1
}
lookupHG = hMask != 0
default:
// We have a color cache lookup. First, insert previous pixels
// into the cache. Note that VP8L assumes ARGB order, but the
// Go image.RGBA type is in RGBA order.
for ; cachedP < p; cachedP += 4 {
argb := uint32(pix[cachedP+0])<<16 |
uint32(pix[cachedP+1])<<8 |
uint32(pix[cachedP+2])<<0 |
uint32(pix[cachedP+3])<<24
ccEntries[(argb*colorCacheMultiplier)>>ccShift] = argb
}
green -= nLiteralCodes + nLengthCodes
if int(green) >= len(ccEntries) {
return nil, errors.New("vp8l: invalid color cache index")
}
argb := ccEntries[green]
pix[p+0] = uint8(argb >> 16)
pix[p+1] = uint8(argb >> 8)
pix[p+2] = uint8(argb >> 0)
pix[p+3] = uint8(argb >> 24)
p += 4
x++
if x == w {
x, y = 0, y+1
}
lookupHG = hMask != 0 && x&hMask == 0
}
}
return pix, nil
}
// lz77Param returns the next LZ77 parameter: a length or a distance, specified
// in section 4.2.2.
func (d *decoder) lz77Param(symbol uint32) (uint32, error) {
if symbol < 4 {
return symbol + 1, nil
}
extraBits := (symbol - 2) >> 1
offset := (2 + symbol&1) << extraBits
n, err := d.read(extraBits)
if err != nil {
return 0, err
}
return offset + n + 1, nil
}
// decodeHeader decodes the VP8L header from r.
func decodeHeader(r io.Reader) (d *decoder, w int32, h int32, err error) {
rr, ok := r.(io.ByteReader)
if !ok {
rr = bufio.NewReader(r)
}
d = &decoder{r: rr}
magic, err := d.read(8)
if err != nil {
return nil, 0, 0, err
}
if magic != 0x2f {
return nil, 0, 0, errors.New("vp8l: invalid header")
}
width, err := d.read(14)
if err != nil {
return nil, 0, 0, err
}
width++
height, err := d.read(14)
if err != nil {
return nil, 0, 0, err
}
height++
_, err = d.read(1) // Read and ignore the hasAlpha hint.
if err != nil {
return nil, 0, 0, err
}
version, err := d.read(3)
if err != nil {
return nil, 0, 0, err
}
if version != 0 {
return nil, 0, 0, errors.New("vp8l: invalid version")
}
return d, int32(width), int32(height), nil
}
// DecodeConfig decodes the color model and dimensions of a VP8L image from r.
func DecodeConfig(r io.Reader) (image.Config, error) {
_, w, h, err := decodeHeader(r)
if err != nil {
return image.Config{}, err
}
return image.Config{
ColorModel: color.NRGBAModel,
Width: int(w),
Height: int(h),
}, nil
}
// Decode decodes a VP8L image from r.
func Decode(r io.Reader) (image.Image, error) {
d, w, h, err := decodeHeader(r)
if err != nil {
return nil, err
}
// Decode the transforms.
var (
nTransforms int
transforms [nTransformTypes]transform
transformsSeen [nTransformTypes]bool
originalW = w
)
for {
more, err := d.read(1)
if err != nil {
return nil, err
}
if more == 0 {
break
}
var t transform
t, w, err = d.decodeTransform(w, h)
if err != nil {
return nil, err
}
if transformsSeen[t.transformType] {
return nil, errors.New("vp8l: repeated transform")
}
transformsSeen[t.transformType] = true
transforms[nTransforms] = t
nTransforms++
}
// Decode the transformed pixels.
pix, err := d.decodePix(w, h, 0, true)
if err != nil {
return nil, err
}
// Apply the inverse transformations.
for i := nTransforms - 1; i >= 0; i-- {
t := &transforms[i]
pix = inverseTransforms[t.transformType](t, pix, h)
}
return &image.NRGBA{
Pix: pix,
Stride: 4 * int(originalW),
Rect: image.Rect(0, 0, int(originalW), int(h)),
}, nil
}
|
vp8l | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8l/huffman.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8l
import (
"io"
)
// reverseBits reverses the bits in a byte.
var reverseBits = [256]uint8{
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
}
// hNode is a node in a Huffman tree.
type hNode struct {
// symbol is the symbol held by this node.
symbol uint32
// children, if positive, is the hTree.nodes index of the first of
// this node's two children. Zero means an uninitialized node,
// and -1 means a leaf node.
children int32
}
const leafNode = -1
// lutSize is the log-2 size of an hTree's look-up table.
const lutSize, lutMask = 7, 1<<7 - 1
// hTree is a Huffman tree.
type hTree struct {
// nodes are the nodes of the Huffman tree. During construction,
// len(nodes) grows from 1 up to cap(nodes) by steps of two.
// After construction, len(nodes) == cap(nodes), and both equal
// 2*theNumberOfSymbols - 1.
nodes []hNode
// lut is a look-up table for walking the nodes. The x in lut[x] is
// the next lutSize bits in the bit-stream. The low 8 bits of lut[x]
// equals 1 plus the number of bits in the next code, or 0 if the
// next code requires more than lutSize bits. The high 24 bits are:
// - the symbol, if the code requires lutSize or fewer bits, or
// - the hTree.nodes index to start the tree traversal from, if
// the next code requires more than lutSize bits.
lut [1 << lutSize]uint32
}
// insert inserts into the hTree a symbol whose encoding is the least
// significant codeLength bits of code.
func (h *hTree) insert(symbol uint32, code uint32, codeLength uint32) error {
if symbol > 0xffff || codeLength > 0xfe {
return errInvalidHuffmanTree
}
baseCode := uint32(0)
if codeLength > lutSize {
baseCode = uint32(reverseBits[(code>>(codeLength-lutSize))&0xff]) >> (8 - lutSize)
} else {
baseCode = uint32(reverseBits[code&0xff]) >> (8 - codeLength)
for i := 0; i < 1<<(lutSize-codeLength); i++ {
h.lut[baseCode|uint32(i)<<codeLength] = symbol<<8 | (codeLength + 1)
}
}
n := uint32(0)
for jump := lutSize; codeLength > 0; {
codeLength--
if int(n) > len(h.nodes) {
return errInvalidHuffmanTree
}
switch h.nodes[n].children {
case leafNode:
return errInvalidHuffmanTree
case 0:
if len(h.nodes) == cap(h.nodes) {
return errInvalidHuffmanTree
}
// Create two empty child nodes.
h.nodes[n].children = int32(len(h.nodes))
h.nodes = h.nodes[:len(h.nodes)+2]
}
n = uint32(h.nodes[n].children) + 1&(code>>codeLength)
jump--
if jump == 0 && h.lut[baseCode] == 0 {
h.lut[baseCode] = n << 8
}
}
switch h.nodes[n].children {
case leafNode:
// No-op.
case 0:
// Turn the uninitialized node into a leaf.
h.nodes[n].children = leafNode
default:
return errInvalidHuffmanTree
}
h.nodes[n].symbol = symbol
return nil
}
// codeLengthsToCodes returns the canonical Huffman codes implied by the
// sequence of code lengths.
func codeLengthsToCodes(codeLengths []uint32) ([]uint32, error) {
maxCodeLength := uint32(0)
for _, cl := range codeLengths {
if maxCodeLength < cl {
maxCodeLength = cl
}
}
const maxAllowedCodeLength = 15
if len(codeLengths) == 0 || maxCodeLength > maxAllowedCodeLength {
return nil, errInvalidHuffmanTree
}
histogram := [maxAllowedCodeLength + 1]uint32{}
for _, cl := range codeLengths {
histogram[cl]++
}
currCode, nextCodes := uint32(0), [maxAllowedCodeLength + 1]uint32{}
for cl := 1; cl < len(nextCodes); cl++ {
currCode = (currCode + histogram[cl-1]) << 1
nextCodes[cl] = currCode
}
codes := make([]uint32, len(codeLengths))
for symbol, cl := range codeLengths {
if cl > 0 {
codes[symbol] = nextCodes[cl]
nextCodes[cl]++
}
}
return codes, nil
}
// build builds a canonical Huffman tree from the given code lengths.
func (h *hTree) build(codeLengths []uint32) error {
// Calculate the number of symbols.
var nSymbols, lastSymbol uint32
for symbol, cl := range codeLengths {
if cl != 0 {
nSymbols++
lastSymbol = uint32(symbol)
}
}
if nSymbols == 0 {
return errInvalidHuffmanTree
}
h.nodes = make([]hNode, 1, 2*nSymbols-1)
// Handle the trivial case.
if nSymbols == 1 {
if len(codeLengths) <= int(lastSymbol) {
return errInvalidHuffmanTree
}
return h.insert(lastSymbol, 0, 0)
}
// Handle the non-trivial case.
codes, err := codeLengthsToCodes(codeLengths)
if err != nil {
return err
}
for symbol, cl := range codeLengths {
if cl > 0 {
if err := h.insert(uint32(symbol), codes[symbol], cl); err != nil {
return err
}
}
}
return nil
}
// buildSimple builds a Huffman tree with 1 or 2 symbols.
func (h *hTree) buildSimple(nSymbols uint32, symbols [2]uint32, alphabetSize uint32) error {
h.nodes = make([]hNode, 1, 2*nSymbols-1)
for i := uint32(0); i < nSymbols; i++ {
if symbols[i] >= alphabetSize {
return errInvalidHuffmanTree
}
if err := h.insert(symbols[i], i, nSymbols-1); err != nil {
return err
}
}
return nil
}
// next returns the next Huffman-encoded symbol from the bit-stream d.
func (h *hTree) next(d *decoder) (uint32, error) {
var n uint32
// Read enough bits so that we can use the look-up table.
if d.nBits < lutSize {
c, err := d.r.ReadByte()
if err != nil {
if err == io.EOF {
// There are no more bytes of data, but we may still be able
// to read the next symbol out of the previously read bits.
goto slowPath
}
return 0, err
}
d.bits |= uint32(c) << d.nBits
d.nBits += 8
}
// Use the look-up table.
n = h.lut[d.bits&lutMask]
if b := n & 0xff; b != 0 {
b--
d.bits >>= b
d.nBits -= b
return n >> 8, nil
}
n >>= 8
d.bits >>= lutSize
d.nBits -= lutSize
slowPath:
for h.nodes[n].children != leafNode {
if d.nBits == 0 {
c, err := d.r.ReadByte()
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return 0, err
}
d.bits = uint32(c)
d.nBits = 8
}
n = uint32(h.nodes[n].children) + 1&d.bits
d.bits >>= 1
d.nBits--
}
return h.nodes[n].symbol, nil
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/filter.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// filter2 modifies a 2-pixel wide or 2-pixel high band along an edge.
func filter2(pix []byte, level, index, iStep, jStep int) {
for n := 16; n > 0; n, index = n-1, index+iStep {
p1 := int(pix[index-2*jStep])
p0 := int(pix[index-1*jStep])
q0 := int(pix[index+0*jStep])
q1 := int(pix[index+1*jStep])
if abs(p0-q0)<<1+abs(p1-q1)>>1 > level {
continue
}
a := 3*(q0-p0) + clamp127(p1-q1)
a1 := clamp15((a + 4) >> 3)
a2 := clamp15((a + 3) >> 3)
pix[index-1*jStep] = clamp255(p0 + a2)
pix[index+0*jStep] = clamp255(q0 - a1)
}
}
// filter246 modifies a 2-, 4- or 6-pixel wide or high band along an edge.
func filter246(pix []byte, n, level, ilevel, hlevel, index, iStep, jStep int, fourNotSix bool) {
for ; n > 0; n, index = n-1, index+iStep {
p3 := int(pix[index-4*jStep])
p2 := int(pix[index-3*jStep])
p1 := int(pix[index-2*jStep])
p0 := int(pix[index-1*jStep])
q0 := int(pix[index+0*jStep])
q1 := int(pix[index+1*jStep])
q2 := int(pix[index+2*jStep])
q3 := int(pix[index+3*jStep])
if abs(p0-q0)<<1+abs(p1-q1)>>1 > level {
continue
}
if abs(p3-p2) > ilevel ||
abs(p2-p1) > ilevel ||
abs(p1-p0) > ilevel ||
abs(q1-q0) > ilevel ||
abs(q2-q1) > ilevel ||
abs(q3-q2) > ilevel {
continue
}
if abs(p1-p0) > hlevel || abs(q1-q0) > hlevel {
// Filter 2 pixels.
a := 3*(q0-p0) + clamp127(p1-q1)
a1 := clamp15((a + 4) >> 3)
a2 := clamp15((a + 3) >> 3)
pix[index-1*jStep] = clamp255(p0 + a2)
pix[index+0*jStep] = clamp255(q0 - a1)
} else if fourNotSix {
// Filter 4 pixels.
a := 3 * (q0 - p0)
a1 := clamp15((a + 4) >> 3)
a2 := clamp15((a + 3) >> 3)
a3 := (a1 + 1) >> 1
pix[index-2*jStep] = clamp255(p1 + a3)
pix[index-1*jStep] = clamp255(p0 + a2)
pix[index+0*jStep] = clamp255(q0 - a1)
pix[index+1*jStep] = clamp255(q1 - a3)
} else {
// Filter 6 pixels.
a := clamp127(3*(q0-p0) + clamp127(p1-q1))
a1 := (27*a + 63) >> 7
a2 := (18*a + 63) >> 7
a3 := (9*a + 63) >> 7
pix[index-3*jStep] = clamp255(p2 + a3)
pix[index-2*jStep] = clamp255(p1 + a2)
pix[index-1*jStep] = clamp255(p0 + a1)
pix[index+0*jStep] = clamp255(q0 - a1)
pix[index+1*jStep] = clamp255(q1 - a2)
pix[index+2*jStep] = clamp255(q2 - a3)
}
}
}
// simpleFilter implements the simple filter, as specified in section 15.2.
func (d *Decoder) simpleFilter() {
for mby := 0; mby < d.mbh; mby++ {
for mbx := 0; mbx < d.mbw; mbx++ {
f := d.perMBFilterParams[d.mbw*mby+mbx]
if f.level == 0 {
continue
}
l := int(f.level)
yIndex := (mby*d.img.YStride + mbx) * 16
if mbx > 0 {
filter2(d.img.Y, l+4, yIndex, d.img.YStride, 1)
}
if f.inner {
filter2(d.img.Y, l, yIndex+0x4, d.img.YStride, 1)
filter2(d.img.Y, l, yIndex+0x8, d.img.YStride, 1)
filter2(d.img.Y, l, yIndex+0xc, d.img.YStride, 1)
}
if mby > 0 {
filter2(d.img.Y, l+4, yIndex, 1, d.img.YStride)
}
if f.inner {
filter2(d.img.Y, l, yIndex+d.img.YStride*0x4, 1, d.img.YStride)
filter2(d.img.Y, l, yIndex+d.img.YStride*0x8, 1, d.img.YStride)
filter2(d.img.Y, l, yIndex+d.img.YStride*0xc, 1, d.img.YStride)
}
}
}
}
// normalFilter implements the normal filter, as specified in section 15.3.
func (d *Decoder) normalFilter() {
for mby := 0; mby < d.mbh; mby++ {
for mbx := 0; mbx < d.mbw; mbx++ {
f := d.perMBFilterParams[d.mbw*mby+mbx]
if f.level == 0 {
continue
}
l, il, hl := int(f.level), int(f.ilevel), int(f.hlevel)
yIndex := (mby*d.img.YStride + mbx) * 16
cIndex := (mby*d.img.CStride + mbx) * 8
if mbx > 0 {
filter246(d.img.Y, 16, l+4, il, hl, yIndex, d.img.YStride, 1, false)
filter246(d.img.Cb, 8, l+4, il, hl, cIndex, d.img.CStride, 1, false)
filter246(d.img.Cr, 8, l+4, il, hl, cIndex, d.img.CStride, 1, false)
}
if f.inner {
filter246(d.img.Y, 16, l, il, hl, yIndex+0x4, d.img.YStride, 1, true)
filter246(d.img.Y, 16, l, il, hl, yIndex+0x8, d.img.YStride, 1, true)
filter246(d.img.Y, 16, l, il, hl, yIndex+0xc, d.img.YStride, 1, true)
filter246(d.img.Cb, 8, l, il, hl, cIndex+0x4, d.img.CStride, 1, true)
filter246(d.img.Cr, 8, l, il, hl, cIndex+0x4, d.img.CStride, 1, true)
}
if mby > 0 {
filter246(d.img.Y, 16, l+4, il, hl, yIndex, 1, d.img.YStride, false)
filter246(d.img.Cb, 8, l+4, il, hl, cIndex, 1, d.img.CStride, false)
filter246(d.img.Cr, 8, l+4, il, hl, cIndex, 1, d.img.CStride, false)
}
if f.inner {
filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0x4, 1, d.img.YStride, true)
filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0x8, 1, d.img.YStride, true)
filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0xc, 1, d.img.YStride, true)
filter246(d.img.Cb, 8, l, il, hl, cIndex+d.img.CStride*0x4, 1, d.img.CStride, true)
filter246(d.img.Cr, 8, l, il, hl, cIndex+d.img.CStride*0x4, 1, d.img.CStride, true)
}
}
}
}
// filterParam holds the loop filter parameters for a macroblock.
type filterParam struct {
// The first three fields are thresholds used by the loop filter to smooth
// over the edges and interior of a macroblock. level is used by both the
// simple and normal filters. The inner level and high edge variance level
// are only used by the normal filter.
level, ilevel, hlevel uint8
// inner is whether the inner loop filter cannot be optimized out as a
// no-op for this particular macroblock.
inner bool
}
// computeFilterParams computes the loop filter parameters, as specified in
// section 15.4.
func (d *Decoder) computeFilterParams() {
for i := range d.filterParams {
baseLevel := d.filterHeader.level
if d.segmentHeader.useSegment {
baseLevel = d.segmentHeader.filterStrength[i]
if d.segmentHeader.relativeDelta {
baseLevel += d.filterHeader.level
}
}
for j := range d.filterParams[i] {
p := &d.filterParams[i][j]
p.inner = j != 0
level := baseLevel
if d.filterHeader.useLFDelta {
// The libwebp C code has a "TODO: only CURRENT is handled for now."
level += d.filterHeader.refLFDelta[0]
if j != 0 {
level += d.filterHeader.modeLFDelta[0]
}
}
if level <= 0 {
p.level = 0
continue
}
if level > 63 {
level = 63
}
ilevel := level
if d.filterHeader.sharpness > 0 {
if d.filterHeader.sharpness > 4 {
ilevel >>= 2
} else {
ilevel >>= 1
}
if x := int8(9 - d.filterHeader.sharpness); ilevel > x {
ilevel = x
}
}
if ilevel < 1 {
ilevel = 1
}
p.ilevel = uint8(ilevel)
p.level = uint8(2*level + ilevel)
if d.frameHeader.KeyFrame {
if level < 15 {
p.hlevel = 0
} else if level < 40 {
p.hlevel = 1
} else {
p.hlevel = 2
}
} else {
if level < 15 {
p.hlevel = 0
} else if level < 20 {
p.hlevel = 1
} else if level < 40 {
p.hlevel = 2
} else {
p.hlevel = 3
}
}
}
}
}
// intSize is either 32 or 64.
const intSize = 32 << (^uint(0) >> 63)
func abs(x int) int {
// m := -1 if x < 0. m := 0 otherwise.
m := x >> (intSize - 1)
// In two's complement representation, the negative number
// of any number (except the smallest one) can be computed
// by flipping all the bits and add 1. This is faster than
// code with a branch.
// See Hacker's Delight, section 2-4.
return (x ^ m) - m
}
func clamp15(x int) int {
if x < -16 {
return -16
}
if x > 15 {
return 15
}
return x
}
func clamp127(x int) int {
if x < -128 {
return -128
}
if x > 127 {
return 127
}
return x
}
func clamp255(x int) uint8 {
if x < 0 {
return 0
}
if x > 255 {
return 255
}
return uint8(x)
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/pred.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// This file implements parsing the predictor modes, as specified in chapter
// 11.
func (d *Decoder) parsePredModeY16(mbx int) {
var p uint8
if !d.fp.readBit(156) {
if !d.fp.readBit(163) {
p = predDC
} else {
p = predVE
}
} else if !d.fp.readBit(128) {
p = predHE
} else {
p = predTM
}
for i := 0; i < 4; i++ {
d.upMB[mbx].pred[i] = p
d.leftMB.pred[i] = p
}
d.predY16 = p
}
func (d *Decoder) parsePredModeC8() {
if !d.fp.readBit(142) {
d.predC8 = predDC
} else if !d.fp.readBit(114) {
d.predC8 = predVE
} else if !d.fp.readBit(183) {
d.predC8 = predHE
} else {
d.predC8 = predTM
}
}
func (d *Decoder) parsePredModeY4(mbx int) {
for j := 0; j < 4; j++ {
p := d.leftMB.pred[j]
for i := 0; i < 4; i++ {
prob := &predProb[d.upMB[mbx].pred[i]][p]
if !d.fp.readBit(prob[0]) {
p = predDC
} else if !d.fp.readBit(prob[1]) {
p = predTM
} else if !d.fp.readBit(prob[2]) {
p = predVE
} else if !d.fp.readBit(prob[3]) {
if !d.fp.readBit(prob[4]) {
p = predHE
} else if !d.fp.readBit(prob[5]) {
p = predRD
} else {
p = predVR
}
} else if !d.fp.readBit(prob[6]) {
p = predLD
} else if !d.fp.readBit(prob[7]) {
p = predVL
} else if !d.fp.readBit(prob[8]) {
p = predHD
} else {
p = predHU
}
d.predY4[j][i] = p
d.upMB[mbx].pred[i] = p
}
d.leftMB.pred[j] = p
}
}
// predProb are the probabilities to decode a 4x4 region's predictor mode given
// the predictor modes of the regions above and left of it.
// These values are specified in section 11.5.
var predProb = [nPred][nPred][9]uint8{
{
{231, 120, 48, 89, 115, 113, 120, 152, 112},
{152, 179, 64, 126, 170, 118, 46, 70, 95},
{175, 69, 143, 80, 85, 82, 72, 155, 103},
{56, 58, 10, 171, 218, 189, 17, 13, 152},
{114, 26, 17, 163, 44, 195, 21, 10, 173},
{121, 24, 80, 195, 26, 62, 44, 64, 85},
{144, 71, 10, 38, 171, 213, 144, 34, 26},
{170, 46, 55, 19, 136, 160, 33, 206, 71},
{63, 20, 8, 114, 114, 208, 12, 9, 226},
{81, 40, 11, 96, 182, 84, 29, 16, 36},
},
{
{134, 183, 89, 137, 98, 101, 106, 165, 148},
{72, 187, 100, 130, 157, 111, 32, 75, 80},
{66, 102, 167, 99, 74, 62, 40, 234, 128},
{41, 53, 9, 178, 241, 141, 26, 8, 107},
{74, 43, 26, 146, 73, 166, 49, 23, 157},
{65, 38, 105, 160, 51, 52, 31, 115, 128},
{104, 79, 12, 27, 217, 255, 87, 17, 7},
{87, 68, 71, 44, 114, 51, 15, 186, 23},
{47, 41, 14, 110, 182, 183, 21, 17, 194},
{66, 45, 25, 102, 197, 189, 23, 18, 22},
},
{
{88, 88, 147, 150, 42, 46, 45, 196, 205},
{43, 97, 183, 117, 85, 38, 35, 179, 61},
{39, 53, 200, 87, 26, 21, 43, 232, 171},
{56, 34, 51, 104, 114, 102, 29, 93, 77},
{39, 28, 85, 171, 58, 165, 90, 98, 64},
{34, 22, 116, 206, 23, 34, 43, 166, 73},
{107, 54, 32, 26, 51, 1, 81, 43, 31},
{68, 25, 106, 22, 64, 171, 36, 225, 114},
{34, 19, 21, 102, 132, 188, 16, 76, 124},
{62, 18, 78, 95, 85, 57, 50, 48, 51},
},
{
{193, 101, 35, 159, 215, 111, 89, 46, 111},
{60, 148, 31, 172, 219, 228, 21, 18, 111},
{112, 113, 77, 85, 179, 255, 38, 120, 114},
{40, 42, 1, 196, 245, 209, 10, 25, 109},
{88, 43, 29, 140, 166, 213, 37, 43, 154},
{61, 63, 30, 155, 67, 45, 68, 1, 209},
{100, 80, 8, 43, 154, 1, 51, 26, 71},
{142, 78, 78, 16, 255, 128, 34, 197, 171},
{41, 40, 5, 102, 211, 183, 4, 1, 221},
{51, 50, 17, 168, 209, 192, 23, 25, 82},
},
{
{138, 31, 36, 171, 27, 166, 38, 44, 229},
{67, 87, 58, 169, 82, 115, 26, 59, 179},
{63, 59, 90, 180, 59, 166, 93, 73, 154},
{40, 40, 21, 116, 143, 209, 34, 39, 175},
{47, 15, 16, 183, 34, 223, 49, 45, 183},
{46, 17, 33, 183, 6, 98, 15, 32, 183},
{57, 46, 22, 24, 128, 1, 54, 17, 37},
{65, 32, 73, 115, 28, 128, 23, 128, 205},
{40, 3, 9, 115, 51, 192, 18, 6, 223},
{87, 37, 9, 115, 59, 77, 64, 21, 47},
},
{
{104, 55, 44, 218, 9, 54, 53, 130, 226},
{64, 90, 70, 205, 40, 41, 23, 26, 57},
{54, 57, 112, 184, 5, 41, 38, 166, 213},
{30, 34, 26, 133, 152, 116, 10, 32, 134},
{39, 19, 53, 221, 26, 114, 32, 73, 255},
{31, 9, 65, 234, 2, 15, 1, 118, 73},
{75, 32, 12, 51, 192, 255, 160, 43, 51},
{88, 31, 35, 67, 102, 85, 55, 186, 85},
{56, 21, 23, 111, 59, 205, 45, 37, 192},
{55, 38, 70, 124, 73, 102, 1, 34, 98},
},
{
{125, 98, 42, 88, 104, 85, 117, 175, 82},
{95, 84, 53, 89, 128, 100, 113, 101, 45},
{75, 79, 123, 47, 51, 128, 81, 171, 1},
{57, 17, 5, 71, 102, 57, 53, 41, 49},
{38, 33, 13, 121, 57, 73, 26, 1, 85},
{41, 10, 67, 138, 77, 110, 90, 47, 114},
{115, 21, 2, 10, 102, 255, 166, 23, 6},
{101, 29, 16, 10, 85, 128, 101, 196, 26},
{57, 18, 10, 102, 102, 213, 34, 20, 43},
{117, 20, 15, 36, 163, 128, 68, 1, 26},
},
{
{102, 61, 71, 37, 34, 53, 31, 243, 192},
{69, 60, 71, 38, 73, 119, 28, 222, 37},
{68, 45, 128, 34, 1, 47, 11, 245, 171},
{62, 17, 19, 70, 146, 85, 55, 62, 70},
{37, 43, 37, 154, 100, 163, 85, 160, 1},
{63, 9, 92, 136, 28, 64, 32, 201, 85},
{75, 15, 9, 9, 64, 255, 184, 119, 16},
{86, 6, 28, 5, 64, 255, 25, 248, 1},
{56, 8, 17, 132, 137, 255, 55, 116, 128},
{58, 15, 20, 82, 135, 57, 26, 121, 40},
},
{
{164, 50, 31, 137, 154, 133, 25, 35, 218},
{51, 103, 44, 131, 131, 123, 31, 6, 158},
{86, 40, 64, 135, 148, 224, 45, 183, 128},
{22, 26, 17, 131, 240, 154, 14, 1, 209},
{45, 16, 21, 91, 64, 222, 7, 1, 197},
{56, 21, 39, 155, 60, 138, 23, 102, 213},
{83, 12, 13, 54, 192, 255, 68, 47, 28},
{85, 26, 85, 85, 128, 128, 32, 146, 171},
{18, 11, 7, 63, 144, 171, 4, 4, 246},
{35, 27, 10, 146, 174, 171, 12, 26, 128},
},
{
{190, 80, 35, 99, 180, 80, 126, 54, 45},
{85, 126, 47, 87, 176, 51, 41, 20, 32},
{101, 75, 128, 139, 118, 146, 116, 128, 85},
{56, 41, 15, 176, 236, 85, 37, 9, 62},
{71, 30, 17, 119, 118, 255, 17, 18, 138},
{101, 38, 60, 138, 55, 70, 43, 26, 142},
{146, 36, 19, 30, 171, 255, 97, 27, 20},
{138, 45, 61, 62, 219, 1, 81, 188, 64},
{32, 41, 20, 117, 151, 142, 20, 21, 163},
{112, 19, 12, 61, 195, 128, 48, 4, 24},
},
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/decode.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package vp8 implements a decoder for the VP8 lossy image format.
//
// The VP8 specification is RFC 6386.
package vp8 // import "golang.org/x/image/vp8"
// This file implements the top-level decoding algorithm.
import (
"errors"
"image"
"io"
)
// limitReader wraps an io.Reader to read at most n bytes from it.
type limitReader struct {
r io.Reader
n int
}
// ReadFull reads exactly len(p) bytes into p.
func (r *limitReader) ReadFull(p []byte) error {
if len(p) > r.n {
return io.ErrUnexpectedEOF
}
n, err := io.ReadFull(r.r, p)
r.n -= n
return err
}
// FrameHeader is a frame header, as specified in section 9.1.
type FrameHeader struct {
KeyFrame bool
VersionNumber uint8
ShowFrame bool
FirstPartitionLen uint32
Width int
Height int
XScale uint8
YScale uint8
}
const (
nSegment = 4
nSegmentProb = 3
)
// segmentHeader holds segment-related header information.
type segmentHeader struct {
useSegment bool
updateMap bool
relativeDelta bool
quantizer [nSegment]int8
filterStrength [nSegment]int8
prob [nSegmentProb]uint8
}
const (
nRefLFDelta = 4
nModeLFDelta = 4
)
// filterHeader holds filter-related header information.
type filterHeader struct {
simple bool
level int8
sharpness uint8
useLFDelta bool
refLFDelta [nRefLFDelta]int8
modeLFDelta [nModeLFDelta]int8
perSegmentLevel [nSegment]int8
}
// mb is the per-macroblock decode state. A decoder maintains mbw+1 of these
// as it is decoding macroblocks left-to-right and top-to-bottom: mbw for the
// macroblocks in the row above, and one for the macroblock to the left.
type mb struct {
// pred is the predictor mode for the 4 bottom or right 4x4 luma regions.
pred [4]uint8
// nzMask is a mask of 8 bits: 4 for the bottom or right 4x4 luma regions,
// and 2 + 2 for the bottom or right 4x4 chroma regions. A 1 bit indicates
// that region has non-zero coefficients.
nzMask uint8
// nzY16 is a 0/1 value that is 1 if the macroblock used Y16 prediction and
// had non-zero coefficients.
nzY16 uint8
}
// Decoder decodes VP8 bitstreams into frames. Decoding one frame consists of
// calling Init, DecodeFrameHeader and then DecodeFrame in that order.
// A Decoder can be re-used to decode multiple frames.
type Decoder struct {
// r is the input bitsream.
r limitReader
// scratch is a scratch buffer.
scratch [8]byte
// img is the YCbCr image to decode into.
img *image.YCbCr
// mbw and mbh are the number of 16x16 macroblocks wide and high the image is.
mbw, mbh int
// frameHeader is the frame header. When decoding multiple frames,
// frames that aren't key frames will inherit the Width, Height,
// XScale and YScale of the most recent key frame.
frameHeader FrameHeader
// Other headers.
segmentHeader segmentHeader
filterHeader filterHeader
// The image data is divided into a number of independent partitions.
// There is 1 "first partition" and between 1 and 8 "other partitions"
// for coefficient data.
fp partition
op [8]partition
nOP int
// Quantization factors.
quant [nSegment]quant
// DCT/WHT coefficient decoding probabilities.
tokenProb [nPlane][nBand][nContext][nProb]uint8
useSkipProb bool
skipProb uint8
// Loop filter parameters.
filterParams [nSegment][2]filterParam
perMBFilterParams []filterParam
// The eight fields below relate to the current macroblock being decoded.
//
// Segment-based adjustments.
segment int
// Per-macroblock state for the macroblock immediately left of and those
// macroblocks immediately above the current macroblock.
leftMB mb
upMB []mb
// Bitmasks for which 4x4 regions of coeff contain non-zero coefficients.
nzDCMask, nzACMask uint32
// Predictor modes.
usePredY16 bool // The libwebp C code calls this !is_i4x4_.
predY16 uint8
predC8 uint8
predY4 [4][4]uint8
// The two fields below form a workspace for reconstructing a macroblock.
// Their specific sizes are documented in reconstruct.go.
coeff [1*16*16 + 2*8*8 + 1*4*4]int16
ybr [1 + 16 + 1 + 8][32]uint8
}
// NewDecoder returns a new Decoder.
func NewDecoder() *Decoder {
return &Decoder{}
}
// Init initializes the decoder to read at most n bytes from r.
func (d *Decoder) Init(r io.Reader, n int) {
d.r = limitReader{r, n}
}
// DecodeFrameHeader decodes the frame header.
func (d *Decoder) DecodeFrameHeader() (fh FrameHeader, err error) {
// All frame headers are at least 3 bytes long.
b := d.scratch[:3]
if err = d.r.ReadFull(b); err != nil {
return
}
d.frameHeader.KeyFrame = (b[0] & 1) == 0
d.frameHeader.VersionNumber = (b[0] >> 1) & 7
d.frameHeader.ShowFrame = (b[0]>>4)&1 == 1
d.frameHeader.FirstPartitionLen = uint32(b[0])>>5 | uint32(b[1])<<3 | uint32(b[2])<<11
if !d.frameHeader.KeyFrame {
return d.frameHeader, nil
}
// Frame headers for key frames are an additional 7 bytes long.
b = d.scratch[:7]
if err = d.r.ReadFull(b); err != nil {
return
}
// Check the magic sync code.
if b[0] != 0x9d || b[1] != 0x01 || b[2] != 0x2a {
err = errors.New("vp8: invalid format")
return
}
d.frameHeader.Width = int(b[4]&0x3f)<<8 | int(b[3])
d.frameHeader.Height = int(b[6]&0x3f)<<8 | int(b[5])
d.frameHeader.XScale = b[4] >> 6
d.frameHeader.YScale = b[6] >> 6
d.mbw = (d.frameHeader.Width + 0x0f) >> 4
d.mbh = (d.frameHeader.Height + 0x0f) >> 4
d.segmentHeader = segmentHeader{
prob: [3]uint8{0xff, 0xff, 0xff},
}
d.tokenProb = defaultTokenProb
d.segment = 0
return d.frameHeader, nil
}
// ensureImg ensures that d.img is large enough to hold the decoded frame.
func (d *Decoder) ensureImg() {
if d.img != nil {
p0, p1 := d.img.Rect.Min, d.img.Rect.Max
if p0.X == 0 && p0.Y == 0 && p1.X >= 16*d.mbw && p1.Y >= 16*d.mbh {
return
}
}
m := image.NewYCbCr(image.Rect(0, 0, 16*d.mbw, 16*d.mbh), image.YCbCrSubsampleRatio420)
d.img = m.SubImage(image.Rect(0, 0, d.frameHeader.Width, d.frameHeader.Height)).(*image.YCbCr)
d.perMBFilterParams = make([]filterParam, d.mbw*d.mbh)
d.upMB = make([]mb, d.mbw)
}
// parseSegmentHeader parses the segment header, as specified in section 9.3.
func (d *Decoder) parseSegmentHeader() {
d.segmentHeader.useSegment = d.fp.readBit(uniformProb)
if !d.segmentHeader.useSegment {
d.segmentHeader.updateMap = false
return
}
d.segmentHeader.updateMap = d.fp.readBit(uniformProb)
if d.fp.readBit(uniformProb) {
d.segmentHeader.relativeDelta = !d.fp.readBit(uniformProb)
for i := range d.segmentHeader.quantizer {
d.segmentHeader.quantizer[i] = int8(d.fp.readOptionalInt(uniformProb, 7))
}
for i := range d.segmentHeader.filterStrength {
d.segmentHeader.filterStrength[i] = int8(d.fp.readOptionalInt(uniformProb, 6))
}
}
if !d.segmentHeader.updateMap {
return
}
for i := range d.segmentHeader.prob {
if d.fp.readBit(uniformProb) {
d.segmentHeader.prob[i] = uint8(d.fp.readUint(uniformProb, 8))
} else {
d.segmentHeader.prob[i] = 0xff
}
}
}
// parseFilterHeader parses the filter header, as specified in section 9.4.
func (d *Decoder) parseFilterHeader() {
d.filterHeader.simple = d.fp.readBit(uniformProb)
d.filterHeader.level = int8(d.fp.readUint(uniformProb, 6))
d.filterHeader.sharpness = uint8(d.fp.readUint(uniformProb, 3))
d.filterHeader.useLFDelta = d.fp.readBit(uniformProb)
if d.filterHeader.useLFDelta && d.fp.readBit(uniformProb) {
for i := range d.filterHeader.refLFDelta {
d.filterHeader.refLFDelta[i] = int8(d.fp.readOptionalInt(uniformProb, 6))
}
for i := range d.filterHeader.modeLFDelta {
d.filterHeader.modeLFDelta[i] = int8(d.fp.readOptionalInt(uniformProb, 6))
}
}
if d.filterHeader.level == 0 {
return
}
if d.segmentHeader.useSegment {
for i := range d.filterHeader.perSegmentLevel {
strength := d.segmentHeader.filterStrength[i]
if d.segmentHeader.relativeDelta {
strength += d.filterHeader.level
}
d.filterHeader.perSegmentLevel[i] = strength
}
} else {
d.filterHeader.perSegmentLevel[0] = d.filterHeader.level
}
d.computeFilterParams()
}
// parseOtherPartitions parses the other partitions, as specified in section 9.5.
func (d *Decoder) parseOtherPartitions() error {
const maxNOP = 1 << 3
var partLens [maxNOP]int
d.nOP = 1 << d.fp.readUint(uniformProb, 2)
// The final partition length is implied by the remaining chunk data
// (d.r.n) and the other d.nOP-1 partition lengths. Those d.nOP-1 partition
// lengths are stored as 24-bit uints, i.e. up to 16 MiB per partition.
n := 3 * (d.nOP - 1)
partLens[d.nOP-1] = d.r.n - n
if partLens[d.nOP-1] < 0 {
return io.ErrUnexpectedEOF
}
if n > 0 {
buf := make([]byte, n)
if err := d.r.ReadFull(buf); err != nil {
return err
}
for i := 0; i < d.nOP-1; i++ {
pl := int(buf[3*i+0]) | int(buf[3*i+1])<<8 | int(buf[3*i+2])<<16
if pl > partLens[d.nOP-1] {
return io.ErrUnexpectedEOF
}
partLens[i] = pl
partLens[d.nOP-1] -= pl
}
}
// We check if the final partition length can also fit into a 24-bit uint.
// Strictly speaking, this isn't part of the spec, but it guards against a
// malicious WEBP image that is too large to ReadFull the encoded DCT
// coefficients into memory, whether that's because the actual WEBP file is
// too large, or whether its RIFF metadata lists too large a chunk.
if 1<<24 <= partLens[d.nOP-1] {
return errors.New("vp8: too much data to decode")
}
buf := make([]byte, d.r.n)
if err := d.r.ReadFull(buf); err != nil {
return err
}
for i, pl := range partLens {
if i == d.nOP {
break
}
d.op[i].init(buf[:pl])
buf = buf[pl:]
}
return nil
}
// parseOtherHeaders parses header information other than the frame header.
func (d *Decoder) parseOtherHeaders() error {
// Initialize and parse the first partition.
firstPartition := make([]byte, d.frameHeader.FirstPartitionLen)
if err := d.r.ReadFull(firstPartition); err != nil {
return err
}
d.fp.init(firstPartition)
if d.frameHeader.KeyFrame {
// Read and ignore the color space and pixel clamp values. They are
// specified in section 9.2, but are unimplemented.
d.fp.readBit(uniformProb)
d.fp.readBit(uniformProb)
}
d.parseSegmentHeader()
d.parseFilterHeader()
if err := d.parseOtherPartitions(); err != nil {
return err
}
d.parseQuant()
if !d.frameHeader.KeyFrame {
// Golden and AltRef frames are specified in section 9.7.
// TODO(nigeltao): implement. Note that they are only used for video, not still images.
return errors.New("vp8: Golden / AltRef frames are not implemented")
}
// Read and ignore the refreshLastFrameBuffer bit, specified in section 9.8.
// It applies only to video, and not still images.
d.fp.readBit(uniformProb)
d.parseTokenProb()
d.useSkipProb = d.fp.readBit(uniformProb)
if d.useSkipProb {
d.skipProb = uint8(d.fp.readUint(uniformProb, 8))
}
if d.fp.unexpectedEOF {
return io.ErrUnexpectedEOF
}
return nil
}
// DecodeFrame decodes the frame and returns it as an YCbCr image.
// The image's contents are valid up until the next call to Decoder.Init.
func (d *Decoder) DecodeFrame() (*image.YCbCr, error) {
d.ensureImg()
if err := d.parseOtherHeaders(); err != nil {
return nil, err
}
// Reconstruct the rows.
for mbx := 0; mbx < d.mbw; mbx++ {
d.upMB[mbx] = mb{}
}
for mby := 0; mby < d.mbh; mby++ {
d.leftMB = mb{}
for mbx := 0; mbx < d.mbw; mbx++ {
skip := d.reconstruct(mbx, mby)
fs := d.filterParams[d.segment][btou(!d.usePredY16)]
fs.inner = fs.inner || !skip
d.perMBFilterParams[d.mbw*mby+mbx] = fs
}
}
if d.fp.unexpectedEOF {
return nil, io.ErrUnexpectedEOF
}
for i := 0; i < d.nOP; i++ {
if d.op[i].unexpectedEOF {
return nil, io.ErrUnexpectedEOF
}
}
// Apply the loop filter.
//
// Even if we are using per-segment levels, section 15 says that "loop
// filtering must be skipped entirely if loop_filter_level at either the
// frame header level or macroblock override level is 0".
if d.filterHeader.level != 0 {
if d.filterHeader.simple {
d.simpleFilter()
} else {
d.normalFilter()
}
}
return d.img, nil
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/partition.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// Each VP8 frame consists of between 2 and 9 bitstream partitions.
// Each partition is byte-aligned and is independently arithmetic-encoded.
//
// This file implements decoding a partition's bitstream, as specified in
// chapter 7. The implementation follows libwebp's approach instead of the
// specification's reference C implementation. For example, we use a look-up
// table instead of a for loop to recalibrate the encoded range.
var (
lutShift = [127]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,
}
lutRangeM1 = [127]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,
}
)
// uniformProb represents a 50% probability that the next bit is 0.
const uniformProb = 128
// partition holds arithmetic-coded bits.
type partition struct {
// buf is the input bytes.
buf []byte
// r is how many of buf's bytes have been consumed.
r int
// rangeM1 is range minus 1, where range is in the arithmetic coding sense,
// not the Go language sense.
rangeM1 uint32
// bits and nBits hold those bits shifted out of buf but not yet consumed.
bits uint32
nBits uint8
// unexpectedEOF tells whether we tried to read past buf.
unexpectedEOF bool
}
// init initializes the partition.
func (p *partition) init(buf []byte) {
p.buf = buf
p.r = 0
p.rangeM1 = 254
p.bits = 0
p.nBits = 0
p.unexpectedEOF = false
}
// readBit returns the next bit.
func (p *partition) readBit(prob uint8) bool {
if p.nBits < 8 {
if p.r >= len(p.buf) {
p.unexpectedEOF = true
return false
}
// Expression split for 386 compiler.
x := uint32(p.buf[p.r])
p.bits |= x << (8 - p.nBits)
p.r++
p.nBits += 8
}
split := (p.rangeM1*uint32(prob))>>8 + 1
bit := p.bits >= split<<8
if bit {
p.rangeM1 -= split
p.bits -= split << 8
} else {
p.rangeM1 = split - 1
}
if p.rangeM1 < 127 {
shift := lutShift[p.rangeM1]
p.rangeM1 = uint32(lutRangeM1[p.rangeM1])
p.bits <<= shift
p.nBits -= shift
}
return bit
}
// readUint returns the next n-bit unsigned integer.
func (p *partition) readUint(prob, n uint8) uint32 {
var u uint32
for n > 0 {
n--
if p.readBit(prob) {
u |= 1 << n
}
}
return u
}
// readInt returns the next n-bit signed integer.
func (p *partition) readInt(prob, n uint8) int32 {
u := p.readUint(prob, n)
b := p.readBit(prob)
if b {
return -int32(u)
}
return int32(u)
}
// readOptionalInt returns the next n-bit signed integer in an encoding
// where the likely result is zero.
func (p *partition) readOptionalInt(prob, n uint8) int32 {
if !p.readBit(prob) {
return 0
}
return p.readInt(prob, n)
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/predfunc.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// This file implements the predicition functions, as specified in chapter 12.
//
// For each macroblock (of 1x16x16 luma and 2x8x8 chroma coefficients), the
// luma values are either predicted as one large 16x16 region or 16 separate
// 4x4 regions. The chroma values are always predicted as one 8x8 region.
//
// For 4x4 regions, the target block's predicted values (Xs) are a function of
// its previously-decoded top and left border values, as well as a number of
// pixels from the top-right:
//
// a b c d e f g h
// p X X X X
// q X X X X
// r X X X X
// s X X X X
//
// The predictor modes are:
// - DC: all Xs = (b + c + d + e + p + q + r + s + 4) / 8.
// - TM: the first X = (b + p - a), the second X = (c + p - a), and so on.
// - VE: each X = the weighted average of its column's top value and that
// value's neighbors, i.e. averages of abc, bcd, cde or def.
// - HE: similar to VE except rows instead of columns, and the final row is
// an average of r, s and s.
// - RD, VR, LD, VL, HD, HU: these diagonal modes ("Right Down", "Vertical
// Right", etc) are more complicated and are described in section 12.3.
// All Xs are clipped to the range [0, 255].
//
// For 8x8 and 16x16 regions, the target block's predicted values are a
// function of the top and left border values without the top-right overhang,
// i.e. without the 8x8 or 16x16 equivalent of f, g and h. Furthermore:
// - There are no diagonal predictor modes, only DC, TM, VE and HE.
// - The DC mode has variants for macroblocks in the top row and/or left
// column, i.e. for macroblocks with mby == 0 || mbx == 0.
// - The VE and HE modes take only the column top or row left values; they do
// not smooth that top/left value with its neighbors.
// nPred is the number of predictor modes, not including the Top/Left versions
// of the DC predictor mode.
const nPred = 10
const (
predDC = iota
predTM
predVE
predHE
predRD
predVR
predLD
predVL
predHD
predHU
predDCTop
predDCLeft
predDCTopLeft
)
func checkTopLeftPred(mbx, mby int, p uint8) uint8 {
if p != predDC {
return p
}
if mbx == 0 {
if mby == 0 {
return predDCTopLeft
}
return predDCLeft
}
if mby == 0 {
return predDCTop
}
return predDC
}
var predFunc4 = [...]func(*Decoder, int, int){
predFunc4DC,
predFunc4TM,
predFunc4VE,
predFunc4HE,
predFunc4RD,
predFunc4VR,
predFunc4LD,
predFunc4VL,
predFunc4HD,
predFunc4HU,
nil,
nil,
nil,
}
var predFunc8 = [...]func(*Decoder, int, int){
predFunc8DC,
predFunc8TM,
predFunc8VE,
predFunc8HE,
nil,
nil,
nil,
nil,
nil,
nil,
predFunc8DCTop,
predFunc8DCLeft,
predFunc8DCTopLeft,
}
var predFunc16 = [...]func(*Decoder, int, int){
predFunc16DC,
predFunc16TM,
predFunc16VE,
predFunc16HE,
nil,
nil,
nil,
nil,
nil,
nil,
predFunc16DCTop,
predFunc16DCLeft,
predFunc16DCTopLeft,
}
func predFunc4DC(z *Decoder, y, x int) {
sum := uint32(4)
for i := 0; i < 4; i++ {
sum += uint32(z.ybr[y-1][x+i])
}
for j := 0; j < 4; j++ {
sum += uint32(z.ybr[y+j][x-1])
}
avg := uint8(sum / 8)
for j := 0; j < 4; j++ {
for i := 0; i < 4; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc4TM(z *Decoder, y, x int) {
delta0 := -int32(z.ybr[y-1][x-1])
for j := 0; j < 4; j++ {
delta1 := delta0 + int32(z.ybr[y+j][x-1])
for i := 0; i < 4; i++ {
delta2 := delta1 + int32(z.ybr[y-1][x+i])
z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255))
}
}
}
func predFunc4VE(z *Decoder, y, x int) {
a := int32(z.ybr[y-1][x-1])
b := int32(z.ybr[y-1][x+0])
c := int32(z.ybr[y-1][x+1])
d := int32(z.ybr[y-1][x+2])
e := int32(z.ybr[y-1][x+3])
f := int32(z.ybr[y-1][x+4])
abc := uint8((a + 2*b + c + 2) / 4)
bcd := uint8((b + 2*c + d + 2) / 4)
cde := uint8((c + 2*d + e + 2) / 4)
def := uint8((d + 2*e + f + 2) / 4)
for j := 0; j < 4; j++ {
z.ybr[y+j][x+0] = abc
z.ybr[y+j][x+1] = bcd
z.ybr[y+j][x+2] = cde
z.ybr[y+j][x+3] = def
}
}
func predFunc4HE(z *Decoder, y, x int) {
s := int32(z.ybr[y+3][x-1])
r := int32(z.ybr[y+2][x-1])
q := int32(z.ybr[y+1][x-1])
p := int32(z.ybr[y+0][x-1])
a := int32(z.ybr[y-1][x-1])
ssr := uint8((s + 2*s + r + 2) / 4)
srq := uint8((s + 2*r + q + 2) / 4)
rqp := uint8((r + 2*q + p + 2) / 4)
apq := uint8((a + 2*p + q + 2) / 4)
for i := 0; i < 4; i++ {
z.ybr[y+0][x+i] = apq
z.ybr[y+1][x+i] = rqp
z.ybr[y+2][x+i] = srq
z.ybr[y+3][x+i] = ssr
}
}
func predFunc4RD(z *Decoder, y, x int) {
s := int32(z.ybr[y+3][x-1])
r := int32(z.ybr[y+2][x-1])
q := int32(z.ybr[y+1][x-1])
p := int32(z.ybr[y+0][x-1])
a := int32(z.ybr[y-1][x-1])
b := int32(z.ybr[y-1][x+0])
c := int32(z.ybr[y-1][x+1])
d := int32(z.ybr[y-1][x+2])
e := int32(z.ybr[y-1][x+3])
srq := uint8((s + 2*r + q + 2) / 4)
rqp := uint8((r + 2*q + p + 2) / 4)
qpa := uint8((q + 2*p + a + 2) / 4)
pab := uint8((p + 2*a + b + 2) / 4)
abc := uint8((a + 2*b + c + 2) / 4)
bcd := uint8((b + 2*c + d + 2) / 4)
cde := uint8((c + 2*d + e + 2) / 4)
z.ybr[y+0][x+0] = pab
z.ybr[y+0][x+1] = abc
z.ybr[y+0][x+2] = bcd
z.ybr[y+0][x+3] = cde
z.ybr[y+1][x+0] = qpa
z.ybr[y+1][x+1] = pab
z.ybr[y+1][x+2] = abc
z.ybr[y+1][x+3] = bcd
z.ybr[y+2][x+0] = rqp
z.ybr[y+2][x+1] = qpa
z.ybr[y+2][x+2] = pab
z.ybr[y+2][x+3] = abc
z.ybr[y+3][x+0] = srq
z.ybr[y+3][x+1] = rqp
z.ybr[y+3][x+2] = qpa
z.ybr[y+3][x+3] = pab
}
func predFunc4VR(z *Decoder, y, x int) {
r := int32(z.ybr[y+2][x-1])
q := int32(z.ybr[y+1][x-1])
p := int32(z.ybr[y+0][x-1])
a := int32(z.ybr[y-1][x-1])
b := int32(z.ybr[y-1][x+0])
c := int32(z.ybr[y-1][x+1])
d := int32(z.ybr[y-1][x+2])
e := int32(z.ybr[y-1][x+3])
ab := uint8((a + b + 1) / 2)
bc := uint8((b + c + 1) / 2)
cd := uint8((c + d + 1) / 2)
de := uint8((d + e + 1) / 2)
rqp := uint8((r + 2*q + p + 2) / 4)
qpa := uint8((q + 2*p + a + 2) / 4)
pab := uint8((p + 2*a + b + 2) / 4)
abc := uint8((a + 2*b + c + 2) / 4)
bcd := uint8((b + 2*c + d + 2) / 4)
cde := uint8((c + 2*d + e + 2) / 4)
z.ybr[y+0][x+0] = ab
z.ybr[y+0][x+1] = bc
z.ybr[y+0][x+2] = cd
z.ybr[y+0][x+3] = de
z.ybr[y+1][x+0] = pab
z.ybr[y+1][x+1] = abc
z.ybr[y+1][x+2] = bcd
z.ybr[y+1][x+3] = cde
z.ybr[y+2][x+0] = qpa
z.ybr[y+2][x+1] = ab
z.ybr[y+2][x+2] = bc
z.ybr[y+2][x+3] = cd
z.ybr[y+3][x+0] = rqp
z.ybr[y+3][x+1] = pab
z.ybr[y+3][x+2] = abc
z.ybr[y+3][x+3] = bcd
}
func predFunc4LD(z *Decoder, y, x int) {
a := int32(z.ybr[y-1][x+0])
b := int32(z.ybr[y-1][x+1])
c := int32(z.ybr[y-1][x+2])
d := int32(z.ybr[y-1][x+3])
e := int32(z.ybr[y-1][x+4])
f := int32(z.ybr[y-1][x+5])
g := int32(z.ybr[y-1][x+6])
h := int32(z.ybr[y-1][x+7])
abc := uint8((a + 2*b + c + 2) / 4)
bcd := uint8((b + 2*c + d + 2) / 4)
cde := uint8((c + 2*d + e + 2) / 4)
def := uint8((d + 2*e + f + 2) / 4)
efg := uint8((e + 2*f + g + 2) / 4)
fgh := uint8((f + 2*g + h + 2) / 4)
ghh := uint8((g + 2*h + h + 2) / 4)
z.ybr[y+0][x+0] = abc
z.ybr[y+0][x+1] = bcd
z.ybr[y+0][x+2] = cde
z.ybr[y+0][x+3] = def
z.ybr[y+1][x+0] = bcd
z.ybr[y+1][x+1] = cde
z.ybr[y+1][x+2] = def
z.ybr[y+1][x+3] = efg
z.ybr[y+2][x+0] = cde
z.ybr[y+2][x+1] = def
z.ybr[y+2][x+2] = efg
z.ybr[y+2][x+3] = fgh
z.ybr[y+3][x+0] = def
z.ybr[y+3][x+1] = efg
z.ybr[y+3][x+2] = fgh
z.ybr[y+3][x+3] = ghh
}
func predFunc4VL(z *Decoder, y, x int) {
a := int32(z.ybr[y-1][x+0])
b := int32(z.ybr[y-1][x+1])
c := int32(z.ybr[y-1][x+2])
d := int32(z.ybr[y-1][x+3])
e := int32(z.ybr[y-1][x+4])
f := int32(z.ybr[y-1][x+5])
g := int32(z.ybr[y-1][x+6])
h := int32(z.ybr[y-1][x+7])
ab := uint8((a + b + 1) / 2)
bc := uint8((b + c + 1) / 2)
cd := uint8((c + d + 1) / 2)
de := uint8((d + e + 1) / 2)
abc := uint8((a + 2*b + c + 2) / 4)
bcd := uint8((b + 2*c + d + 2) / 4)
cde := uint8((c + 2*d + e + 2) / 4)
def := uint8((d + 2*e + f + 2) / 4)
efg := uint8((e + 2*f + g + 2) / 4)
fgh := uint8((f + 2*g + h + 2) / 4)
z.ybr[y+0][x+0] = ab
z.ybr[y+0][x+1] = bc
z.ybr[y+0][x+2] = cd
z.ybr[y+0][x+3] = de
z.ybr[y+1][x+0] = abc
z.ybr[y+1][x+1] = bcd
z.ybr[y+1][x+2] = cde
z.ybr[y+1][x+3] = def
z.ybr[y+2][x+0] = bc
z.ybr[y+2][x+1] = cd
z.ybr[y+2][x+2] = de
z.ybr[y+2][x+3] = efg
z.ybr[y+3][x+0] = bcd
z.ybr[y+3][x+1] = cde
z.ybr[y+3][x+2] = def
z.ybr[y+3][x+3] = fgh
}
func predFunc4HD(z *Decoder, y, x int) {
s := int32(z.ybr[y+3][x-1])
r := int32(z.ybr[y+2][x-1])
q := int32(z.ybr[y+1][x-1])
p := int32(z.ybr[y+0][x-1])
a := int32(z.ybr[y-1][x-1])
b := int32(z.ybr[y-1][x+0])
c := int32(z.ybr[y-1][x+1])
d := int32(z.ybr[y-1][x+2])
sr := uint8((s + r + 1) / 2)
rq := uint8((r + q + 1) / 2)
qp := uint8((q + p + 1) / 2)
pa := uint8((p + a + 1) / 2)
srq := uint8((s + 2*r + q + 2) / 4)
rqp := uint8((r + 2*q + p + 2) / 4)
qpa := uint8((q + 2*p + a + 2) / 4)
pab := uint8((p + 2*a + b + 2) / 4)
abc := uint8((a + 2*b + c + 2) / 4)
bcd := uint8((b + 2*c + d + 2) / 4)
z.ybr[y+0][x+0] = pa
z.ybr[y+0][x+1] = pab
z.ybr[y+0][x+2] = abc
z.ybr[y+0][x+3] = bcd
z.ybr[y+1][x+0] = qp
z.ybr[y+1][x+1] = qpa
z.ybr[y+1][x+2] = pa
z.ybr[y+1][x+3] = pab
z.ybr[y+2][x+0] = rq
z.ybr[y+2][x+1] = rqp
z.ybr[y+2][x+2] = qp
z.ybr[y+2][x+3] = qpa
z.ybr[y+3][x+0] = sr
z.ybr[y+3][x+1] = srq
z.ybr[y+3][x+2] = rq
z.ybr[y+3][x+3] = rqp
}
func predFunc4HU(z *Decoder, y, x int) {
s := int32(z.ybr[y+3][x-1])
r := int32(z.ybr[y+2][x-1])
q := int32(z.ybr[y+1][x-1])
p := int32(z.ybr[y+0][x-1])
pq := uint8((p + q + 1) / 2)
qr := uint8((q + r + 1) / 2)
rs := uint8((r + s + 1) / 2)
pqr := uint8((p + 2*q + r + 2) / 4)
qrs := uint8((q + 2*r + s + 2) / 4)
rss := uint8((r + 2*s + s + 2) / 4)
sss := uint8(s)
z.ybr[y+0][x+0] = pq
z.ybr[y+0][x+1] = pqr
z.ybr[y+0][x+2] = qr
z.ybr[y+0][x+3] = qrs
z.ybr[y+1][x+0] = qr
z.ybr[y+1][x+1] = qrs
z.ybr[y+1][x+2] = rs
z.ybr[y+1][x+3] = rss
z.ybr[y+2][x+0] = rs
z.ybr[y+2][x+1] = rss
z.ybr[y+2][x+2] = sss
z.ybr[y+2][x+3] = sss
z.ybr[y+3][x+0] = sss
z.ybr[y+3][x+1] = sss
z.ybr[y+3][x+2] = sss
z.ybr[y+3][x+3] = sss
}
func predFunc8DC(z *Decoder, y, x int) {
sum := uint32(8)
for i := 0; i < 8; i++ {
sum += uint32(z.ybr[y-1][x+i])
}
for j := 0; j < 8; j++ {
sum += uint32(z.ybr[y+j][x-1])
}
avg := uint8(sum / 16)
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc8TM(z *Decoder, y, x int) {
delta0 := -int32(z.ybr[y-1][x-1])
for j := 0; j < 8; j++ {
delta1 := delta0 + int32(z.ybr[y+j][x-1])
for i := 0; i < 8; i++ {
delta2 := delta1 + int32(z.ybr[y-1][x+i])
z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255))
}
}
}
func predFunc8VE(z *Decoder, y, x int) {
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
z.ybr[y+j][x+i] = z.ybr[y-1][x+i]
}
}
}
func predFunc8HE(z *Decoder, y, x int) {
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
z.ybr[y+j][x+i] = z.ybr[y+j][x-1]
}
}
}
func predFunc8DCTop(z *Decoder, y, x int) {
sum := uint32(4)
for j := 0; j < 8; j++ {
sum += uint32(z.ybr[y+j][x-1])
}
avg := uint8(sum / 8)
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc8DCLeft(z *Decoder, y, x int) {
sum := uint32(4)
for i := 0; i < 8; i++ {
sum += uint32(z.ybr[y-1][x+i])
}
avg := uint8(sum / 8)
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc8DCTopLeft(z *Decoder, y, x int) {
for j := 0; j < 8; j++ {
for i := 0; i < 8; i++ {
z.ybr[y+j][x+i] = 0x80
}
}
}
func predFunc16DC(z *Decoder, y, x int) {
sum := uint32(16)
for i := 0; i < 16; i++ {
sum += uint32(z.ybr[y-1][x+i])
}
for j := 0; j < 16; j++ {
sum += uint32(z.ybr[y+j][x-1])
}
avg := uint8(sum / 32)
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc16TM(z *Decoder, y, x int) {
delta0 := -int32(z.ybr[y-1][x-1])
for j := 0; j < 16; j++ {
delta1 := delta0 + int32(z.ybr[y+j][x-1])
for i := 0; i < 16; i++ {
delta2 := delta1 + int32(z.ybr[y-1][x+i])
z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255))
}
}
}
func predFunc16VE(z *Decoder, y, x int) {
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
z.ybr[y+j][x+i] = z.ybr[y-1][x+i]
}
}
}
func predFunc16HE(z *Decoder, y, x int) {
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
z.ybr[y+j][x+i] = z.ybr[y+j][x-1]
}
}
}
func predFunc16DCTop(z *Decoder, y, x int) {
sum := uint32(8)
for j := 0; j < 16; j++ {
sum += uint32(z.ybr[y+j][x-1])
}
avg := uint8(sum / 16)
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc16DCLeft(z *Decoder, y, x int) {
sum := uint32(8)
for i := 0; i < 16; i++ {
sum += uint32(z.ybr[y-1][x+i])
}
avg := uint8(sum / 16)
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
z.ybr[y+j][x+i] = avg
}
}
}
func predFunc16DCTopLeft(z *Decoder, y, x int) {
for j := 0; j < 16; j++ {
for i := 0; i < 16; i++ {
z.ybr[y+j][x+i] = 0x80
}
}
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/reconstruct.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// This file implements decoding DCT/WHT residual coefficients and
// reconstructing YCbCr data equal to predicted values plus residuals.
//
// There are 1*16*16 + 2*8*8 + 1*4*4 coefficients per macroblock:
// - 1*16*16 luma DCT coefficients,
// - 2*8*8 chroma DCT coefficients, and
// - 1*4*4 luma WHT coefficients.
// Coefficients are read in lots of 16, and the later coefficients in each lot
// are often zero.
//
// The YCbCr data consists of 1*16*16 luma values and 2*8*8 chroma values,
// plus previously decoded values along the top and left borders. The combined
// values are laid out as a [1+16+1+8][32]uint8 so that vertically adjacent
// samples are 32 bytes apart. In detail, the layout is:
//
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// . . . . . . . a b b b b b b b b b b b b b b b b c c c c . . . . 0
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 1
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 2
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 3
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 4
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 5
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 6
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 7
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 8
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 9
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 10
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 11
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 12
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 13
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 14
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 15
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 16
// . . . . . . . e f f f f f f f f . . . . . . . g h h h h h h h h 17
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 18
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 19
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 20
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 21
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 22
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 23
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 24
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 25
//
// Y, B and R are the reconstructed luma (Y) and chroma (B, R) values.
// The Y values are predicted (either as one 16x16 region or 16 4x4 regions)
// based on the row above's Y values (some combination of {abc} or {dYC}) and
// the column left's Y values (either {ad} or {bY}). Similarly, B and R values
// are predicted on the row above and column left of their respective 8x8
// region: {efi} for B, {ghj} for R.
//
// For uppermost macroblocks (i.e. those with mby == 0), the {abcefgh} values
// are initialized to 0x81. Otherwise, they are copied from the bottom row of
// the macroblock above. The {c} values are then duplicated from row 0 to rows
// 4, 8 and 12 of the ybr workspace.
// Similarly, for leftmost macroblocks (i.e. those with mbx == 0), the {adeigj}
// values are initialized to 0x7f. Otherwise, they are copied from the right
// column of the macroblock to the left.
// For the top-left macroblock (with mby == 0 && mbx == 0), {aeg} is 0x81.
//
// When moving from one macroblock to the next horizontally, the {adeigj}
// values can simply be copied from the workspace to itself, shifted by 8 or
// 16 columns. When moving from one macroblock to the next vertically,
// filtering can occur and hence the row values have to be copied from the
// post-filtered image instead of the pre-filtered workspace.
const (
bCoeffBase = 1*16*16 + 0*8*8
rCoeffBase = 1*16*16 + 1*8*8
whtCoeffBase = 1*16*16 + 2*8*8
)
const (
ybrYX = 8
ybrYY = 1
ybrBX = 8
ybrBY = 18
ybrRX = 24
ybrRY = 18
)
// prepareYBR prepares the {abcdefghij} elements of ybr.
func (d *Decoder) prepareYBR(mbx, mby int) {
if mbx == 0 {
for y := 0; y < 17; y++ {
d.ybr[y][7] = 0x81
}
for y := 17; y < 26; y++ {
d.ybr[y][7] = 0x81
d.ybr[y][23] = 0x81
}
} else {
for y := 0; y < 17; y++ {
d.ybr[y][7] = d.ybr[y][7+16]
}
for y := 17; y < 26; y++ {
d.ybr[y][7] = d.ybr[y][15]
d.ybr[y][23] = d.ybr[y][31]
}
}
if mby == 0 {
for x := 7; x < 28; x++ {
d.ybr[0][x] = 0x7f
}
for x := 7; x < 16; x++ {
d.ybr[17][x] = 0x7f
}
for x := 23; x < 32; x++ {
d.ybr[17][x] = 0x7f
}
} else {
for i := 0; i < 16; i++ {
d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+i]
}
for i := 0; i < 8; i++ {
d.ybr[17][8+i] = d.img.Cb[(8*mby-1)*d.img.CStride+8*mbx+i]
}
for i := 0; i < 8; i++ {
d.ybr[17][24+i] = d.img.Cr[(8*mby-1)*d.img.CStride+8*mbx+i]
}
if mbx == d.mbw-1 {
for i := 16; i < 20; i++ {
d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+15]
}
} else {
for i := 16; i < 20; i++ {
d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+i]
}
}
}
for y := 4; y < 16; y += 4 {
d.ybr[y][24] = d.ybr[0][24]
d.ybr[y][25] = d.ybr[0][25]
d.ybr[y][26] = d.ybr[0][26]
d.ybr[y][27] = d.ybr[0][27]
}
}
// btou converts a bool to a 0/1 value.
func btou(b bool) uint8 {
if b {
return 1
}
return 0
}
// pack packs four 0/1 values into four bits of a uint32.
func pack(x [4]uint8, shift int) uint32 {
u := uint32(x[0])<<0 | uint32(x[1])<<1 | uint32(x[2])<<2 | uint32(x[3])<<3
return u << uint(shift)
}
// unpack unpacks four 0/1 values from a four-bit value.
var unpack = [16][4]uint8{
{0, 0, 0, 0},
{1, 0, 0, 0},
{0, 1, 0, 0},
{1, 1, 0, 0},
{0, 0, 1, 0},
{1, 0, 1, 0},
{0, 1, 1, 0},
{1, 1, 1, 0},
{0, 0, 0, 1},
{1, 0, 0, 1},
{0, 1, 0, 1},
{1, 1, 0, 1},
{0, 0, 1, 1},
{1, 0, 1, 1},
{0, 1, 1, 1},
{1, 1, 1, 1},
}
var (
// The mapping from 4x4 region position to band is specified in section 13.3.
bands = [17]uint8{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0}
// Category probabilties are specified in section 13.2.
// Decoding categories 1 and 2 are done inline.
cat3456 = [4][12]uint8{
{173, 148, 140, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{176, 155, 140, 135, 0, 0, 0, 0, 0, 0, 0, 0},
{180, 157, 141, 134, 130, 0, 0, 0, 0, 0, 0, 0},
{254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0},
}
// The zigzag order is:
// 0 1 5 6
// 2 4 7 12
// 3 8 11 13
// 9 10 14 15
zigzag = [16]uint8{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15}
)
// parseResiduals4 parses a 4x4 region of residual coefficients, as specified
// in section 13.3, and returns a 0/1 value indicating whether there was at
// least one non-zero coefficient.
// r is the partition to read bits from.
// plane and context describe which token probability table to use. context is
// either 0, 1 or 2, and equals how many of the macroblock left and macroblock
// above have non-zero coefficients.
// quant are the DC/AC quantization factors.
// skipFirstCoeff is whether the DC coefficient has already been parsed.
// coeffBase is the base index of d.coeff to write to.
func (d *Decoder) parseResiduals4(r *partition, plane int, context uint8, quant [2]uint16, skipFirstCoeff bool, coeffBase int) uint8 {
prob, n := &d.tokenProb[plane], 0
if skipFirstCoeff {
n = 1
}
p := prob[bands[n]][context]
if !r.readBit(p[0]) {
return 0
}
for n != 16 {
n++
if !r.readBit(p[1]) {
p = prob[bands[n]][0]
continue
}
var v uint32
if !r.readBit(p[2]) {
v = 1
p = prob[bands[n]][1]
} else {
if !r.readBit(p[3]) {
if !r.readBit(p[4]) {
v = 2
} else {
v = 3 + r.readUint(p[5], 1)
}
} else if !r.readBit(p[6]) {
if !r.readBit(p[7]) {
// Category 1.
v = 5 + r.readUint(159, 1)
} else {
// Category 2.
v = 7 + 2*r.readUint(165, 1) + r.readUint(145, 1)
}
} else {
// Categories 3, 4, 5 or 6.
b1 := r.readUint(p[8], 1)
b0 := r.readUint(p[9+b1], 1)
cat := 2*b1 + b0
tab := &cat3456[cat]
v = 0
for i := 0; tab[i] != 0; i++ {
v *= 2
v += r.readUint(tab[i], 1)
}
v += 3 + (8 << cat)
}
p = prob[bands[n]][2]
}
z := zigzag[n-1]
c := int32(v) * int32(quant[btou(z > 0)])
if r.readBit(uniformProb) {
c = -c
}
d.coeff[coeffBase+int(z)] = int16(c)
if n == 16 || !r.readBit(p[0]) {
return 1
}
}
return 1
}
// parseResiduals parses the residuals and returns whether inner loop filtering
// should be skipped for this macroblock.
func (d *Decoder) parseResiduals(mbx, mby int) (skip bool) {
partition := &d.op[mby&(d.nOP-1)]
plane := planeY1SansY2
quant := &d.quant[d.segment]
// Parse the DC coefficient of each 4x4 luma region.
if d.usePredY16 {
nz := d.parseResiduals4(partition, planeY2, d.leftMB.nzY16+d.upMB[mbx].nzY16, quant.y2, false, whtCoeffBase)
d.leftMB.nzY16 = nz
d.upMB[mbx].nzY16 = nz
d.inverseWHT16()
plane = planeY1WithY2
}
var (
nzDC, nzAC [4]uint8
nzDCMask, nzACMask uint32
coeffBase int
)
// Parse the luma coefficients.
lnz := unpack[d.leftMB.nzMask&0x0f]
unz := unpack[d.upMB[mbx].nzMask&0x0f]
for y := 0; y < 4; y++ {
nz := lnz[y]
for x := 0; x < 4; x++ {
nz = d.parseResiduals4(partition, plane, nz+unz[x], quant.y1, d.usePredY16, coeffBase)
unz[x] = nz
nzAC[x] = nz
nzDC[x] = btou(d.coeff[coeffBase] != 0)
coeffBase += 16
}
lnz[y] = nz
nzDCMask |= pack(nzDC, y*4)
nzACMask |= pack(nzAC, y*4)
}
lnzMask := pack(lnz, 0)
unzMask := pack(unz, 0)
// Parse the chroma coefficients.
lnz = unpack[d.leftMB.nzMask>>4]
unz = unpack[d.upMB[mbx].nzMask>>4]
for c := 0; c < 4; c += 2 {
for y := 0; y < 2; y++ {
nz := lnz[y+c]
for x := 0; x < 2; x++ {
nz = d.parseResiduals4(partition, planeUV, nz+unz[x+c], quant.uv, false, coeffBase)
unz[x+c] = nz
nzAC[y*2+x] = nz
nzDC[y*2+x] = btou(d.coeff[coeffBase] != 0)
coeffBase += 16
}
lnz[y+c] = nz
}
nzDCMask |= pack(nzDC, 16+c*2)
nzACMask |= pack(nzAC, 16+c*2)
}
lnzMask |= pack(lnz, 4)
unzMask |= pack(unz, 4)
// Save decoder state.
d.leftMB.nzMask = uint8(lnzMask)
d.upMB[mbx].nzMask = uint8(unzMask)
d.nzDCMask = nzDCMask
d.nzACMask = nzACMask
// Section 15.1 of the spec says that "Steps 2 and 4 [of the loop filter]
// are skipped... [if] there is no DCT coefficient coded for the whole
// macroblock."
return nzDCMask == 0 && nzACMask == 0
}
// reconstructMacroblock applies the predictor functions and adds the inverse-
// DCT transformed residuals to recover the YCbCr data.
func (d *Decoder) reconstructMacroblock(mbx, mby int) {
if d.usePredY16 {
p := checkTopLeftPred(mbx, mby, d.predY16)
predFunc16[p](d, 1, 8)
for j := 0; j < 4; j++ {
for i := 0; i < 4; i++ {
n := 4*j + i
y := 4*j + 1
x := 4*i + 8
mask := uint32(1) << uint(n)
if d.nzACMask&mask != 0 {
d.inverseDCT4(y, x, 16*n)
} else if d.nzDCMask&mask != 0 {
d.inverseDCT4DCOnly(y, x, 16*n)
}
}
}
} else {
for j := 0; j < 4; j++ {
for i := 0; i < 4; i++ {
n := 4*j + i
y := 4*j + 1
x := 4*i + 8
predFunc4[d.predY4[j][i]](d, y, x)
mask := uint32(1) << uint(n)
if d.nzACMask&mask != 0 {
d.inverseDCT4(y, x, 16*n)
} else if d.nzDCMask&mask != 0 {
d.inverseDCT4DCOnly(y, x, 16*n)
}
}
}
}
p := checkTopLeftPred(mbx, mby, d.predC8)
predFunc8[p](d, ybrBY, ybrBX)
if d.nzACMask&0x0f0000 != 0 {
d.inverseDCT8(ybrBY, ybrBX, bCoeffBase)
} else if d.nzDCMask&0x0f0000 != 0 {
d.inverseDCT8DCOnly(ybrBY, ybrBX, bCoeffBase)
}
predFunc8[p](d, ybrRY, ybrRX)
if d.nzACMask&0xf00000 != 0 {
d.inverseDCT8(ybrRY, ybrRX, rCoeffBase)
} else if d.nzDCMask&0xf00000 != 0 {
d.inverseDCT8DCOnly(ybrRY, ybrRX, rCoeffBase)
}
}
// reconstruct reconstructs one macroblock and returns whether inner loop
// filtering should be skipped for it.
func (d *Decoder) reconstruct(mbx, mby int) (skip bool) {
if d.segmentHeader.updateMap {
if !d.fp.readBit(d.segmentHeader.prob[0]) {
d.segment = int(d.fp.readUint(d.segmentHeader.prob[1], 1))
} else {
d.segment = int(d.fp.readUint(d.segmentHeader.prob[2], 1)) + 2
}
}
if d.useSkipProb {
skip = d.fp.readBit(d.skipProb)
}
// Prepare the workspace.
for i := range d.coeff {
d.coeff[i] = 0
}
d.prepareYBR(mbx, mby)
// Parse the predictor modes.
d.usePredY16 = d.fp.readBit(145)
if d.usePredY16 {
d.parsePredModeY16(mbx)
} else {
d.parsePredModeY4(mbx)
}
d.parsePredModeC8()
// Parse the residuals.
if !skip {
skip = d.parseResiduals(mbx, mby)
} else {
if d.usePredY16 {
d.leftMB.nzY16 = 0
d.upMB[mbx].nzY16 = 0
}
d.leftMB.nzMask = 0
d.upMB[mbx].nzMask = 0
d.nzDCMask = 0
d.nzACMask = 0
}
// Reconstruct the YCbCr data and copy it to the image.
d.reconstructMacroblock(mbx, mby)
for i, y := (mby*d.img.YStride+mbx)*16, 0; y < 16; i, y = i+d.img.YStride, y+1 {
copy(d.img.Y[i:i+16], d.ybr[ybrYY+y][ybrYX:ybrYX+16])
}
for i, y := (mby*d.img.CStride+mbx)*8, 0; y < 8; i, y = i+d.img.CStride, y+1 {
copy(d.img.Cb[i:i+8], d.ybr[ybrBY+y][ybrBX:ybrBX+8])
copy(d.img.Cr[i:i+8], d.ybr[ybrRY+y][ybrRX:ybrRX+8])
}
return skip
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/token.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// This file contains token probabilities for decoding DCT/WHT coefficients, as
// specified in chapter 13.
func (d *Decoder) parseTokenProb() {
for i := range d.tokenProb {
for j := range d.tokenProb[i] {
for k := range d.tokenProb[i][j] {
for l := range d.tokenProb[i][j][k] {
if d.fp.readBit(tokenProbUpdateProb[i][j][k][l]) {
d.tokenProb[i][j][k][l] = uint8(d.fp.readUint(uniformProb, 8))
}
}
}
}
}
}
// The plane enumeration is specified in section 13.3.
const (
planeY1WithY2 = iota
planeY2
planeUV
planeY1SansY2
nPlane
)
const (
nBand = 8
nContext = 3
nProb = 11
)
// Token probability update probabilities are specified in section 13.4.
var tokenProbUpdateProb = [nPlane][nBand][nContext][nProb]uint8{
{
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255},
{249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255},
{234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255},
{250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
{
{
{217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255},
{234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255},
},
{
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
{
{
{186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255},
{234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255},
{251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255},
},
{
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
{
{
{248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255},
{248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255},
},
{
{255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255},
{248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255},
{250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
{
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
},
},
}
// Default token probabilities are specified in section 13.5.
var defaultTokenProb = [nPlane][nBand][nContext][nProb]uint8{
{
{
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128},
{189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128},
{106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128},
},
{
{1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128},
{181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128},
{78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128},
},
{
{1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128},
{184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128},
{77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128},
},
{
{1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128},
{170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128},
{37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128},
},
{
{1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128},
{207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128},
{102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128},
},
{
{1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128},
{177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128},
{80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128},
},
{
{1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
},
},
{
{
{198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62},
{131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1},
{68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128},
},
{
{1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128},
{184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128},
{81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128},
},
{
{1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128},
{99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128},
{23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128},
},
{
{1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128},
{109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128},
{44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128},
},
{
{1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128},
{94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128},
{22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128},
},
{
{1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128},
{124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128},
{35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128},
},
{
{1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128},
{121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128},
{45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128},
},
{
{1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128},
{203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128},
{137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128},
},
},
{
{
{253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128},
{175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128},
{73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128},
},
{
{1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128},
{239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128},
{155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128},
},
{
{1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128},
{201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128},
{69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128},
},
{
{1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128},
{223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128},
{141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128},
},
{
{1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128},
{190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128},
{149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128},
{213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128},
{55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
{
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
},
},
{
{
{202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255},
{126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128},
{61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128},
},
{
{1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128},
{166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128},
{39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128},
},
{
{1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128},
{124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128},
{24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128},
},
{
{1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128},
{149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128},
{28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128},
},
{
{1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128},
{123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128},
{20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128},
},
{
{1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128},
{168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128},
{47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128},
},
{
{1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128},
{141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128},
{42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128},
},
{
{1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
{238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
},
},
}
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/quant.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// This file implements parsing the quantization factors.
// quant are DC/AC quantization factors.
type quant struct {
y1 [2]uint16
y2 [2]uint16
uv [2]uint16
}
// clip clips x to the range [min, max] inclusive.
func clip(x, min, max int32) int32 {
if x < min {
return min
}
if x > max {
return max
}
return x
}
// parseQuant parses the quantization factors, as specified in section 9.6.
func (d *Decoder) parseQuant() {
baseQ0 := d.fp.readUint(uniformProb, 7)
dqy1DC := d.fp.readOptionalInt(uniformProb, 4)
const dqy1AC = 0
dqy2DC := d.fp.readOptionalInt(uniformProb, 4)
dqy2AC := d.fp.readOptionalInt(uniformProb, 4)
dquvDC := d.fp.readOptionalInt(uniformProb, 4)
dquvAC := d.fp.readOptionalInt(uniformProb, 4)
for i := 0; i < nSegment; i++ {
q := int32(baseQ0)
if d.segmentHeader.useSegment {
if d.segmentHeader.relativeDelta {
q += int32(d.segmentHeader.quantizer[i])
} else {
q = int32(d.segmentHeader.quantizer[i])
}
}
d.quant[i].y1[0] = dequantTableDC[clip(q+dqy1DC, 0, 127)]
d.quant[i].y1[1] = dequantTableAC[clip(q+dqy1AC, 0, 127)]
d.quant[i].y2[0] = dequantTableDC[clip(q+dqy2DC, 0, 127)] * 2
d.quant[i].y2[1] = dequantTableAC[clip(q+dqy2AC, 0, 127)] * 155 / 100
if d.quant[i].y2[1] < 8 {
d.quant[i].y2[1] = 8
}
// The 117 is not a typo. The dequant_init function in the spec's Reference
// Decoder Source Code (http://tools.ietf.org/html/rfc6386#section-9.6 Page 145)
// says to clamp the LHS value at 132, which is equal to dequantTableDC[117].
d.quant[i].uv[0] = dequantTableDC[clip(q+dquvDC, 0, 117)]
d.quant[i].uv[1] = dequantTableAC[clip(q+dquvAC, 0, 127)]
}
}
// The dequantization tables are specified in section 14.1.
var (
dequantTableDC = [128]uint16{
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,
}
dequantTableAC = [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,
}
)
|
vp8 | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/vp8/idct.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vp8
// This file implements the inverse Discrete Cosine Transform and the inverse
// Walsh Hadamard Transform (WHT), as specified in sections 14.3 and 14.4.
func clip8(i int32) uint8 {
if i < 0 {
return 0
}
if i > 255 {
return 255
}
return uint8(i)
}
func (z *Decoder) inverseDCT4(y, x, coeffBase int) {
const (
c1 = 85627 // 65536 * cos(pi/8) * sqrt(2).
c2 = 35468 // 65536 * sin(pi/8) * sqrt(2).
)
var m [4][4]int32
for i := 0; i < 4; i++ {
a := int32(z.coeff[coeffBase+0]) + int32(z.coeff[coeffBase+8])
b := int32(z.coeff[coeffBase+0]) - int32(z.coeff[coeffBase+8])
c := (int32(z.coeff[coeffBase+4])*c2)>>16 - (int32(z.coeff[coeffBase+12])*c1)>>16
d := (int32(z.coeff[coeffBase+4])*c1)>>16 + (int32(z.coeff[coeffBase+12])*c2)>>16
m[i][0] = a + d
m[i][1] = b + c
m[i][2] = b - c
m[i][3] = a - d
coeffBase++
}
for j := 0; j < 4; j++ {
dc := m[0][j] + 4
a := dc + m[2][j]
b := dc - m[2][j]
c := (m[1][j]*c2)>>16 - (m[3][j]*c1)>>16
d := (m[1][j]*c1)>>16 + (m[3][j]*c2)>>16
z.ybr[y+j][x+0] = clip8(int32(z.ybr[y+j][x+0]) + (a+d)>>3)
z.ybr[y+j][x+1] = clip8(int32(z.ybr[y+j][x+1]) + (b+c)>>3)
z.ybr[y+j][x+2] = clip8(int32(z.ybr[y+j][x+2]) + (b-c)>>3)
z.ybr[y+j][x+3] = clip8(int32(z.ybr[y+j][x+3]) + (a-d)>>3)
}
}
func (z *Decoder) inverseDCT4DCOnly(y, x, coeffBase int) {
dc := (int32(z.coeff[coeffBase+0]) + 4) >> 3
for j := 0; j < 4; j++ {
for i := 0; i < 4; i++ {
z.ybr[y+j][x+i] = clip8(int32(z.ybr[y+j][x+i]) + dc)
}
}
}
func (z *Decoder) inverseDCT8(y, x, coeffBase int) {
z.inverseDCT4(y+0, x+0, coeffBase+0*16)
z.inverseDCT4(y+0, x+4, coeffBase+1*16)
z.inverseDCT4(y+4, x+0, coeffBase+2*16)
z.inverseDCT4(y+4, x+4, coeffBase+3*16)
}
func (z *Decoder) inverseDCT8DCOnly(y, x, coeffBase int) {
z.inverseDCT4DCOnly(y+0, x+0, coeffBase+0*16)
z.inverseDCT4DCOnly(y+0, x+4, coeffBase+1*16)
z.inverseDCT4DCOnly(y+4, x+0, coeffBase+2*16)
z.inverseDCT4DCOnly(y+4, x+4, coeffBase+3*16)
}
func (d *Decoder) inverseWHT16() {
var m [16]int32
for i := 0; i < 4; i++ {
a0 := int32(d.coeff[384+0+i]) + int32(d.coeff[384+12+i])
a1 := int32(d.coeff[384+4+i]) + int32(d.coeff[384+8+i])
a2 := int32(d.coeff[384+4+i]) - int32(d.coeff[384+8+i])
a3 := int32(d.coeff[384+0+i]) - int32(d.coeff[384+12+i])
m[0+i] = a0 + a1
m[8+i] = a0 - a1
m[4+i] = a3 + a2
m[12+i] = a3 - a2
}
out := 0
for i := 0; i < 4; i++ {
dc := m[0+i*4] + 3
a0 := dc + m[3+i*4]
a1 := m[1+i*4] + m[2+i*4]
a2 := m[1+i*4] - m[2+i*4]
a3 := dc - m[3+i*4]
d.coeff[out+0] = int16((a0 + a1) >> 3)
d.coeff[out+16] = int16((a3 + a2) >> 3)
d.coeff[out+32] = int16((a0 - a1) >> 3)
d.coeff[out+48] = int16((a3 - a2) >> 3)
out += 64
}
}
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/scale.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run gen.go
package draw
import (
"image"
"image/color"
"math"
"sync"
"golang.org/x/image/math/f64"
)
// Copy copies the part of the source image defined by src and sr and writes
// the result of a Porter-Duff composition to the part of the destination image
// defined by dst and the translation of sr so that sr.Min translates to dp.
func Copy(dst Image, dp image.Point, src image.Image, sr image.Rectangle, op Op, opts *Options) {
var o Options
if opts != nil {
o = *opts
}
dr := sr.Add(dp.Sub(sr.Min))
if o.DstMask == nil {
DrawMask(dst, dr, src, sr.Min, o.SrcMask, o.SrcMaskP.Add(sr.Min), op)
} else {
NearestNeighbor.Scale(dst, dr, src, sr, op, opts)
}
}
// Scaler scales the part of the source image defined by src and sr and writes
// the result of a Porter-Duff composition to the part of the destination image
// defined by dst and dr.
//
// A Scaler is safe to use concurrently.
type Scaler interface {
Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options)
}
// Transformer transforms the part of the source image defined by src and sr
// and writes the result of a Porter-Duff composition to the part of the
// destination image defined by dst and the affine transform m applied to sr.
//
// For example, if m is the matrix
//
// m00 m01 m02
// m10 m11 m12
//
// then the src-space point (sx, sy) maps to the dst-space point
// (m00*sx + m01*sy + m02, m10*sx + m11*sy + m12).
//
// A Transformer is safe to use concurrently.
type Transformer interface {
Transform(dst Image, m f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options)
}
// Options are optional parameters to Copy, Scale and Transform.
//
// A nil *Options means to use the default (zero) values of each field.
type Options struct {
// Masks limit what parts of the dst image are drawn to and what parts of
// the src image are drawn from.
//
// A dst or src mask image having a zero alpha (transparent) pixel value in
// the respective coordinate space means that dst pixel is entirely
// unaffected or that src pixel is considered transparent black. A full
// alpha (opaque) value means that the dst pixel is maximally affected or
// the src pixel contributes maximally. The default values, nil, are
// equivalent to fully opaque, infinitely large mask images.
//
// The DstMask is otherwise known as a clip mask, and its pixels map 1:1 to
// the dst image's pixels. DstMaskP in DstMask space corresponds to
// image.Point{X:0, Y:0} in dst space. For example, when limiting
// repainting to a 'dirty rectangle', use that image.Rectangle and a zero
// image.Point as the DstMask and DstMaskP.
//
// The SrcMask's pixels map 1:1 to the src image's pixels. SrcMaskP in
// SrcMask space corresponds to image.Point{X:0, Y:0} in src space. For
// example, when drawing font glyphs in a uniform color, use an
// *image.Uniform as the src, and use the glyph atlas image and the
// per-glyph offset as SrcMask and SrcMaskP:
// Copy(dst, dp, image.NewUniform(color), image.Rect(0, 0, glyphWidth, glyphHeight), &Options{
// SrcMask: glyphAtlas,
// SrcMaskP: glyphOffset,
// })
DstMask image.Image
DstMaskP image.Point
SrcMask image.Image
SrcMaskP image.Point
// TODO: a smooth vs sharp edges option, for arbitrary rotations?
}
// Interpolator is an interpolation algorithm, when dst and src pixels don't
// have a 1:1 correspondence.
//
// Of the interpolators provided by this package:
// - NearestNeighbor is fast but usually looks worst.
// - CatmullRom is slow but usually looks best.
// - ApproxBiLinear has reasonable speed and quality.
//
// The time taken depends on the size of dr. For kernel interpolators, the
// speed also depends on the size of sr, and so are often slower than
// non-kernel interpolators, especially when scaling down.
type Interpolator interface {
Scaler
Transformer
}
// Kernel is an interpolator that blends source pixels weighted by a symmetric
// kernel function.
type Kernel struct {
// Support is the kernel support and must be >= 0. At(t) is assumed to be
// zero when t >= Support.
Support float64
// At is the kernel function. It will only be called with t in the
// range [0, Support).
At func(t float64) float64
}
// Scale implements the Scaler interface.
func (q *Kernel) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
q.newScaler(dr.Dx(), dr.Dy(), sr.Dx(), sr.Dy(), false).Scale(dst, dr, src, sr, op, opts)
}
// NewScaler returns a Scaler that is optimized for scaling multiple times with
// the same fixed destination and source width and height.
func (q *Kernel) NewScaler(dw, dh, sw, sh int) Scaler {
return q.newScaler(dw, dh, sw, sh, true)
}
func (q *Kernel) newScaler(dw, dh, sw, sh int, usePool bool) Scaler {
z := &kernelScaler{
kernel: q,
dw: int32(dw),
dh: int32(dh),
sw: int32(sw),
sh: int32(sh),
horizontal: newDistrib(q, int32(dw), int32(sw)),
vertical: newDistrib(q, int32(dh), int32(sh)),
}
if usePool {
z.pool.New = func() interface{} {
tmp := z.makeTmpBuf()
return &tmp
}
}
return z
}
var (
// NearestNeighbor is the nearest neighbor interpolator. It is very fast,
// but usually gives very low quality results. When scaling up, the result
// will look 'blocky'.
NearestNeighbor = Interpolator(nnInterpolator{})
// ApproxBiLinear is a mixture of the nearest neighbor and bi-linear
// interpolators. It is fast, but usually gives medium quality results.
//
// It implements bi-linear interpolation when upscaling and a bi-linear
// blend of the 4 nearest neighbor pixels when downscaling. This yields
// nicer quality than nearest neighbor interpolation when upscaling, but
// the time taken is independent of the number of source pixels, unlike the
// bi-linear interpolator. When downscaling a large image, the performance
// difference can be significant.
ApproxBiLinear = Interpolator(ablInterpolator{})
// BiLinear is the tent kernel. It is slow, but usually gives high quality
// results.
BiLinear = &Kernel{1, func(t float64) float64 {
return 1 - t
}}
// CatmullRom is the Catmull-Rom kernel. It is very slow, but usually gives
// very high quality results.
//
// It is an instance of the more general cubic BC-spline kernel with parameters
// B=0 and C=0.5. See Mitchell and Netravali, "Reconstruction Filters in
// Computer Graphics", Computer Graphics, Vol. 22, No. 4, pp. 221-228.
CatmullRom = &Kernel{2, func(t float64) float64 {
if t < 1 {
return float64((float64(1.5*t)-2.5)*t*t) + 1
}
return float64((float64(float64(float64(-0.5*t)+2.5)*t)-4)*t) + 2
}}
// TODO: a Kaiser-Bessel kernel?
)
type nnInterpolator struct{}
type ablInterpolator struct{}
type kernelScaler struct {
kernel *Kernel
dw, dh, sw, sh int32
horizontal, vertical distrib
pool sync.Pool
}
func (z *kernelScaler) makeTmpBuf() [][4]float64 {
return make([][4]float64, z.dw*z.sh)
}
// source is a range of contribs, their inverse total weight, and that ITW
// divided by 0xffff.
type source struct {
i, j int32
invTotalWeight float64
invTotalWeightFFFF float64
}
// contrib is the weight of a column or row.
type contrib struct {
coord int32
weight float64
}
// distrib measures how source pixels are distributed over destination pixels.
type distrib struct {
// sources are what contribs each column or row in the source image owns,
// and the total weight of those contribs.
sources []source
// contribs are the contributions indexed by sources[s].i and sources[s].j.
contribs []contrib
}
// newDistrib returns a distrib that distributes sw source columns (or rows)
// over dw destination columns (or rows).
func newDistrib(q *Kernel, dw, sw int32) distrib {
scale := float64(sw) / float64(dw)
halfWidth, kernelArgScale := q.Support, 1.0
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
if scale > 1 {
halfWidth *= scale
kernelArgScale = 1 / scale
}
// Make the sources slice, one source for each column or row, and temporarily
// appropriate its elements' fields so that invTotalWeight is the scaled
// coordinate of the source column or row, and i and j are the lower and
// upper bounds of the range of destination columns or rows affected by the
// source column or row.
n, sources := int32(0), make([]source, dw)
for x := range sources {
center := float64((float64(x)+0.5)*scale) - 0.5
i := int32(math.Floor(center - halfWidth))
if i < 0 {
i = 0
}
j := int32(math.Ceil(center + halfWidth))
if j > sw {
j = sw
if j < i {
j = i
}
}
sources[x] = source{i: i, j: j, invTotalWeight: center}
n += j - i
}
contribs := make([]contrib, 0, n)
for k, b := range sources {
totalWeight := 0.0
l := int32(len(contribs))
for coord := b.i; coord < b.j; coord++ {
t := abs((b.invTotalWeight - float64(coord)) * kernelArgScale)
if t >= q.Support {
continue
}
weight := q.At(t)
if weight == 0 {
continue
}
totalWeight += weight
contribs = append(contribs, contrib{coord, weight})
}
totalWeight = 1 / totalWeight
sources[k] = source{
i: l,
j: int32(len(contribs)),
invTotalWeight: totalWeight,
invTotalWeightFFFF: totalWeight / 0xffff,
}
}
return distrib{sources, contribs}
}
// abs is like math.Abs, but it doesn't care about negative zero, infinities or
// NaNs.
func abs(f float64) float64 {
if f < 0 {
f = -f
}
return f
}
// ftou converts the range [0.0, 1.0] to [0, 0xffff].
func ftou(f float64) uint16 {
i := int32(float64(0xffff*f) + 0.5)
if i > 0xffff {
return 0xffff
}
if i > 0 {
return uint16(i)
}
return 0
}
// fffftou converts the range [0.0, 65535.0] to [0, 0xffff].
func fffftou(f float64) uint16 {
i := int32(f + 0.5)
if i > 0xffff {
return 0xffff
}
if i > 0 {
return uint16(i)
}
return 0
}
// invert returns the inverse of m.
//
// TODO: move this into the f64 package, once we work out the convention for
// matrix methods in that package: do they modify the receiver, take a dst
// pointer argument, or return a new value?
func invert(m *f64.Aff3) f64.Aff3 {
m00 := +m[3*1+1]
m01 := -m[3*0+1]
m02 := +float64(m[3*1+2]*m[3*0+1]) - float64(m[3*1+1]*m[3*0+2])
m10 := -m[3*1+0]
m11 := +m[3*0+0]
m12 := +float64(m[3*1+0]*m[3*0+2]) - float64(m[3*1+2]*m[3*0+0])
det := float64(m00*m11) - float64(m10*m01)
return f64.Aff3{
m00 / det,
m01 / det,
m02 / det,
m10 / det,
m11 / det,
m12 / det,
}
}
func matMul(p, q *f64.Aff3) f64.Aff3 {
return f64.Aff3{
float64(p[3*0+0]*q[3*0+0]) + float64(p[3*0+1]*q[3*1+0]),
float64(p[3*0+0]*q[3*0+1]) + float64(p[3*0+1]*q[3*1+1]),
float64(p[3*0+0]*q[3*0+2]) + float64(p[3*0+1]*q[3*1+2]) + p[3*0+2],
float64(p[3*1+0]*q[3*0+0]) + float64(p[3*1+1]*q[3*1+0]),
float64(p[3*1+0]*q[3*0+1]) + float64(p[3*1+1]*q[3*1+1]),
float64(p[3*1+0]*q[3*0+2]) + float64(p[3*1+1]*q[3*1+2]) + p[3*1+2],
}
}
// transformRect returns a rectangle dr that contains sr transformed by s2d.
func transformRect(s2d *f64.Aff3, sr *image.Rectangle) (dr image.Rectangle) {
ps := [...]image.Point{
{sr.Min.X, sr.Min.Y},
{sr.Max.X, sr.Min.Y},
{sr.Min.X, sr.Max.Y},
{sr.Max.X, sr.Max.Y},
}
for i, p := range ps {
sxf := float64(p.X)
syf := float64(p.Y)
dx := int(math.Floor(float64(s2d[0]*sxf) + float64(s2d[1]*syf) + s2d[2]))
dy := int(math.Floor(float64(s2d[3]*sxf) + float64(s2d[4]*syf) + s2d[5]))
// The +1 adjustments below are because an image.Rectangle is inclusive
// on the low end but exclusive on the high end.
if i == 0 {
dr = image.Rectangle{
Min: image.Point{dx + 0, dy + 0},
Max: image.Point{dx + 1, dy + 1},
}
continue
}
if dr.Min.X > dx {
dr.Min.X = dx
}
dx++
if dr.Max.X < dx {
dr.Max.X = dx
}
if dr.Min.Y > dy {
dr.Min.Y = dy
}
dy++
if dr.Max.Y < dy {
dr.Max.Y = dy
}
}
return dr
}
func clipAffectedDestRect(adr image.Rectangle, dstMask image.Image, dstMaskP image.Point) (image.Rectangle, image.Image) {
if dstMask == nil {
return adr, nil
}
if r, ok := dstMask.(image.Rectangle); ok {
return adr.Intersect(r.Sub(dstMaskP)), nil
}
// TODO: clip to dstMask.Bounds() if the color model implies that out-of-bounds means 0 alpha?
return adr, dstMask
}
func transform_Uniform(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Uniform, sr image.Rectangle, bias image.Point, op Op) {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
pr, pg, pb, pa := src.C.RGBA()
pa1 := (0xffff - pa) * 0x101
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := dst.PixOffset(dr.Min.X+adr.Min.X, dr.Min.Y+int(dy))
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
default:
pr, pg, pb, pa := src.C.RGBA()
pa1 := 0xffff - pa
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
pr, pg, pb, pa := src.C.RGBA()
pr8 := uint8(pr >> 8)
pg8 := uint8(pg >> 8)
pb8 := uint8(pb >> 8)
pa8 := uint8(pa >> 8)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := dst.PixOffset(dr.Min.X+adr.Min.X, dr.Min.Y+int(dy))
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
dst.Pix[d+0] = pr8
dst.Pix[d+1] = pg8
dst.Pix[d+2] = pb8
dst.Pix[d+3] = pa8
}
}
default:
pr, pg, pb, pa := src.C.RGBA()
dstColorRGBA64 := &color.RGBA64{
uint16(pr),
uint16(pg),
uint16(pb),
uint16(pa),
}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
}
}
func opaque(m image.Image) bool {
o, ok := m.(interface {
Opaque() bool
})
return ok && o.Opaque()
}
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/impl.go | // generated by "go run gen.go". DO NOT EDIT.
package draw
import (
"image"
"image/color"
"math"
"golang.org/x/image/math/f64"
)
func (z nnInterpolator) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
// Try to simplify a Scale to a Copy when DstMask is not specified.
// If DstMask is not nil, Copy will call Scale back with same dr and sr, and cause stack overflow.
if dr.Size() == sr.Size() && (opts == nil || opts.DstMask == nil) {
Copy(dst, dr.Min, src, sr, op, opts)
return
}
var o Options
if opts != nil {
o = *opts
}
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o)
case Src:
z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o)
}
} else if _, ok := src.(*image.Uniform); ok {
Draw(dst, dr, src, src.Bounds().Min, op)
} else {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.NRGBA:
z.scale_RGBA_NRGBA_Over(dst, dr, adr, src, sr, &o)
case *image.RGBA:
z.scale_RGBA_RGBA_Over(dst, dr, adr, src, sr, &o)
case image.RGBA64Image:
z.scale_RGBA_RGBA64Image_Over(dst, dr, adr, src, sr, &o)
default:
z.scale_RGBA_Image_Over(dst, dr, adr, src, sr, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.scale_RGBA64Image_RGBA64Image_Over(dst, dr, adr, src, sr, &o)
}
default:
switch src := src.(type) {
default:
z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o)
}
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.Gray:
z.scale_RGBA_Gray_Src(dst, dr, adr, src, sr, &o)
case *image.NRGBA:
z.scale_RGBA_NRGBA_Src(dst, dr, adr, src, sr, &o)
case *image.RGBA:
z.scale_RGBA_RGBA_Src(dst, dr, adr, src, sr, &o)
case *image.YCbCr:
switch src.SubsampleRatio {
default:
z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio444:
z.scale_RGBA_YCbCr444_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio422:
z.scale_RGBA_YCbCr422_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio420:
z.scale_RGBA_YCbCr420_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio440:
z.scale_RGBA_YCbCr440_Src(dst, dr, adr, src, sr, &o)
}
case image.RGBA64Image:
z.scale_RGBA_RGBA64Image_Src(dst, dr, adr, src, sr, &o)
default:
z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.scale_RGBA64Image_RGBA64Image_Src(dst, dr, adr, src, sr, &o)
}
default:
switch src := src.(type) {
default:
z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o)
}
}
}
}
}
func (z nnInterpolator) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) {
// Try to simplify a Transform to a Copy.
if s2d[0] == 1 && s2d[1] == 0 && s2d[3] == 0 && s2d[4] == 1 {
dx := int(s2d[2])
dy := int(s2d[5])
if float64(dx) == s2d[2] && float64(dy) == s2d[5] {
Copy(dst, image.Point{X: sr.Min.X + dx, Y: sr.Min.X + dy}, src, sr, op, opts)
return
}
}
var o Options
if opts != nil {
o = *opts
}
dr := transformRect(&s2d, &sr)
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
d2s := invert(&s2d)
// bias is a translation of the mapping from dst coordinates to src
// coordinates such that the latter temporarily have non-negative X
// and Y coordinates. This allows us to write int(f) instead of
// int(math.Floor(f)), since "round to zero" and "round down" are
// equivalent when f >= 0, but the former is much cheaper. The X--
// and Y-- are because the TransformLeaf methods have a "sx -= 0.5"
// adjustment.
bias := transformRect(&d2s, &adr).Min
bias.X--
bias.Y--
d2s[2] -= float64(bias.X)
d2s[5] -= float64(bias.Y)
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case Src:
z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
} else if u, ok := src.(*image.Uniform); ok {
transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op)
} else {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.NRGBA:
z.transform_RGBA_NRGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.RGBA:
z.transform_RGBA_RGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.RGBA64Image:
z.transform_RGBA_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
default:
z.transform_RGBA_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.transform_RGBA64Image_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
}
default:
switch src := src.(type) {
default:
z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
}
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.Gray:
z.transform_RGBA_Gray_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.NRGBA:
z.transform_RGBA_NRGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.RGBA:
z.transform_RGBA_RGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.YCbCr:
switch src.SubsampleRatio {
default:
z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio444:
z.transform_RGBA_YCbCr444_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio422:
z.transform_RGBA_YCbCr422_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio420:
z.transform_RGBA_YCbCr420_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio440:
z.transform_RGBA_YCbCr440_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
case image.RGBA64Image:
z.transform_RGBA_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
default:
z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.transform_RGBA64Image_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
default:
switch src := src.(type) {
default:
z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
}
}
}
}
func (nnInterpolator) scale_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.Gray, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx) - src.Rect.Min.X)
pr := uint32(src.Pix[pi]) * 0x101
out := uint8(pr >> 8)
dst.Pix[d+0] = out
dst.Pix[d+1] = out
dst.Pix[d+2] = out
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) scale_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4
pa := uint32(src.Pix[pi+3]) * 0x101
pr := uint32(src.Pix[pi+0]) * pa / 0xff
pg := uint32(src.Pix[pi+1]) * pa / 0xff
pb := uint32(src.Pix[pi+2]) * pa / 0xff
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4
pa := uint32(src.Pix[pi+3]) * 0x101
pr := uint32(src.Pix[pi+0]) * pa / 0xff
pg := uint32(src.Pix[pi+1]) * pa / 0xff
pb := uint32(src.Pix[pi+2]) * pa / 0xff
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4
pr := uint32(src.Pix[pi+0]) * 0x101
pg := uint32(src.Pix[pi+1]) * 0x101
pb := uint32(src.Pix[pi+2]) * 0x101
pa := uint32(src.Pix[pi+3]) * 0x101
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4
pr := uint32(src.Pix[pi+0]) * 0x101
pg := uint32(src.Pix[pi+1]) * 0x101
pb := uint32(src.Pix[pi+2]) * 0x101
pa := uint32(src.Pix[pi+3]) * 0x101
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X)
pj := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) scale_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X)
pj := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) scale_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X)
pj := ((sr.Min.Y+int(sy))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) scale_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X)
pj := ((sr.Min.Y+int(sy))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) scale_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy))
pa1 := (0xffff - uint32(p.A)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy))
dst.Pix[d+0] = uint8(p.R >> 8)
dst.Pix[d+1] = uint8(p.G >> 8)
dst.Pix[d+2] = uint8(p.B >> 8)
dst.Pix[d+3] = uint8(p.A >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA()
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (nnInterpolator) scale_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := (2*uint64(dx) + 1) * sw / dw2
pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA()
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (nnInterpolator) scale_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := (2*uint64(dx) + 1) * sw / dw2
p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
pa1 := 0xffff - uint32(p.A)
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
}
}
}
func (nnInterpolator) scale_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := (2*uint64(dx) + 1) * sw / dw2
p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
if dstMask != nil {
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
} else {
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p)
}
}
}
}
func (nnInterpolator) scale_Image_Image_Over(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := (2*uint64(dx) + 1) * sw / dw2
pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
pa1 := 0xffff - pa
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
func (nnInterpolator) scale_Image_Image_Src(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := (2*uint64(dx) + 1) * sw / dw2
pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
if dstMask != nil {
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
} else {
dstColorRGBA64.R = uint16(pr)
dstColorRGBA64.G = uint16(pg)
dstColorRGBA64.B = uint16(pb)
dstColorRGBA64.A = uint16(pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
}
func (nnInterpolator) transform_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Gray, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0 - src.Rect.Min.X)
pr := uint32(src.Pix[pi]) * 0x101
out := uint8(pr >> 8)
dst.Pix[d+0] = out
dst.Pix[d+1] = out
dst.Pix[d+2] = out
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) transform_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
pa := uint32(src.Pix[pi+3]) * 0x101
pr := uint32(src.Pix[pi+0]) * pa / 0xff
pg := uint32(src.Pix[pi+1]) * pa / 0xff
pb := uint32(src.Pix[pi+2]) * pa / 0xff
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
pa := uint32(src.Pix[pi+3]) * 0x101
pr := uint32(src.Pix[pi+0]) * pa / 0xff
pg := uint32(src.Pix[pi+1]) * pa / 0xff
pb := uint32(src.Pix[pi+2]) * pa / 0xff
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
pr := uint32(src.Pix[pi+0]) * 0x101
pg := uint32(src.Pix[pi+1]) * 0x101
pb := uint32(src.Pix[pi+2]) * 0x101
pa := uint32(src.Pix[pi+3]) * 0x101
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
pr := uint32(src.Pix[pi+0]) * 0x101
pg := uint32(src.Pix[pi+1]) * 0x101
pb := uint32(src.Pix[pi+2]) * 0x101
pa := uint32(src.Pix[pi+3]) * 0x101
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
pj := (sy0-src.Rect.Min.Y)*src.CStride + (sx0 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) transform_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
pj := (sy0-src.Rect.Min.Y)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) transform_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
pj := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) transform_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
pj := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + (sx0 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pr := (pyy1 + 91881*pcr1) >> 8
pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pb := (pyy1 + 116130*pcb1) >> 8
if pr < 0 {
pr = 0
} else if pr > 0xffff {
pr = 0xffff
}
if pg < 0 {
pg = 0
} else if pg > 0xffff {
pg = 0xffff
}
if pb < 0 {
pb = 0
} else if pb > 0xffff {
pb = 0xffff
}
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (nnInterpolator) transform_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
p := src.RGBA64At(sx0, sy0)
pa1 := (0xffff - uint32(p.A)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
p := src.RGBA64At(sx0, sy0)
dst.Pix[d+0] = uint8(p.R >> 8)
dst.Pix[d+1] = uint8(p.G >> 8)
dst.Pix[d+2] = uint8(p.B >> 8)
dst.Pix[d+3] = uint8(p.A >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pr, pg, pb, pa := src.At(sx0, sy0).RGBA()
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (nnInterpolator) transform_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pr, pg, pb, pa := src.At(sx0, sy0).RGBA()
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (nnInterpolator) transform_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
p := src.RGBA64At(sx0, sy0)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
pa1 := 0xffff - uint32(p.A)
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
}
}
}
func (nnInterpolator) transform_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
p := src.RGBA64At(sx0, sy0)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
if dstMask != nil {
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
} else {
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p)
}
}
}
}
func (nnInterpolator) transform_Image_Image_Over(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pr, pg, pb, pa := src.At(sx0, sy0).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
pa1 := 0xffff - pa
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
func (nnInterpolator) transform_Image_Image_Src(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
pr, pg, pb, pa := src.At(sx0, sy0).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
if dstMask != nil {
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
} else {
dstColorRGBA64.R = uint16(pr)
dstColorRGBA64.G = uint16(pg)
dstColorRGBA64.B = uint16(pb)
dstColorRGBA64.A = uint16(pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
}
func (z ablInterpolator) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
// Try to simplify a Scale to a Copy when DstMask is not specified.
// If DstMask is not nil, Copy will call Scale back with same dr and sr, and cause stack overflow.
if dr.Size() == sr.Size() && (opts == nil || opts.DstMask == nil) {
Copy(dst, dr.Min, src, sr, op, opts)
return
}
var o Options
if opts != nil {
o = *opts
}
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o)
case Src:
z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o)
}
} else if _, ok := src.(*image.Uniform); ok {
Draw(dst, dr, src, src.Bounds().Min, op)
} else {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.NRGBA:
z.scale_RGBA_NRGBA_Over(dst, dr, adr, src, sr, &o)
case *image.RGBA:
z.scale_RGBA_RGBA_Over(dst, dr, adr, src, sr, &o)
case image.RGBA64Image:
z.scale_RGBA_RGBA64Image_Over(dst, dr, adr, src, sr, &o)
default:
z.scale_RGBA_Image_Over(dst, dr, adr, src, sr, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.scale_RGBA64Image_RGBA64Image_Over(dst, dr, adr, src, sr, &o)
}
default:
switch src := src.(type) {
default:
z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o)
}
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.Gray:
z.scale_RGBA_Gray_Src(dst, dr, adr, src, sr, &o)
case *image.NRGBA:
z.scale_RGBA_NRGBA_Src(dst, dr, adr, src, sr, &o)
case *image.RGBA:
z.scale_RGBA_RGBA_Src(dst, dr, adr, src, sr, &o)
case *image.YCbCr:
switch src.SubsampleRatio {
default:
z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio444:
z.scale_RGBA_YCbCr444_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio422:
z.scale_RGBA_YCbCr422_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio420:
z.scale_RGBA_YCbCr420_Src(dst, dr, adr, src, sr, &o)
case image.YCbCrSubsampleRatio440:
z.scale_RGBA_YCbCr440_Src(dst, dr, adr, src, sr, &o)
}
case image.RGBA64Image:
z.scale_RGBA_RGBA64Image_Src(dst, dr, adr, src, sr, &o)
default:
z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.scale_RGBA64Image_RGBA64Image_Src(dst, dr, adr, src, sr, &o)
}
default:
switch src := src.(type) {
default:
z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o)
}
}
}
}
}
func (z ablInterpolator) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) {
// Try to simplify a Transform to a Copy.
if s2d[0] == 1 && s2d[1] == 0 && s2d[3] == 0 && s2d[4] == 1 {
dx := int(s2d[2])
dy := int(s2d[5])
if float64(dx) == s2d[2] && float64(dy) == s2d[5] {
Copy(dst, image.Point{X: sr.Min.X + dx, Y: sr.Min.X + dy}, src, sr, op, opts)
return
}
}
var o Options
if opts != nil {
o = *opts
}
dr := transformRect(&s2d, &sr)
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
d2s := invert(&s2d)
// bias is a translation of the mapping from dst coordinates to src
// coordinates such that the latter temporarily have non-negative X
// and Y coordinates. This allows us to write int(f) instead of
// int(math.Floor(f)), since "round to zero" and "round down" are
// equivalent when f >= 0, but the former is much cheaper. The X--
// and Y-- are because the TransformLeaf methods have a "sx -= 0.5"
// adjustment.
bias := transformRect(&d2s, &adr).Min
bias.X--
bias.Y--
d2s[2] -= float64(bias.X)
d2s[5] -= float64(bias.Y)
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case Src:
z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
} else if u, ok := src.(*image.Uniform); ok {
transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op)
} else {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.NRGBA:
z.transform_RGBA_NRGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.RGBA:
z.transform_RGBA_RGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.RGBA64Image:
z.transform_RGBA_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
default:
z.transform_RGBA_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.transform_RGBA64Image_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
}
default:
switch src := src.(type) {
default:
z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
}
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.Gray:
z.transform_RGBA_Gray_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.NRGBA:
z.transform_RGBA_NRGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.RGBA:
z.transform_RGBA_RGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case *image.YCbCr:
switch src.SubsampleRatio {
default:
z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio444:
z.transform_RGBA_YCbCr444_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio422:
z.transform_RGBA_YCbCr422_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio420:
z.transform_RGBA_YCbCr420_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
case image.YCbCrSubsampleRatio440:
z.transform_RGBA_YCbCr440_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
case image.RGBA64Image:
z.transform_RGBA_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
default:
z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
z.transform_RGBA64Image_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
default:
switch src := src.(type) {
default:
z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
}
}
}
}
func (ablInterpolator) scale_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.Gray, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s00ru := uint32(src.Pix[s00i]) * 0x101
s00r := float64(s00ru)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s10ru := uint32(src.Pix[s10i]) * 0x101
s10r := float64(s10ru)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s01ru := uint32(src.Pix[s01i]) * 0x101
s01r := float64(s01ru)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s11ru := uint32(src.Pix[s11i]) * 0x101
s11r := float64(s11ru)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
pr := uint32(s11r)
out := uint8(pr >> 8)
dst.Pix[d+0] = out
dst.Pix[d+1] = out
dst.Pix[d+2] = out
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) scale_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff
s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff
s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff
s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff
s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff
s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff
s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff
s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff
s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff
s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff
s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff
s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff
s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff
s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff
s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff
s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff
s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s00ru := uint32(src.Pix[s00i+0]) * 0x101
s00gu := uint32(src.Pix[s00i+1]) * 0x101
s00bu := uint32(src.Pix[s00i+2]) * 0x101
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s10ru := uint32(src.Pix[s10i+0]) * 0x101
s10gu := uint32(src.Pix[s10i+1]) * 0x101
s10bu := uint32(src.Pix[s10i+2]) * 0x101
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s01ru := uint32(src.Pix[s01i+0]) * 0x101
s01gu := uint32(src.Pix[s01i+1]) * 0x101
s01bu := uint32(src.Pix[s01i+2]) * 0x101
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s11ru := uint32(src.Pix[s11i+0]) * 0x101
s11gu := uint32(src.Pix[s11i+1]) * 0x101
s11bu := uint32(src.Pix[s11i+2]) * 0x101
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s00ru := uint32(src.Pix[s00i+0]) * 0x101
s00gu := uint32(src.Pix[s00i+1]) * 0x101
s00bu := uint32(src.Pix[s00i+2]) * 0x101
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s10ru := uint32(src.Pix[s10i+0]) * 0x101
s10gu := uint32(src.Pix[s10i+1]) * 0x101
s10bu := uint32(src.Pix[s10i+2]) * 0x101
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4
s01ru := uint32(src.Pix[s01i+0]) * 0x101
s01gu := uint32(src.Pix[s01i+1]) * 0x101
s01bu := uint32(src.Pix[s01i+2]) * 0x101
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4
s11ru := uint32(src.Pix[s11i+0]) * 0x101
s11gu := uint32(src.Pix[s11i+1]) * 0x101
s11bu := uint32(src.Pix[s11i+2]) * 0x101
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s00j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s10j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s01j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s11j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) scale_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s00j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s10j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s01j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s11j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) scale_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s00j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s10j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s01j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s11j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) scale_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s00j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s10j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
s01j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
s11j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) scale_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0))
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0))
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1))
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1))
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
pa1 := (0xffff - uint32(p.A)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0))
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0))
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1))
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1))
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
dst.Pix[d+0] = uint8(p.R >> 8)
dst.Pix[d+1] = uint8(p.G >> 8)
dst.Pix[d+2] = uint8(p.B >> 8)
dst.Pix[d+3] = uint8(p.A >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA()
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA()
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA()
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA()
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (ablInterpolator) scale_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA()
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA()
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA()
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA()
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (ablInterpolator) scale_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s00u.R = uint16(uint32(s00u.R) * ma / 0xffff)
s00u.G = uint16(uint32(s00u.G) * ma / 0xffff)
s00u.B = uint16(uint32(s00u.B) * ma / 0xffff)
s00u.A = uint16(uint32(s00u.A) * ma / 0xffff)
}
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s10u.R = uint16(uint32(s10u.R) * ma / 0xffff)
s10u.G = uint16(uint32(s10u.G) * ma / 0xffff)
s10u.B = uint16(uint32(s10u.B) * ma / 0xffff)
s10u.A = uint16(uint32(s10u.A) * ma / 0xffff)
}
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s01u.R = uint16(uint32(s01u.R) * ma / 0xffff)
s01u.G = uint16(uint32(s01u.G) * ma / 0xffff)
s01u.B = uint16(uint32(s01u.B) * ma / 0xffff)
s01u.A = uint16(uint32(s01u.A) * ma / 0xffff)
}
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s11u.R = uint16(uint32(s11u.R) * ma / 0xffff)
s11u.G = uint16(uint32(s11u.G) * ma / 0xffff)
s11u.B = uint16(uint32(s11u.B) * ma / 0xffff)
s11u.A = uint16(uint32(s11u.A) * ma / 0xffff)
}
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
pa1 := 0xffff - uint32(p.A)
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
}
}
}
func (ablInterpolator) scale_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s00u.R = uint16(uint32(s00u.R) * ma / 0xffff)
s00u.G = uint16(uint32(s00u.G) * ma / 0xffff)
s00u.B = uint16(uint32(s00u.B) * ma / 0xffff)
s00u.A = uint16(uint32(s00u.A) * ma / 0xffff)
}
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s10u.R = uint16(uint32(s10u.R) * ma / 0xffff)
s10u.G = uint16(uint32(s10u.G) * ma / 0xffff)
s10u.B = uint16(uint32(s10u.B) * ma / 0xffff)
s10u.A = uint16(uint32(s10u.A) * ma / 0xffff)
}
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s01u.R = uint16(uint32(s01u.R) * ma / 0xffff)
s01u.G = uint16(uint32(s01u.G) * ma / 0xffff)
s01u.B = uint16(uint32(s01u.B) * ma / 0xffff)
s01u.A = uint16(uint32(s01u.A) * ma / 0xffff)
}
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s11u.R = uint16(uint32(s11u.R) * ma / 0xffff)
s11u.G = uint16(uint32(s11u.G) * ma / 0xffff)
s11u.B = uint16(uint32(s11u.B) * ma / 0xffff)
s11u.A = uint16(uint32(s11u.A) * ma / 0xffff)
}
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
if dstMask != nil {
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
} else {
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p)
}
}
}
}
func (ablInterpolator) scale_Image_Image_Over(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s00ru = s00ru * ma / 0xffff
s00gu = s00gu * ma / 0xffff
s00bu = s00bu * ma / 0xffff
s00au = s00au * ma / 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s10ru = s10ru * ma / 0xffff
s10gu = s10gu * ma / 0xffff
s10bu = s10bu * ma / 0xffff
s10au = s10au * ma / 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s01ru = s01ru * ma / 0xffff
s01gu = s01gu * ma / 0xffff
s01bu = s01bu * ma / 0xffff
s01au = s01au * ma / 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s11ru = s11ru * ma / 0xffff
s11gu = s11gu * ma / 0xffff
s11bu = s11bu * ma / 0xffff
s11au = s11au * ma / 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
pa1 := 0xffff - pa
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
func (ablInterpolator) scale_Image_Image_Src(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw-1, sh-1
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s00ru = s00ru * ma / 0xffff
s00gu = s00gu * ma / 0xffff
s00bu = s00bu * ma / 0xffff
s00au = s00au * ma / 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA()
s10ru = s10ru * ma / 0xffff
s10gu = s10gu * ma / 0xffff
s10bu = s10bu * ma / 0xffff
s10au = s10au * ma / 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s01ru = s01ru * ma / 0xffff
s01gu = s01gu * ma / 0xffff
s01bu = s01bu * ma / 0xffff
s01au = s01au * ma / 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA()
s11ru = s11ru * ma / 0xffff
s11gu = s11gu * ma / 0xffff
s11bu = s11bu * ma / 0xffff
s11au = s11au * ma / 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
if dstMask != nil {
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
} else {
dstColorRGBA64.R = uint16(pr)
dstColorRGBA64.G = uint16(pg)
dstColorRGBA64.B = uint16(pb)
dstColorRGBA64.A = uint16(pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
}
func (ablInterpolator) transform_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Gray, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0 - src.Rect.Min.X)
s00ru := uint32(src.Pix[s00i]) * 0x101
s00r := float64(s00ru)
s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1 - src.Rect.Min.X)
s10ru := uint32(src.Pix[s10i]) * 0x101
s10r := float64(s10ru)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0 - src.Rect.Min.X)
s01ru := uint32(src.Pix[s01i]) * 0x101
s01r := float64(s01ru)
s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1 - src.Rect.Min.X)
s11ru := uint32(src.Pix[s11i]) * 0x101
s11r := float64(s11ru)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
pr := uint32(s11r)
out := uint8(pr >> 8)
dst.Pix[d+0] = out
dst.Pix[d+1] = out
dst.Pix[d+2] = out
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) transform_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff
s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff
s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff
s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff
s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff
s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff
s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff
s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff
s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff
s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff
s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff
s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff
s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff
s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff
s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff
s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff
s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s00ru := uint32(src.Pix[s00i+0]) * 0x101
s00gu := uint32(src.Pix[s00i+1]) * 0x101
s00bu := uint32(src.Pix[s00i+2]) * 0x101
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s10ru := uint32(src.Pix[s10i+0]) * 0x101
s10gu := uint32(src.Pix[s10i+1]) * 0x101
s10bu := uint32(src.Pix[s10i+2]) * 0x101
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s01ru := uint32(src.Pix[s01i+0]) * 0x101
s01gu := uint32(src.Pix[s01i+1]) * 0x101
s01bu := uint32(src.Pix[s01i+2]) * 0x101
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s11ru := uint32(src.Pix[s11i+0]) * 0x101
s11gu := uint32(src.Pix[s11i+1]) * 0x101
s11bu := uint32(src.Pix[s11i+2]) * 0x101
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s00ru := uint32(src.Pix[s00i+0]) * 0x101
s00gu := uint32(src.Pix[s00i+1]) * 0x101
s00bu := uint32(src.Pix[s00i+2]) * 0x101
s00au := uint32(src.Pix[s00i+3]) * 0x101
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s10ru := uint32(src.Pix[s10i+0]) * 0x101
s10gu := uint32(src.Pix[s10i+1]) * 0x101
s10bu := uint32(src.Pix[s10i+2]) * 0x101
s10au := uint32(src.Pix[s10i+3]) * 0x101
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4
s01ru := uint32(src.Pix[s01i+0]) * 0x101
s01gu := uint32(src.Pix[s01i+1]) * 0x101
s01bu := uint32(src.Pix[s01i+2]) * 0x101
s01au := uint32(src.Pix[s01i+3]) * 0x101
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4
s11ru := uint32(src.Pix[s11i+0]) * 0x101
s11gu := uint32(src.Pix[s11i+1]) * 0x101
s11bu := uint32(src.Pix[s11i+2]) * 0x101
s11au := uint32(src.Pix[s11i+3]) * 0x101
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s00j := (sy0-src.Rect.Min.Y)*src.CStride + (sx0 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s10j := (sy0-src.Rect.Min.Y)*src.CStride + (sx1 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s01j := (sy1-src.Rect.Min.Y)*src.CStride + (sx0 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s11j := (sy1-src.Rect.Min.Y)*src.CStride + (sx1 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) transform_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s00j := (sy0-src.Rect.Min.Y)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s10j := (sy0-src.Rect.Min.Y)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s01j := (sy1-src.Rect.Min.Y)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s11j := (sy1-src.Rect.Min.Y)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) transform_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s00j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s10j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s01j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s11j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) transform_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s00j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + (sx0 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s00yy1 := int(src.Y[s00i]) * 0x10101
s00cb1 := int(src.Cb[s00j]) - 128
s00cr1 := int(src.Cr[s00j]) - 128
s00ru := (s00yy1 + 91881*s00cr1) >> 8
s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8
s00bu := (s00yy1 + 116130*s00cb1) >> 8
if s00ru < 0 {
s00ru = 0
} else if s00ru > 0xffff {
s00ru = 0xffff
}
if s00gu < 0 {
s00gu = 0
} else if s00gu > 0xffff {
s00gu = 0xffff
}
if s00bu < 0 {
s00bu = 0
} else if s00bu > 0xffff {
s00bu = 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s10j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + (sx1 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s10yy1 := int(src.Y[s10i]) * 0x10101
s10cb1 := int(src.Cb[s10j]) - 128
s10cr1 := int(src.Cr[s10j]) - 128
s10ru := (s10yy1 + 91881*s10cr1) >> 8
s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8
s10bu := (s10yy1 + 116130*s10cb1) >> 8
if s10ru < 0 {
s10ru = 0
} else if s10ru > 0xffff {
s10ru = 0xffff
}
if s10gu < 0 {
s10gu = 0
} else if s10gu > 0xffff {
s10gu = 0xffff
}
if s10bu < 0 {
s10bu = 0
} else if s10bu > 0xffff {
s10bu = 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X)
s01j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + (sx0 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s01yy1 := int(src.Y[s01i]) * 0x10101
s01cb1 := int(src.Cb[s01j]) - 128
s01cr1 := int(src.Cr[s01j]) - 128
s01ru := (s01yy1 + 91881*s01cr1) >> 8
s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8
s01bu := (s01yy1 + 116130*s01cb1) >> 8
if s01ru < 0 {
s01ru = 0
} else if s01ru > 0xffff {
s01ru = 0xffff
}
if s01gu < 0 {
s01gu = 0
} else if s01gu > 0xffff {
s01gu = 0xffff
}
if s01bu < 0 {
s01bu = 0
} else if s01bu > 0xffff {
s01bu = 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X)
s11j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + (sx1 - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
s11yy1 := int(src.Y[s11i]) * 0x10101
s11cb1 := int(src.Cb[s11j]) - 128
s11cr1 := int(src.Cr[s11j]) - 128
s11ru := (s11yy1 + 91881*s11cr1) >> 8
s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8
s11bu := (s11yy1 + 116130*s11cb1) >> 8
if s11ru < 0 {
s11ru = 0
} else if s11ru > 0xffff {
s11ru = 0xffff
}
if s11gu < 0 {
s11gu = 0
} else if s11gu > 0xffff {
s11gu = 0xffff
}
if s11bu < 0 {
s11bu = 0
} else if s11bu > 0xffff {
s11bu = 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (ablInterpolator) transform_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00u := src.RGBA64At(sx0, sy0)
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sx1, sy0)
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sx0, sy1)
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sx1, sy1)
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
pa1 := (0xffff - uint32(p.A)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00u := src.RGBA64At(sx0, sy0)
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sx1, sy0)
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sx0, sy1)
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sx1, sy1)
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
dst.Pix[d+0] = uint8(p.R >> 8)
dst.Pix[d+1] = uint8(p.G >> 8)
dst.Pix[d+2] = uint8(p.B >> 8)
dst.Pix[d+3] = uint8(p.A >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA()
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA()
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA()
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA()
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
pa1 := (0xffff - pa) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
}
}
}
func (ablInterpolator) transform_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA()
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA()
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA()
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA()
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
dst.Pix[d+0] = uint8(pr >> 8)
dst.Pix[d+1] = uint8(pg >> 8)
dst.Pix[d+2] = uint8(pb >> 8)
dst.Pix[d+3] = uint8(pa >> 8)
}
}
}
func (ablInterpolator) transform_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00u := src.RGBA64At(sx0, sy0)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
s00u.R = uint16(uint32(s00u.R) * ma / 0xffff)
s00u.G = uint16(uint32(s00u.G) * ma / 0xffff)
s00u.B = uint16(uint32(s00u.B) * ma / 0xffff)
s00u.A = uint16(uint32(s00u.A) * ma / 0xffff)
}
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sx1, sy0)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA()
s10u.R = uint16(uint32(s10u.R) * ma / 0xffff)
s10u.G = uint16(uint32(s10u.G) * ma / 0xffff)
s10u.B = uint16(uint32(s10u.B) * ma / 0xffff)
s10u.A = uint16(uint32(s10u.A) * ma / 0xffff)
}
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sx0, sy1)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA()
s01u.R = uint16(uint32(s01u.R) * ma / 0xffff)
s01u.G = uint16(uint32(s01u.G) * ma / 0xffff)
s01u.B = uint16(uint32(s01u.B) * ma / 0xffff)
s01u.A = uint16(uint32(s01u.A) * ma / 0xffff)
}
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sx1, sy1)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA()
s11u.R = uint16(uint32(s11u.R) * ma / 0xffff)
s11u.G = uint16(uint32(s11u.G) * ma / 0xffff)
s11u.B = uint16(uint32(s11u.B) * ma / 0xffff)
s11u.A = uint16(uint32(s11u.A) * ma / 0xffff)
}
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
}
pa1 := 0xffff - uint32(p.A)
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
}
}
}
func (ablInterpolator) transform_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00u := src.RGBA64At(sx0, sy0)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
s00u.R = uint16(uint32(s00u.R) * ma / 0xffff)
s00u.G = uint16(uint32(s00u.G) * ma / 0xffff)
s00u.B = uint16(uint32(s00u.B) * ma / 0xffff)
s00u.A = uint16(uint32(s00u.A) * ma / 0xffff)
}
s00r := float64(s00u.R)
s00g := float64(s00u.G)
s00b := float64(s00u.B)
s00a := float64(s00u.A)
s10u := src.RGBA64At(sx1, sy0)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA()
s10u.R = uint16(uint32(s10u.R) * ma / 0xffff)
s10u.G = uint16(uint32(s10u.G) * ma / 0xffff)
s10u.B = uint16(uint32(s10u.B) * ma / 0xffff)
s10u.A = uint16(uint32(s10u.A) * ma / 0xffff)
}
s10r := float64(s10u.R)
s10g := float64(s10u.G)
s10b := float64(s10u.B)
s10a := float64(s10u.A)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01u := src.RGBA64At(sx0, sy1)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA()
s01u.R = uint16(uint32(s01u.R) * ma / 0xffff)
s01u.G = uint16(uint32(s01u.G) * ma / 0xffff)
s01u.B = uint16(uint32(s01u.B) * ma / 0xffff)
s01u.A = uint16(uint32(s01u.A) * ma / 0xffff)
}
s01r := float64(s01u.R)
s01g := float64(s01u.G)
s01b := float64(s01u.B)
s01a := float64(s01u.A)
s11u := src.RGBA64At(sx1, sy1)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA()
s11u.R = uint16(uint32(s11u.R) * ma / 0xffff)
s11u.G = uint16(uint32(s11u.G) * ma / 0xffff)
s11u.B = uint16(uint32(s11u.B) * ma / 0xffff)
s11u.A = uint16(uint32(s11u.A) * ma / 0xffff)
}
s11r := float64(s11u.R)
s11g := float64(s11u.G)
s11b := float64(s11u.B)
s11a := float64(s11u.A)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)}
if dstMask != nil {
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
p.R = uint16(uint32(p.R) * ma / 0xffff)
p.G = uint16(uint32(p.G) * ma / 0xffff)
p.B = uint16(uint32(p.B) * ma / 0xffff)
p.A = uint16(uint32(p.A) * ma / 0xffff)
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R))
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G))
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B))
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A))
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
} else {
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p)
}
}
}
}
func (ablInterpolator) transform_Image_Image_Over(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
s00ru = s00ru * ma / 0xffff
s00gu = s00gu * ma / 0xffff
s00bu = s00bu * ma / 0xffff
s00au = s00au * ma / 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA()
s10ru = s10ru * ma / 0xffff
s10gu = s10gu * ma / 0xffff
s10bu = s10bu * ma / 0xffff
s10au = s10au * ma / 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA()
s01ru = s01ru * ma / 0xffff
s01gu = s01gu * ma / 0xffff
s01bu = s01bu * ma / 0xffff
s01au = s01au * ma / 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA()
s11ru = s11ru * ma / 0xffff
s11gu = s11gu * ma / 0xffff
s11bu = s11bu * ma / 0xffff
s11au = s11au * ma / 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
}
pa1 := 0xffff - pa
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
func (ablInterpolator) transform_Image_Image_Src(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) {
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA()
s00ru = s00ru * ma / 0xffff
s00gu = s00gu * ma / 0xffff
s00bu = s00bu * ma / 0xffff
s00au = s00au * ma / 0xffff
}
s00r := float64(s00ru)
s00g := float64(s00gu)
s00b := float64(s00bu)
s00a := float64(s00au)
s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA()
s10ru = s10ru * ma / 0xffff
s10gu = s10gu * ma / 0xffff
s10bu = s10bu * ma / 0xffff
s10au = s10au * ma / 0xffff
}
s10r := float64(s10ru)
s10g := float64(s10gu)
s10b := float64(s10bu)
s10a := float64(s10au)
s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r)
s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g)
s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b)
s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a)
s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA()
s01ru = s01ru * ma / 0xffff
s01gu = s01gu * ma / 0xffff
s01bu = s01bu * ma / 0xffff
s01au = s01au * ma / 0xffff
}
s01r := float64(s01ru)
s01g := float64(s01gu)
s01b := float64(s01bu)
s01a := float64(s01au)
s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA()
s11ru = s11ru * ma / 0xffff
s11gu = s11gu * ma / 0xffff
s11bu = s11bu * ma / 0xffff
s11au = s11au * ma / 0xffff
}
s11r := float64(s11ru)
s11g := float64(s11gu)
s11b := float64(s11bu)
s11a := float64(s11au)
s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r)
s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g)
s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b)
s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a)
s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r)
s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g)
s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b)
s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a)
pr := uint32(s11r)
pg := uint32(s11g)
pb := uint32(s11b)
pa := uint32(s11a)
if dstMask != nil {
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr = pr * ma / 0xffff
pg = pg * ma / 0xffff
pb = pb * ma / 0xffff
pa = pa * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
} else {
dstColorRGBA64.R = uint16(pr)
dstColorRGBA64.G = uint16(pg)
dstColorRGBA64.B = uint16(pb)
dstColorRGBA64.A = uint16(pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
}
func (z *kernelScaler) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
if z.dw != int32(dr.Dx()) || z.dh != int32(dr.Dy()) || z.sw != int32(sr.Dx()) || z.sh != int32(sr.Dy()) {
z.kernel.Scale(dst, dr, src, sr, op, opts)
return
}
var o Options
if opts != nil {
o = *opts
}
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
if _, ok := src.(*image.Uniform); ok && o.DstMask == nil && o.SrcMask == nil && sr.In(src.Bounds()) {
Draw(dst, dr, src, src.Bounds().Min, op)
return
}
// Create a temporary buffer:
// scaleX distributes the source image's columns over the temporary image.
// scaleY distributes the temporary image's rows over the destination image.
var tmp [][4]float64
if z.pool.New != nil {
tmpp := z.pool.Get().(*[][4]float64)
defer z.pool.Put(tmpp)
tmp = *tmpp
} else {
tmp = z.makeTmpBuf()
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.SrcMask != nil || !sr.In(src.Bounds()) {
z.scaleX_Image(tmp, src, sr, &o)
} else {
switch src := src.(type) {
case *image.Gray:
z.scaleX_Gray(tmp, src, sr, &o)
case *image.NRGBA:
z.scaleX_NRGBA(tmp, src, sr, &o)
case *image.RGBA:
z.scaleX_RGBA(tmp, src, sr, &o)
case *image.YCbCr:
switch src.SubsampleRatio {
default:
z.scaleX_Image(tmp, src, sr, &o)
case image.YCbCrSubsampleRatio444:
z.scaleX_YCbCr444(tmp, src, sr, &o)
case image.YCbCrSubsampleRatio422:
z.scaleX_YCbCr422(tmp, src, sr, &o)
case image.YCbCrSubsampleRatio420:
z.scaleX_YCbCr420(tmp, src, sr, &o)
case image.YCbCrSubsampleRatio440:
z.scaleX_YCbCr440(tmp, src, sr, &o)
}
case image.RGBA64Image:
z.scaleX_RGBA64Image(tmp, src, sr, &o)
default:
z.scaleX_Image(tmp, src, sr, &o)
}
}
if o.DstMask != nil {
switch op {
case Over:
z.scaleY_Image_Over(dst, dr, adr, tmp, &o)
case Src:
z.scaleY_Image_Src(dst, dr, adr, tmp, &o)
}
} else {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
z.scaleY_RGBA_Over(dst, dr, adr, tmp, &o)
case RGBA64Image:
z.scaleY_RGBA64Image_Over(dst, dr, adr, tmp, &o)
default:
z.scaleY_Image_Over(dst, dr, adr, tmp, &o)
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
z.scaleY_RGBA_Src(dst, dr, adr, tmp, &o)
case RGBA64Image:
z.scaleY_RGBA64Image_Src(dst, dr, adr, tmp, &o)
default:
z.scaleY_Image_Src(dst, dr, adr, tmp, &o)
}
}
}
}
func (q *Kernel) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) {
var o Options
if opts != nil {
o = *opts
}
dr := transformRect(&s2d, &sr)
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
d2s := invert(&s2d)
// bias is a translation of the mapping from dst coordinates to src
// coordinates such that the latter temporarily have non-negative X
// and Y coordinates. This allows us to write int(f) instead of
// int(math.Floor(f)), since "round to zero" and "round down" are
// equivalent when f >= 0, but the former is much cheaper. The X--
// and Y-- are because the TransformLeaf methods have a "sx -= 0.5"
// adjustment.
bias := transformRect(&d2s, &adr).Min
bias.X--
bias.Y--
d2s[2] -= float64(bias.X)
d2s[5] -= float64(bias.Y)
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if u, ok := src.(*image.Uniform); ok && o.DstMask != nil && o.SrcMask != nil && sr.In(src.Bounds()) {
transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op)
return
}
xscale := abs(d2s[0])
if s := abs(d2s[1]); xscale < s {
xscale = s
}
yscale := abs(d2s[3])
if s := abs(d2s[4]); yscale < s {
yscale = s
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
q.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case Src:
q.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
} else {
switch op {
case Over:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.NRGBA:
q.transform_RGBA_NRGBA_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case *image.RGBA:
q.transform_RGBA_RGBA_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case image.RGBA64Image:
q.transform_RGBA_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
default:
q.transform_RGBA_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
q.transform_RGBA64Image_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
default:
switch src := src.(type) {
default:
q.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
}
case Src:
switch dst := dst.(type) {
case *image.RGBA:
switch src := src.(type) {
case *image.Gray:
q.transform_RGBA_Gray_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case *image.NRGBA:
q.transform_RGBA_NRGBA_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case *image.RGBA:
q.transform_RGBA_RGBA_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case *image.YCbCr:
switch src.SubsampleRatio {
default:
q.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case image.YCbCrSubsampleRatio444:
q.transform_RGBA_YCbCr444_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case image.YCbCrSubsampleRatio422:
q.transform_RGBA_YCbCr422_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case image.YCbCrSubsampleRatio420:
q.transform_RGBA_YCbCr420_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case image.YCbCrSubsampleRatio440:
q.transform_RGBA_YCbCr440_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
case image.RGBA64Image:
q.transform_RGBA_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
default:
q.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
case RGBA64Image:
switch src := src.(type) {
case image.RGBA64Image:
q.transform_RGBA64Image_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
default:
switch src := src.(type) {
default:
q.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
}
}
}
}
func (z *kernelScaler) scaleX_Gray(tmp [][4]float64, src *image.Gray, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
pru := uint32(src.Pix[pi]) * 0x101
pr += float64(float64(pru) * c.weight)
}
pr *= s.invTotalWeightFFFF
tmp[t] = [4]float64{
pr,
pr,
pr,
1,
}
t++
}
}
}
func (z *kernelScaler) scaleX_NRGBA(tmp [][4]float64, src *image.NRGBA, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb, pa float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(c.coord)-src.Rect.Min.X)*4
pau := uint32(src.Pix[pi+3]) * 0x101
pru := uint32(src.Pix[pi+0]) * pau / 0xff
pgu := uint32(src.Pix[pi+1]) * pau / 0xff
pbu := uint32(src.Pix[pi+2]) * pau / 0xff
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
pa += float64(float64(pau) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
pa * s.invTotalWeightFFFF,
}
t++
}
}
}
func (z *kernelScaler) scaleX_RGBA(tmp [][4]float64, src *image.RGBA, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb, pa float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(c.coord)-src.Rect.Min.X)*4
pru := uint32(src.Pix[pi+0]) * 0x101
pgu := uint32(src.Pix[pi+1]) * 0x101
pbu := uint32(src.Pix[pi+2]) * 0x101
pau := uint32(src.Pix[pi+3]) * 0x101
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
pa += float64(float64(pau) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
pa * s.invTotalWeightFFFF,
}
t++
}
}
}
func (z *kernelScaler) scaleX_YCbCr444(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
pj := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
1,
}
t++
}
}
}
func (z *kernelScaler) scaleX_YCbCr422(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
pj := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(c.coord))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
1,
}
t++
}
}
}
func (z *kernelScaler) scaleX_YCbCr420(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
pj := ((sr.Min.Y+int(y))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(c.coord))/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
1,
}
t++
}
}
}
func (z *kernelScaler) scaleX_YCbCr440(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) {
t := 0
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
pj := ((sr.Min.Y+int(y))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
1,
}
t++
}
}
}
func (z *kernelScaler) scaleX_RGBA64Image(tmp [][4]float64, src image.RGBA64Image, sr image.Rectangle, opts *Options) {
t := 0
srcMask, smp := opts.SrcMask, opts.SrcMaskP
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb, pa float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pu := src.RGBA64At(sr.Min.X+int(c.coord), sr.Min.Y+int(y))
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(c.coord), smp.Y+sr.Min.Y+int(y)).RGBA()
pu.R = uint16(uint32(pu.R) * ma / 0xffff)
pu.G = uint16(uint32(pu.G) * ma / 0xffff)
pu.B = uint16(uint32(pu.B) * ma / 0xffff)
pu.A = uint16(uint32(pu.A) * ma / 0xffff)
}
pr += float64(float64(pu.R) * c.weight)
pg += float64(float64(pu.G) * c.weight)
pb += float64(float64(pu.B) * c.weight)
pa += float64(float64(pu.A) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
pa * s.invTotalWeightFFFF,
}
t++
}
}
}
func (z *kernelScaler) scaleX_Image(tmp [][4]float64, src image.Image, sr image.Rectangle, opts *Options) {
t := 0
srcMask, smp := opts.SrcMask, opts.SrcMaskP
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb, pa float64
for _, c := range z.horizontal.contribs[s.i:s.j] {
pru, pgu, pbu, pau := src.At(sr.Min.X+int(c.coord), sr.Min.Y+int(y)).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(c.coord), smp.Y+sr.Min.Y+int(y)).RGBA()
pru = pru * ma / 0xffff
pgu = pgu * ma / 0xffff
pbu = pbu * ma / 0xffff
pau = pau * ma / 0xffff
}
pr += float64(float64(pru) * c.weight)
pg += float64(float64(pgu) * c.weight)
pb += float64(float64(pbu) * c.weight)
pa += float64(float64(pau) * c.weight)
}
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF,
pg * s.invTotalWeightFFFF,
pb * s.invTotalWeightFFFF,
pa * s.invTotalWeightFFFF,
}
t++
}
}
}
func (z *kernelScaler) scaleY_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
d := (dr.Min.Y+adr.Min.Y-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+int(dx)-dst.Rect.Min.X)*4
for _, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] {
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
pr0 := uint32(ftou(pr * s.invTotalWeight))
pg0 := uint32(ftou(pg * s.invTotalWeight))
pb0 := uint32(ftou(pb * s.invTotalWeight))
pa0 := uint32(ftou(pa * s.invTotalWeight))
pa1 := (0xffff - uint32(pa0)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8)
d += dst.Stride
}
}
}
func (z *kernelScaler) scaleY_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
d := (dr.Min.Y+adr.Min.Y-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+int(dx)-dst.Rect.Min.X)*4
for _, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] {
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
dst.Pix[d+0] = uint8(ftou(pr*s.invTotalWeight) >> 8)
dst.Pix[d+1] = uint8(ftou(pg*s.invTotalWeight) >> 8)
dst.Pix[d+2] = uint8(ftou(pb*s.invTotalWeight) >> 8)
dst.Pix[d+3] = uint8(ftou(pa*s.invTotalWeight) >> 8)
d += dst.Stride
}
}
}
func (z *kernelScaler) scaleY_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] {
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy))
pr0 := uint32(ftou(pr * s.invTotalWeight))
pg0 := uint32(ftou(pg * s.invTotalWeight))
pb0 := uint32(ftou(pb * s.invTotalWeight))
pa0 := uint32(ftou(pa * s.invTotalWeight))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA()
pr0 = pr0 * ma / 0xffff
pg0 = pg0 * ma / 0xffff
pb0 = pb0 * ma / 0xffff
pa0 = pa0 * ma / 0xffff
}
pa1 := 0xffff - pa0
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr0)
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg0)
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb0)
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa0)
dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColorRGBA64)
}
}
}
func (z *kernelScaler) scaleY_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] {
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
if dstMask != nil {
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy))
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA()
pr := uint32(ftou(pr*s.invTotalWeight)) * ma / 0xffff
pg := uint32(ftou(pg*s.invTotalWeight)) * ma / 0xffff
pb := uint32(ftou(pb*s.invTotalWeight)) * ma / 0xffff
pa := uint32(ftou(pa*s.invTotalWeight)) * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa)
dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColorRGBA64)
} else {
dstColorRGBA64.R = ftou(pr * s.invTotalWeight)
dstColorRGBA64.G = ftou(pg * s.invTotalWeight)
dstColorRGBA64.B = ftou(pb * s.invTotalWeight)
dstColorRGBA64.A = ftou(pa * s.invTotalWeight)
dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColorRGBA64)
}
}
}
}
func (z *kernelScaler) scaleY_Image_Over(dst Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] {
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy)).RGBA()
pr0 := uint32(ftou(pr * s.invTotalWeight))
pg0 := uint32(ftou(pg * s.invTotalWeight))
pb0 := uint32(ftou(pb * s.invTotalWeight))
pa0 := uint32(ftou(pa * s.invTotalWeight))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA()
pr0 = pr0 * ma / 0xffff
pg0 = pg0 * ma / 0xffff
pb0 = pb0 * ma / 0xffff
pa0 = pa0 * ma / 0xffff
}
pa1 := 0xffff - pa0
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr0)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg0)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb0)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa0)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColor)
}
}
}
func (z *kernelScaler) scaleY_Image_Src(dst Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] {
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
if dstMask != nil {
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy)).RGBA()
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA()
pr := uint32(ftou(pr*s.invTotalWeight)) * ma / 0xffff
pg := uint32(ftou(pg*s.invTotalWeight)) * ma / 0xffff
pb := uint32(ftou(pb*s.invTotalWeight)) * ma / 0xffff
pa := uint32(ftou(pa*s.invTotalWeight)) * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColor)
} else {
dstColorRGBA64.R = ftou(pr * s.invTotalWeight)
dstColorRGBA64.G = ftou(pg * s.invTotalWeight)
dstColorRGBA64.B = ftou(pb * s.invTotalWeight)
dstColorRGBA64.A = ftou(pa * s.invTotalWeight)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColor)
}
}
}
}
func (q *Kernel) transform_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Gray, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.Stride + (kx - src.Rect.Min.X)
pru := uint32(src.Pix[pi]) * 0x101
pr += float64(float64(pru) * w)
}
}
}
}
out := uint8(fffftou(pr) >> 8)
dst.Pix[d+0] = out
dst.Pix[d+1] = out
dst.Pix[d+2] = out
dst.Pix[d+3] = 0xff
}
}
}
func (q *Kernel) transform_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4
pau := uint32(src.Pix[pi+3]) * 0x101
pru := uint32(src.Pix[pi+0]) * pau / 0xff
pgu := uint32(src.Pix[pi+1]) * pau / 0xff
pbu := uint32(src.Pix[pi+2]) * pau / 0xff
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
pr0 := uint32(fffftou(pr))
pg0 := uint32(fffftou(pg))
pb0 := uint32(fffftou(pb))
pa0 := uint32(fffftou(pa))
pa1 := (0xffff - uint32(pa0)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4
pau := uint32(src.Pix[pi+3]) * 0x101
pru := uint32(src.Pix[pi+0]) * pau / 0xff
pgu := uint32(src.Pix[pi+1]) * pau / 0xff
pbu := uint32(src.Pix[pi+2]) * pau / 0xff
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = uint8(fffftou(pa) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4
pru := uint32(src.Pix[pi+0]) * 0x101
pgu := uint32(src.Pix[pi+1]) * 0x101
pbu := uint32(src.Pix[pi+2]) * 0x101
pau := uint32(src.Pix[pi+3]) * 0x101
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
pr0 := uint32(fffftou(pr))
pg0 := uint32(fffftou(pg))
pb0 := uint32(fffftou(pb))
pa0 := uint32(fffftou(pa))
pa1 := (0xffff - uint32(pa0)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4
pru := uint32(src.Pix[pi+0]) * 0x101
pgu := uint32(src.Pix[pi+1]) * 0x101
pbu := uint32(src.Pix[pi+2]) * 0x101
pau := uint32(src.Pix[pi+3]) * 0x101
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = uint8(fffftou(pa) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X)
pj := (ky-src.Rect.Min.Y)*src.CStride + (kx - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
}
}
}
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (q *Kernel) transform_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X)
pj := (ky-src.Rect.Min.Y)*src.CStride + ((kx)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
}
}
}
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (q *Kernel) transform_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X)
pj := ((ky)/2-src.Rect.Min.Y/2)*src.CStride + ((kx)/2 - src.Rect.Min.X/2)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
}
}
}
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (q *Kernel) transform_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X)
pj := ((ky)/2-src.Rect.Min.Y/2)*src.CStride + (kx - src.Rect.Min.X)
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
pyy1 := int(src.Y[pi]) * 0x10101
pcb1 := int(src.Cb[pj]) - 128
pcr1 := int(src.Cr[pj]) - 128
pru := (pyy1 + 91881*pcr1) >> 8
pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8
pbu := (pyy1 + 116130*pcb1) >> 8
if pru < 0 {
pru = 0
} else if pru > 0xffff {
pru = 0xffff
}
if pgu < 0 {
pgu = 0
} else if pgu > 0xffff {
pgu = 0xffff
}
if pbu < 0 {
pbu = 0
} else if pbu > 0xffff {
pbu = 0xffff
}
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
}
}
}
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = 0xff
}
}
}
func (q *Kernel) transform_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pu := src.RGBA64At(kx, ky)
pr += float64(float64(pu.R) * w)
pg += float64(float64(pu.G) * w)
pb += float64(float64(pu.B) * w)
pa += float64(float64(pu.A) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
pr0 := uint32(fffftou(pr))
pg0 := uint32(fffftou(pg))
pb0 := uint32(fffftou(pb))
pa0 := uint32(fffftou(pa))
pa1 := (0xffff - uint32(pa0)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pu := src.RGBA64At(kx, ky)
pr += float64(float64(pu.R) * w)
pg += float64(float64(pu.G) * w)
pb += float64(float64(pu.B) * w)
pa += float64(float64(pu.A) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = uint8(fffftou(pa) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pru, pgu, pbu, pau := src.At(kx, ky).RGBA()
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
pr0 := uint32(fffftou(pr))
pg0 := uint32(fffftou(pg))
pb0 := uint32(fffftou(pb))
pa0 := uint32(fffftou(pa))
pa1 := (0xffff - uint32(pa0)) * 0x101
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8)
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8)
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8)
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8)
}
}
}
func (q *Kernel) transform_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pru, pgu, pbu, pau := src.At(kx, ky).RGBA()
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
dst.Pix[d+0] = uint8(fffftou(pr) >> 8)
dst.Pix[d+1] = uint8(fffftou(pg) >> 8)
dst.Pix[d+2] = uint8(fffftou(pb) >> 8)
dst.Pix[d+3] = uint8(fffftou(pa) >> 8)
}
}
}
func (q *Kernel) transform_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pu := src.RGBA64At(kx, ky)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA()
pu.R = uint16(uint32(pu.R) * ma / 0xffff)
pu.G = uint16(uint32(pu.G) * ma / 0xffff)
pu.B = uint16(uint32(pu.B) * ma / 0xffff)
pu.A = uint16(uint32(pu.A) * ma / 0xffff)
}
pr += float64(float64(pu.R) * w)
pg += float64(float64(pu.G) * w)
pb += float64(float64(pu.B) * w)
pa += float64(float64(pu.A) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
pr0 := uint32(fffftou(pr))
pg0 := uint32(fffftou(pg))
pb0 := uint32(fffftou(pb))
pa0 := uint32(fffftou(pa))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr0 = pr0 * ma / 0xffff
pg0 = pg0 * ma / 0xffff
pb0 = pb0 * ma / 0xffff
pa0 = pa0 * ma / 0xffff
}
pa1 := 0xffff - pa0
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr0)
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg0)
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb0)
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa0)
dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
}
}
}
func (q *Kernel) transform_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := color.RGBA64{}
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pu := src.RGBA64At(kx, ky)
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA()
pu.R = uint16(uint32(pu.R) * ma / 0xffff)
pu.G = uint16(uint32(pu.G) * ma / 0xffff)
pu.B = uint16(uint32(pu.B) * ma / 0xffff)
pu.A = uint16(uint32(pu.A) * ma / 0xffff)
}
pr += float64(float64(pu.R) * w)
pg += float64(float64(pu.G) * w)
pb += float64(float64(pu.B) * w)
pa += float64(float64(pu.A) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
if dstMask != nil {
q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy))
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr := uint32(fffftou(pr)) * ma / 0xffff
pg := uint32(fffftou(pg)) * ma / 0xffff
pb := uint32(fffftou(pb)) * ma / 0xffff
pa := uint32(fffftou(pa)) * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa)
dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
} else {
dstColorRGBA64.R = fffftou(pr)
dstColorRGBA64.G = fffftou(pg)
dstColorRGBA64.B = fffftou(pb)
dstColorRGBA64.A = fffftou(pa)
dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64)
}
}
}
}
func (q *Kernel) transform_Image_Image_Over(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pru, pgu, pbu, pau := src.At(kx, ky).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA()
pru = pru * ma / 0xffff
pgu = pgu * ma / 0xffff
pbu = pbu * ma / 0xffff
pau = pau * ma / 0xffff
}
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
pr0 := uint32(fffftou(pr))
pg0 := uint32(fffftou(pg))
pb0 := uint32(fffftou(pb))
pa0 := uint32(fffftou(pa))
if dstMask != nil {
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr0 = pr0 * ma / 0xffff
pg0 = pg0 * ma / 0xffff
pb0 = pb0 * ma / 0xffff
pa0 = pa0 * ma / 0xffff
}
pa1 := 0xffff - pa0
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr0)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg0)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb0)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa0)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
func (q *Kernel) transform_Image_Image_Src(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth)))
srcMask, smp := opts.SrcMask, opts.SrcMaskP
dstMask, dmp := opts.DstMask, opts.DstMaskP
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y+int(dy)) + 0.5
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
dxf := float64(dr.Min.X+int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx-ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky-iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky-iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx-ix] * yWeight; w != 0 {
pru, pgu, pbu, pau := src.At(kx, ky).RGBA()
if srcMask != nil {
_, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA()
pru = pru * ma / 0xffff
pgu = pgu * ma / 0xffff
pbu = pbu * ma / 0xffff
pau = pau * ma / 0xffff
}
pr += float64(float64(pru) * w)
pg += float64(float64(pgu) * w)
pb += float64(float64(pbu) * w)
pa += float64(float64(pau) * w)
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
if dstMask != nil {
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
_, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA()
pr := uint32(fffftou(pr)) * ma / 0xffff
pg := uint32(fffftou(pg)) * ma / 0xffff
pb := uint32(fffftou(pb)) * ma / 0xffff
pa := uint32(fffftou(pa)) * ma / 0xffff
pa1 := 0xffff - ma
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
} else {
dstColorRGBA64.R = fffftou(pr)
dstColorRGBA64.G = fffftou(pg)
dstColorRGBA64.B = fffftou(pb)
dstColorRGBA64.A = fffftou(pa)
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
}
}
}
}
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/scale_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package draw
import (
"bytes"
"flag"
"fmt"
"image"
"image/color"
"image/png"
"math/rand"
"os"
"reflect"
"testing"
"golang.org/x/image/math/f64"
_ "image/jpeg"
)
var genGoldenFiles = flag.Bool("gen_golden_files", false, "whether to generate the TestXxx golden files.")
var transformMatrix = func(scale, tx, ty float64) f64.Aff3 {
const cos30, sin30 = 0.866025404, 0.5
return f64.Aff3{
+scale * cos30, -scale * sin30, tx,
+scale * sin30, +scale * cos30, ty,
}
}
func encode(filename string, m image.Image) error {
f, err := os.Create(filename)
if err != nil {
return fmt.Errorf("Create: %v", err)
}
defer f.Close()
if err := png.Encode(f, m); err != nil {
return fmt.Errorf("Encode: %v", err)
}
return nil
}
// testInterp tests that interpolating the source image gives the exact
// destination image. This is to ensure that any refactoring or optimization of
// the interpolation code doesn't change the behavior. Changing the actual
// algorithm or kernel used by any particular quality setting will obviously
// change the resultant pixels. In such a case, use the gen_golden_files flag
// to regenerate the golden files.
func testInterp(t *testing.T, w int, h int, direction, prefix, suffix string) {
f, err := os.Open("../testdata/" + prefix + suffix)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
src, _, err := image.Decode(f)
if err != nil {
t.Fatalf("Decode: %v", err)
}
op, scale := Src, 3.75
if prefix == "tux" {
op, scale = Over, 0.125
}
green := image.NewUniform(color.RGBA{0x00, 0x22, 0x11, 0xff})
testCases := map[string]Interpolator{
"nn": NearestNeighbor,
"ab": ApproxBiLinear,
"bl": BiLinear,
"cr": CatmullRom,
}
for name, q := range testCases {
goldenFilename := fmt.Sprintf("../testdata/%s-%s-%s.png", prefix, direction, name)
got := image.NewRGBA(image.Rect(0, 0, w, h))
Copy(got, image.Point{}, green, got.Bounds(), Src, nil)
if direction == "rotate" {
q.Transform(got, transformMatrix(scale, 40, 10), src, src.Bounds(), op, nil)
} else {
q.Scale(got, got.Bounds(), src, src.Bounds(), op, nil)
}
if *genGoldenFiles {
if err := encode(goldenFilename, got); err != nil {
t.Error(err)
}
continue
}
g, err := os.Open(goldenFilename)
if err != nil {
t.Errorf("Open: %v", err)
continue
}
defer g.Close()
wantRaw, err := png.Decode(g)
if err != nil {
t.Errorf("Decode: %v", err)
continue
}
// convert wantRaw to RGBA.
want, ok := wantRaw.(*image.RGBA)
if !ok {
b := wantRaw.Bounds()
want = image.NewRGBA(b)
Draw(want, b, wantRaw, b.Min, Src)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("%s: actual image differs from golden image", goldenFilename)
continue
}
}
}
func TestScaleDown(t *testing.T) { testInterp(t, 100, 100, "down", "go-turns-two", "-280x360.jpeg") }
func TestScaleUp(t *testing.T) { testInterp(t, 75, 100, "up", "go-turns-two", "-14x18.png") }
func TestTformSrc(t *testing.T) { testInterp(t, 100, 100, "rotate", "go-turns-two", "-14x18.png") }
func TestTformOver(t *testing.T) { testInterp(t, 100, 100, "rotate", "tux", ".png") }
// TestSimpleTransforms tests Scale and Transform calls that simplify to Copy
// or Scale calls.
func TestSimpleTransforms(t *testing.T) {
f, err := os.Open("../testdata/testpattern.png") // A 100x100 image.
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
src, _, err := image.Decode(f)
if err != nil {
t.Fatalf("Decode: %v", err)
}
dst0 := image.NewRGBA(image.Rect(0, 0, 120, 150))
dst1 := image.NewRGBA(image.Rect(0, 0, 120, 150))
for _, op := range []string{"scale/copy", "tform/copy", "tform/scale"} {
for _, epsilon := range []float64{0, 1e-50, 1e-1} {
Copy(dst0, image.Point{}, image.Transparent, dst0.Bounds(), Src, nil)
Copy(dst1, image.Point{}, image.Transparent, dst1.Bounds(), Src, nil)
switch op {
case "scale/copy":
dr := image.Rect(10, 30, 10+100, 30+100)
if epsilon > 1e-10 {
dr.Max.X++
}
Copy(dst0, image.Point{10, 30}, src, src.Bounds(), Src, nil)
ApproxBiLinear.Scale(dst1, dr, src, src.Bounds(), Src, nil)
case "tform/copy":
Copy(dst0, image.Point{10, 30}, src, src.Bounds(), Src, nil)
ApproxBiLinear.Transform(dst1, f64.Aff3{
1, 0 + epsilon, 10,
0, 1, 30,
}, src, src.Bounds(), Src, nil)
case "tform/scale":
ApproxBiLinear.Scale(dst0, image.Rect(10, 50, 10+50, 50+50), src, src.Bounds(), Src, nil)
ApproxBiLinear.Transform(dst1, f64.Aff3{
0.5, 0.0 + epsilon, 10,
0.0, 0.5, 50,
}, src, src.Bounds(), Src, nil)
}
differ := !bytes.Equal(dst0.Pix, dst1.Pix)
if epsilon > 1e-10 {
if !differ {
t.Errorf("%s yielded same pixels, want different pixels: epsilon=%v", op, epsilon)
}
} else {
if differ {
t.Errorf("%s yielded different pixels, want same pixels: epsilon=%v", op, epsilon)
}
}
}
}
}
func BenchmarkSimpleScaleCopy(b *testing.B) {
dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
src := image.NewRGBA(image.Rect(0, 0, 400, 300))
b.ResetTimer()
for i := 0; i < b.N; i++ {
ApproxBiLinear.Scale(dst, image.Rect(10, 20, 10+400, 20+300), src, src.Bounds(), Src, nil)
}
}
func BenchmarkSimpleTransformCopy(b *testing.B) {
dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
src := image.NewRGBA(image.Rect(0, 0, 400, 300))
b.ResetTimer()
for i := 0; i < b.N; i++ {
ApproxBiLinear.Transform(dst, f64.Aff3{
1, 0, 10,
0, 1, 20,
}, src, src.Bounds(), Src, nil)
}
}
func BenchmarkSimpleTransformScale(b *testing.B) {
dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
src := image.NewRGBA(image.Rect(0, 0, 400, 300))
b.ResetTimer()
for i := 0; i < b.N; i++ {
ApproxBiLinear.Transform(dst, f64.Aff3{
0.5, 0.0, 10,
0.0, 0.5, 20,
}, src, src.Bounds(), Src, nil)
}
}
func TestOps(t *testing.T) {
blue := image.NewUniform(color.RGBA{0x00, 0x00, 0xff, 0xff})
testCases := map[Op]color.RGBA{
Over: color.RGBA{0x7f, 0x00, 0x80, 0xff},
Src: color.RGBA{0x7f, 0x00, 0x00, 0x7f},
}
for op, want := range testCases {
dst := image.NewRGBA(image.Rect(0, 0, 2, 2))
Copy(dst, image.Point{}, blue, dst.Bounds(), Src, nil)
src := image.NewRGBA(image.Rect(0, 0, 1, 1))
src.SetRGBA(0, 0, color.RGBA{0x7f, 0x00, 0x00, 0x7f})
NearestNeighbor.Scale(dst, dst.Bounds(), src, src.Bounds(), op, nil)
if got := dst.RGBAAt(0, 0); got != want {
t.Errorf("op=%v: got %v, want %v", op, got, want)
}
}
}
// TestNegativeWeights tests that scaling by a kernel that produces negative
// weights, such as the Catmull-Rom kernel, doesn't produce an invalid color
// according to Go's alpha-premultiplied model.
func TestNegativeWeights(t *testing.T) {
check := func(m *image.RGBA) error {
b := m.Bounds()
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
if c := m.RGBAAt(x, y); c.R > c.A || c.G > c.A || c.B > c.A {
return fmt.Errorf("invalid color.RGBA at (%d, %d): %v", x, y, c)
}
}
}
return nil
}
src := image.NewRGBA(image.Rect(0, 0, 16, 16))
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
a := y * 0x11
src.Set(x, y, color.RGBA{
R: uint8(x * 0x11 * a / 0xff),
A: uint8(a),
})
}
}
if err := check(src); err != nil {
t.Fatalf("src image: %v", err)
}
dst := image.NewRGBA(image.Rect(0, 0, 32, 32))
CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), Over, nil)
if err := check(dst); err != nil {
t.Fatalf("dst image: %v", err)
}
}
func fillPix(r *rand.Rand, pixs ...[]byte) {
for _, pix := range pixs {
for i := range pix {
pix[i] = uint8(r.Intn(256))
}
}
}
func TestInterpClipCommute(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 20, 20))
fillPix(rand.New(rand.NewSource(0)), src.Pix)
outer := image.Rect(1, 1, 8, 5)
inner := image.Rect(2, 3, 6, 5)
qs := []Interpolator{
NearestNeighbor,
ApproxBiLinear,
CatmullRom,
}
for _, transform := range []bool{false, true} {
for _, q := range qs {
dst0 := image.NewRGBA(image.Rect(1, 1, 10, 10))
dst1 := image.NewRGBA(image.Rect(1, 1, 10, 10))
for i := range dst0.Pix {
dst0.Pix[i] = uint8(i / 4)
dst1.Pix[i] = uint8(i / 4)
}
var interp func(dst *image.RGBA)
if transform {
interp = func(dst *image.RGBA) {
q.Transform(dst, transformMatrix(3.75, 2, 1), src, src.Bounds(), Over, nil)
}
} else {
interp = func(dst *image.RGBA) {
q.Scale(dst, outer, src, src.Bounds(), Over, nil)
}
}
// Interpolate then clip.
interp(dst0)
dst0 = dst0.SubImage(inner).(*image.RGBA)
// Clip then interpolate.
dst1 = dst1.SubImage(inner).(*image.RGBA)
interp(dst1)
loop:
for y := inner.Min.Y; y < inner.Max.Y; y++ {
for x := inner.Min.X; x < inner.Max.X; x++ {
if c0, c1 := dst0.RGBAAt(x, y), dst1.RGBAAt(x, y); c0 != c1 {
t.Errorf("q=%T: at (%d, %d): c0=%v, c1=%v", q, x, y, c0, c1)
break loop
}
}
}
}
}
}
// translatedImage is an image m translated by t.
type translatedImage struct {
m image.Image
t image.Point
}
func (t *translatedImage) At(x, y int) color.Color { return t.m.At(x-t.t.X, y-t.t.Y) }
func (t *translatedImage) Bounds() image.Rectangle { return t.m.Bounds().Add(t.t) }
func (t *translatedImage) ColorModel() color.Model { return t.m.ColorModel() }
// TestSrcTranslationInvariance tests that Scale and Transform are invariant
// under src translations. Specifically, when some source pixels are not in the
// bottom-right quadrant of src coordinate space, we consistently round down,
// not round towards zero.
func TestSrcTranslationInvariance(t *testing.T) {
f, err := os.Open("../testdata/testpattern.png")
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
src, _, err := image.Decode(f)
if err != nil {
t.Fatalf("Decode: %v", err)
}
sr := image.Rect(2, 3, 16, 12)
if !sr.In(src.Bounds()) {
t.Fatalf("src bounds too small: got %v", src.Bounds())
}
qs := []Interpolator{
NearestNeighbor,
ApproxBiLinear,
CatmullRom,
}
deltas := []image.Point{
{+0, +0},
{+0, +5},
{+0, -5},
{+5, +0},
{-5, +0},
{+8, +8},
{+8, -8},
{-8, +8},
{-8, -8},
}
m00 := transformMatrix(3.75, 0, 0)
for _, transform := range []bool{false, true} {
for _, q := range qs {
want := image.NewRGBA(image.Rect(0, 0, 20, 20))
if transform {
q.Transform(want, m00, src, sr, Over, nil)
} else {
q.Scale(want, want.Bounds(), src, sr, Over, nil)
}
for _, delta := range deltas {
tsrc := &translatedImage{src, delta}
got := image.NewRGBA(image.Rect(0, 0, 20, 20))
if transform {
m := matMul(&m00, &f64.Aff3{
1, 0, -float64(delta.X),
0, 1, -float64(delta.Y),
})
q.Transform(got, m, tsrc, sr.Add(delta), Over, nil)
} else {
q.Scale(got, got.Bounds(), tsrc, sr.Add(delta), Over, nil)
}
if !bytes.Equal(got.Pix, want.Pix) {
t.Errorf("pix differ for delta=%v, transform=%t, q=%T", delta, transform, q)
}
}
}
}
}
func TestSrcMask(t *testing.T) {
srcMask := image.NewRGBA(image.Rect(0, 0, 23, 1))
srcMask.SetRGBA(19, 0, color.RGBA{0x00, 0x00, 0x00, 0x7f})
srcMask.SetRGBA(20, 0, color.RGBA{0x00, 0x00, 0x00, 0xff})
srcMask.SetRGBA(21, 0, color.RGBA{0x00, 0x00, 0x00, 0x3f})
srcMask.SetRGBA(22, 0, color.RGBA{0x00, 0x00, 0x00, 0x00})
red := image.NewUniform(color.RGBA{0xff, 0x00, 0x00, 0xff})
blue := image.NewUniform(color.RGBA{0x00, 0x00, 0xff, 0xff})
dst := image.NewRGBA(image.Rect(0, 0, 6, 1))
Copy(dst, image.Point{}, blue, dst.Bounds(), Src, nil)
NearestNeighbor.Scale(dst, dst.Bounds(), red, image.Rect(0, 0, 3, 1), Over, &Options{
SrcMask: srcMask,
SrcMaskP: image.Point{20, 0},
})
got := [6]color.RGBA{
dst.RGBAAt(0, 0),
dst.RGBAAt(1, 0),
dst.RGBAAt(2, 0),
dst.RGBAAt(3, 0),
dst.RGBAAt(4, 0),
dst.RGBAAt(5, 0),
}
want := [6]color.RGBA{
{0xff, 0x00, 0x00, 0xff},
{0xff, 0x00, 0x00, 0xff},
{0x3f, 0x00, 0xc0, 0xff},
{0x3f, 0x00, 0xc0, 0xff},
{0x00, 0x00, 0xff, 0xff},
{0x00, 0x00, 0xff, 0xff},
}
if got != want {
t.Errorf("\ngot %v\nwant %v", got, want)
}
}
func TestDstMask(t *testing.T) {
dstMask := image.NewRGBA(image.Rect(0, 0, 23, 1))
dstMask.SetRGBA(19, 0, color.RGBA{0x00, 0x00, 0x00, 0x7f})
dstMask.SetRGBA(20, 0, color.RGBA{0x00, 0x00, 0x00, 0xff})
dstMask.SetRGBA(21, 0, color.RGBA{0x00, 0x00, 0x00, 0x3f})
dstMask.SetRGBA(22, 0, color.RGBA{0x00, 0x00, 0x00, 0x00})
red := image.NewRGBA(image.Rect(0, 0, 1, 1))
red.SetRGBA(0, 0, color.RGBA{0xff, 0x00, 0x00, 0xff})
blue := image.NewUniform(color.RGBA{0x00, 0x00, 0xff, 0xff})
qs := []Interpolator{
NearestNeighbor,
ApproxBiLinear,
CatmullRom,
}
for _, q := range qs {
dst := image.NewRGBA(image.Rect(0, 0, 3, 1))
Copy(dst, image.Point{}, blue, dst.Bounds(), Src, nil)
q.Scale(dst, dst.Bounds(), red, red.Bounds(), Over, &Options{
DstMask: dstMask,
DstMaskP: image.Point{20, 0},
})
got := [3]color.RGBA{
dst.RGBAAt(0, 0),
dst.RGBAAt(1, 0),
dst.RGBAAt(2, 0),
}
want := [3]color.RGBA{
{0xff, 0x00, 0x00, 0xff},
{0x3f, 0x00, 0xc0, 0xff},
{0x00, 0x00, 0xff, 0xff},
}
if got != want {
t.Errorf("q=%T:\ngot %v\nwant %v", q, got, want)
}
}
}
func TestRectDstMask(t *testing.T) {
f, err := os.Open("../testdata/testpattern.png")
if err != nil {
t.Fatalf("Open: %v", err)
}
defer f.Close()
src, _, err := image.Decode(f)
if err != nil {
t.Fatalf("Decode: %v", err)
}
m00 := transformMatrix(1, 0, 0)
bounds := image.Rect(0, 0, 50, 50)
dstOutside := image.NewRGBA(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
dstOutside.SetRGBA(x, y, color.RGBA{uint8(5 * x), uint8(5 * y), 0x00, 0xff})
}
}
mk := func(q Transformer, dstMask image.Image, dstMaskP image.Point) *image.RGBA {
m := image.NewRGBA(bounds)
Copy(m, bounds.Min, dstOutside, bounds, Src, nil)
q.Transform(m, m00, src, src.Bounds(), Over, &Options{
DstMask: dstMask,
DstMaskP: dstMaskP,
})
return m
}
qs := []Interpolator{
NearestNeighbor,
ApproxBiLinear,
CatmullRom,
}
dstMaskPs := []image.Point{
{0, 0},
{5, 7},
{-3, 0},
}
rect := image.Rect(10, 10, 30, 40)
for _, q := range qs {
for _, dstMaskP := range dstMaskPs {
dstInside := mk(q, nil, image.Point{})
for _, wrap := range []bool{false, true} {
dstMask := image.Image(rect)
if wrap {
dstMask = srcWrapper{dstMask}
}
dst := mk(q, dstMask, dstMaskP)
nError := 0
loop:
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
which := dstOutside
if (image.Point{x, y}).Add(dstMaskP).In(rect) {
which = dstInside
}
if got, want := dst.RGBAAt(x, y), which.RGBAAt(x, y); got != want {
if nError == 10 {
t.Errorf("q=%T dmp=%v wrap=%v: ...and more errors", q, dstMaskP, wrap)
break loop
}
nError++
t.Errorf("q=%T dmp=%v wrap=%v: x=%3d y=%3d: got %v, want %v",
q, dstMaskP, wrap, x, y, got, want)
}
}
}
}
}
}
}
func TestDstMaskSameSizeCopy(t *testing.T) {
bounds := image.Rect(0, 0, 42, 42)
src := image.Opaque
dst := image.NewRGBA(bounds)
mask := image.NewRGBA(bounds)
Copy(dst, image.Point{}, src, bounds, Src, &Options{
DstMask: mask,
})
}
func TestScaleRGBA64ImageAllocations(t *testing.T) {
// The goal of RGBA64Image is to prevent heap allocation of the color
// argument by using a non-interface type. Assert that we meet that goal.
// This assumes there is no fast path for *image.RGBA64.
src := image.NewRGBA64(image.Rect(0, 0, 16, 32))
dst := image.NewRGBA64(image.Rect(0, 0, 32, 16))
fillPix(rand.New(rand.NewSource(1)), src.Pix, dst.Pix)
t.Run("Over", func(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), Over, nil)
})
// Scale and Transform below allocate on their own, so allocations will
// never be zero. The expectation we want to check is that the number
// of allocations does not scale linearly with the number of pixels in
// the image. We could test that directly, but it's sufficient to test
// that we have much fewer allocations than the number of pixels, 512.
if allocs > 8 {
t.Errorf("too many allocations: %v", allocs)
}
})
t.Run("Src", func(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), Src, nil)
})
if allocs > 8 {
t.Errorf("too many allocations: %v", allocs)
}
})
}
func TestTransformRGBA64ImageAllocations(t *testing.T) {
// This assumes there is no fast path for *image.RGBA64.
src := image.NewRGBA64(image.Rect(0, 0, 16, 32))
dst := image.NewRGBA64(image.Rect(0, 0, 32, 16))
fillPix(rand.New(rand.NewSource(1)), src.Pix, dst.Pix)
mat := f64.Aff3{
2, 0, 0,
0, 0.5, 0,
}
t.Run("Over", func(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
CatmullRom.Transform(dst, mat, src, src.Bounds(), Over, nil)
})
if allocs > 8 {
t.Errorf("too many allocations: %v", allocs)
}
})
t.Run("Src", func(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
CatmullRom.Transform(dst, mat, src, src.Bounds(), Src, nil)
})
if allocs > 8 {
t.Errorf("too many allocations: %v", allocs)
}
})
}
// The fooWrapper types wrap the dst or src image to avoid triggering the
// type-specific fast path implementations.
type (
dstWrapper struct{ Image }
srcWrapper struct{ image.Image }
)
func srcGray(boundsHint image.Rectangle) (image.Image, error) {
m := image.NewGray(boundsHint)
fillPix(rand.New(rand.NewSource(0)), m.Pix)
return m, nil
}
func srcNRGBA(boundsHint image.Rectangle) (image.Image, error) {
m := image.NewNRGBA(boundsHint)
fillPix(rand.New(rand.NewSource(1)), m.Pix)
return m, nil
}
func srcRGBA(boundsHint image.Rectangle) (image.Image, error) {
m := image.NewRGBA(boundsHint)
fillPix(rand.New(rand.NewSource(2)), m.Pix)
// RGBA is alpha-premultiplied, so the R, G and B values should
// be <= the A values.
for i := 0; i < len(m.Pix); i += 4 {
m.Pix[i+0] = uint8(uint32(m.Pix[i+0]) * uint32(m.Pix[i+3]) / 0xff)
m.Pix[i+1] = uint8(uint32(m.Pix[i+1]) * uint32(m.Pix[i+3]) / 0xff)
m.Pix[i+2] = uint8(uint32(m.Pix[i+2]) * uint32(m.Pix[i+3]) / 0xff)
}
return m, nil
}
func srcUnif(boundsHint image.Rectangle) (image.Image, error) {
return image.NewUniform(color.RGBA64{0x1234, 0x5555, 0x9181, 0xbeef}), nil
}
func srcYCbCr(boundsHint image.Rectangle) (image.Image, error) {
m := image.NewYCbCr(boundsHint, image.YCbCrSubsampleRatio420)
fillPix(rand.New(rand.NewSource(3)), m.Y, m.Cb, m.Cr)
return m, nil
}
func srcRGBA64(boundsHint image.Rectangle) (image.Image, error) {
m := image.NewRGBA64(boundsHint)
fillPix(rand.New(rand.NewSource(4)), m.Pix)
return m, nil
}
func srcLarge(boundsHint image.Rectangle) (image.Image, error) {
// 3072 x 2304 is over 7 million pixels at 4:3, comparable to a
// 2015 smart-phone camera's output.
return srcYCbCr(image.Rect(0, 0, 3072, 2304))
}
func srcTux(boundsHint image.Rectangle) (image.Image, error) {
// tux.png is a 386 x 395 image.
f, err := os.Open("../testdata/tux.png")
if err != nil {
return nil, fmt.Errorf("Open: %v", err)
}
defer f.Close()
src, err := png.Decode(f)
if err != nil {
return nil, fmt.Errorf("Decode: %v", err)
}
return src, nil
}
func benchScale(b *testing.B, w int, h int, op Op, srcf func(image.Rectangle) (image.Image, error), q Interpolator) {
dst := image.NewRGBA(image.Rect(0, 0, w, h))
src, err := srcf(image.Rect(0, 0, 1024, 768))
if err != nil {
b.Fatal(err)
}
dr, sr := dst.Bounds(), src.Bounds()
scaler := Scaler(q)
if n, ok := q.(interface {
NewScaler(int, int, int, int) Scaler
}); ok {
scaler = n.NewScaler(dr.Dx(), dr.Dy(), sr.Dx(), sr.Dy())
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
scaler.Scale(dst, dr, src, sr, op, nil)
}
}
func benchTform(b *testing.B, w int, h int, op Op, srcf func(image.Rectangle) (image.Image, error), q Interpolator) {
dst := image.NewRGBA(image.Rect(0, 0, w, h))
src, err := srcf(image.Rect(0, 0, 1024, 768))
if err != nil {
b.Fatal(err)
}
sr := src.Bounds()
m := transformMatrix(3.75, 40, 10)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
q.Transform(dst, m, src, sr, op, nil)
}
}
func BenchmarkScaleNNLargeDown(b *testing.B) { benchScale(b, 200, 150, Src, srcLarge, NearestNeighbor) }
func BenchmarkScaleABLargeDown(b *testing.B) { benchScale(b, 200, 150, Src, srcLarge, ApproxBiLinear) }
func BenchmarkScaleBLLargeDown(b *testing.B) { benchScale(b, 200, 150, Src, srcLarge, BiLinear) }
func BenchmarkScaleCRLargeDown(b *testing.B) { benchScale(b, 200, 150, Src, srcLarge, CatmullRom) }
func BenchmarkScaleNNDown(b *testing.B) { benchScale(b, 120, 80, Src, srcTux, NearestNeighbor) }
func BenchmarkScaleABDown(b *testing.B) { benchScale(b, 120, 80, Src, srcTux, ApproxBiLinear) }
func BenchmarkScaleBLDown(b *testing.B) { benchScale(b, 120, 80, Src, srcTux, BiLinear) }
func BenchmarkScaleCRDown(b *testing.B) { benchScale(b, 120, 80, Src, srcTux, CatmullRom) }
func BenchmarkScaleNNUp(b *testing.B) { benchScale(b, 800, 600, Src, srcTux, NearestNeighbor) }
func BenchmarkScaleABUp(b *testing.B) { benchScale(b, 800, 600, Src, srcTux, ApproxBiLinear) }
func BenchmarkScaleBLUp(b *testing.B) { benchScale(b, 800, 600, Src, srcTux, BiLinear) }
func BenchmarkScaleCRUp(b *testing.B) { benchScale(b, 800, 600, Src, srcTux, CatmullRom) }
func BenchmarkScaleNNSrcRGBA(b *testing.B) { benchScale(b, 200, 150, Src, srcRGBA, NearestNeighbor) }
func BenchmarkScaleNNSrcUnif(b *testing.B) { benchScale(b, 200, 150, Src, srcUnif, NearestNeighbor) }
func BenchmarkScaleNNOverRGBA(b *testing.B) { benchScale(b, 200, 150, Over, srcRGBA, NearestNeighbor) }
func BenchmarkScaleNNOverUnif(b *testing.B) { benchScale(b, 200, 150, Over, srcUnif, NearestNeighbor) }
func BenchmarkTformNNSrcRGBA(b *testing.B) { benchTform(b, 200, 150, Src, srcRGBA, NearestNeighbor) }
func BenchmarkTformNNSrcUnif(b *testing.B) { benchTform(b, 200, 150, Src, srcUnif, NearestNeighbor) }
func BenchmarkTformNNOverRGBA(b *testing.B) { benchTform(b, 200, 150, Over, srcRGBA, NearestNeighbor) }
func BenchmarkTformNNOverUnif(b *testing.B) { benchTform(b, 200, 150, Over, srcUnif, NearestNeighbor) }
func BenchmarkScaleABSrcGray(b *testing.B) { benchScale(b, 200, 150, Src, srcGray, ApproxBiLinear) }
func BenchmarkScaleABSrcNRGBA(b *testing.B) { benchScale(b, 200, 150, Src, srcNRGBA, ApproxBiLinear) }
func BenchmarkScaleABSrcRGBA(b *testing.B) { benchScale(b, 200, 150, Src, srcRGBA, ApproxBiLinear) }
func BenchmarkScaleABSrcYCbCr(b *testing.B) { benchScale(b, 200, 150, Src, srcYCbCr, ApproxBiLinear) }
func BenchmarkScaleABSrcRGBA64(b *testing.B) { benchScale(b, 200, 150, Src, srcRGBA64, ApproxBiLinear) }
func BenchmarkScaleABOverGray(b *testing.B) { benchScale(b, 200, 150, Over, srcGray, ApproxBiLinear) }
func BenchmarkScaleABOverNRGBA(b *testing.B) { benchScale(b, 200, 150, Over, srcNRGBA, ApproxBiLinear) }
func BenchmarkScaleABOverRGBA(b *testing.B) { benchScale(b, 200, 150, Over, srcRGBA, ApproxBiLinear) }
func BenchmarkScaleABOverYCbCr(b *testing.B) { benchScale(b, 200, 150, Over, srcYCbCr, ApproxBiLinear) }
func BenchmarkScaleABOverRGBA64(b *testing.B) {
benchScale(b, 200, 150, Over, srcRGBA64, ApproxBiLinear)
}
func BenchmarkTformABSrcGray(b *testing.B) { benchTform(b, 200, 150, Src, srcGray, ApproxBiLinear) }
func BenchmarkTformABSrcNRGBA(b *testing.B) { benchTform(b, 200, 150, Src, srcNRGBA, ApproxBiLinear) }
func BenchmarkTformABSrcRGBA(b *testing.B) { benchTform(b, 200, 150, Src, srcRGBA, ApproxBiLinear) }
func BenchmarkTformABSrcYCbCr(b *testing.B) { benchTform(b, 200, 150, Src, srcYCbCr, ApproxBiLinear) }
func BenchmarkTformABSrcRGBA64(b *testing.B) { benchTform(b, 200, 150, Src, srcRGBA64, ApproxBiLinear) }
func BenchmarkTformABOverGray(b *testing.B) { benchTform(b, 200, 150, Over, srcGray, ApproxBiLinear) }
func BenchmarkTformABOverNRGBA(b *testing.B) { benchTform(b, 200, 150, Over, srcNRGBA, ApproxBiLinear) }
func BenchmarkTformABOverRGBA(b *testing.B) { benchTform(b, 200, 150, Over, srcRGBA, ApproxBiLinear) }
func BenchmarkTformABOverYCbCr(b *testing.B) { benchTform(b, 200, 150, Over, srcYCbCr, ApproxBiLinear) }
func BenchmarkTformABOverRGBA64(b *testing.B) {
benchTform(b, 200, 150, Over, srcRGBA64, ApproxBiLinear)
}
func BenchmarkScaleCRSrcGray(b *testing.B) { benchScale(b, 200, 150, Src, srcGray, CatmullRom) }
func BenchmarkScaleCRSrcNRGBA(b *testing.B) { benchScale(b, 200, 150, Src, srcNRGBA, CatmullRom) }
func BenchmarkScaleCRSrcRGBA(b *testing.B) { benchScale(b, 200, 150, Src, srcRGBA, CatmullRom) }
func BenchmarkScaleCRSrcYCbCr(b *testing.B) { benchScale(b, 200, 150, Src, srcYCbCr, CatmullRom) }
func BenchmarkScaleCRSrcRGBA64(b *testing.B) { benchScale(b, 200, 150, Src, srcRGBA64, CatmullRom) }
func BenchmarkScaleCROverGray(b *testing.B) { benchScale(b, 200, 150, Over, srcGray, CatmullRom) }
func BenchmarkScaleCROverNRGBA(b *testing.B) { benchScale(b, 200, 150, Over, srcNRGBA, CatmullRom) }
func BenchmarkScaleCROverRGBA(b *testing.B) { benchScale(b, 200, 150, Over, srcRGBA, CatmullRom) }
func BenchmarkScaleCROverYCbCr(b *testing.B) { benchScale(b, 200, 150, Over, srcYCbCr, CatmullRom) }
func BenchmarkScaleCROverRGBA64(b *testing.B) { benchScale(b, 200, 150, Over, srcRGBA64, CatmullRom) }
func BenchmarkTformCRSrcGray(b *testing.B) { benchTform(b, 200, 150, Src, srcGray, CatmullRom) }
func BenchmarkTformCRSrcNRGBA(b *testing.B) { benchTform(b, 200, 150, Src, srcNRGBA, CatmullRom) }
func BenchmarkTformCRSrcRGBA(b *testing.B) { benchTform(b, 200, 150, Src, srcRGBA, CatmullRom) }
func BenchmarkTformCRSrcYCbCr(b *testing.B) { benchTform(b, 200, 150, Src, srcYCbCr, CatmullRom) }
func BenchmarkTformCRSrcRGBA64(b *testing.B) { benchTform(b, 200, 150, Src, srcRGBA64, CatmullRom) }
func BenchmarkTformCROverGray(b *testing.B) { benchTform(b, 200, 150, Over, srcGray, CatmullRom) }
func BenchmarkTformCROverNRGBA(b *testing.B) { benchTform(b, 200, 150, Over, srcNRGBA, CatmullRom) }
func BenchmarkTformCROverRGBA(b *testing.B) { benchTform(b, 200, 150, Over, srcRGBA, CatmullRom) }
func BenchmarkTformCROverYCbCr(b *testing.B) { benchTform(b, 200, 150, Over, srcYCbCr, CatmullRom) }
func BenchmarkTformCROverRGBA64(b *testing.B) { benchTform(b, 200, 150, Over, srcRGBA64, CatmullRom) }
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/draw.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package draw provides image composition functions.
//
// See "The Go image/draw package" for an introduction to this package:
// http://golang.org/doc/articles/image_draw.html
//
// This package is a superset of and a drop-in replacement for the image/draw
// package in the standard library.
package draw
// This file just contains the API exported by the image/draw package in the
// standard library. Other files in this package provide additional features.
import (
"image"
"image/draw"
)
// Draw calls DrawMask with a nil mask.
func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op) {
draw.Draw(dst, r, src, sp, draw.Op(op))
}
// DrawMask aligns r.Min in dst with sp in src and mp in mask and then
// replaces the rectangle r in dst with the result of a Porter-Duff
// composition. A nil mask is treated as opaque.
func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op) {
draw.DrawMask(dst, r, src, sp, mask, mp, draw.Op(op))
}
// Drawer contains the Draw method.
type Drawer = draw.Drawer
// FloydSteinberg is a Drawer that is the Src Op with Floyd-Steinberg error
// diffusion.
var FloydSteinberg Drawer = floydSteinberg{}
type floydSteinberg struct{}
func (floydSteinberg) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point) {
draw.FloydSteinberg.Draw(dst, r, src, sp)
}
// Image is an image.Image with a Set method to change a single pixel.
type Image = draw.Image
// RGBA64Image extends both the Image and image.RGBA64Image interfaces with a
// SetRGBA64 method to change a single pixel. SetRGBA64 is equivalent to
// calling Set, but it can avoid allocations from converting concrete color
// types to the color.Color interface type.
type RGBA64Image = draw.RGBA64Image
// Op is a Porter-Duff compositing operator.
type Op = draw.Op
const (
// Over specifies ``(src in mask) over dst''.
Over Op = draw.Over
// Src specifies ``src in mask''.
Src Op = draw.Src
)
// Quantizer produces a palette for an image.
type Quantizer = draw.Quantizer
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/stdlib_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package draw
import (
"bytes"
"image"
"image/color"
"testing"
)
// TestFastPaths tests that the fast path implementations produce identical
// results to the generic implementation.
func TestFastPaths(t *testing.T) {
drs := []image.Rectangle{
image.Rect(0, 0, 10, 10), // The dst bounds.
image.Rect(3, 4, 8, 6), // A strict subset of the dst bounds.
image.Rect(-3, -5, 2, 4), // Partial out-of-bounds #0.
image.Rect(4, -2, 6, 12), // Partial out-of-bounds #1.
image.Rect(12, 14, 23, 45), // Complete out-of-bounds.
image.Rect(5, 5, 5, 5), // Empty.
}
srs := []image.Rectangle{
image.Rect(0, 0, 12, 9), // The src bounds.
image.Rect(2, 2, 10, 8), // A strict subset of the src bounds.
image.Rect(10, 5, 20, 20), // Partial out-of-bounds #0.
image.Rect(-40, 0, 40, 8), // Partial out-of-bounds #1.
image.Rect(-8, -8, -4, -4), // Complete out-of-bounds.
image.Rect(5, 5, 5, 5), // Empty.
}
srcfs := []func(image.Rectangle) (image.Image, error){
srcGray,
srcNRGBA,
srcRGBA,
srcUnif,
srcYCbCr,
}
var srcs []image.Image
for _, srcf := range srcfs {
src, err := srcf(srs[0])
if err != nil {
t.Fatal(err)
}
srcs = append(srcs, src)
}
qs := []Interpolator{
NearestNeighbor,
ApproxBiLinear,
CatmullRom,
}
ops := []Op{
Over,
Src,
}
blue := image.NewUniform(color.RGBA{0x11, 0x22, 0x44, 0x7f})
for _, dr := range drs {
for _, src := range srcs {
for _, sr := range srs {
for _, transform := range []bool{false, true} {
for _, q := range qs {
for _, op := range ops {
dst0 := image.NewRGBA(drs[0])
dst1 := image.NewRGBA(drs[0])
Draw(dst0, dst0.Bounds(), blue, image.Point{}, Src)
Draw(dstWrapper{dst1}, dst1.Bounds(), srcWrapper{blue}, image.Point{}, Src)
if transform {
m := transformMatrix(3.75, 2, 1)
q.Transform(dst0, m, src, sr, op, nil)
q.Transform(dstWrapper{dst1}, m, srcWrapper{src}, sr, op, nil)
} else {
q.Scale(dst0, dr, src, sr, op, nil)
q.Scale(dstWrapper{dst1}, dr, srcWrapper{src}, sr, op, nil)
}
if !bytes.Equal(dst0.Pix, dst1.Pix) {
t.Errorf("pix differ for dr=%v, src=%T, sr=%v, transform=%t, q=%T",
dr, src, sr, transform, q)
}
}
}
}
}
}
}
}
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/example_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package draw_test
import (
"fmt"
"image"
"image/color"
"image/png"
"log"
"math"
"os"
"golang.org/x/image/draw"
"golang.org/x/image/math/f64"
)
func ExampleDraw() {
fSrc, err := os.Open("../testdata/blue-purple-pink.png")
if err != nil {
log.Fatal(err)
}
defer fSrc.Close()
src, err := png.Decode(fSrc)
if err != nil {
log.Fatal(err)
}
dst := image.NewRGBA(image.Rect(0, 0, 400, 300))
green := image.NewUniform(color.RGBA{0x00, 0x1f, 0x00, 0xff})
draw.Copy(dst, image.Point{}, green, dst.Bounds(), draw.Src, nil)
qs := []draw.Interpolator{
draw.NearestNeighbor,
draw.ApproxBiLinear,
draw.CatmullRom,
}
const cos60, sin60 = 0.5, 0.866025404
t := f64.Aff3{
+2 * cos60, -2 * sin60, 100,
+2 * sin60, +2 * cos60, 100,
}
draw.Copy(dst, image.Point{20, 30}, src, src.Bounds(), draw.Over, nil)
for i, q := range qs {
q.Scale(dst, image.Rect(200+10*i, 100*i, 600+10*i, 150+100*i), src, src.Bounds(), draw.Over, nil)
}
draw.NearestNeighbor.Transform(dst, t, src, src.Bounds(), draw.Over, nil)
red := image.NewNRGBA(image.Rect(0, 0, 16, 16))
for y := 0; y < 16; y++ {
for x := 0; x < 16; x++ {
red.SetNRGBA(x, y, color.NRGBA{
R: uint8(x * 0x11),
A: uint8(y * 0x11),
})
}
}
red.SetNRGBA(0, 0, color.NRGBA{0xff, 0xff, 0x00, 0xff})
red.SetNRGBA(15, 15, color.NRGBA{0xff, 0xff, 0x00, 0xff})
ops := []draw.Op{
draw.Over,
draw.Src,
}
for i, op := range ops {
dr := image.Rect(120+10*i, 150+60*i, 170+10*i, 200+60*i)
draw.NearestNeighbor.Scale(dst, dr, red, red.Bounds(), op, nil)
t := f64.Aff3{
+cos60, -sin60, float64(190 + 10*i),
+sin60, +cos60, float64(140 + 50*i),
}
draw.NearestNeighbor.Transform(dst, t, red, red.Bounds(), op, nil)
}
dr := image.Rect(0, 0, 128, 128)
checkerboard := image.NewAlpha(dr)
for y := dr.Min.Y; y < dr.Max.Y; y++ {
for x := dr.Min.X; x < dr.Max.X; x++ {
if (x/20)%2 == (y/20)%2 {
checkerboard.SetAlpha(x, y, color.Alpha{0xff})
}
}
}
sr := image.Rect(0, 0, 16, 16)
circle := image.NewAlpha(sr)
for y := sr.Min.Y; y < sr.Max.Y; y++ {
for x := sr.Min.X; x < sr.Max.X; x++ {
dx, dy := x-10, y-8
if d := 32 * math.Sqrt(float64(dx*dx)+float64(dy*dy)); d < 0xff {
circle.SetAlpha(x, y, color.Alpha{0xff - uint8(d)})
}
}
}
cyan := image.NewUniform(color.RGBA{0x00, 0xff, 0xff, 0xff})
draw.NearestNeighbor.Scale(dst, dr, cyan, sr, draw.Over, &draw.Options{
DstMask: checkerboard,
SrcMask: circle,
})
// Change false to true to write the resultant image to disk.
if false {
fDst, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
defer fDst.Close()
err = png.Encode(fDst, dst)
if err != nil {
log.Fatal(err)
}
}
fmt.Printf("dst has bounds %v.\n", dst.Bounds())
// Output:
// dst has bounds (0,0)-(400,300).
}
|
draw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/draw/gen.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"log"
"os"
"strings"
)
var debug = flag.Bool("debug", false, "")
func main() {
flag.Parse()
w := new(bytes.Buffer)
w.WriteString("// generated by \"go run gen.go\". DO NOT EDIT.\n\n" +
"package draw\n\nimport (\n" +
"\"image\"\n" +
"\"image/color\"\n" +
"\"math\"\n" +
"\n" +
"\"golang.org/x/image/math/f64\"\n" +
")\n")
gen(w, "nnInterpolator", codeNNScaleLeaf, codeNNTransformLeaf)
gen(w, "ablInterpolator", codeABLScaleLeaf, codeABLTransformLeaf)
genKernel(w)
if *debug {
os.Stdout.Write(w.Bytes())
return
}
out, err := format.Source(w.Bytes())
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("impl.go", out, 0660); err != nil {
log.Fatal(err)
}
}
var (
// dsTypes are the (dst image type, src image type) pairs to generate
// scale_DType_SType implementations for. The last element in the slice
// should be the fallback pair ("Image", "image.Image").
//
// TODO: add *image.CMYK src type after Go 1.5 is released.
// An *image.CMYK is also alwaysOpaque.
dsTypes = []struct{ dType, sType string }{
{"*image.RGBA", "*image.Gray"},
{"*image.RGBA", "*image.NRGBA"},
{"*image.RGBA", "*image.RGBA"},
{"*image.RGBA", "*image.YCbCr"},
{"*image.RGBA", "image.RGBA64Image"},
{"*image.RGBA", "image.Image"},
{"RGBA64Image", "image.RGBA64Image"},
{"Image", "image.Image"},
}
dTypes, sTypes []string
sTypesForDType = map[string][]string{}
subsampleRatios = []string{
"444",
"422",
"420",
"440",
}
ops = []string{"Over", "Src"}
// alwaysOpaque are those image.Image implementations that are always
// opaque. For these types, Over is equivalent to the faster Src, in the
// absence of a source mask.
alwaysOpaque = map[string]bool{
"*image.Gray": true,
"*image.YCbCr": true,
}
)
func init() {
dTypesSeen := map[string]bool{}
sTypesSeen := map[string]bool{}
for _, t := range dsTypes {
if !sTypesSeen[t.sType] {
sTypesSeen[t.sType] = true
sTypes = append(sTypes, t.sType)
}
if !dTypesSeen[t.dType] {
dTypesSeen[t.dType] = true
dTypes = append(dTypes, t.dType)
}
sTypesForDType[t.dType] = append(sTypesForDType[t.dType], t.sType)
}
sTypesForDType["anyDType"] = sTypes
}
type data struct {
dType string
sType string
sratio string
receiver string
op string
}
func gen(w *bytes.Buffer, receiver string, codes ...string) {
expn(w, codeRoot, &data{receiver: receiver})
for _, code := range codes {
for _, t := range dsTypes {
for _, op := range ops {
if op == "Over" && alwaysOpaque[t.sType] {
continue
}
expn(w, code, &data{
dType: t.dType,
sType: t.sType,
receiver: receiver,
op: op,
})
}
}
}
}
func genKernel(w *bytes.Buffer) {
expn(w, codeKernelRoot, &data{})
for _, sType := range sTypes {
expn(w, codeKernelScaleLeafX, &data{
sType: sType,
})
}
for _, dType := range dTypes {
for _, op := range ops {
expn(w, codeKernelScaleLeafY, &data{
dType: dType,
op: op,
})
}
}
for _, t := range dsTypes {
for _, op := range ops {
if op == "Over" && alwaysOpaque[t.sType] {
continue
}
expn(w, codeKernelTransformLeaf, &data{
dType: t.dType,
sType: t.sType,
op: op,
})
}
}
}
func expn(w *bytes.Buffer, code string, d *data) {
if d.sType == "*image.YCbCr" && d.sratio == "" {
for _, sratio := range subsampleRatios {
e := *d
e.sratio = sratio
expn(w, code, &e)
}
return
}
for _, line := range strings.Split(code, "\n") {
line = expnLine(line, d)
if line == ";" {
continue
}
fmt.Fprintln(w, line)
}
}
func expnLine(line string, d *data) string {
for {
i := strings.IndexByte(line, '$')
if i < 0 {
break
}
prefix, s := line[:i], line[i+1:]
i = len(s)
for j, c := range s {
if !('A' <= c && c <= 'Z' || 'a' <= c && c <= 'z') {
i = j
break
}
}
dollar, suffix := s[:i], s[i:]
e := expnDollar(prefix, dollar, suffix, d)
if e == "" {
log.Fatalf("couldn't expand %q", line)
}
line = e
}
return line
}
// expnDollar expands a "$foo" fragment in a line of generated code. It returns
// the empty string if there was a problem. It returns ";" if the generated
// code is a no-op.
func expnDollar(prefix, dollar, suffix string, d *data) string {
switch dollar {
case "dType":
return prefix + d.dType + suffix
case "dTypeRN":
return prefix + relName(d.dType) + suffix
case "sratio":
return prefix + d.sratio + suffix
case "sType":
return prefix + d.sType + suffix
case "sTypeRN":
return prefix + relName(d.sType) + suffix
case "receiver":
return prefix + d.receiver + suffix
case "op":
return prefix + d.op + suffix
case "switch":
return expnSwitch("", "", true, suffix)
case "switchD":
return expnSwitch("", "", false, suffix)
case "switchS":
return expnSwitch("", "anyDType", false, suffix)
case "preOuter":
switch d.dType {
default:
return ";"
case "Image":
s := ""
if d.sType == "image.Image" || d.sType == "image.RGBA64Image" {
s = "srcMask, smp := opts.SrcMask, opts.SrcMaskP\n"
}
return s +
"dstMask, dmp := opts.DstMask, opts.DstMaskP\n" +
"dstColorRGBA64 := &color.RGBA64{}\n" +
"dstColor := color.Color(dstColorRGBA64)"
case "RGBA64Image":
s := ""
if d.sType == "image.Image" || d.sType == "image.RGBA64Image" {
s = "srcMask, smp := opts.SrcMask, opts.SrcMaskP\n"
}
return s +
"dstMask, dmp := opts.DstMask, opts.DstMaskP\n" +
"dstColorRGBA64 := color.RGBA64{}\n"
}
case "preInner":
switch d.dType {
default:
return ";"
case "*image.RGBA":
return "d := " + pixOffset("dst", "dr.Min.X+adr.Min.X", "dr.Min.Y+int(dy)", "*4", "*dst.Stride")
}
case "preKernelOuter":
switch d.sType {
default:
return ";"
case "image.Image", "image.RGBA64Image":
return "srcMask, smp := opts.SrcMask, opts.SrcMaskP"
}
case "preKernelInner":
switch d.dType {
default:
return ";"
case "*image.RGBA":
return "d := " + pixOffset("dst", "dr.Min.X+int(dx)", "dr.Min.Y+adr.Min.Y", "*4", "*dst.Stride")
}
case "blend":
args, _ := splitArgs(suffix)
if len(args) != 4 {
return ""
}
switch d.sType {
default:
return argf(args, ""+
"$3r = float64($0*$1r) + float64($2*$3r)\n"+
"$3g = float64($0*$1g) + float64($2*$3g)\n"+
"$3b = float64($0*$1b) + float64($2*$3b)\n"+
"$3a = float64($0*$1a) + float64($2*$3a)",
)
case "*image.Gray":
return argf(args, ""+
"$3r = float64($0*$1r) + float64($2*$3r)",
)
case "*image.YCbCr":
return argf(args, ""+
"$3r = float64($0*$1r) + float64($2*$3r)\n"+
"$3g = float64($0*$1g) + float64($2*$3g)\n"+
"$3b = float64($0*$1b) + float64($2*$3b)",
)
}
case "clampToAlpha":
if alwaysOpaque[d.sType] {
return ";"
}
// Go uses alpha-premultiplied color. The naive computation can lead to
// invalid colors, e.g. red > alpha, when some weights are negative.
return `
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
`
case "convFtou":
args, _ := splitArgs(suffix)
if len(args) != 2 {
return ""
}
switch d.sType {
default:
return argf(args, ""+
"$0r := uint32($1r)\n"+
"$0g := uint32($1g)\n"+
"$0b := uint32($1b)\n"+
"$0a := uint32($1a)",
)
case "*image.Gray":
return argf(args, ""+
"$0r := uint32($1r)",
)
case "*image.YCbCr":
return argf(args, ""+
"$0r := uint32($1r)\n"+
"$0g := uint32($1g)\n"+
"$0b := uint32($1b)",
)
case "image.RGBA64Image":
return argf(args, ""+
"$0 := color.RGBA64{uint16($1r), uint16($1g), uint16($1b), uint16($1a)}",
)
}
case "outputu":
args, _ := splitArgs(suffix)
if len(args) != 3 {
return ""
}
switch d.op {
case "Over":
switch d.dType {
default:
log.Fatalf("bad dType %q", d.dType)
case "Image":
return argf(args, ""+
"qr, qg, qb, qa := dst.At($0, $1).RGBA()\n"+
"if dstMask != nil {\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" $2r = $2r * ma / 0xffff\n"+
" $2g = $2g * ma / 0xffff\n"+
" $2b = $2b * ma / 0xffff\n"+
" $2a = $2a * ma / 0xffff\n"+
"}\n"+
"$2a1 := 0xffff - $2a\n"+
"dstColorRGBA64.R = uint16(qr*$2a1/0xffff + $2r)\n"+
"dstColorRGBA64.G = uint16(qg*$2a1/0xffff + $2g)\n"+
"dstColorRGBA64.B = uint16(qb*$2a1/0xffff + $2b)\n"+
"dstColorRGBA64.A = uint16(qa*$2a1/0xffff + $2a)\n"+
"dst.Set($0, $1, dstColor)",
)
case "RGBA64Image":
switch d.sType {
default:
return argf(args, ""+
"q := dst.RGBA64At($0, $1)\n"+
"if dstMask != nil {\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" $2r = $2r * ma / 0xffff\n"+
" $2g = $2g * ma / 0xffff\n"+
" $2b = $2b * ma / 0xffff\n"+
" $2a = $2a * ma / 0xffff\n"+
"}\n"+
"$2a1 := 0xffff - $2a\n"+
"dstColorRGBA64.R = uint16(uint32(q.R)*$2a1/0xffff + $2r)\n"+
"dstColorRGBA64.G = uint16(uint32(q.G)*$2a1/0xffff + $2g)\n"+
"dstColorRGBA64.B = uint16(uint32(q.B)*$2a1/0xffff + $2b)\n"+
"dstColorRGBA64.A = uint16(uint32(q.A)*$2a1/0xffff + $2a)\n"+
"dst.Set($0, $1, dstColorRGBA64)",
)
case "image.RGBA64Image":
return argf(args, ""+
"q := dst.RGBA64At($0, $1)\n"+
"if dstMask != nil {\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" $2.R = uint16(uint32($2.R) * ma / 0xffff)\n"+
" $2.G = uint16(uint32($2.G) * ma / 0xffff)\n"+
" $2.B = uint16(uint32($2.B) * ma / 0xffff)\n"+
" $2.A = uint16(uint32($2.A) * ma / 0xffff)\n"+
"}\n"+
"$2a1 := 0xffff - uint32($2.A)\n"+
"dstColorRGBA64.R = uint16(uint32(q.R)*$2a1/0xffff + uint32($2.R))\n"+
"dstColorRGBA64.G = uint16(uint32(q.G)*$2a1/0xffff + uint32($2.G))\n"+
"dstColorRGBA64.B = uint16(uint32(q.B)*$2a1/0xffff + uint32($2.B))\n"+
"dstColorRGBA64.A = uint16(uint32(q.A)*$2a1/0xffff + uint32($2.A))\n"+
"dst.Set($0, $1, dstColorRGBA64)",
)
}
case "*image.RGBA":
switch d.sType {
default:
return argf(args, ""+
"$2a1 := (0xffff - $2a) * 0x101\n"+
"dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*$2a1/0xffff + $2r) >> 8)\n"+
"dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*$2a1/0xffff + $2g) >> 8)\n"+
"dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*$2a1/0xffff + $2b) >> 8)\n"+
"dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*$2a1/0xffff + $2a) >> 8)",
)
case "image.RGBA64Image":
return argf(args, ""+
"$2a1 := (0xffff - uint32($2.A)) * 0x101\n"+
"dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*$2a1/0xffff + uint32($2.R)) >> 8)\n"+
"dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*$2a1/0xffff + uint32($2.G)) >> 8)\n"+
"dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*$2a1/0xffff + uint32($2.B)) >> 8)\n"+
"dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*$2a1/0xffff + uint32($2.A)) >> 8)",
)
}
}
case "Src":
switch d.dType {
default:
log.Fatalf("bad dType %q", d.dType)
case "Image":
return argf(args, ""+
"if dstMask != nil {\n"+
" qr, qg, qb, qa := dst.At($0, $1).RGBA()\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" pr = pr * ma / 0xffff\n"+
" pg = pg * ma / 0xffff\n"+
" pb = pb * ma / 0xffff\n"+
" pa = pa * ma / 0xffff\n"+
" $2a1 := 0xffff - ma\n"+ // Note that this is ma, not $2a.
" dstColorRGBA64.R = uint16(qr*$2a1/0xffff + $2r)\n"+
" dstColorRGBA64.G = uint16(qg*$2a1/0xffff + $2g)\n"+
" dstColorRGBA64.B = uint16(qb*$2a1/0xffff + $2b)\n"+
" dstColorRGBA64.A = uint16(qa*$2a1/0xffff + $2a)\n"+
" dst.Set($0, $1, dstColor)\n"+
"} else {\n"+
" dstColorRGBA64.R = uint16($2r)\n"+
" dstColorRGBA64.G = uint16($2g)\n"+
" dstColorRGBA64.B = uint16($2b)\n"+
" dstColorRGBA64.A = uint16($2a)\n"+
" dst.Set($0, $1, dstColor)\n"+
"}",
)
case "RGBA64Image":
switch d.sType {
default:
return argf(args, ""+
"if dstMask != nil {\n"+
" q := dst.RGBA64At($0, $1)\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" pr = pr * ma / 0xffff\n"+
" pg = pg * ma / 0xffff\n"+
" pb = pb * ma / 0xffff\n"+
" pa = pa * ma / 0xffff\n"+
" $2a1 := 0xffff - ma\n"+ // Note that this is ma, not $2a.
" dstColorRGBA64.R = uint16(uint32(q.R)*$2a1/0xffff + $2r)\n"+
" dstColorRGBA64.G = uint16(uint32(q.G)*$2a1/0xffff + $2g)\n"+
" dstColorRGBA64.B = uint16(uint32(q.B)*$2a1/0xffff + $2b)\n"+
" dstColorRGBA64.A = uint16(uint32(q.A)*$2a1/0xffff + $2a)\n"+
" dst.Set($0, $1, dstColorRGBA64)\n"+
"} else {\n"+
" dstColorRGBA64.R = uint16($2r)\n"+
" dstColorRGBA64.G = uint16($2g)\n"+
" dstColorRGBA64.B = uint16($2b)\n"+
" dstColorRGBA64.A = uint16($2a)\n"+
" dst.Set($0, $1, dstColorRGBA64)\n"+
"}",
)
case "image.RGBA64Image":
return argf(args, ""+
"if dstMask != nil {\n"+
" q := dst.RGBA64At($0, $1)\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" p.R = uint16(uint32(p.R) * ma / 0xffff)\n"+
" p.G = uint16(uint32(p.G) * ma / 0xffff)\n"+
" p.B = uint16(uint32(p.B) * ma / 0xffff)\n"+
" p.A = uint16(uint32(p.A) * ma / 0xffff)\n"+
" $2a1 := 0xffff - ma\n"+ // Note that this is ma, not $2a.
" dstColorRGBA64.R = uint16(uint32(q.R)*$2a1/0xffff + uint32($2.R))\n"+
" dstColorRGBA64.G = uint16(uint32(q.G)*$2a1/0xffff + uint32($2.G))\n"+
" dstColorRGBA64.B = uint16(uint32(q.B)*$2a1/0xffff + uint32($2.B))\n"+
" dstColorRGBA64.A = uint16(uint32(q.A)*$2a1/0xffff + uint32($2.A))\n"+
" dst.Set($0, $1, dstColorRGBA64)\n"+
"} else {\n"+
" dst.Set($0, $1, $2)\n"+
"}",
)
}
case "*image.RGBA":
switch d.sType {
default:
return argf(args, ""+
"dst.Pix[d+0] = uint8($2r >> 8)\n"+
"dst.Pix[d+1] = uint8($2g >> 8)\n"+
"dst.Pix[d+2] = uint8($2b >> 8)\n"+
"dst.Pix[d+3] = uint8($2a >> 8)",
)
case "*image.Gray":
return argf(args, ""+
"out := uint8($2r >> 8)\n"+
"dst.Pix[d+0] = out\n"+
"dst.Pix[d+1] = out\n"+
"dst.Pix[d+2] = out\n"+
"dst.Pix[d+3] = 0xff",
)
case "*image.YCbCr":
return argf(args, ""+
"dst.Pix[d+0] = uint8($2r >> 8)\n"+
"dst.Pix[d+1] = uint8($2g >> 8)\n"+
"dst.Pix[d+2] = uint8($2b >> 8)\n"+
"dst.Pix[d+3] = 0xff",
)
case "image.RGBA64Image":
return argf(args, ""+
"dst.Pix[d+0] = uint8($2.R >> 8)\n"+
"dst.Pix[d+1] = uint8($2.G >> 8)\n"+
"dst.Pix[d+2] = uint8($2.B >> 8)\n"+
"dst.Pix[d+3] = uint8($2.A >> 8)",
)
}
}
}
case "outputf":
args, _ := splitArgs(suffix)
if len(args) != 5 {
return ""
}
ret := ""
switch d.op {
case "Over":
switch d.dType {
default:
log.Fatalf("bad dType %q", d.dType)
case "Image":
ret = argf(args, ""+
"qr, qg, qb, qa := dst.At($0, $1).RGBA()\n"+
"$3r0 := uint32($2($3r * $4))\n"+
"$3g0 := uint32($2($3g * $4))\n"+
"$3b0 := uint32($2($3b * $4))\n"+
"$3a0 := uint32($2($3a * $4))\n"+
"if dstMask != nil {\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" $3r0 = $3r0 * ma / 0xffff\n"+
" $3g0 = $3g0 * ma / 0xffff\n"+
" $3b0 = $3b0 * ma / 0xffff\n"+
" $3a0 = $3a0 * ma / 0xffff\n"+
"}\n"+
"$3a1 := 0xffff - $3a0\n"+
"dstColorRGBA64.R = uint16(qr*$3a1/0xffff + $3r0)\n"+
"dstColorRGBA64.G = uint16(qg*$3a1/0xffff + $3g0)\n"+
"dstColorRGBA64.B = uint16(qb*$3a1/0xffff + $3b0)\n"+
"dstColorRGBA64.A = uint16(qa*$3a1/0xffff + $3a0)\n"+
"dst.Set($0, $1, dstColor)",
)
case "RGBA64Image":
ret = argf(args, ""+
"q := dst.RGBA64At($0, $1)\n"+
"$3r0 := uint32($2($3r * $4))\n"+
"$3g0 := uint32($2($3g * $4))\n"+
"$3b0 := uint32($2($3b * $4))\n"+
"$3a0 := uint32($2($3a * $4))\n"+
"if dstMask != nil {\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" $3r0 = $3r0 * ma / 0xffff\n"+
" $3g0 = $3g0 * ma / 0xffff\n"+
" $3b0 = $3b0 * ma / 0xffff\n"+
" $3a0 = $3a0 * ma / 0xffff\n"+
"}\n"+
"$3a1 := 0xffff - $3a0\n"+
"dstColorRGBA64.R = uint16(uint32(q.R)*$3a1/0xffff + $3r0)\n"+
"dstColorRGBA64.G = uint16(uint32(q.G)*$3a1/0xffff + $3g0)\n"+
"dstColorRGBA64.B = uint16(uint32(q.B)*$3a1/0xffff + $3b0)\n"+
"dstColorRGBA64.A = uint16(uint32(q.A)*$3a1/0xffff + $3a0)\n"+
"dst.SetRGBA64($0, $1, dstColorRGBA64)",
)
case "*image.RGBA":
ret = argf(args, ""+
"$3r0 := uint32($2($3r * $4))\n"+
"$3g0 := uint32($2($3g * $4))\n"+
"$3b0 := uint32($2($3b * $4))\n"+
"$3a0 := uint32($2($3a * $4))\n"+
"$3a1 := (0xffff - uint32($3a0)) * 0x101\n"+
"dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*$3a1/0xffff + $3r0) >> 8)\n"+
"dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*$3a1/0xffff + $3g0) >> 8)\n"+
"dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*$3a1/0xffff + $3b0) >> 8)\n"+
"dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*$3a1/0xffff + $3a0) >> 8)",
)
}
case "Src":
switch d.dType {
default:
log.Fatalf("bad dType %q", d.dType)
case "Image":
ret = argf(args, ""+
"if dstMask != nil {\n"+
" qr, qg, qb, qa := dst.At($0, $1).RGBA()\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" pr := uint32($2($3r * $4)) * ma / 0xffff\n"+
" pg := uint32($2($3g * $4)) * ma / 0xffff\n"+
" pb := uint32($2($3b * $4)) * ma / 0xffff\n"+
" pa := uint32($2($3a * $4)) * ma / 0xffff\n"+
" pa1 := 0xffff - ma\n"+ // Note that this is ma, not pa.
" dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)\n"+
" dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)\n"+
" dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)\n"+
" dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)\n"+
" dst.Set($0, $1, dstColor)\n"+
"} else {\n"+
" dstColorRGBA64.R = $2($3r * $4)\n"+
" dstColorRGBA64.G = $2($3g * $4)\n"+
" dstColorRGBA64.B = $2($3b * $4)\n"+
" dstColorRGBA64.A = $2($3a * $4)\n"+
" dst.Set($0, $1, dstColor)\n"+
"}",
)
case "RGBA64Image":
ret = argf(args, ""+
"if dstMask != nil {\n"+
" q := dst.RGBA64At($0, $1)\n"+
" _, _, _, ma := dstMask.At(dmp.X + $0, dmp.Y + $1).RGBA()\n"+
" pr := uint32($2($3r * $4)) * ma / 0xffff\n"+
" pg := uint32($2($3g * $4)) * ma / 0xffff\n"+
" pb := uint32($2($3b * $4)) * ma / 0xffff\n"+
" pa := uint32($2($3a * $4)) * ma / 0xffff\n"+
" pa1 := 0xffff - ma\n"+ // Note that this is ma, not pa.
" dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr)\n"+
" dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg)\n"+
" dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb)\n"+
" dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa)\n"+
" dst.SetRGBA64($0, $1, dstColorRGBA64)\n"+
"} else {\n"+
" dstColorRGBA64.R = $2($3r * $4)\n"+
" dstColorRGBA64.G = $2($3g * $4)\n"+
" dstColorRGBA64.B = $2($3b * $4)\n"+
" dstColorRGBA64.A = $2($3a * $4)\n"+
" dst.SetRGBA64($0, $1, dstColorRGBA64)\n"+
"}",
)
case "*image.RGBA":
switch d.sType {
default:
ret = argf(args, ""+
"dst.Pix[d+0] = uint8($2($3r * $4) >> 8)\n"+
"dst.Pix[d+1] = uint8($2($3g * $4) >> 8)\n"+
"dst.Pix[d+2] = uint8($2($3b * $4) >> 8)\n"+
"dst.Pix[d+3] = uint8($2($3a * $4) >> 8)",
)
case "*image.Gray":
ret = argf(args, ""+
"out := uint8($2($3r * $4) >> 8)\n"+
"dst.Pix[d+0] = out\n"+
"dst.Pix[d+1] = out\n"+
"dst.Pix[d+2] = out\n"+
"dst.Pix[d+3] = 0xff",
)
case "*image.YCbCr":
ret = argf(args, ""+
"dst.Pix[d+0] = uint8($2($3r * $4) >> 8)\n"+
"dst.Pix[d+1] = uint8($2($3g * $4) >> 8)\n"+
"dst.Pix[d+2] = uint8($2($3b * $4) >> 8)\n"+
"dst.Pix[d+3] = 0xff",
)
}
}
}
return strings.Replace(ret, " * 1)", ")", -1)
case "srcf", "srcu":
lhs, eqOp := splitEq(prefix)
if lhs == "" {
return ""
}
args, extra := splitArgs(suffix)
if len(args) != 2 {
return ""
}
tmp := ""
if dollar == "srcf" {
tmp = "u"
}
// TODO: there's no need to multiply by 0x101 in the switch below if
// the next thing we're going to do is shift right by 8.
buf := new(bytes.Buffer)
switch d.sType {
default:
log.Fatalf("bad sType %q", d.sType)
case "image.Image":
fmt.Fprintf(buf, ""+
"%sr%s, %sg%s, %sb%s, %sa%s := src.At(%s, %s).RGBA()\n",
lhs, tmp, lhs, tmp, lhs, tmp, lhs, tmp, args[0], args[1],
)
if d.dType == "" || d.dType == "Image" || d.dType == "RGBA64Image" {
fmt.Fprintf(buf, ""+
"if srcMask != nil {\n"+
" _, _, _, ma := srcMask.At(smp.X+%[1]s, smp.Y+%[2]s).RGBA()\n"+
" %[3]sr%[4]s = %[3]sr%[4]s * ma / 0xffff\n"+
" %[3]sg%[4]s = %[3]sg%[4]s * ma / 0xffff\n"+
" %[3]sb%[4]s = %[3]sb%[4]s * ma / 0xffff\n"+
" %[3]sa%[4]s = %[3]sa%[4]s * ma / 0xffff\n"+
"}\n",
args[0], args[1],
lhs, tmp,
)
}
case "image.RGBA64Image":
fmt.Fprintf(buf, ""+
"%s%s := src.RGBA64At(%s, %s)\n",
lhs, tmp, args[0], args[1],
)
if d.dType == "" || d.dType == "Image" || d.dType == "RGBA64Image" {
fmt.Fprintf(buf, ""+
"if srcMask != nil {\n"+
" _, _, _, ma := srcMask.At(smp.X+%[1]s, smp.Y+%[2]s).RGBA()\n"+
" %[3]s%[4]s.R = uint16(uint32(%[3]s%[4]s.R) * ma / 0xffff)\n"+
" %[3]s%[4]s.G = uint16(uint32(%[3]s%[4]s.G) * ma / 0xffff)\n"+
" %[3]s%[4]s.B = uint16(uint32(%[3]s%[4]s.B) * ma / 0xffff)\n"+
" %[3]s%[4]s.A = uint16(uint32(%[3]s%[4]s.A) * ma / 0xffff)\n"+
"}\n",
args[0], args[1],
lhs, tmp,
)
}
case "*image.Gray":
fmt.Fprintf(buf, ""+
"%[1]si := %[3]s\n"+
"%[1]sr%[2]s := uint32(src.Pix[%[1]si]) * 0x101\n",
lhs, tmp, pixOffset("src", args[0], args[1], "", "*src.Stride"),
)
case "*image.NRGBA":
fmt.Fprintf(buf, ""+
"%[1]si := %[3]s\n"+
"%[1]sa%[2]s := uint32(src.Pix[%[1]si+3]) * 0x101\n"+
"%[1]sr%[2]s := uint32(src.Pix[%[1]si+0]) * %[1]sa%s / 0xff\n"+
"%[1]sg%[2]s := uint32(src.Pix[%[1]si+1]) * %[1]sa%s / 0xff\n"+
"%[1]sb%[2]s := uint32(src.Pix[%[1]si+2]) * %[1]sa%s / 0xff\n",
lhs, tmp, pixOffset("src", args[0], args[1], "*4", "*src.Stride"),
)
case "*image.RGBA":
fmt.Fprintf(buf, ""+
"%[1]si := %[3]s\n"+
"%[1]sr%[2]s := uint32(src.Pix[%[1]si+0]) * 0x101\n"+
"%[1]sg%[2]s := uint32(src.Pix[%[1]si+1]) * 0x101\n"+
"%[1]sb%[2]s := uint32(src.Pix[%[1]si+2]) * 0x101\n"+
"%[1]sa%[2]s := uint32(src.Pix[%[1]si+3]) * 0x101\n",
lhs, tmp, pixOffset("src", args[0], args[1], "*4", "*src.Stride"),
)
case "*image.YCbCr":
fmt.Fprintf(buf, ""+
"%[1]si := %[2]s\n"+
"%[1]sj := %[3]s\n"+
"%[4]s\n",
lhs, pixOffset("src", args[0], args[1], "", "*src.YStride"),
cOffset(args[0], args[1], d.sratio),
ycbcrToRGB(lhs, tmp),
)
}
if dollar == "srcf" {
avoidFMA0, avoidFMA1 := "", "" // FMA is Fused Multiply Add.
if extra != "" {
avoidFMA0, avoidFMA1 = "float64(", ")"
}
switch d.sType {
default:
fmt.Fprintf(buf, ""+
"%[1]sr %[2]s %[4]sfloat64(%[1]sru)%[3]s%[5]s\n"+
"%[1]sg %[2]s %[4]sfloat64(%[1]sgu)%[3]s%[5]s\n"+
"%[1]sb %[2]s %[4]sfloat64(%[1]sbu)%[3]s%[5]s\n"+
"%[1]sa %[2]s %[4]sfloat64(%[1]sau)%[3]s%[5]s\n",
lhs, eqOp, extra, avoidFMA0, avoidFMA1,
)
case "*image.Gray":
fmt.Fprintf(buf, ""+
"%[1]sr %[2]s %[4]sfloat64(%[1]sru)%[3]s%[5]s\n",
lhs, eqOp, extra, avoidFMA0, avoidFMA1,
)
case "*image.YCbCr":
fmt.Fprintf(buf, ""+
"%[1]sr %[2]s %[4]sfloat64(%[1]sru)%[3]s%[5]s\n"+
"%[1]sg %[2]s %[4]sfloat64(%[1]sgu)%[3]s%[5]s\n"+
"%[1]sb %[2]s %[4]sfloat64(%[1]sbu)%[3]s%[5]s\n",
lhs, eqOp, extra, avoidFMA0, avoidFMA1,
)
case "image.RGBA64Image":
fmt.Fprintf(buf, ""+
"%[1]sr %[2]s %[4]sfloat64(%[1]su.R)%[3]s%[5]s\n"+
"%[1]sg %[2]s %[4]sfloat64(%[1]su.G)%[3]s%[5]s\n"+
"%[1]sb %[2]s %[4]sfloat64(%[1]su.B)%[3]s%[5]s\n"+
"%[1]sa %[2]s %[4]sfloat64(%[1]su.A)%[3]s%[5]s\n",
lhs, eqOp, extra, avoidFMA0, avoidFMA1,
)
}
}
return strings.TrimSpace(buf.String())
case "tweakD":
if d.dType == "*image.RGBA" {
return "d += dst.Stride"
}
return ";"
case "tweakDx":
if d.dType == "*image.RGBA" {
return strings.Replace(prefix, "dx++", "dx, d = dx+1, d+4", 1)
}
return prefix
case "tweakDy":
if d.dType == "*image.RGBA" {
return strings.Replace(prefix, "for dy, s", "for _, s", 1)
}
return prefix
case "tweakP":
switch d.sType {
case "*image.Gray":
if strings.HasPrefix(strings.TrimSpace(prefix), "pa * ") {
return "1,"
}
return "pr,"
case "*image.YCbCr":
if strings.HasPrefix(strings.TrimSpace(prefix), "pa * ") {
return "1,"
}
}
return prefix
case "tweakPr":
if d.sType == "*image.Gray" {
return "pr *= s.invTotalWeightFFFF"
}
return ";"
case "tweakVarP":
switch d.sType {
case "*image.Gray":
return strings.Replace(prefix, "var pr, pg, pb, pa", "var pr", 1)
case "*image.YCbCr":
return strings.Replace(prefix, "var pr, pg, pb, pa", "var pr, pg, pb", 1)
}
return prefix
}
return ""
}
func expnSwitch(op, dType string, expandBoth bool, template string) string {
if op == "" && dType != "anyDType" {
lines := []string{"switch op {"}
for _, op = range ops {
lines = append(lines,
fmt.Sprintf("case %s:", op),
expnSwitch(op, dType, expandBoth, template),
)
}
lines = append(lines, "}")
return strings.Join(lines, "\n")
}
switchVar := "dst"
if dType != "" {
switchVar = "src"
}
lines := []string{fmt.Sprintf("switch %s := %s.(type) {", switchVar, switchVar)}
fallback, values := "Image", dTypes
if dType != "" {
fallback, values = "image.Image", sTypesForDType[dType]
}
for _, v := range values {
if dType != "" {
// v is the sType. Skip those always-opaque sTypes, where Over is
// equivalent to Src.
if op == "Over" && alwaysOpaque[v] {
continue
}
}
if v == fallback {
lines = append(lines, "default:")
} else {
lines = append(lines, fmt.Sprintf("case %s:", v))
}
if dType != "" {
if v == "*image.YCbCr" {
lines = append(lines, expnSwitchYCbCr(op, dType, template))
} else {
lines = append(lines, expnLine(template, &data{dType: dType, sType: v, op: op}))
}
} else if !expandBoth {
lines = append(lines, expnLine(template, &data{dType: v, op: op}))
} else {
lines = append(lines, expnSwitch(op, v, false, template))
}
}
lines = append(lines, "}")
return strings.Join(lines, "\n")
}
func expnSwitchYCbCr(op, dType, template string) string {
lines := []string{
"switch src.SubsampleRatio {",
"default:",
expnLine(template, &data{dType: dType, sType: "image.Image", op: op}),
}
for _, sratio := range subsampleRatios {
lines = append(lines,
fmt.Sprintf("case image.YCbCrSubsampleRatio%s:", sratio),
expnLine(template, &data{dType: dType, sType: "*image.YCbCr", sratio: sratio, op: op}),
)
}
lines = append(lines, "}")
return strings.Join(lines, "\n")
}
func argf(args []string, s string) string {
if len(args) > 9 {
panic("too many args")
}
for i, a := range args {
old := fmt.Sprintf("$%d", i)
s = strings.Replace(s, old, a, -1)
}
return s
}
func pixOffset(m, x, y, xstride, ystride string) string {
return fmt.Sprintf("(%s-%s.Rect.Min.Y)%s + (%s-%s.Rect.Min.X)%s", y, m, ystride, x, m, xstride)
}
func cOffset(x, y, sratio string) string {
switch sratio {
case "444":
return fmt.Sprintf("( %s - src.Rect.Min.Y )*src.CStride + ( %s - src.Rect.Min.X )", y, x)
case "422":
return fmt.Sprintf("( %s - src.Rect.Min.Y )*src.CStride + ((%s)/2 - src.Rect.Min.X/2)", y, x)
case "420":
return fmt.Sprintf("((%s)/2 - src.Rect.Min.Y/2)*src.CStride + ((%s)/2 - src.Rect.Min.X/2)", y, x)
case "440":
return fmt.Sprintf("((%s)/2 - src.Rect.Min.Y/2)*src.CStride + ( %s - src.Rect.Min.X )", y, x)
}
return fmt.Sprintf("unsupported sratio %q", sratio)
}
func ycbcrToRGB(lhs, tmp string) string {
s := `
// This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method.
$yy1 := int(src.Y[$i]) * 0x10101
$cb1 := int(src.Cb[$j]) - 128
$cr1 := int(src.Cr[$j]) - 128
$r@ := ($yy1 + 91881*$cr1) >> 8
$g@ := ($yy1 - 22554*$cb1 - 46802*$cr1) >> 8
$b@ := ($yy1 + 116130*$cb1) >> 8
if $r@ < 0 {
$r@ = 0
} else if $r@ > 0xffff {
$r@ = 0xffff
}
if $g@ < 0 {
$g@ = 0
} else if $g@ > 0xffff {
$g@ = 0xffff
}
if $b@ < 0 {
$b@ = 0
} else if $b@ > 0xffff {
$b@ = 0xffff
}
`
s = strings.Replace(s, "$", lhs, -1)
s = strings.Replace(s, "@", tmp, -1)
return s
}
func split(s, sep string) (string, string) {
if i := strings.Index(s, sep); i >= 0 {
return strings.TrimSpace(s[:i]), strings.TrimSpace(s[i+len(sep):])
}
return "", ""
}
func splitEq(s string) (lhs, eqOp string) {
s = strings.TrimSpace(s)
if lhs, _ = split(s, ":="); lhs != "" {
return lhs, ":="
}
if lhs, _ = split(s, "+="); lhs != "" {
return lhs, "+="
}
return "", ""
}
func splitArgs(s string) (args []string, extra string) {
s = strings.TrimSpace(s)
if s == "" || s[0] != '[' {
return nil, ""
}
s = s[1:]
i := strings.IndexByte(s, ']')
if i < 0 {
return nil, ""
}
args, extra = strings.Split(s[:i], ","), s[i+1:]
for i := range args {
args[i] = strings.TrimSpace(args[i])
}
return args, extra
}
func relName(s string) string {
if i := strings.LastIndex(s, "."); i >= 0 {
return s[i+1:]
}
return s
}
const (
codeRoot = `
func (z $receiver) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
// Try to simplify a Scale to a Copy when DstMask is not specified.
// If DstMask is not nil, Copy will call Scale back with same dr and sr, and cause stack overflow.
if dr.Size() == sr.Size() && (opts == nil || opts.DstMask == nil) {
Copy(dst, dr.Min, src, sr, op, opts)
return
}
var o Options
if opts != nil {
o = *opts
}
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o)
case Src:
z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o)
}
} else if _, ok := src.(*image.Uniform); ok {
Draw(dst, dr, src, src.Bounds().Min, op)
} else {
$switch z.scale_$dTypeRN_$sTypeRN$sratio_$op(dst, dr, adr, src, sr, &o)
}
}
func (z $receiver) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) {
// Try to simplify a Transform to a Copy.
if s2d[0] == 1 && s2d[1] == 0 && s2d[3] == 0 && s2d[4] == 1 {
dx := int(s2d[2])
dy := int(s2d[5])
if float64(dx) == s2d[2] && float64(dy) == s2d[5] {
Copy(dst, image.Point{X: sr.Min.X + dx, Y: sr.Min.X + dy}, src, sr, op, opts)
return
}
}
var o Options
if opts != nil {
o = *opts
}
dr := transformRect(&s2d, &sr)
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
d2s := invert(&s2d)
// bias is a translation of the mapping from dst coordinates to src
// coordinates such that the latter temporarily have non-negative X
// and Y coordinates. This allows us to write int(f) instead of
// int(math.Floor(f)), since "round to zero" and "round down" are
// equivalent when f >= 0, but the former is much cheaper. The X--
// and Y-- are because the TransformLeaf methods have a "sx -= 0.5"
// adjustment.
bias := transformRect(&d2s, &adr).Min
bias.X--
bias.Y--
d2s[2] -= float64(bias.X)
d2s[5] -= float64(bias.Y)
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o)
case Src:
z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o)
}
} else if u, ok := src.(*image.Uniform); ok {
transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op)
} else {
$switch z.transform_$dTypeRN_$sTypeRN$sratio_$op(dst, dr, adr, &d2s, src, sr, bias, &o)
}
}
`
codeNNScaleLeaf = `
func (nnInterpolator) scale_$dTypeRN_$sTypeRN$sratio_$op(dst $dType, dr, adr image.Rectangle, src $sType, sr image.Rectangle, opts *Options) {
dw2 := uint64(dr.Dx()) * 2
dh2 := uint64(dr.Dy()) * 2
sw := uint64(sr.Dx())
sh := uint64(sr.Dy())
$preOuter
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := (2*uint64(dy) + 1) * sh / dh2
$preInner
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { $tweakDx
sx := (2*uint64(dx) + 1) * sw / dw2
p := $srcu[sr.Min.X + int(sx), sr.Min.Y + int(sy)]
$outputu[dr.Min.X + int(dx), dr.Min.Y + int(dy), p]
}
}
}
`
codeNNTransformLeaf = `
func (nnInterpolator) transform_$dTypeRN_$sTypeRN$sratio_$op(dst $dType, dr, adr image.Rectangle, d2s *f64.Aff3, src $sType, sr image.Rectangle, bias image.Point, opts *Options) {
$preOuter
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y + int(dy)) + 0.5
$preInner
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { $tweakDx
dxf := float64(dr.Min.X + int(dx)) + 0.5
sx0 := int(float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]) + bias.X
sy0 := int(float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]) + bias.Y
if !(image.Point{sx0, sy0}).In(sr) {
continue
}
p := $srcu[sx0, sy0]
$outputu[dr.Min.X + int(dx), dr.Min.Y + int(dy), p]
}
}
}
`
codeABLScaleLeaf = `
func (ablInterpolator) scale_$dTypeRN_$sTypeRN$sratio_$op(dst $dType, dr, adr image.Rectangle, src $sType, sr image.Rectangle, opts *Options) {
sw := int32(sr.Dx())
sh := int32(sr.Dy())
yscale := float64(sh) / float64(dr.Dy())
xscale := float64(sw) / float64(dr.Dx())
swMinus1, shMinus1 := sw - 1, sh - 1
$preOuter
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
sy := float64((float64(dy)+0.5)*yscale) - 0.5
// If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if
// we say int32(sy) instead of int32(math.Floor(sy)). Similarly for
// sx, below.
sy0 := int32(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy1 := sy0 + 1
if sy < 0 {
sy0, sy1 = 0, 0
yFrac0, yFrac1 = 0, 1
} else if sy1 > shMinus1 {
sy0, sy1 = shMinus1, shMinus1
yFrac0, yFrac1 = 1, 0
}
$preInner
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { $tweakDx
sx := float64((float64(dx)+0.5)*xscale) - 0.5
sx0 := int32(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx1 := sx0 + 1
if sx < 0 {
sx0, sx1 = 0, 0
xFrac0, xFrac1 = 0, 1
} else if sx1 > swMinus1 {
sx0, sx1 = swMinus1, swMinus1
xFrac0, xFrac1 = 1, 0
}
s00 := $srcf[sr.Min.X + int(sx0), sr.Min.Y + int(sy0)]
s10 := $srcf[sr.Min.X + int(sx1), sr.Min.Y + int(sy0)]
$blend[xFrac1, s00, xFrac0, s10]
s01 := $srcf[sr.Min.X + int(sx0), sr.Min.Y + int(sy1)]
s11 := $srcf[sr.Min.X + int(sx1), sr.Min.Y + int(sy1)]
$blend[xFrac1, s01, xFrac0, s11]
$blend[yFrac1, s10, yFrac0, s11]
$convFtou[p, s11]
$outputu[dr.Min.X + int(dx), dr.Min.Y + int(dy), p]
}
}
}
`
codeABLTransformLeaf = `
func (ablInterpolator) transform_$dTypeRN_$sTypeRN$sratio_$op(dst $dType, dr, adr image.Rectangle, d2s *f64.Aff3, src $sType, sr image.Rectangle, bias image.Point, opts *Options) {
$preOuter
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y + int(dy)) + 0.5
$preInner
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { $tweakDx
dxf := float64(dr.Min.X + int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
sx -= 0.5
sx0 := int(sx)
xFrac0 := sx - float64(sx0)
xFrac1 := 1 - xFrac0
sx0 += bias.X
sx1 := sx0 + 1
if sx0 < sr.Min.X {
sx0, sx1 = sr.Min.X, sr.Min.X
xFrac0, xFrac1 = 0, 1
} else if sx1 >= sr.Max.X {
sx0, sx1 = sr.Max.X-1, sr.Max.X-1
xFrac0, xFrac1 = 1, 0
}
sy -= 0.5
sy0 := int(sy)
yFrac0 := sy - float64(sy0)
yFrac1 := 1 - yFrac0
sy0 += bias.Y
sy1 := sy0 + 1
if sy0 < sr.Min.Y {
sy0, sy1 = sr.Min.Y, sr.Min.Y
yFrac0, yFrac1 = 0, 1
} else if sy1 >= sr.Max.Y {
sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1
yFrac0, yFrac1 = 1, 0
}
s00 := $srcf[sx0, sy0]
s10 := $srcf[sx1, sy0]
$blend[xFrac1, s00, xFrac0, s10]
s01 := $srcf[sx0, sy1]
s11 := $srcf[sx1, sy1]
$blend[xFrac1, s01, xFrac0, s11]
$blend[yFrac1, s10, yFrac0, s11]
$convFtou[p, s11]
$outputu[dr.Min.X + int(dx), dr.Min.Y + int(dy), p]
}
}
}
`
codeKernelRoot = `
func (z *kernelScaler) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
if z.dw != int32(dr.Dx()) || z.dh != int32(dr.Dy()) || z.sw != int32(sr.Dx()) || z.sh != int32(sr.Dy()) {
z.kernel.Scale(dst, dr, src, sr, op, opts)
return
}
var o Options
if opts != nil {
o = *opts
}
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
if _, ok := src.(*image.Uniform); ok && o.DstMask == nil && o.SrcMask == nil && sr.In(src.Bounds()) {
Draw(dst, dr, src, src.Bounds().Min, op)
return
}
// Create a temporary buffer:
// scaleX distributes the source image's columns over the temporary image.
// scaleY distributes the temporary image's rows over the destination image.
var tmp [][4]float64
if z.pool.New != nil {
tmpp := z.pool.Get().(*[][4]float64)
defer z.pool.Put(tmpp)
tmp = *tmpp
} else {
tmp = z.makeTmpBuf()
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.SrcMask != nil || !sr.In(src.Bounds()) {
z.scaleX_Image(tmp, src, sr, &o)
} else {
$switchS z.scaleX_$sTypeRN$sratio(tmp, src, sr, &o)
}
if o.DstMask != nil {
switch op {
case Over:
z.scaleY_Image_Over(dst, dr, adr, tmp, &o)
case Src:
z.scaleY_Image_Src(dst, dr, adr, tmp, &o)
}
} else {
$switchD z.scaleY_$dTypeRN_$op(dst, dr, adr, tmp, &o)
}
}
func (q *Kernel) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) {
var o Options
if opts != nil {
o = *opts
}
dr := transformRect(&s2d, &sr)
// adr is the affected destination pixels.
adr := dst.Bounds().Intersect(dr)
adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP)
if adr.Empty() || sr.Empty() {
return
}
if op == Over && o.SrcMask == nil && opaque(src) {
op = Src
}
d2s := invert(&s2d)
// bias is a translation of the mapping from dst coordinates to src
// coordinates such that the latter temporarily have non-negative X
// and Y coordinates. This allows us to write int(f) instead of
// int(math.Floor(f)), since "round to zero" and "round down" are
// equivalent when f >= 0, but the former is much cheaper. The X--
// and Y-- are because the TransformLeaf methods have a "sx -= 0.5"
// adjustment.
bias := transformRect(&d2s, &adr).Min
bias.X--
bias.Y--
d2s[2] -= float64(bias.X)
d2s[5] -= float64(bias.Y)
// Make adr relative to dr.Min.
adr = adr.Sub(dr.Min)
if u, ok := src.(*image.Uniform); ok && o.DstMask != nil && o.SrcMask != nil && sr.In(src.Bounds()) {
transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op)
return
}
xscale := abs(d2s[0])
if s := abs(d2s[1]); xscale < s {
xscale = s
}
yscale := abs(d2s[3])
if s := abs(d2s[4]); yscale < s {
yscale = s
}
// sr is the source pixels. If it extends beyond the src bounds,
// we cannot use the type-specific fast paths, as they access
// the Pix fields directly without bounds checking.
//
// Similarly, the fast paths assume that the masks are nil.
if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) {
switch op {
case Over:
q.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
case Src:
q.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
} else {
$switch q.transform_$dTypeRN_$sTypeRN$sratio_$op(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o)
}
}
`
codeKernelScaleLeafX = `
func (z *kernelScaler) scaleX_$sTypeRN$sratio(tmp [][4]float64, src $sType, sr image.Rectangle, opts *Options) {
t := 0
$preKernelOuter
for y := int32(0); y < z.sh; y++ {
for _, s := range z.horizontal.sources {
var pr, pg, pb, pa float64 $tweakVarP
for _, c := range z.horizontal.contribs[s.i:s.j] {
p += $srcf[sr.Min.X + int(c.coord), sr.Min.Y + int(y)] * c.weight
}
$tweakPr
tmp[t] = [4]float64{
pr * s.invTotalWeightFFFF, $tweakP
pg * s.invTotalWeightFFFF, $tweakP
pb * s.invTotalWeightFFFF, $tweakP
pa * s.invTotalWeightFFFF, $tweakP
}
t++
}
}
}
`
codeKernelScaleLeafY = `
func (z *kernelScaler) scaleY_$dTypeRN_$op(dst $dType, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) {
$preOuter
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
$preKernelInner
for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { $tweakDy
var pr, pg, pb, pa float64
for _, c := range z.vertical.contribs[s.i:s.j] {
p := &tmp[c.coord*z.dw+dx]
pr += float64(p[0] * c.weight)
pg += float64(p[1] * c.weight)
pb += float64(p[2] * c.weight)
pa += float64(p[3] * c.weight)
}
$clampToAlpha
$outputf[dr.Min.X + int(dx), dr.Min.Y + int(adr.Min.Y + dy), ftou, p, s.invTotalWeight]
$tweakD
}
}
}
`
codeKernelTransformLeaf = `
func (q *Kernel) transform_$dTypeRN_$sTypeRN$sratio_$op(dst $dType, dr, adr image.Rectangle, d2s *f64.Aff3, src $sType, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) {
// When shrinking, broaden the effective kernel support so that we still
// visit every source pixel.
xHalfWidth, xKernelArgScale := q.Support, 1.0
if xscale > 1 {
xHalfWidth *= xscale
xKernelArgScale = 1 / xscale
}
yHalfWidth, yKernelArgScale := q.Support, 1.0
if yscale > 1 {
yHalfWidth *= yscale
yKernelArgScale = 1 / yscale
}
xWeights := make([]float64, 1 + 2*int(math.Ceil(xHalfWidth)))
yWeights := make([]float64, 1 + 2*int(math.Ceil(yHalfWidth)))
$preOuter
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
dyf := float64(dr.Min.Y + int(dy)) + 0.5
$preInner
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { $tweakDx
dxf := float64(dr.Min.X + int(dx)) + 0.5
sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2]
sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5]
if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) {
continue
}
// TODO: adjust the bias so that we can use int(f) instead
// of math.Floor(f) and math.Ceil(f).
sx += float64(bias.X)
sx -= 0.5
ix := int(math.Floor(sx - xHalfWidth))
if ix < sr.Min.X {
ix = sr.Min.X
}
jx := int(math.Ceil(sx + xHalfWidth))
if jx > sr.Max.X {
jx = sr.Max.X
}
totalXWeight := 0.0
for kx := ix; kx < jx; kx++ {
xWeight := 0.0
if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support {
xWeight = q.At(t)
}
xWeights[kx - ix] = xWeight
totalXWeight += xWeight
}
for x := range xWeights[:jx-ix] {
xWeights[x] /= totalXWeight
}
sy += float64(bias.Y)
sy -= 0.5
iy := int(math.Floor(sy - yHalfWidth))
if iy < sr.Min.Y {
iy = sr.Min.Y
}
jy := int(math.Ceil(sy + yHalfWidth))
if jy > sr.Max.Y {
jy = sr.Max.Y
}
totalYWeight := 0.0
for ky := iy; ky < jy; ky++ {
yWeight := 0.0
if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support {
yWeight = q.At(t)
}
yWeights[ky - iy] = yWeight
totalYWeight += yWeight
}
for y := range yWeights[:jy-iy] {
yWeights[y] /= totalYWeight
}
var pr, pg, pb, pa float64 $tweakVarP
for ky := iy; ky < jy; ky++ {
if yWeight := yWeights[ky - iy]; yWeight != 0 {
for kx := ix; kx < jx; kx++ {
if w := xWeights[kx - ix] * yWeight; w != 0 {
p += $srcf[kx, ky] * w
}
}
}
}
$clampToAlpha
$outputf[dr.Min.X + int(dx), dr.Min.Y + int(dy), fffftou, p, 1]
}
}
}
`
)
|
bmp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/bmp/writer.go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bmp
import (
"encoding/binary"
"errors"
"image"
"io"
)
type header struct {
sigBM [2]byte
fileSize uint32
resverved [2]uint16
pixOffset uint32
dibHeaderSize uint32
width uint32
height uint32
colorPlane uint16
bpp uint16
compression uint32
imageSize uint32
xPixelsPerMeter uint32
yPixelsPerMeter uint32
colorUse uint32
colorImportant uint32
}
func encodePaletted(w io.Writer, pix []uint8, dx, dy, stride, step int) error {
var padding []byte
if dx < step {
padding = make([]byte, step-dx)
}
for y := dy - 1; y >= 0; y-- {
min := y*stride + 0
max := y*stride + dx
if _, err := w.Write(pix[min:max]); err != nil {
return err
}
if padding != nil {
if _, err := w.Write(padding); err != nil {
return err
}
}
}
return nil
}
func encodeRGBA(w io.Writer, pix []uint8, dx, dy, stride, step int, opaque bool) error {
buf := make([]byte, step)
if opaque {
for y := dy - 1; y >= 0; y-- {
min := y*stride + 0
max := y*stride + dx*4
off := 0
for i := min; i < max; i += 4 {
buf[off+2] = pix[i+0]
buf[off+1] = pix[i+1]
buf[off+0] = pix[i+2]
off += 3
}
if _, err := w.Write(buf); err != nil {
return err
}
}
} else {
for y := dy - 1; y >= 0; y-- {
min := y*stride + 0
max := y*stride + dx*4
off := 0
for i := min; i < max; i += 4 {
a := uint32(pix[i+3])
if a == 0 {
buf[off+2] = 0
buf[off+1] = 0
buf[off+0] = 0
buf[off+3] = 0
off += 4
continue
} else if a == 0xff {
buf[off+2] = pix[i+0]
buf[off+1] = pix[i+1]
buf[off+0] = pix[i+2]
buf[off+3] = 0xff
off += 4
continue
}
buf[off+2] = uint8(((uint32(pix[i+0]) * 0xffff) / a) >> 8)
buf[off+1] = uint8(((uint32(pix[i+1]) * 0xffff) / a) >> 8)
buf[off+0] = uint8(((uint32(pix[i+2]) * 0xffff) / a) >> 8)
buf[off+3] = uint8(a)
off += 4
}
if _, err := w.Write(buf); err != nil {
return err
}
}
}
return nil
}
func encodeNRGBA(w io.Writer, pix []uint8, dx, dy, stride, step int, opaque bool) error {
buf := make([]byte, step)
if opaque {
for y := dy - 1; y >= 0; y-- {
min := y*stride + 0
max := y*stride + dx*4
off := 0
for i := min; i < max; i += 4 {
buf[off+2] = pix[i+0]
buf[off+1] = pix[i+1]
buf[off+0] = pix[i+2]
off += 3
}
if _, err := w.Write(buf); err != nil {
return err
}
}
} else {
for y := dy - 1; y >= 0; y-- {
min := y*stride + 0
max := y*stride + dx*4
off := 0
for i := min; i < max; i += 4 {
buf[off+2] = pix[i+0]
buf[off+1] = pix[i+1]
buf[off+0] = pix[i+2]
buf[off+3] = pix[i+3]
off += 4
}
if _, err := w.Write(buf); err != nil {
return err
}
}
}
return nil
}
func encode(w io.Writer, m image.Image, step int) error {
b := m.Bounds()
buf := make([]byte, step)
for y := b.Max.Y - 1; y >= b.Min.Y; y-- {
off := 0
for x := b.Min.X; x < b.Max.X; x++ {
r, g, b, _ := m.At(x, y).RGBA()
buf[off+2] = byte(r >> 8)
buf[off+1] = byte(g >> 8)
buf[off+0] = byte(b >> 8)
off += 3
}
if _, err := w.Write(buf); err != nil {
return err
}
}
return nil
}
// Encode writes the image m to w in BMP format.
func Encode(w io.Writer, m image.Image) error {
d := m.Bounds().Size()
if d.X < 0 || d.Y < 0 {
return errors.New("bmp: negative bounds")
}
h := &header{
sigBM: [2]byte{'B', 'M'},
fileSize: 14 + 40,
pixOffset: 14 + 40,
dibHeaderSize: 40,
width: uint32(d.X),
height: uint32(d.Y),
colorPlane: 1,
}
var step int
var palette []byte
var opaque bool
switch m := m.(type) {
case *image.Gray:
step = (d.X + 3) &^ 3
palette = make([]byte, 1024)
for i := 0; i < 256; i++ {
palette[i*4+0] = uint8(i)
palette[i*4+1] = uint8(i)
palette[i*4+2] = uint8(i)
palette[i*4+3] = 0xFF
}
h.imageSize = uint32(d.Y * step)
h.fileSize += uint32(len(palette)) + h.imageSize
h.pixOffset += uint32(len(palette))
h.bpp = 8
case *image.Paletted:
step = (d.X + 3) &^ 3
palette = make([]byte, 1024)
for i := 0; i < len(m.Palette) && i < 256; i++ {
r, g, b, _ := m.Palette[i].RGBA()
palette[i*4+0] = uint8(b >> 8)
palette[i*4+1] = uint8(g >> 8)
palette[i*4+2] = uint8(r >> 8)
palette[i*4+3] = 0xFF
}
h.imageSize = uint32(d.Y * step)
h.fileSize += uint32(len(palette)) + h.imageSize
h.pixOffset += uint32(len(palette))
h.bpp = 8
case *image.RGBA:
opaque = m.Opaque()
if opaque {
step = (3*d.X + 3) &^ 3
h.bpp = 24
} else {
step = 4 * d.X
h.bpp = 32
}
h.imageSize = uint32(d.Y * step)
h.fileSize += h.imageSize
case *image.NRGBA:
opaque = m.Opaque()
if opaque {
step = (3*d.X + 3) &^ 3
h.bpp = 24
} else {
step = 4 * d.X
h.bpp = 32
}
h.imageSize = uint32(d.Y * step)
h.fileSize += h.imageSize
default:
step = (3*d.X + 3) &^ 3
h.imageSize = uint32(d.Y * step)
h.fileSize += h.imageSize
h.bpp = 24
}
if err := binary.Write(w, binary.LittleEndian, h); err != nil {
return err
}
if palette != nil {
if err := binary.Write(w, binary.LittleEndian, palette); err != nil {
return err
}
}
if d.X == 0 || d.Y == 0 {
return nil
}
switch m := m.(type) {
case *image.Gray:
return encodePaletted(w, m.Pix, d.X, d.Y, m.Stride, step)
case *image.Paletted:
return encodePaletted(w, m.Pix, d.X, d.Y, m.Stride, step)
case *image.RGBA:
return encodeRGBA(w, m.Pix, d.X, d.Y, m.Stride, step, opaque)
case *image.NRGBA:
return encodeNRGBA(w, m.Pix, d.X, d.Y, m.Stride, step, opaque)
}
return encode(w, m, step)
}
|
bmp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/bmp/reader_test.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bmp
import (
"bytes"
"fmt"
"image"
"io"
"os"
"testing"
_ "image/png"
)
const testdataDir = "../testdata/"
func compare(img0, img1 image.Image) error {
b := img1.Bounds()
if !b.Eq(img0.Bounds()) {
return fmt.Errorf("wrong image size: want %s, got %s", img0.Bounds(), b)
}
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
c0 := img0.At(x, y)
c1 := img1.At(x, y)
r0, g0, b0, a0 := c0.RGBA()
r1, g1, b1, a1 := c1.RGBA()
if r0 != r1 || g0 != g1 || b0 != b1 || a0 != a1 {
return fmt.Errorf("pixel at (%d, %d) has wrong color: want %v, got %v", x, y, c0, c1)
}
}
}
return nil
}
// TestDecode tests that decoding a PNG image and a BMP image result in the
// same pixel data.
func TestDecode(t *testing.T) {
testCases := []string{
"colormap",
"colormap-0",
"colormap-251",
"video-001",
"yellow_rose-small",
"yellow_rose-small-v5",
}
for _, tc := range testCases {
f0, err := os.Open(testdataDir + tc + ".png")
if err != nil {
t.Errorf("%s: Open PNG: %v", tc, err)
continue
}
defer f0.Close()
img0, _, err := image.Decode(f0)
if err != nil {
t.Errorf("%s: Decode PNG: %v", tc, err)
continue
}
f1, err := os.Open(testdataDir + tc + ".bmp")
if err != nil {
t.Errorf("%s: Open BMP: %v", tc, err)
continue
}
defer f1.Close()
img1, _, err := image.Decode(f1)
if err != nil {
t.Errorf("%s: Decode BMP: %v", tc, err)
continue
}
if err := compare(img0, img1); err != nil {
t.Errorf("%s: %v", tc, err)
continue
}
}
}
// TestEOF tests that decoding a BMP image returns io.ErrUnexpectedEOF
// when there are no headers or data is empty
func TestEOF(t *testing.T) {
_, err := Decode(bytes.NewReader(nil))
if err != io.ErrUnexpectedEOF {
t.Errorf("Error should be io.ErrUnexpectedEOF on nil but got %v", err)
}
}
|
bmp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/bmp/writer_test.go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bmp
import (
"bytes"
"fmt"
"image"
"image/draw"
"io/ioutil"
"os"
"testing"
"time"
)
func openImage(filename string) (image.Image, error) {
f, err := os.Open(testdataDir + filename)
if err != nil {
return nil, err
}
defer f.Close()
return Decode(f)
}
func convertToRGBA(in image.Image) image.Image {
b := in.Bounds()
out := image.NewRGBA(b)
draw.Draw(out, b, in, b.Min, draw.Src)
return out
}
func convertToNRGBA(in image.Image) image.Image {
b := in.Bounds()
out := image.NewNRGBA(b)
draw.Draw(out, b, in, b.Min, draw.Src)
return out
}
func TestEncode(t *testing.T) {
testCases := []string{
"video-001.bmp",
"yellow_rose-small.bmp",
}
for _, tc := range testCases {
img0, err := openImage(tc)
if err != nil {
t.Errorf("%s: Open BMP: %v", tc, err)
continue
}
buf := new(bytes.Buffer)
err = Encode(buf, img0)
if err != nil {
t.Errorf("%s: Encode BMP: %v", tc, err)
continue
}
img1, err := Decode(buf)
if err != nil {
t.Errorf("%s: Decode BMP: %v", tc, err)
continue
}
err = compare(img0, img1)
if err != nil {
t.Errorf("%s: Compare BMP: %v", tc, err)
continue
}
buf2 := new(bytes.Buffer)
rgba := convertToRGBA(img0)
err = Encode(buf2, rgba)
if err != nil {
t.Errorf("%s: Encode pre-multiplied BMP: %v", tc, err)
continue
}
img2, err := Decode(buf2)
if err != nil {
t.Errorf("%s: Decode pre-multiplied BMP: %v", tc, err)
continue
}
// We need to do another round trip to NRGBA to compare to, since
// the conversion process is lossy.
img3 := convertToNRGBA(rgba)
err = compare(img3, img2)
if err != nil {
t.Errorf("%s: Compare pre-multiplied BMP: %v", tc, err)
}
}
}
// TestZeroWidthVeryLargeHeight tests that encoding and decoding a degenerate
// image with zero width but over one billion pixels in height is faster than
// naively calling an io.Reader or io.Writer method once per row.
func TestZeroWidthVeryLargeHeight(t *testing.T) {
c := make(chan error, 1)
go func() {
b := image.Rect(0, 0, 0, 0x3fffffff)
var buf bytes.Buffer
if err := Encode(&buf, image.NewRGBA(b)); err != nil {
c <- err
return
}
m, err := Decode(&buf)
if err != nil {
c <- err
return
}
if got := m.Bounds(); got != b {
c <- fmt.Errorf("bounds: got %v, want %v", got, b)
return
}
c <- nil
}()
select {
case err := <-c:
if err != nil {
t.Fatal(err)
}
case <-time.After(3 * time.Second):
t.Fatalf("timed out")
}
}
// BenchmarkEncode benchmarks the encoding of an image.
func BenchmarkEncode(b *testing.B) {
img, err := openImage("video-001.bmp")
if err != nil {
b.Fatal(err)
}
s := img.Bounds().Size()
b.SetBytes(int64(s.X * s.Y * 4))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Encode(ioutil.Discard, img)
}
}
|
bmp | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/bmp/reader.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bmp implements a BMP image decoder and encoder.
//
// The BMP specification is at http://www.digicamsoft.com/bmp/bmp.html.
package bmp // import "golang.org/x/image/bmp"
import (
"errors"
"image"
"image/color"
"io"
)
// ErrUnsupported means that the input BMP image uses a valid but unsupported
// feature.
var ErrUnsupported = errors.New("bmp: unsupported BMP image")
func readUint16(b []byte) uint16 {
return uint16(b[0]) | uint16(b[1])<<8
}
func readUint32(b []byte) uint32 {
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}
// decodePaletted reads an 8 bit-per-pixel BMP image from r.
// If topDown is false, the image rows will be read bottom-up.
func decodePaletted(r io.Reader, c image.Config, topDown bool) (image.Image, error) {
paletted := image.NewPaletted(image.Rect(0, 0, c.Width, c.Height), c.ColorModel.(color.Palette))
if c.Width == 0 || c.Height == 0 {
return paletted, nil
}
var tmp [4]byte
y0, y1, yDelta := c.Height-1, -1, -1
if topDown {
y0, y1, yDelta = 0, c.Height, +1
}
for y := y0; y != y1; y += yDelta {
p := paletted.Pix[y*paletted.Stride : y*paletted.Stride+c.Width]
if _, err := io.ReadFull(r, p); err != nil {
return nil, err
}
// Each row is 4-byte aligned.
if c.Width%4 != 0 {
_, err := io.ReadFull(r, tmp[:4-c.Width%4])
if err != nil {
return nil, err
}
}
}
return paletted, nil
}
// decodeRGB reads a 24 bit-per-pixel BMP image from r.
// If topDown is false, the image rows will be read bottom-up.
func decodeRGB(r io.Reader, c image.Config, topDown bool) (image.Image, error) {
rgba := image.NewRGBA(image.Rect(0, 0, c.Width, c.Height))
if c.Width == 0 || c.Height == 0 {
return rgba, nil
}
// There are 3 bytes per pixel, and each row is 4-byte aligned.
b := make([]byte, (3*c.Width+3)&^3)
y0, y1, yDelta := c.Height-1, -1, -1
if topDown {
y0, y1, yDelta = 0, c.Height, +1
}
for y := y0; y != y1; y += yDelta {
if _, err := io.ReadFull(r, b); err != nil {
return nil, err
}
p := rgba.Pix[y*rgba.Stride : y*rgba.Stride+c.Width*4]
for i, j := 0, 0; i < len(p); i, j = i+4, j+3 {
// BMP images are stored in BGR order rather than RGB order.
p[i+0] = b[j+2]
p[i+1] = b[j+1]
p[i+2] = b[j+0]
p[i+3] = 0xFF
}
}
return rgba, nil
}
// decodeNRGBA reads a 32 bit-per-pixel BMP image from r.
// If topDown is false, the image rows will be read bottom-up.
func decodeNRGBA(r io.Reader, c image.Config, topDown, allowAlpha bool) (image.Image, error) {
rgba := image.NewNRGBA(image.Rect(0, 0, c.Width, c.Height))
if c.Width == 0 || c.Height == 0 {
return rgba, nil
}
y0, y1, yDelta := c.Height-1, -1, -1
if topDown {
y0, y1, yDelta = 0, c.Height, +1
}
for y := y0; y != y1; y += yDelta {
p := rgba.Pix[y*rgba.Stride : y*rgba.Stride+c.Width*4]
if _, err := io.ReadFull(r, p); err != nil {
return nil, err
}
for i := 0; i < len(p); i += 4 {
// BMP images are stored in BGRA order rather than RGBA order.
p[i+0], p[i+2] = p[i+2], p[i+0]
if !allowAlpha {
p[i+3] = 0xFF
}
}
}
return rgba, nil
}
// Decode reads a BMP image from r and returns it as an image.Image.
// Limitation: The file must be 8, 24 or 32 bits per pixel.
func Decode(r io.Reader) (image.Image, error) {
c, bpp, topDown, allowAlpha, err := decodeConfig(r)
if err != nil {
return nil, err
}
switch bpp {
case 8:
return decodePaletted(r, c, topDown)
case 24:
return decodeRGB(r, c, topDown)
case 32:
return decodeNRGBA(r, c, topDown, allowAlpha)
}
panic("unreachable")
}
// DecodeConfig returns the color model and dimensions of a BMP image without
// decoding the entire image.
// Limitation: The file must be 8, 24 or 32 bits per pixel.
func DecodeConfig(r io.Reader) (image.Config, error) {
config, _, _, _, err := decodeConfig(r)
return config, err
}
func decodeConfig(r io.Reader) (config image.Config, bitsPerPixel int, topDown bool, allowAlpha bool, err error) {
// We only support those BMP images with one of the following DIB headers:
// - BITMAPINFOHEADER (40 bytes)
// - BITMAPV4HEADER (108 bytes)
// - BITMAPV5HEADER (124 bytes)
const (
fileHeaderLen = 14
infoHeaderLen = 40
v4InfoHeaderLen = 108
v5InfoHeaderLen = 124
)
var b [1024]byte
if _, err := io.ReadFull(r, b[:fileHeaderLen+4]); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return image.Config{}, 0, false, false, err
}
if string(b[:2]) != "BM" {
return image.Config{}, 0, false, false, errors.New("bmp: invalid format")
}
offset := readUint32(b[10:14])
infoLen := readUint32(b[14:18])
if infoLen != infoHeaderLen && infoLen != v4InfoHeaderLen && infoLen != v5InfoHeaderLen {
return image.Config{}, 0, false, false, ErrUnsupported
}
if _, err := io.ReadFull(r, b[fileHeaderLen+4:fileHeaderLen+infoLen]); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return image.Config{}, 0, false, false, err
}
width := int(int32(readUint32(b[18:22])))
height := int(int32(readUint32(b[22:26])))
if height < 0 {
height, topDown = -height, true
}
if width < 0 || height < 0 {
return image.Config{}, 0, false, false, ErrUnsupported
}
// We only support 1 plane and 8, 24 or 32 bits per pixel and no
// compression.
planes, bpp, compression := readUint16(b[26:28]), readUint16(b[28:30]), readUint32(b[30:34])
// if compression is set to BI_BITFIELDS, but the bitmask is set to the default bitmask
// that would be used if compression was set to 0, we can continue as if compression was 0
if compression == 3 && infoLen > infoHeaderLen &&
readUint32(b[54:58]) == 0xff0000 && readUint32(b[58:62]) == 0xff00 &&
readUint32(b[62:66]) == 0xff && readUint32(b[66:70]) == 0xff000000 {
compression = 0
}
if planes != 1 || compression != 0 {
return image.Config{}, 0, false, false, ErrUnsupported
}
switch bpp {
case 8:
colorUsed := readUint32(b[46:50])
// If colorUsed is 0, it is set to the maximum number of colors for the given bpp, which is 2^bpp.
if colorUsed == 0 {
colorUsed = 256
} else if colorUsed > 256 {
return image.Config{}, 0, false, false, ErrUnsupported
}
if offset != fileHeaderLen+infoLen+colorUsed*4 {
return image.Config{}, 0, false, false, ErrUnsupported
}
_, err = io.ReadFull(r, b[:colorUsed*4])
if err != nil {
return image.Config{}, 0, false, false, err
}
pcm := make(color.Palette, colorUsed)
for i := range pcm {
// BMP images are stored in BGR order rather than RGB order.
// Every 4th byte is padding.
pcm[i] = color.RGBA{b[4*i+2], b[4*i+1], b[4*i+0], 0xFF}
}
return image.Config{ColorModel: pcm, Width: width, Height: height}, 8, topDown, false, nil
case 24:
if offset != fileHeaderLen+infoLen {
return image.Config{}, 0, false, false, ErrUnsupported
}
return image.Config{ColorModel: color.RGBAModel, Width: width, Height: height}, 24, topDown, false, nil
case 32:
if offset != fileHeaderLen+infoLen {
return image.Config{}, 0, false, false, ErrUnsupported
}
// 32 bits per pixel is possibly RGBX (X is padding) or RGBA (A is
// alpha transparency). However, for BMP images, "Alpha is a
// poorly-documented and inconsistently-used feature" says
// https://source.chromium.org/chromium/chromium/src/+/bc0a792d7ebc587190d1a62ccddba10abeea274b:third_party/blink/renderer/platform/image-decoders/bmp/bmp_image_reader.cc;l=621
//
// That goes on to say "BITMAPV3HEADER+ have an alpha bitmask in the
// info header... so we respect it at all times... [For earlier
// (smaller) headers we] ignore alpha in Windows V3 BMPs except inside
// ICO files".
//
// "Ignore" means to always set alpha to 0xFF (fully opaque):
// https://source.chromium.org/chromium/chromium/src/+/bc0a792d7ebc587190d1a62ccddba10abeea274b:third_party/blink/renderer/platform/image-decoders/bmp/bmp_image_reader.h;l=272
//
// Confusingly, "Windows V3" does not correspond to BITMAPV3HEADER, but
// instead corresponds to the earlier (smaller) BITMAPINFOHEADER:
// https://source.chromium.org/chromium/chromium/src/+/bc0a792d7ebc587190d1a62ccddba10abeea274b:third_party/blink/renderer/platform/image-decoders/bmp/bmp_image_reader.cc;l=258
//
// This Go package does not support ICO files and the (infoLen >
// infoHeaderLen) condition distinguishes BITMAPINFOHEADER (40 bytes)
// vs later (larger) headers.
allowAlpha = infoLen > infoHeaderLen
return image.Config{ColorModel: color.RGBAModel, Width: width, Height: height}, 32, topDown, allowAlpha, nil
}
return image.Config{}, 0, false, false, ErrUnsupported
}
func init() {
image.RegisterFormat("bmp", "BM????\x00\x00\x00\x00", Decode, DecodeConfig)
}
|
webp-manual-test | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/cmd/webp-manual-test/main.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
// +build ignore
// This build tag means that "go install golang.org/x/image/..." doesn't
// install this manual test. Use "go run main.go" to explicitly run it.
// Program webp-manual-test checks that the Go WEBP library's decodings match
// the C WEBP library's.
package main // import "golang.org/x/image/cmd/webp-manual-test"
import (
"bytes"
"encoding/hex"
"flag"
"fmt"
"image"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"golang.org/x/image/webp"
)
var (
dwebp = flag.String("dwebp", "/usr/bin/dwebp", "path to the dwebp program "+
"installed from https://developers.google.com/speed/webp/download")
testdata = flag.String("testdata", "", "path to the libwebp-test-data directory "+
"checked out from https://chromium.googlesource.com/webm/libwebp-test-data")
)
func main() {
flag.Parse()
if err := checkDwebp(); err != nil {
flag.Usage()
log.Fatal(err)
}
if *testdata == "" {
flag.Usage()
log.Fatal("testdata flag was not specified")
}
f, err := os.Open(*testdata)
if err != nil {
log.Fatalf("Open: %v", err)
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
log.Fatalf("Readdirnames: %v", err)
}
sort.Strings(names)
nFail, nPass := 0, 0
for _, name := range names {
if !strings.HasSuffix(name, "webp") {
continue
}
if err := test(name); err != nil {
fmt.Printf("FAIL\t%s\t%v\n", name, err)
nFail++
} else {
fmt.Printf("PASS\t%s\n", name)
nPass++
}
}
fmt.Printf("%d PASS, %d FAIL, %d TOTAL\n", nPass, nFail, nPass+nFail)
if nFail != 0 {
os.Exit(1)
}
}
func checkDwebp() error {
if *dwebp == "" {
return fmt.Errorf("dwebp flag was not specified")
}
if _, err := os.Stat(*dwebp); err != nil {
return fmt.Errorf("could not find dwebp program at %q", *dwebp)
}
b, err := exec.Command(*dwebp, "-version").Output()
if err != nil {
return fmt.Errorf("could not determine the dwebp program version for %q: %v", *dwebp, err)
}
switch s := string(bytes.TrimSpace(b)); s {
case "0.4.0", "0.4.1", "0.4.2":
return fmt.Errorf("the dwebp program version %q for %q has a known bug "+
"(https://bugs.chromium.org/p/webp/issues/detail?id=239). Please use a newer version.", s, *dwebp)
}
return nil
}
// test tests a single WEBP image.
func test(name string) error {
filename := filepath.Join(*testdata, name)
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf("Open: %v", err)
}
defer f.Close()
gotImage, err := webp.Decode(f)
if err != nil {
return fmt.Errorf("Decode: %v", err)
}
format, encode := "-pgm", encodePGM
if _, lossless := gotImage.(*image.NRGBA); lossless {
format, encode = "-pam", encodePAM
}
got, err := encode(gotImage)
if err != nil {
return fmt.Errorf("encode: %v", err)
}
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
c := exec.Command(*dwebp, filename, format, "-o", "/dev/stdout")
c.Stdout = stdout
c.Stderr = stderr
if err := c.Run(); err != nil {
os.Stderr.Write(stderr.Bytes())
return fmt.Errorf("executing dwebp: %v", err)
}
want := stdout.Bytes()
if len(got) != len(want) {
return fmt.Errorf("encodings have different length: got %d, want %d", len(got), len(want))
}
for i, g := range got {
if w := want[i]; g != w {
return fmt.Errorf("encodings differ at position 0x%x: got 0x%02x, want 0x%02x", i, g, w)
}
}
return nil
}
// encodePAM encodes gotImage in the PAM format.
func encodePAM(gotImage image.Image) ([]byte, error) {
m, ok := gotImage.(*image.NRGBA)
if !ok {
return nil, fmt.Errorf("lossless image did not decode to an *image.NRGBA")
}
b := m.Bounds()
w, h := b.Dx(), b.Dy()
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", w, h)
for y := b.Min.Y; y < b.Max.Y; y++ {
o := m.PixOffset(b.Min.X, y)
buf.Write(m.Pix[o : o+4*w])
}
return buf.Bytes(), nil
}
// encodePGM encodes gotImage in the PGM format in the IMC4 layout.
func encodePGM(gotImage image.Image) ([]byte, error) {
var (
m *image.YCbCr
ma *image.NYCbCrA
)
switch g := gotImage.(type) {
case *image.YCbCr:
m = g
case *image.NYCbCrA:
m = &g.YCbCr
ma = g
default:
return nil, fmt.Errorf("lossy image did not decode to an *image.YCbCr")
}
if m.SubsampleRatio != image.YCbCrSubsampleRatio420 {
return nil, fmt.Errorf("lossy image did not decode to a 4:2:0 YCbCr")
}
b := m.Bounds()
w, h := b.Dx(), b.Dy()
w2, h2 := (w+1)/2, (h+1)/2
outW, outH := 2*w2, h+h2
if ma != nil {
outH += h
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "P5\n%d %d\n255\n", outW, outH)
for y := b.Min.Y; y < b.Max.Y; y++ {
o := m.YOffset(b.Min.X, y)
buf.Write(m.Y[o : o+w])
if w&1 != 0 {
buf.WriteByte(0x00)
}
}
for y := b.Min.Y; y < b.Max.Y; y += 2 {
o := m.COffset(b.Min.X, y)
buf.Write(m.Cb[o : o+w2])
buf.Write(m.Cr[o : o+w2])
}
if ma != nil {
for y := b.Min.Y; y < b.Max.Y; y++ {
o := ma.AOffset(b.Min.X, y)
buf.Write(ma.A[o : o+w])
if w&1 != 0 {
buf.WriteByte(0x00)
}
}
}
return buf.Bytes(), nil
}
// dump can be useful for debugging.
func dump(w io.Writer, b []byte) {
h := hex.Dumper(w)
h.Write(b)
h.Close()
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/writer.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
import (
"bytes"
"compress/zlib"
"encoding/binary"
"errors"
"image"
"io"
"sort"
)
// The TIFF format allows to choose the order of the different elements freely.
// The basic structure of a TIFF file written by this package is:
//
// 1. Header (8 bytes).
// 2. Image data.
// 3. Image File Directory (IFD).
// 4. "Pointer area" for larger entries in the IFD.
// We only write little-endian TIFF files.
var enc = binary.LittleEndian
// An ifdEntry is a single entry in an Image File Directory.
// A value of type dtRational is composed of two 32-bit values,
// thus data contains two uints (numerator and denominator) for a single number.
type ifdEntry struct {
tag int
datatype int
data []uint32
}
func (e ifdEntry) putData(p []byte) {
for _, d := range e.data {
switch e.datatype {
case dtByte, dtASCII:
p[0] = byte(d)
p = p[1:]
case dtShort:
enc.PutUint16(p, uint16(d))
p = p[2:]
case dtLong, dtRational:
enc.PutUint32(p, uint32(d))
p = p[4:]
}
}
}
type byTag []ifdEntry
func (d byTag) Len() int { return len(d) }
func (d byTag) Less(i, j int) bool { return d[i].tag < d[j].tag }
func (d byTag) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func encodeGray(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
if !predictor {
return writePix(w, pix, dy, dx, stride)
}
buf := make([]byte, dx)
for y := 0; y < dy; y++ {
min := y*stride + 0
max := y*stride + dx
off := 0
var v0 uint8
for i := min; i < max; i++ {
v1 := pix[i]
buf[off] = v1 - v0
v0 = v1
off++
}
if _, err := w.Write(buf); err != nil {
return err
}
}
return nil
}
func encodeGray16(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
buf := make([]byte, dx*2)
for y := 0; y < dy; y++ {
min := y*stride + 0
max := y*stride + dx*2
off := 0
var v0 uint16
for i := min; i < max; i += 2 {
// An image.Gray16's Pix is in big-endian order.
v1 := uint16(pix[i])<<8 | uint16(pix[i+1])
if predictor {
v0, v1 = v1, v1-v0
}
// We only write little-endian TIFF files.
buf[off+0] = byte(v1)
buf[off+1] = byte(v1 >> 8)
off += 2
}
if _, err := w.Write(buf); err != nil {
return err
}
}
return nil
}
func encodeRGBA(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
if !predictor {
return writePix(w, pix, dy, dx*4, stride)
}
buf := make([]byte, dx*4)
for y := 0; y < dy; y++ {
min := y*stride + 0
max := y*stride + dx*4
off := 0
var r0, g0, b0, a0 uint8
for i := min; i < max; i += 4 {
r1, g1, b1, a1 := pix[i+0], pix[i+1], pix[i+2], pix[i+3]
buf[off+0] = r1 - r0
buf[off+1] = g1 - g0
buf[off+2] = b1 - b0
buf[off+3] = a1 - a0
off += 4
r0, g0, b0, a0 = r1, g1, b1, a1
}
if _, err := w.Write(buf); err != nil {
return err
}
}
return nil
}
func encodeRGBA64(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
buf := make([]byte, dx*8)
for y := 0; y < dy; y++ {
min := y*stride + 0
max := y*stride + dx*8
off := 0
var r0, g0, b0, a0 uint16
for i := min; i < max; i += 8 {
// An image.RGBA64's Pix is in big-endian order.
r1 := uint16(pix[i+0])<<8 | uint16(pix[i+1])
g1 := uint16(pix[i+2])<<8 | uint16(pix[i+3])
b1 := uint16(pix[i+4])<<8 | uint16(pix[i+5])
a1 := uint16(pix[i+6])<<8 | uint16(pix[i+7])
if predictor {
r0, r1 = r1, r1-r0
g0, g1 = g1, g1-g0
b0, b1 = b1, b1-b0
a0, a1 = a1, a1-a0
}
// We only write little-endian TIFF files.
buf[off+0] = byte(r1)
buf[off+1] = byte(r1 >> 8)
buf[off+2] = byte(g1)
buf[off+3] = byte(g1 >> 8)
buf[off+4] = byte(b1)
buf[off+5] = byte(b1 >> 8)
buf[off+6] = byte(a1)
buf[off+7] = byte(a1 >> 8)
off += 8
}
if _, err := w.Write(buf); err != nil {
return err
}
}
return nil
}
func encode(w io.Writer, m image.Image, predictor bool) error {
bounds := m.Bounds()
buf := make([]byte, 4*bounds.Dx())
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
off := 0
if predictor {
var r0, g0, b0, a0 uint8
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := m.At(x, y).RGBA()
r1 := uint8(r >> 8)
g1 := uint8(g >> 8)
b1 := uint8(b >> 8)
a1 := uint8(a >> 8)
buf[off+0] = r1 - r0
buf[off+1] = g1 - g0
buf[off+2] = b1 - b0
buf[off+3] = a1 - a0
off += 4
r0, g0, b0, a0 = r1, g1, b1, a1
}
} else {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := m.At(x, y).RGBA()
buf[off+0] = uint8(r >> 8)
buf[off+1] = uint8(g >> 8)
buf[off+2] = uint8(b >> 8)
buf[off+3] = uint8(a >> 8)
off += 4
}
}
if _, err := w.Write(buf); err != nil {
return err
}
}
return nil
}
// writePix writes the internal byte array of an image to w. It is less general
// but much faster then encode. writePix is used when pix directly
// corresponds to one of the TIFF image types.
func writePix(w io.Writer, pix []byte, nrows, length, stride int) error {
if length == stride {
_, err := w.Write(pix[:nrows*length])
return err
}
for ; nrows > 0; nrows-- {
if _, err := w.Write(pix[:length]); err != nil {
return err
}
pix = pix[stride:]
}
return nil
}
func writeIFD(w io.Writer, ifdOffset int, d []ifdEntry) error {
var buf [ifdLen]byte
// Make space for "pointer area" containing IFD entry data
// longer than 4 bytes.
parea := make([]byte, 1024)
pstart := ifdOffset + ifdLen*len(d) + 6
var o int // Current offset in parea.
// The IFD has to be written with the tags in ascending order.
sort.Sort(byTag(d))
// Write the number of entries in this IFD.
if err := binary.Write(w, enc, uint16(len(d))); err != nil {
return err
}
for _, ent := range d {
enc.PutUint16(buf[0:2], uint16(ent.tag))
enc.PutUint16(buf[2:4], uint16(ent.datatype))
count := uint32(len(ent.data))
if ent.datatype == dtRational {
count /= 2
}
enc.PutUint32(buf[4:8], count)
datalen := int(count * lengths[ent.datatype])
if datalen <= 4 {
ent.putData(buf[8:12])
} else {
if (o + datalen) > len(parea) {
newlen := len(parea) + 1024
for (o + datalen) > newlen {
newlen += 1024
}
newarea := make([]byte, newlen)
copy(newarea, parea)
parea = newarea
}
ent.putData(parea[o : o+datalen])
enc.PutUint32(buf[8:12], uint32(pstart+o))
o += datalen
}
if _, err := w.Write(buf[:]); err != nil {
return err
}
}
// The IFD ends with the offset of the next IFD in the file,
// or zero if it is the last one (page 14).
if err := binary.Write(w, enc, uint32(0)); err != nil {
return err
}
_, err := w.Write(parea[:o])
return err
}
// Options are the encoding parameters.
type Options struct {
// Compression is the type of compression used.
Compression CompressionType
// Predictor determines whether a differencing predictor is used;
// if true, instead of each pixel's color, the color difference to the
// preceding one is saved. This improves the compression for certain
// types of images and compressors. For example, it works well for
// photos with Deflate compression.
Predictor bool
}
// Encode writes the image m to w. opt determines the options used for
// encoding, such as the compression type. If opt is nil, an uncompressed
// image is written.
func Encode(w io.Writer, m image.Image, opt *Options) error {
d := m.Bounds().Size()
compression := uint32(cNone)
predictor := false
if opt != nil {
compression = opt.Compression.specValue()
// The predictor field is only used with LZW. See page 64 of the spec.
predictor = opt.Predictor && compression == cLZW
}
_, err := io.WriteString(w, leHeader)
if err != nil {
return err
}
// Compressed data is written into a buffer first, so that we
// know the compressed size.
var buf bytes.Buffer
// dst holds the destination for the pixel data of the image --
// either w or a writer to buf.
var dst io.Writer
// imageLen is the length of the pixel data in bytes.
// The offset of the IFD is imageLen + 8 header bytes.
var imageLen int
switch compression {
case cNone:
dst = w
// Write IFD offset before outputting pixel data.
switch m.(type) {
case *image.Paletted:
imageLen = d.X * d.Y * 1
case *image.Gray:
imageLen = d.X * d.Y * 1
case *image.Gray16:
imageLen = d.X * d.Y * 2
case *image.RGBA64:
imageLen = d.X * d.Y * 8
case *image.NRGBA64:
imageLen = d.X * d.Y * 8
default:
imageLen = d.X * d.Y * 4
}
err = binary.Write(w, enc, uint32(imageLen+8))
if err != nil {
return err
}
case cDeflate:
dst = zlib.NewWriter(&buf)
default:
return errors.New("tiff: unsupported compression")
}
pr := uint32(prNone)
photometricInterpretation := uint32(pRGB)
samplesPerPixel := uint32(4)
bitsPerSample := []uint32{8, 8, 8, 8}
extraSamples := uint32(0)
colorMap := []uint32{}
if predictor {
pr = prHorizontal
}
switch m := m.(type) {
case *image.Paletted:
photometricInterpretation = pPaletted
samplesPerPixel = 1
bitsPerSample = []uint32{8}
colorMap = make([]uint32, 256*3)
for i := 0; i < 256 && i < len(m.Palette); i++ {
r, g, b, _ := m.Palette[i].RGBA()
colorMap[i+0*256] = uint32(r)
colorMap[i+1*256] = uint32(g)
colorMap[i+2*256] = uint32(b)
}
err = encodeGray(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
case *image.Gray:
photometricInterpretation = pBlackIsZero
samplesPerPixel = 1
bitsPerSample = []uint32{8}
err = encodeGray(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
case *image.Gray16:
photometricInterpretation = pBlackIsZero
samplesPerPixel = 1
bitsPerSample = []uint32{16}
err = encodeGray16(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
case *image.NRGBA:
extraSamples = 2 // Unassociated alpha.
err = encodeRGBA(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
case *image.NRGBA64:
extraSamples = 2 // Unassociated alpha.
bitsPerSample = []uint32{16, 16, 16, 16}
err = encodeRGBA64(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
case *image.RGBA:
extraSamples = 1 // Associated alpha.
err = encodeRGBA(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
case *image.RGBA64:
extraSamples = 1 // Associated alpha.
bitsPerSample = []uint32{16, 16, 16, 16}
err = encodeRGBA64(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
default:
extraSamples = 1 // Associated alpha.
err = encode(dst, m, predictor)
}
if err != nil {
return err
}
if compression != cNone {
if err = dst.(io.Closer).Close(); err != nil {
return err
}
imageLen = buf.Len()
if err = binary.Write(w, enc, uint32(imageLen+8)); err != nil {
return err
}
if _, err = buf.WriteTo(w); err != nil {
return err
}
}
ifd := []ifdEntry{
{tImageWidth, dtShort, []uint32{uint32(d.X)}},
{tImageLength, dtShort, []uint32{uint32(d.Y)}},
{tBitsPerSample, dtShort, bitsPerSample},
{tCompression, dtShort, []uint32{compression}},
{tPhotometricInterpretation, dtShort, []uint32{photometricInterpretation}},
{tStripOffsets, dtLong, []uint32{8}},
{tSamplesPerPixel, dtShort, []uint32{samplesPerPixel}},
{tRowsPerStrip, dtShort, []uint32{uint32(d.Y)}},
{tStripByteCounts, dtLong, []uint32{uint32(imageLen)}},
// There is currently no support for storing the image
// resolution, so give a bogus value of 72x72 dpi.
{tXResolution, dtRational, []uint32{72, 1}},
{tYResolution, dtRational, []uint32{72, 1}},
{tResolutionUnit, dtShort, []uint32{resPerInch}},
}
if pr != prNone {
ifd = append(ifd, ifdEntry{tPredictor, dtShort, []uint32{pr}})
}
if len(colorMap) != 0 {
ifd = append(ifd, ifdEntry{tColorMap, dtShort, colorMap})
}
if extraSamples > 0 {
ifd = append(ifd, ifdEntry{tExtraSamples, dtShort, []uint32{extraSamples}})
}
return writeIFD(w, imageLen+8, ifd)
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/reader_test.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
import (
"bytes"
"compress/zlib"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"image"
"io"
"io/ioutil"
"os"
"sort"
"strings"
"testing"
_ "image/png"
)
const testdataDir = "../testdata/"
// Read makes *buffer implements io.Reader, so that we can pass one to Decode.
func (*buffer) Read([]byte) (int, error) {
panic("unimplemented")
}
func load(name string) (image.Image, error) {
f, err := os.Open(testdataDir + name)
if err != nil {
return nil, err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
// TestNoRPS tests decoding an image that has no RowsPerStrip tag. The tag is
// mandatory according to the spec but some software omits it in the case of a
// single strip.
func TestNoRPS(t *testing.T) {
_, err := load("no_rps.tiff")
if err != nil {
t.Fatal(err)
}
}
// TestNoCompression tests decoding an image that has no Compression tag. This
// tag is mandatory, but most tools interpret a missing value as no
// compression.
func TestNoCompression(t *testing.T) {
_, err := load("no_compress.tiff")
if err != nil {
t.Fatal(err)
}
}
// TestUnpackBits tests the decoding of PackBits-encoded data.
func TestUnpackBits(t *testing.T) {
var unpackBitsTests = []struct {
compressed string
uncompressed string
}{{
// Example data from Wikipedia.
"\xfe\xaa\x02\x80\x00\x2a\xfd\xaa\x03\x80\x00\x2a\x22\xf7\xaa",
"\xaa\xaa\xaa\x80\x00\x2a\xaa\xaa\xaa\xaa\x80\x00\x2a\x22\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa",
}}
for _, u := range unpackBitsTests {
buf, err := unpackBits(strings.NewReader(u.compressed))
if err != nil {
t.Fatal(err)
}
if string(buf) != u.uncompressed {
t.Fatalf("unpackBits: want %x, got %x", u.uncompressed, buf)
}
}
}
func TestShortBlockData(t *testing.T) {
b, err := ioutil.ReadFile("../testdata/bw-uncompressed.tiff")
if err != nil {
t.Fatal(err)
}
// The bw-uncompressed.tiff image is a 153x55 bi-level image. This is 1 bit
// per pixel, or 20 bytes per row, times 55 rows, or 1100 bytes of pixel
// data. 1100 in hex is 0x44c, or "\x4c\x04" in little-endian. We replace
// that byte count (StripByteCounts-tagged data) by something less than
// that, so that there is not enough pixel data.
old := []byte{0x4c, 0x04}
new := []byte{0x01, 0x01}
i := bytes.Index(b, old)
if i < 0 {
t.Fatal(`could not find "\x4c\x04" byte count`)
}
if bytes.Contains(b[i+len(old):], old) {
t.Fatal(`too many occurrences of "\x4c\x04"`)
}
b[i+0] = new[0]
b[i+1] = new[1]
if _, err = Decode(bytes.NewReader(b)); err == nil {
t.Fatal("got nil error, want non-nil")
}
}
func TestDecodeInvalidDataType(t *testing.T) {
b, err := ioutil.ReadFile("../testdata/bw-uncompressed.tiff")
if err != nil {
t.Fatal(err)
}
// off is the offset of the ImageWidth tag. It is the offset of the overall
// IFD block (0x00000454), plus 2 for the uint16 number of IFD entries, plus 12
// to skip the first entry.
const off = 0x00000454 + 2 + 12*1
if v := binary.LittleEndian.Uint16(b[off : off+2]); v != tImageWidth {
t.Fatal(`could not find ImageWidth tag`)
}
binary.LittleEndian.PutUint16(b[off+2:], uint16(len(lengths))) // invalid datatype
if _, err = Decode(bytes.NewReader(b)); err == nil {
t.Fatal("got nil error, want non-nil")
}
}
func compare(t *testing.T, img0, img1 image.Image) {
t.Helper()
b0 := img0.Bounds()
b1 := img1.Bounds()
if b0.Dx() != b1.Dx() || b0.Dy() != b1.Dy() {
t.Fatalf("wrong image size: want %s, got %s", b0, b1)
}
x1 := b1.Min.X - b0.Min.X
y1 := b1.Min.Y - b0.Min.Y
for y := b0.Min.Y; y < b0.Max.Y; y++ {
for x := b0.Min.X; x < b0.Max.X; x++ {
c0 := img0.At(x, y)
c1 := img1.At(x+x1, y+y1)
r0, g0, b0, a0 := c0.RGBA()
r1, g1, b1, a1 := c1.RGBA()
if r0 != r1 || g0 != g1 || b0 != b1 || a0 != a1 {
t.Fatalf("pixel at (%d, %d) has wrong color: want %v, got %v", x, y, c0, c1)
}
}
}
}
// TestDecode tests that decoding a PNG image and a TIFF image result in the
// same pixel data.
func TestDecode(t *testing.T) {
img0, err := load("video-001.png")
if err != nil {
t.Fatal(err)
}
img1, err := load("video-001.tiff")
if err != nil {
t.Fatal(err)
}
img2, err := load("video-001-strip-64.tiff")
if err != nil {
t.Fatal(err)
}
img3, err := load("video-001-tile-64x64.tiff")
if err != nil {
t.Fatal(err)
}
img4, err := load("video-001-16bit.tiff")
if err != nil {
t.Fatal(err)
}
compare(t, img0, img1)
compare(t, img0, img2)
compare(t, img0, img3)
compare(t, img0, img4)
}
// TestDecodeLZW tests that decoding a PNG image and a LZW-compressed TIFF
// image result in the same pixel data.
func TestDecodeLZW(t *testing.T) {
img0, err := load("blue-purple-pink.png")
if err != nil {
t.Fatal(err)
}
img1, err := load("blue-purple-pink.lzwcompressed.tiff")
if err != nil {
t.Fatal(err)
}
compare(t, img0, img1)
}
// TestEOF tests that decoding a TIFF image returns io.ErrUnexpectedEOF
// when there are no headers or data is empty
func TestEOF(t *testing.T) {
_, err := Decode(bytes.NewReader(nil))
if err != io.ErrUnexpectedEOF {
t.Errorf("Error should be io.ErrUnexpectedEOF on nil but got %v", err)
}
}
// TestDecodeCCITT tests that decoding a PNG image and a CCITT compressed TIFF
// image result in the same pixel data.
func TestDecodeCCITT(t *testing.T) {
// TODO Add more tests.
for _, fn := range []string{
"bw-gopher",
} {
img0, err := load(fn + ".png")
if err != nil {
t.Fatal(err)
}
img1, err := load(fn + "_ccittGroup3.tiff")
if err != nil {
t.Fatal(err)
}
compare(t, img0, img1)
img2, err := load(fn + "_ccittGroup4.tiff")
if err != nil {
t.Fatal(err)
}
compare(t, img0, img2)
}
}
// TestDecodeTagOrder tests that a malformed image with unsorted IFD entries is
// correctly rejected.
func TestDecodeTagOrder(t *testing.T) {
data, err := ioutil.ReadFile("../testdata/video-001.tiff")
if err != nil {
t.Fatal(err)
}
// Swap the first two IFD entries.
ifdOffset := int64(binary.LittleEndian.Uint32(data[4:8]))
for i := ifdOffset + 2; i < ifdOffset+14; i++ {
data[i], data[i+12] = data[i+12], data[i]
}
if _, _, err := image.Decode(bytes.NewReader(data)); err == nil {
t.Fatal("got nil error, want non-nil")
}
}
// TestDecompress tests that decoding some TIFF images that use different
// compression formats result in the same pixel data.
func TestDecompress(t *testing.T) {
var decompressTests = []string{
"bw-uncompressed.tiff",
"bw-deflate.tiff",
"bw-packbits.tiff",
}
var img0 image.Image
for _, name := range decompressTests {
img1, err := load(name)
if err != nil {
t.Fatalf("decoding %s: %v", name, err)
}
if img0 == nil {
img0 = img1
continue
}
compare(t, img0, img1)
}
}
func replace(src []byte, find, repl string) ([]byte, error) {
removeSpaces := func(r rune) rune {
if r != ' ' {
return r
}
return -1
}
f, err := hex.DecodeString(strings.Map(removeSpaces, find))
if err != nil {
return nil, err
}
r, err := hex.DecodeString(strings.Map(removeSpaces, repl))
if err != nil {
return nil, err
}
dst := bytes.Replace(src, f, r, 1)
if bytes.Equal(dst, src) {
return nil, errors.New("replacement failed")
}
return dst, nil
}
// TestZeroBitsPerSample tests that an IFD with a bitsPerSample of 0 does not
// cause a crash.
// Issue 10711.
func TestZeroBitsPerSample(t *testing.T) {
b0, err := ioutil.ReadFile(testdataDir + "bw-deflate.tiff")
if err != nil {
t.Fatal(err)
}
// Mutate the loaded image to have the problem.
// 02 01: tag number (tBitsPerSample)
// 03 00: data type (short, or uint16)
// 01 00 00 00: count
// ?? 00 00 00: value (1 -> 0)
b1, err := replace(b0,
"02 01 03 00 01 00 00 00 01 00 00 00",
"02 01 03 00 01 00 00 00 00 00 00 00",
)
if err != nil {
t.Fatal(err)
}
_, err = Decode(bytes.NewReader(b1))
if err == nil {
t.Fatal("Decode with 0 bits per sample: got nil error, want non-nil")
}
}
// TestTileTooBig tests that we do not panic when a tile is too big compared to
// the data available.
// Issue 10712
func TestTileTooBig(t *testing.T) {
b0, err := ioutil.ReadFile(testdataDir + "video-001-tile-64x64.tiff")
if err != nil {
t.Fatal(err)
}
// Mutate the loaded image to have the problem.
//
// 42 01: tag number (tTileWidth)
// 03 00: data type (short, or uint16)
// 01 00 00 00: count
// xx 00 00 00: value (0x40 -> 0x44: a wider tile consumes more data
// than is available)
b1, err := replace(b0,
"42 01 03 00 01 00 00 00 40 00 00 00",
"42 01 03 00 01 00 00 00 44 00 00 00",
)
if err != nil {
t.Fatal(err)
}
// Turn off the predictor, which makes it possible to hit the
// place with the defect. Without this patch to the image, we run
// out of data too early, and do not hit the part of the code where
// the original panic was.
//
// 3d 01: tag number (tPredictor)
// 03 00: data type (short, or uint16)
// 01 00 00 00: count
// xx 00 00 00: value (2 -> 1: 2 = horizontal, 1 = none)
b2, err := replace(b1,
"3d 01 03 00 01 00 00 00 02 00 00 00",
"3d 01 03 00 01 00 00 00 01 00 00 00",
)
if err != nil {
t.Fatal(err)
}
_, err = Decode(bytes.NewReader(b2))
if err == nil {
t.Fatal("did not expect nil error")
}
}
// TestZeroSizedImages tests that decoding does not panic when image dimensions
// are zero, and returns a zero-sized image instead.
// Issue 10393.
func TestZeroSizedImages(t *testing.T) {
testsizes := []struct {
w, h int
}{
{0, 0},
{1, 0},
{0, 1},
{1, 1},
}
for _, r := range testsizes {
img := image.NewRGBA(image.Rect(0, 0, r.w, r.h))
var buf bytes.Buffer
if err := Encode(&buf, img, nil); err != nil {
t.Errorf("encode w=%d h=%d: %v", r.w, r.h, err)
continue
}
if _, err := Decode(&buf); err != nil {
t.Errorf("decode w=%d h=%d: %v", r.w, r.h, err)
}
}
}
// TestLargeIFDEntry tests that a large IFD entry does not cause Decode to
// panic.
// Issue 10596.
func TestLargeIFDEntry(t *testing.T) {
testdata := "II*\x00\x08\x00\x00\x00\f\x000000000000" +
"00000000000000000000" +
"00000000000000000000" +
"00000000000000000000" +
"00000000000000\x17\x01\x04\x00\x01\x00" +
"\x00\xc0000000000000000000" +
"00000000000000000000" +
"00000000000000000000" +
"000000"
_, err := Decode(strings.NewReader(testdata))
if err == nil {
t.Fatal("Decode with large IFD entry: got nil error, want non-nil")
}
}
func TestInvalidPaletteRef(t *testing.T) {
contents, err := ioutil.ReadFile(testdataDir + "invalid-palette-ref.tiff")
if err != nil {
t.Fatal(err)
}
if _, err := Decode(bytes.NewReader(contents)); err == nil {
t.Fatal("Decode with invalid palette index: got nil error, want non-nil")
}
}
// benchmarkDecode benchmarks the decoding of an image.
func benchmarkDecode(b *testing.B, filename string) {
b.Helper()
contents, err := ioutil.ReadFile(testdataDir + filename)
if err != nil {
b.Fatal(err)
}
benchmarkDecodeData(b, contents)
}
func benchmarkDecodeData(b *testing.B, data []byte) {
b.Helper()
r := &buffer{buf: data}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := Decode(r)
if err != nil {
b.Fatal("Decode:", err)
}
}
}
func BenchmarkDecodeCompressed(b *testing.B) { benchmarkDecode(b, "video-001.tiff") }
func BenchmarkDecodeUncompressed(b *testing.B) { benchmarkDecode(b, "video-001-uncompressed.tiff") }
func BenchmarkZeroHeightTile(b *testing.B) {
enc := binary.BigEndian
data := newTIFF(enc)
data = appendIFD(data, enc, map[uint16]interface{}{
tImageWidth: uint32(4294967295),
tImageLength: uint32(0),
tTileWidth: uint32(1),
tTileLength: uint32(0),
})
benchmarkDecodeData(b, data)
}
func BenchmarkRepeatedOversizedTileData(b *testing.B) {
const (
imageWidth = 256
imageHeight = 256
tileWidth = 8
tileLength = 8
numTiles = (imageWidth * imageHeight) / (tileWidth * tileLength)
)
// Create a chunk of tile data that decompresses to a large size.
zdata := func() []byte {
var zbuf bytes.Buffer
zw := zlib.NewWriter(&zbuf)
zeros := make([]byte, 1024)
for i := 0; i < 1<<16; i++ {
zw.Write(zeros)
}
zw.Close()
return zbuf.Bytes()
}()
enc := binary.BigEndian
data := newTIFF(enc)
zoff := len(data)
data = append(data, zdata...)
// Each tile refers to the same compressed data chunk.
var tileoffs []uint32
var tilesizes []uint32
for i := 0; i < numTiles; i++ {
tileoffs = append(tileoffs, uint32(zoff))
tilesizes = append(tilesizes, uint32(len(zdata)))
}
data = appendIFD(data, enc, map[uint16]interface{}{
tImageWidth: uint32(imageWidth),
tImageLength: uint32(imageHeight),
tTileWidth: uint32(tileWidth),
tTileLength: uint32(tileLength),
tTileOffsets: tileoffs,
tTileByteCounts: tilesizes,
tCompression: uint16(cDeflate),
tBitsPerSample: []uint16{16, 16, 16},
tPhotometricInterpretation: uint16(pRGB),
})
benchmarkDecodeData(b, data)
}
type byteOrder interface {
binary.ByteOrder
binary.AppendByteOrder
}
// newTIFF returns the TIFF header.
func newTIFF(enc byteOrder) []byte {
b := []byte{0, 0, 0, 42, 0, 0, 0, 0}
switch enc.Uint16([]byte{1, 0}) {
case 0x1:
b[0], b[1] = 'I', 'I'
case 0x100:
b[0], b[1] = 'M', 'M'
default:
panic("odd byte order")
}
return b
}
// appendIFD appends an IFD to the TIFF in b,
// updating the IFD location in the header.
func appendIFD(b []byte, enc byteOrder, entries map[uint16]interface{}) []byte {
var tags []uint16
for tag := range entries {
tags = append(tags, tag)
}
sort.Slice(tags, func(i, j int) bool {
return tags[i] < tags[j]
})
var ifd []byte
for _, tag := range tags {
ifd = enc.AppendUint16(ifd, tag)
switch v := entries[tag].(type) {
case uint16:
ifd = enc.AppendUint16(ifd, dtShort)
ifd = enc.AppendUint32(ifd, 1)
ifd = enc.AppendUint16(ifd, v)
ifd = enc.AppendUint16(ifd, v)
case uint32:
ifd = enc.AppendUint16(ifd, dtLong)
ifd = enc.AppendUint32(ifd, 1)
ifd = enc.AppendUint32(ifd, v)
case []uint16:
ifd = enc.AppendUint16(ifd, dtShort)
ifd = enc.AppendUint32(ifd, uint32(len(v)))
switch len(v) {
case 0:
ifd = enc.AppendUint32(ifd, 0)
case 1:
ifd = enc.AppendUint16(ifd, v[0])
ifd = enc.AppendUint16(ifd, v[1])
default:
ifd = enc.AppendUint32(ifd, uint32(len(b)))
for _, e := range v {
b = enc.AppendUint16(b, e)
}
}
case []uint32:
ifd = enc.AppendUint16(ifd, dtLong)
ifd = enc.AppendUint32(ifd, uint32(len(v)))
switch len(v) {
case 0:
ifd = enc.AppendUint32(ifd, 0)
case 1:
ifd = enc.AppendUint32(ifd, v[0])
default:
ifd = enc.AppendUint32(ifd, uint32(len(b)))
for _, e := range v {
b = enc.AppendUint32(b, e)
}
}
default:
panic(fmt.Errorf("unhandled type %T", v))
}
}
enc.PutUint32(b[4:8], uint32(len(b)))
b = enc.AppendUint16(b, uint16(len(entries)))
b = append(b, ifd...)
b = enc.AppendUint32(b, 0)
return b
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/consts.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
// A tiff image file contains one or more images. The metadata
// of each image is contained in an Image File Directory (IFD),
// which contains entries of 12 bytes each and is described
// on page 14-16 of the specification. An IFD entry consists of
//
// - a tag, which describes the signification of the entry,
// - the data type and length of the entry,
// - the data itself or a pointer to it if it is more than 4 bytes.
//
// The presence of a length means that each IFD is effectively an array.
const (
leHeader = "II\x2A\x00" // Header for little-endian files.
beHeader = "MM\x00\x2A" // Header for big-endian files.
ifdLen = 12 // Length of an IFD entry in bytes.
)
// Data types (p. 14-16 of the spec).
const (
dtByte = 1
dtASCII = 2
dtShort = 3
dtLong = 4
dtRational = 5
)
// The length of one instance of each data type in bytes.
var lengths = [...]uint32{0, 1, 1, 2, 4, 8}
// Tags (see p. 28-41 of the spec).
const (
tImageWidth = 256
tImageLength = 257
tBitsPerSample = 258
tCompression = 259
tPhotometricInterpretation = 262
tFillOrder = 266
tStripOffsets = 273
tSamplesPerPixel = 277
tRowsPerStrip = 278
tStripByteCounts = 279
tT4Options = 292 // CCITT Group 3 options, a set of 32 flag bits.
tT6Options = 293 // CCITT Group 4 options, a set of 32 flag bits.
tTileWidth = 322
tTileLength = 323
tTileOffsets = 324
tTileByteCounts = 325
tXResolution = 282
tYResolution = 283
tResolutionUnit = 296
tPredictor = 317
tColorMap = 320
tExtraSamples = 338
tSampleFormat = 339
)
// Compression types (defined in various places in the spec and supplements).
const (
cNone = 1
cCCITT = 2
cG3 = 3 // Group 3 Fax.
cG4 = 4 // Group 4 Fax.
cLZW = 5
cJPEGOld = 6 // Superseded by cJPEG.
cJPEG = 7
cDeflate = 8 // zlib compression.
cPackBits = 32773
cDeflateOld = 32946 // Superseded by cDeflate.
)
// Photometric interpretation values (see p. 37 of the spec).
const (
pWhiteIsZero = 0
pBlackIsZero = 1
pRGB = 2
pPaletted = 3
pTransMask = 4 // transparency mask
pCMYK = 5
pYCbCr = 6
pCIELab = 8
)
// Values for the tPredictor tag (page 64-65 of the spec).
const (
prNone = 1
prHorizontal = 2
)
// Values for the tResolutionUnit tag (page 18).
const (
resNone = 1
resPerInch = 2 // Dots per inch.
resPerCM = 3 // Dots per centimeter.
)
// imageMode represents the mode of the image.
type imageMode int
const (
mBilevel imageMode = iota
mPaletted
mGray
mGrayInvert
mRGB
mRGBA
mNRGBA
mCMYK
)
// CompressionType describes the type of compression used in Options.
type CompressionType int
// Constants for supported compression types.
const (
Uncompressed CompressionType = iota
Deflate
LZW
CCITTGroup3
CCITTGroup4
)
// specValue returns the compression type constant from the TIFF spec that
// is equivalent to c.
func (c CompressionType) specValue() uint32 {
switch c {
case LZW:
return cLZW
case Deflate:
return cDeflate
case CCITTGroup3:
return cG3
case CCITTGroup4:
return cG4
}
return cNone
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/writer_test.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
import (
"bytes"
"image"
"io/ioutil"
"os"
"testing"
)
var roundtripTests = []struct {
filename string
opts *Options
}{
{"video-001.tiff", nil},
{"video-001-16bit.tiff", nil},
{"video-001-gray.tiff", nil},
{"video-001-gray-16bit.tiff", nil},
{"video-001-paletted.tiff", nil},
{"bw-packbits.tiff", nil},
{"video-001.tiff", &Options{Predictor: true}},
{"video-001.tiff", &Options{Compression: Deflate}},
{"video-001.tiff", &Options{Predictor: true, Compression: Deflate}},
}
func openImage(filename string) (image.Image, error) {
f, err := os.Open(testdataDir + filename)
if err != nil {
return nil, err
}
defer f.Close()
return Decode(f)
}
func TestRoundtrip(t *testing.T) {
for _, rt := range roundtripTests {
img, err := openImage(rt.filename)
if err != nil {
t.Fatal(err)
}
out := new(bytes.Buffer)
err = Encode(out, img, rt.opts)
if err != nil {
t.Fatal(err)
}
img2, err := Decode(&buffer{buf: out.Bytes()})
if err != nil {
t.Fatal(err)
}
compare(t, img, img2)
}
}
// TestRoundtrip2 tests that encoding and decoding an image whose
// origin is not (0, 0) gives the same thing.
func TestRoundtrip2(t *testing.T) {
m0 := image.NewRGBA(image.Rect(3, 4, 9, 8))
for i := range m0.Pix {
m0.Pix[i] = byte(i)
}
out := new(bytes.Buffer)
if err := Encode(out, m0, nil); err != nil {
t.Fatal(err)
}
m1, err := Decode(&buffer{buf: out.Bytes()})
if err != nil {
t.Fatal(err)
}
compare(t, m0, m1)
}
func TestUnsupported(t *testing.T) {
img := image.NewGray(image.Rect(0, 0, 1, 1))
out := new(bytes.Buffer)
err := Encode(out, img, &Options{Compression: LZW})
if err == nil {
t.Error("tiff.Encode(LZW): no error returned, expected an error")
}
}
func benchmarkEncode(b *testing.B, name string, pixelSize int) {
b.Helper()
img, err := openImage(name)
if err != nil {
b.Fatal(err)
}
s := img.Bounds().Size()
b.SetBytes(int64(s.X * s.Y * pixelSize))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Encode(ioutil.Discard, img, nil)
}
}
func BenchmarkEncode(b *testing.B) { benchmarkEncode(b, "video-001.tiff", 4) }
func BenchmarkEncodePaletted(b *testing.B) { benchmarkEncode(b, "video-001-paletted.tiff", 1) }
func BenchmarkEncodeGray(b *testing.B) { benchmarkEncode(b, "video-001-gray.tiff", 1) }
func BenchmarkEncodeGray16(b *testing.B) { benchmarkEncode(b, "video-001-gray-16bit.tiff", 2) }
func BenchmarkEncodeRGBA(b *testing.B) { benchmarkEncode(b, "video-001.tiff", 4) }
func BenchmarkEncodeRGBA64(b *testing.B) { benchmarkEncode(b, "video-001-16bit.tiff", 8) }
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/fuzz.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build gofuzz
package tiff
import "bytes"
func Fuzz(data []byte) int {
cfg, err := DecodeConfig(bytes.NewReader(data))
if err != nil {
return 0
}
if cfg.Width*cfg.Height > 1e6 {
return 0
}
img, err := Decode(bytes.NewReader(data))
if err != nil {
return 0
}
var w bytes.Buffer
err = Encode(&w, img, nil)
if err != nil {
panic(err)
}
return 1
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/buffer_test.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
import (
"io"
"strings"
"testing"
)
var readAtTests = []struct {
n int
off int64
s string
err error
}{
{2, 0, "ab", nil},
{6, 0, "abcdef", nil},
{3, 3, "def", nil},
{3, 5, "f", io.EOF},
{3, 6, "", io.EOF},
}
func TestReadAt(t *testing.T) {
r := newReaderAt(strings.NewReader("abcdef"))
b := make([]byte, 10)
for _, test := range readAtTests {
n, err := r.ReadAt(b[:test.n], test.off)
s := string(b[:n])
if s != test.s || err != test.err {
t.Errorf("buffer.ReadAt(<%v bytes>, %v): got %v, %q; want %v, %q", test.n, test.off, err, s, test.err, test.s)
}
}
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/compress.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
import (
"bufio"
"io"
)
type byteReader interface {
io.Reader
io.ByteReader
}
// unpackBits decodes the PackBits-compressed data in src and returns the
// uncompressed data.
//
// The PackBits compression format is described in section 9 (p. 42)
// of the TIFF spec.
func unpackBits(r io.Reader) ([]byte, error) {
buf := make([]byte, 128)
dst := make([]byte, 0, 1024)
br, ok := r.(byteReader)
if !ok {
br = bufio.NewReader(r)
}
for {
b, err := br.ReadByte()
if err != nil {
if err == io.EOF {
return dst, nil
}
return nil, err
}
code := int(int8(b))
switch {
case code >= 0:
n, err := io.ReadFull(br, buf[:code+1])
if err != nil {
return nil, err
}
dst = append(dst, buf[:n]...)
case code == -128:
// No-op.
default:
if b, err = br.ReadByte(); err != nil {
return nil, err
}
for j := 0; j < 1-code; j++ {
buf[j] = b
}
dst = append(dst, buf[:1-code]...)
}
}
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/buffer.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tiff
import "io"
// buffer buffers an io.Reader to satisfy io.ReaderAt.
type buffer struct {
r io.Reader
buf []byte
}
// fill reads data from b.r until the buffer contains at least end bytes.
func (b *buffer) fill(end int) error {
m := len(b.buf)
if end > m {
if end > cap(b.buf) {
newcap := 1024
for newcap < end {
newcap *= 2
}
newbuf := make([]byte, end, newcap)
copy(newbuf, b.buf)
b.buf = newbuf
} else {
b.buf = b.buf[:end]
}
if n, err := io.ReadFull(b.r, b.buf[m:end]); err != nil {
end = m + n
b.buf = b.buf[:end]
return err
}
}
return nil
}
func (b *buffer) ReadAt(p []byte, off int64) (int, error) {
o := int(off)
end := o + len(p)
if int64(end) != off+int64(len(p)) {
return 0, io.ErrUnexpectedEOF
}
err := b.fill(end)
return copy(p, b.buf[o:end]), err
}
// Slice returns a slice of the underlying buffer. The slice contains
// n bytes starting at offset off.
func (b *buffer) Slice(off, n int) ([]byte, error) {
end := off + n
if err := b.fill(end); err != nil {
return nil, err
}
return b.buf[off:end], nil
}
// newReaderAt converts an io.Reader into an io.ReaderAt.
func newReaderAt(r io.Reader) io.ReaderAt {
if ra, ok := r.(io.ReaderAt); ok {
return ra
}
return &buffer{
r: r,
buf: make([]byte, 0, 1024),
}
}
|
tiff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/reader.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tiff implements a TIFF image decoder and encoder.
//
// The TIFF specification is at http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
package tiff // import "golang.org/x/image/tiff"
import (
"bytes"
"compress/zlib"
"encoding/binary"
"fmt"
"image"
"image/color"
"io"
"math"
"golang.org/x/image/ccitt"
"golang.org/x/image/tiff/lzw"
)
// A FormatError reports that the input is not a valid TIFF image.
type FormatError string
func (e FormatError) Error() string {
return "tiff: invalid format: " + string(e)
}
// An UnsupportedError reports that the input uses a valid but
// unimplemented feature.
type UnsupportedError string
func (e UnsupportedError) Error() string {
return "tiff: unsupported feature: " + string(e)
}
var (
errNoPixels = FormatError("not enough pixel data")
errInvalidColorIndex = FormatError("invalid color index")
)
const maxChunkSize = 10 << 20 // 10M
// safeReadAt is a verbatim copy of internal/saferio.ReadDataAt from the
// standard library, which is used to read data from a reader using a length
// provided by untrusted data, without allocating the entire slice ahead of time
// if it is large (>maxChunkSize). This allows us to avoid allocating giant
// slices before learning that we can't actually read that much data from the
// reader.
func safeReadAt(r io.ReaderAt, n uint64, off int64) ([]byte, error) {
if int64(n) < 0 || n != uint64(int(n)) {
// n is too large to fit in int, so we can't allocate
// a buffer large enough. Treat this as a read failure.
return nil, io.ErrUnexpectedEOF
}
if n < maxChunkSize {
buf := make([]byte, n)
_, err := r.ReadAt(buf, off)
if err != nil {
// io.SectionReader can return EOF for n == 0,
// but for our purposes that is a success.
if err != io.EOF || n > 0 {
return nil, err
}
}
return buf, nil
}
var buf []byte
buf1 := make([]byte, maxChunkSize)
for n > 0 {
next := n
if next > maxChunkSize {
next = maxChunkSize
}
_, err := r.ReadAt(buf1[:next], off)
if err != nil {
return nil, err
}
buf = append(buf, buf1[:next]...)
n -= next
off += int64(next)
}
return buf, nil
}
type decoder struct {
r io.ReaderAt
byteOrder binary.ByteOrder
config image.Config
mode imageMode
bpp uint
features map[int][]uint
palette []color.Color
buf []byte
off int // Current offset in buf.
v uint32 // Buffer value for reading with arbitrary bit depths.
nbits uint // Remaining number of bits in v.
}
// firstVal returns the first uint of the features entry with the given tag,
// or 0 if the tag does not exist.
func (d *decoder) firstVal(tag int) uint {
f := d.features[tag]
if len(f) == 0 {
return 0
}
return f[0]
}
// ifdUint decodes the IFD entry in p, which must be of the Byte, Short
// or Long type, and returns the decoded uint values.
func (d *decoder) ifdUint(p []byte) (u []uint, err error) {
var raw []byte
if len(p) < ifdLen {
return nil, FormatError("bad IFD entry")
}
datatype := d.byteOrder.Uint16(p[2:4])
if dt := int(datatype); dt <= 0 || dt >= len(lengths) {
return nil, UnsupportedError("IFD entry datatype")
}
count := d.byteOrder.Uint32(p[4:8])
if count > math.MaxInt32/lengths[datatype] {
return nil, FormatError("IFD data too large")
}
if datalen := lengths[datatype] * count; datalen > 4 {
// The IFD contains a pointer to the real value.
raw, err = safeReadAt(d.r, uint64(datalen), int64(d.byteOrder.Uint32(p[8:12])))
} else {
raw = p[8 : 8+datalen]
}
if err != nil {
return nil, err
}
u = make([]uint, count)
switch datatype {
case dtByte:
for i := uint32(0); i < count; i++ {
u[i] = uint(raw[i])
}
case dtShort:
for i := uint32(0); i < count; i++ {
u[i] = uint(d.byteOrder.Uint16(raw[2*i : 2*(i+1)]))
}
case dtLong:
for i := uint32(0); i < count; i++ {
u[i] = uint(d.byteOrder.Uint32(raw[4*i : 4*(i+1)]))
}
default:
return nil, UnsupportedError("data type")
}
return u, nil
}
// parseIFD decides whether the IFD entry in p is "interesting" and
// stows away the data in the decoder. It returns the tag number of the
// entry and an error, if any.
func (d *decoder) parseIFD(p []byte) (int, error) {
tag := d.byteOrder.Uint16(p[0:2])
switch tag {
case tBitsPerSample,
tExtraSamples,
tPhotometricInterpretation,
tCompression,
tPredictor,
tStripOffsets,
tStripByteCounts,
tRowsPerStrip,
tTileWidth,
tTileLength,
tTileOffsets,
tTileByteCounts,
tImageLength,
tImageWidth,
tFillOrder,
tT4Options,
tT6Options:
val, err := d.ifdUint(p)
if err != nil {
return 0, err
}
d.features[int(tag)] = val
case tColorMap:
val, err := d.ifdUint(p)
if err != nil {
return 0, err
}
numcolors := len(val) / 3
if len(val)%3 != 0 || numcolors <= 0 || numcolors > 256 {
return 0, FormatError("bad ColorMap length")
}
d.palette = make([]color.Color, numcolors)
for i := 0; i < numcolors; i++ {
d.palette[i] = color.RGBA64{
uint16(val[i]),
uint16(val[i+numcolors]),
uint16(val[i+2*numcolors]),
0xffff,
}
}
case tSampleFormat:
// Page 27 of the spec: If the SampleFormat is present and
// the value is not 1 [= unsigned integer data], a Baseline
// TIFF reader that cannot handle the SampleFormat value
// must terminate the import process gracefully.
val, err := d.ifdUint(p)
if err != nil {
return 0, err
}
for _, v := range val {
if v != 1 {
return 0, UnsupportedError("sample format")
}
}
}
return int(tag), nil
}
// readBits reads n bits from the internal buffer starting at the current offset.
func (d *decoder) readBits(n uint) (v uint32, ok bool) {
for d.nbits < n {
d.v <<= 8
if d.off >= len(d.buf) {
return 0, false
}
d.v |= uint32(d.buf[d.off])
d.off++
d.nbits += 8
}
d.nbits -= n
rv := d.v >> d.nbits
d.v &^= rv << d.nbits
return rv, true
}
// flushBits discards the unread bits in the buffer used by readBits.
// It is used at the end of a line.
func (d *decoder) flushBits() {
d.v = 0
d.nbits = 0
}
// minInt returns the smaller of x or y.
func minInt(a, b int) int {
if a <= b {
return a
}
return b
}
// decode decodes the raw data of an image.
// It reads from d.buf and writes the strip or tile into dst.
func (d *decoder) decode(dst image.Image, xmin, ymin, xmax, ymax int) error {
d.off = 0
// Apply horizontal predictor if necessary.
// In this case, p contains the color difference to the preceding pixel.
// See page 64-65 of the spec.
if d.firstVal(tPredictor) == prHorizontal {
switch d.bpp {
case 16:
var off int
n := 2 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
for y := ymin; y < ymax; y++ {
off += n
for x := 0; x < (xmax-xmin-1)*n; x += 2 {
if off+2 > len(d.buf) {
return errNoPixels
}
v0 := d.byteOrder.Uint16(d.buf[off-n : off-n+2])
v1 := d.byteOrder.Uint16(d.buf[off : off+2])
d.byteOrder.PutUint16(d.buf[off:off+2], v1+v0)
off += 2
}
}
case 8:
var off int
n := 1 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
for y := ymin; y < ymax; y++ {
off += n
for x := 0; x < (xmax-xmin-1)*n; x++ {
if off >= len(d.buf) {
return errNoPixels
}
d.buf[off] += d.buf[off-n]
off++
}
}
case 1:
return UnsupportedError("horizontal predictor with 1 BitsPerSample")
}
}
rMaxX := minInt(xmax, dst.Bounds().Max.X)
rMaxY := minInt(ymax, dst.Bounds().Max.Y)
switch d.mode {
case mGray, mGrayInvert:
if d.bpp == 16 {
img := dst.(*image.Gray16)
for y := ymin; y < rMaxY; y++ {
for x := xmin; x < rMaxX; x++ {
if d.off+2 > len(d.buf) {
return errNoPixels
}
v := d.byteOrder.Uint16(d.buf[d.off : d.off+2])
d.off += 2
if d.mode == mGrayInvert {
v = 0xffff - v
}
img.SetGray16(x, y, color.Gray16{v})
}
if rMaxX == img.Bounds().Max.X {
d.off += 2 * (xmax - img.Bounds().Max.X)
}
}
} else {
img := dst.(*image.Gray)
max := uint32((1 << d.bpp) - 1)
for y := ymin; y < rMaxY; y++ {
for x := xmin; x < rMaxX; x++ {
v, ok := d.readBits(d.bpp)
if !ok {
return errNoPixels
}
v = v * 0xff / max
if d.mode == mGrayInvert {
v = 0xff - v
}
img.SetGray(x, y, color.Gray{uint8(v)})
}
d.flushBits()
}
}
case mPaletted:
img := dst.(*image.Paletted)
pLen := len(d.palette)
for y := ymin; y < rMaxY; y++ {
for x := xmin; x < rMaxX; x++ {
v, ok := d.readBits(d.bpp)
if !ok {
return errNoPixels
}
idx := uint8(v)
if int(idx) >= pLen {
return errInvalidColorIndex
}
img.SetColorIndex(x, y, idx)
}
d.flushBits()
}
case mRGB:
if d.bpp == 16 {
img := dst.(*image.RGBA64)
for y := ymin; y < rMaxY; y++ {
for x := xmin; x < rMaxX; x++ {
if d.off+6 > len(d.buf) {
return errNoPixels
}
r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
d.off += 6
img.SetRGBA64(x, y, color.RGBA64{r, g, b, 0xffff})
}
}
} else {
img := dst.(*image.RGBA)
for y := ymin; y < rMaxY; y++ {
min := img.PixOffset(xmin, y)
max := img.PixOffset(rMaxX, y)
off := (y - ymin) * (xmax - xmin) * 3
for i := min; i < max; i += 4 {
if off+3 > len(d.buf) {
return errNoPixels
}
img.Pix[i+0] = d.buf[off+0]
img.Pix[i+1] = d.buf[off+1]
img.Pix[i+2] = d.buf[off+2]
img.Pix[i+3] = 0xff
off += 3
}
}
}
case mNRGBA:
if d.bpp == 16 {
img := dst.(*image.NRGBA64)
for y := ymin; y < rMaxY; y++ {
for x := xmin; x < rMaxX; x++ {
if d.off+8 > len(d.buf) {
return errNoPixels
}
r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
d.off += 8
img.SetNRGBA64(x, y, color.NRGBA64{r, g, b, a})
}
}
} else {
img := dst.(*image.NRGBA)
for y := ymin; y < rMaxY; y++ {
min := img.PixOffset(xmin, y)
max := img.PixOffset(rMaxX, y)
i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
if i1 > len(d.buf) {
return errNoPixels
}
copy(img.Pix[min:max], d.buf[i0:i1])
}
}
case mRGBA:
if d.bpp == 16 {
img := dst.(*image.RGBA64)
for y := ymin; y < rMaxY; y++ {
for x := xmin; x < rMaxX; x++ {
if d.off+8 > len(d.buf) {
return errNoPixels
}
r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
d.off += 8
img.SetRGBA64(x, y, color.RGBA64{r, g, b, a})
}
}
} else {
img := dst.(*image.RGBA)
for y := ymin; y < rMaxY; y++ {
min := img.PixOffset(xmin, y)
max := img.PixOffset(rMaxX, y)
i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
if i1 > len(d.buf) {
return errNoPixels
}
copy(img.Pix[min:max], d.buf[i0:i1])
}
}
}
return nil
}
func newDecoder(r io.Reader) (*decoder, error) {
d := &decoder{
r: newReaderAt(r),
features: make(map[int][]uint),
}
p := make([]byte, 8)
if _, err := d.r.ReadAt(p, 0); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
switch string(p[0:4]) {
case leHeader:
d.byteOrder = binary.LittleEndian
case beHeader:
d.byteOrder = binary.BigEndian
default:
return nil, FormatError("malformed header")
}
ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
// The first two bytes contain the number of entries (12 bytes each).
if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
return nil, err
}
numItems := int(d.byteOrder.Uint16(p[0:2]))
// All IFD entries are read in one chunk.
var err error
p, err = safeReadAt(d.r, uint64(ifdLen*numItems), ifdOffset+2)
if err != nil {
return nil, err
}
prevTag := -1
for i := 0; i < len(p); i += ifdLen {
tag, err := d.parseIFD(p[i : i+ifdLen])
if err != nil {
return nil, err
}
if tag <= prevTag {
return nil, FormatError("tags are not sorted in ascending order")
}
prevTag = tag
}
d.config.Width = int(d.firstVal(tImageWidth))
d.config.Height = int(d.firstVal(tImageLength))
if _, ok := d.features[tBitsPerSample]; !ok {
// Default is 1 per specification.
d.features[tBitsPerSample] = []uint{1}
}
d.bpp = d.firstVal(tBitsPerSample)
switch d.bpp {
case 0:
return nil, FormatError("BitsPerSample must not be 0")
case 1, 8, 16:
// Nothing to do, these are accepted by this implementation.
default:
return nil, UnsupportedError(fmt.Sprintf("BitsPerSample of %v", d.bpp))
}
// Determine the image mode.
switch d.firstVal(tPhotometricInterpretation) {
case pRGB:
if d.bpp == 16 {
for _, b := range d.features[tBitsPerSample] {
if b != 16 {
return nil, FormatError("wrong number of samples for 16bit RGB")
}
}
} else {
for _, b := range d.features[tBitsPerSample] {
if b != 8 {
return nil, FormatError("wrong number of samples for 8bit RGB")
}
}
}
// RGB images normally have 3 samples per pixel.
// If there are more, ExtraSamples (p. 31-32 of the spec)
// gives their meaning (usually an alpha channel).
//
// This implementation does not support extra samples
// of an unspecified type.
switch len(d.features[tBitsPerSample]) {
case 3:
d.mode = mRGB
if d.bpp == 16 {
d.config.ColorModel = color.RGBA64Model
} else {
d.config.ColorModel = color.RGBAModel
}
case 4:
switch d.firstVal(tExtraSamples) {
case 1:
d.mode = mRGBA
if d.bpp == 16 {
d.config.ColorModel = color.RGBA64Model
} else {
d.config.ColorModel = color.RGBAModel
}
case 2:
d.mode = mNRGBA
if d.bpp == 16 {
d.config.ColorModel = color.NRGBA64Model
} else {
d.config.ColorModel = color.NRGBAModel
}
default:
return nil, FormatError("wrong number of samples for RGB")
}
default:
return nil, FormatError("wrong number of samples for RGB")
}
case pPaletted:
d.mode = mPaletted
d.config.ColorModel = color.Palette(d.palette)
case pWhiteIsZero:
d.mode = mGrayInvert
if d.bpp == 16 {
d.config.ColorModel = color.Gray16Model
} else {
d.config.ColorModel = color.GrayModel
}
case pBlackIsZero:
d.mode = mGray
if d.bpp == 16 {
d.config.ColorModel = color.Gray16Model
} else {
d.config.ColorModel = color.GrayModel
}
default:
return nil, UnsupportedError("color model")
}
if d.firstVal(tPhotometricInterpretation) != pRGB {
if len(d.features[tBitsPerSample]) != 1 {
return nil, UnsupportedError("extra samples")
}
}
return d, nil
}
// DecodeConfig returns the color model and dimensions of a TIFF image without
// decoding the entire image.
func DecodeConfig(r io.Reader) (image.Config, error) {
d, err := newDecoder(r)
if err != nil {
return image.Config{}, err
}
return d.config, nil
}
func ccittFillOrder(tiffFillOrder uint) ccitt.Order {
if tiffFillOrder == 2 {
return ccitt.LSB
}
return ccitt.MSB
}
// Decode reads a TIFF image from r and returns it as an image.Image.
// The type of Image returned depends on the contents of the TIFF.
func Decode(r io.Reader) (img image.Image, err error) {
d, err := newDecoder(r)
if err != nil {
return
}
blockPadding := false
blockWidth := d.config.Width
blockHeight := d.config.Height
blocksAcross := 1
blocksDown := 1
if d.config.Width == 0 {
blocksAcross = 0
}
if d.config.Height == 0 {
blocksDown = 0
}
var blockOffsets, blockCounts []uint
if int(d.firstVal(tTileWidth)) != 0 {
blockPadding = true
blockWidth = int(d.firstVal(tTileWidth))
blockHeight = int(d.firstVal(tTileLength))
// The specification says that tile widths and lengths must be a multiple of 16.
// We currently permit invalid sizes, but reject anything too small to limit the
// amount of work a malicious input can force us to perform.
if blockWidth < 8 || blockHeight < 8 {
return nil, FormatError("tile size is too small")
}
if blockWidth != 0 {
blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
}
if blockHeight != 0 {
blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
}
blockCounts = d.features[tTileByteCounts]
blockOffsets = d.features[tTileOffsets]
} else {
if int(d.firstVal(tRowsPerStrip)) != 0 {
blockHeight = int(d.firstVal(tRowsPerStrip))
}
if blockHeight != 0 {
blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
}
blockOffsets = d.features[tStripOffsets]
blockCounts = d.features[tStripByteCounts]
}
// Check if we have the right number of strips/tiles, offsets and counts.
if n := blocksAcross * blocksDown; len(blockOffsets) < n || len(blockCounts) < n {
return nil, FormatError("inconsistent header")
}
imgRect := image.Rect(0, 0, d.config.Width, d.config.Height)
switch d.mode {
case mGray, mGrayInvert:
if d.bpp == 16 {
img = image.NewGray16(imgRect)
} else {
img = image.NewGray(imgRect)
}
case mPaletted:
img = image.NewPaletted(imgRect, d.palette)
case mNRGBA:
if d.bpp == 16 {
img = image.NewNRGBA64(imgRect)
} else {
img = image.NewNRGBA(imgRect)
}
case mRGB, mRGBA:
if d.bpp == 16 {
img = image.NewRGBA64(imgRect)
} else {
img = image.NewRGBA(imgRect)
}
}
if blocksAcross == 0 || blocksDown == 0 {
return
}
// Maximum data per pixel is 8 bytes (RGBA64).
blockMaxDataSize := int64(blockWidth) * int64(blockHeight) * 8
for i := 0; i < blocksAcross; i++ {
blkW := blockWidth
if !blockPadding && i == blocksAcross-1 && d.config.Width%blockWidth != 0 {
blkW = d.config.Width % blockWidth
}
for j := 0; j < blocksDown; j++ {
blkH := blockHeight
if !blockPadding && j == blocksDown-1 && d.config.Height%blockHeight != 0 {
blkH = d.config.Height % blockHeight
}
offset := int64(blockOffsets[j*blocksAcross+i])
n := int64(blockCounts[j*blocksAcross+i])
switch d.firstVal(tCompression) {
// According to the spec, Compression does not have a default value,
// but some tools interpret a missing Compression value as none so we do
// the same.
case cNone, 0:
if b, ok := d.r.(*buffer); ok {
d.buf, err = b.Slice(int(offset), int(n))
} else {
d.buf, err = safeReadAt(d.r, uint64(n), offset)
}
case cG3:
inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
order := ccittFillOrder(d.firstVal(tFillOrder))
r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group3, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
case cG4:
inv := d.firstVal(tPhotometricInterpretation) == pWhiteIsZero
order := ccittFillOrder(d.firstVal(tFillOrder))
r := ccitt.NewReader(io.NewSectionReader(d.r, offset, n), order, ccitt.Group4, blkW, blkH, &ccitt.Options{Invert: inv, Align: false})
d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
case cLZW:
r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
r.Close()
case cDeflate, cDeflateOld:
var r io.ReadCloser
r, err = zlib.NewReader(io.NewSectionReader(d.r, offset, n))
if err != nil {
return nil, err
}
d.buf, err = readBuf(r, d.buf, blockMaxDataSize)
r.Close()
case cPackBits:
d.buf, err = unpackBits(io.NewSectionReader(d.r, offset, n))
default:
err = UnsupportedError(fmt.Sprintf("compression value %d", d.firstVal(tCompression)))
}
if err != nil {
return nil, err
}
xmin := i * blockWidth
ymin := j * blockHeight
xmax := xmin + blkW
ymax := ymin + blkH
err = d.decode(img, xmin, ymin, xmax, ymax)
if err != nil {
return nil, err
}
}
}
return
}
func readBuf(r io.Reader, buf []byte, lim int64) ([]byte, error) {
b := bytes.NewBuffer(buf[:0])
_, err := b.ReadFrom(io.LimitReader(r, lim))
return b.Bytes(), err
}
func init() {
image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)
}
|
lzw | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/tiff/lzw/reader.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lzw implements the Lempel-Ziv-Welch compressed data format,
// described in T. A. Welch, “A Technique for High-Performance Data
// Compression”, Computer, 17(6) (June 1984), pp 8-19.
//
// In particular, it implements LZW as used by the TIFF file format, including
// an "off by one" algorithmic difference when compared to standard LZW.
package lzw // import "golang.org/x/image/tiff/lzw"
/*
This file was branched from src/pkg/compress/lzw/reader.go in the
standard library. Differences from the original are marked with "NOTE".
The tif_lzw.c file in the libtiff C library has this comment:
----
The 5.0 spec describes a different algorithm than Aldus
implements. Specifically, Aldus does code length transitions
one code earlier than should be done (for real LZW).
Earlier versions of this library implemented the correct
LZW algorithm, but emitted codes in a bit order opposite
to the TIFF spec. Thus, to maintain compatibility w/ Aldus
we interpret MSB-LSB ordered codes to be images written w/
old versions of this library, but otherwise adhere to the
Aldus "off by one" algorithm.
----
The Go code doesn't read (invalid) TIFF files written by old versions of
libtiff, but the LZW algorithm in this package still differs from the one in
Go's standard package library to accommodate this "off by one" in valid TIFFs.
*/
import (
"bufio"
"errors"
"fmt"
"io"
)
// Order specifies the bit ordering in an LZW data stream.
type Order int
const (
// LSB means Least Significant Bits first, as used in the GIF file format.
LSB Order = iota
// MSB means Most Significant Bits first, as used in the TIFF and PDF
// file formats.
MSB
)
const (
maxWidth = 12
decoderInvalidCode = 0xffff
flushBuffer = 1 << maxWidth
)
// decoder is the state from which the readXxx method converts a byte
// stream into a code stream.
type decoder struct {
r io.ByteReader
bits uint32
nBits uint
width uint
read func(*decoder) (uint16, error) // readLSB or readMSB
litWidth int // width in bits of literal codes
err error
// The first 1<<litWidth codes are literal codes.
// The next two codes mean clear and EOF.
// Other valid codes are in the range [lo, hi] where lo := clear + 2,
// with the upper bound incrementing on each code seen.
// overflow is the code at which hi overflows the code width. NOTE: TIFF's LZW is "off by one".
// last is the most recently seen code, or decoderInvalidCode.
clear, eof, hi, overflow, last uint16
// Each code c in [lo, hi] expands to two or more bytes. For c != hi:
// suffix[c] is the last of these bytes.
// prefix[c] is the code for all but the last byte.
// This code can either be a literal code or another code in [lo, c).
// The c == hi case is a special case.
suffix [1 << maxWidth]uint8
prefix [1 << maxWidth]uint16
// output is the temporary output buffer.
// Literal codes are accumulated from the start of the buffer.
// Non-literal codes decode to a sequence of suffixes that are first
// written right-to-left from the end of the buffer before being copied
// to the start of the buffer.
// It is flushed when it contains >= 1<<maxWidth bytes,
// so that there is always room to decode an entire code.
output [2 * 1 << maxWidth]byte
o int // write index into output
toRead []byte // bytes to return from Read
}
// readLSB returns the next code for "Least Significant Bits first" data.
func (d *decoder) readLSB() (uint16, error) {
for d.nBits < d.width {
x, err := d.r.ReadByte()
if err != nil {
return 0, err
}
d.bits |= uint32(x) << d.nBits
d.nBits += 8
}
code := uint16(d.bits & (1<<d.width - 1))
d.bits >>= d.width
d.nBits -= d.width
return code, nil
}
// readMSB returns the next code for "Most Significant Bits first" data.
func (d *decoder) readMSB() (uint16, error) {
for d.nBits < d.width {
x, err := d.r.ReadByte()
if err != nil {
return 0, err
}
d.bits |= uint32(x) << (24 - d.nBits)
d.nBits += 8
}
code := uint16(d.bits >> (32 - d.width))
d.bits <<= d.width
d.nBits -= d.width
return code, nil
}
func (d *decoder) Read(b []byte) (int, error) {
for {
if len(d.toRead) > 0 {
n := copy(b, d.toRead)
d.toRead = d.toRead[n:]
return n, nil
}
if d.err != nil {
return 0, d.err
}
d.decode()
}
}
// decode decompresses bytes from r and leaves them in d.toRead.
// read specifies how to decode bytes into codes.
// litWidth is the width in bits of literal codes.
func (d *decoder) decode() {
// Loop over the code stream, converting codes into decompressed bytes.
loop:
for {
code, err := d.read(d)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
d.err = err
break
}
switch {
case code < d.clear:
// We have a literal code.
d.output[d.o] = uint8(code)
d.o++
if d.last != decoderInvalidCode {
// Save what the hi code expands to.
d.suffix[d.hi] = uint8(code)
d.prefix[d.hi] = d.last
}
case code == d.clear:
d.width = 1 + uint(d.litWidth)
d.hi = d.eof
d.overflow = 1 << d.width
d.last = decoderInvalidCode
continue
case code == d.eof:
d.err = io.EOF
break loop
case code <= d.hi:
c, i := code, len(d.output)-1
if code == d.hi && d.last != decoderInvalidCode {
// code == hi is a special case which expands to the last expansion
// followed by the head of the last expansion. To find the head, we walk
// the prefix chain until we find a literal code.
c = d.last
for c >= d.clear {
c = d.prefix[c]
}
d.output[i] = uint8(c)
i--
c = d.last
}
// Copy the suffix chain into output and then write that to w.
for c >= d.clear {
d.output[i] = d.suffix[c]
i--
c = d.prefix[c]
}
d.output[i] = uint8(c)
d.o += copy(d.output[d.o:], d.output[i:])
if d.last != decoderInvalidCode {
// Save what the hi code expands to.
d.suffix[d.hi] = uint8(c)
d.prefix[d.hi] = d.last
}
default:
d.err = errors.New("lzw: invalid code")
break loop
}
d.last, d.hi = code, d.hi+1
if d.hi+1 >= d.overflow { // NOTE: the "+1" is where TIFF's LZW differs from the standard algorithm.
if d.width == maxWidth {
d.last = decoderInvalidCode
} else {
d.width++
d.overflow <<= 1
}
}
if d.o >= flushBuffer {
break
}
}
// Flush pending output.
d.toRead = d.output[:d.o]
d.o = 0
}
var errClosed = errors.New("lzw: reader/writer is closed")
func (d *decoder) Close() error {
d.err = errClosed // in case any Reads come along
return nil
}
// NewReader creates a new io.ReadCloser.
// Reads from the returned io.ReadCloser read and decompress data from r.
// If r does not also implement io.ByteReader,
// the decompressor may read more data than necessary from r.
// It is the caller's responsibility to call Close on the ReadCloser when
// finished reading.
// The number of bits to use for literal codes, litWidth, must be in the
// range [2,8] and is typically 8. It must equal the litWidth
// used during compression.
func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser {
d := new(decoder)
switch order {
case LSB:
d.read = (*decoder).readLSB
case MSB:
d.read = (*decoder).readMSB
default:
d.err = errors.New("lzw: unknown order")
return d
}
if litWidth < 2 || 8 < litWidth {
d.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth)
return d
}
if br, ok := r.(io.ByteReader); ok {
d.r = br
} else {
d.r = bufio.NewReader(r)
}
d.litWidth = litWidth
d.width = 1 + uint(litWidth)
d.clear = uint16(1) << uint(litWidth)
d.eof, d.hi = d.clear+1, d.clear+1
d.overflow = uint16(1) << d.width
d.last = decoderInvalidCode
return d
}
|
font | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/example/font/main.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build example
// +build example
// This build tag means that "go install golang.org/x/image/..." doesn't
// install this example program. Use "go run main.go" to run it or "go install
// -tags=example" to install it.
// Font is a basic example of using fonts.
package main
import (
"flag"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/image/font"
"golang.org/x/image/font/plan9font"
"golang.org/x/image/math/fixed"
)
var (
fontFlag = flag.String("font", "",
`filename of the Plan 9 font or subfont file, such as "lucsans/unicode.8.font" or "lucsans/lsr.14"`)
firstRuneFlag = flag.Int("firstrune", 0, "the Unicode code point of the first rune in the subfont file")
)
func pt(p fixed.Point26_6) image.Point {
return image.Point{
X: int(p.X+32) >> 6,
Y: int(p.Y+32) >> 6,
}
}
func main() {
flag.Parse()
// TODO: mmap the files.
if *fontFlag == "" {
flag.Usage()
log.Fatal("no font specified")
}
var face font.Face
if strings.HasSuffix(*fontFlag, ".font") {
fontData, err := ioutil.ReadFile(*fontFlag)
if err != nil {
log.Fatal(err)
}
dir := filepath.Dir(*fontFlag)
face, err = plan9font.ParseFont(fontData, func(name string) ([]byte, error) {
return ioutil.ReadFile(filepath.Join(dir, filepath.FromSlash(name)))
})
if err != nil {
log.Fatal(err)
}
} else {
fontData, err := ioutil.ReadFile(*fontFlag)
if err != nil {
log.Fatal(err)
}
face, err = plan9font.ParseSubfont(fontData, rune(*firstRuneFlag))
if err != nil {
log.Fatal(err)
}
}
dst := image.NewRGBA(image.Rect(0, 0, 800, 300))
draw.Draw(dst, dst.Bounds(), image.Black, image.Point{}, draw.Src)
d := &font.Drawer{
Dst: dst,
Src: image.White,
Face: face,
}
ss := []string{
"The quick brown fox jumps over the lazy dog.",
"Hello, 世界.",
"U+FFFD is \ufffd.",
}
for i, s := range ss {
d.Dot = fixed.P(20, 100*i+80)
dot0 := pt(d.Dot)
d.DrawString(s)
dot1 := pt(d.Dot)
dst.SetRGBA(dot0.X, dot0.Y, color.RGBA{0xff, 0x00, 0x00, 0xff})
dst.SetRGBA(dot1.X, dot1.Y, color.RGBA{0x00, 0x00, 0xff, 0xff})
}
out, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
if err := png.Encode(out, dst); err != nil {
log.Fatal(err)
}
}
|
riff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/riff/riff.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package riff implements the Resource Interchange File Format, used by media
// formats such as AVI, WAVE and WEBP.
//
// A RIFF stream contains a sequence of chunks. Each chunk consists of an 8-byte
// header (containing a 4-byte chunk type and a 4-byte chunk length), the chunk
// data (presented as an io.Reader), and some padding bytes.
//
// A detailed description of the format is at
// http://www.tactilemedia.com/info/MCI_Control_Info.html
package riff // import "golang.org/x/image/riff"
import (
"errors"
"io"
"io/ioutil"
"math"
)
var (
errMissingPaddingByte = errors.New("riff: missing padding byte")
errMissingRIFFChunkHeader = errors.New("riff: missing RIFF chunk header")
errListSubchunkTooLong = errors.New("riff: list subchunk too long")
errShortChunkData = errors.New("riff: short chunk data")
errShortChunkHeader = errors.New("riff: short chunk header")
errStaleReader = errors.New("riff: stale reader")
)
// u32 decodes the first four bytes of b as a little-endian integer.
func u32(b []byte) uint32 {
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}
const chunkHeaderSize = 8
// FourCC is a four character code.
type FourCC [4]byte
// LIST is the "LIST" FourCC.
var LIST = FourCC{'L', 'I', 'S', 'T'}
// NewReader returns the RIFF stream's form type, such as "AVI " or "WAVE", and
// its chunks as a *Reader.
func NewReader(r io.Reader) (formType FourCC, data *Reader, err error) {
var buf [chunkHeaderSize]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
err = errMissingRIFFChunkHeader
}
return FourCC{}, nil, err
}
if buf[0] != 'R' || buf[1] != 'I' || buf[2] != 'F' || buf[3] != 'F' {
return FourCC{}, nil, errMissingRIFFChunkHeader
}
return NewListReader(u32(buf[4:]), r)
}
// NewListReader returns a LIST chunk's list type, such as "movi" or "wavl",
// and its chunks as a *Reader.
func NewListReader(chunkLen uint32, chunkData io.Reader) (listType FourCC, data *Reader, err error) {
if chunkLen < 4 {
return FourCC{}, nil, errShortChunkData
}
z := &Reader{r: chunkData}
if _, err := io.ReadFull(chunkData, z.buf[:4]); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
err = errShortChunkData
}
return FourCC{}, nil, err
}
z.totalLen = chunkLen - 4
return FourCC{z.buf[0], z.buf[1], z.buf[2], z.buf[3]}, z, nil
}
// Reader reads chunks from an underlying io.Reader.
type Reader struct {
r io.Reader
err error
totalLen uint32
chunkLen uint32
chunkReader *chunkReader
buf [chunkHeaderSize]byte
padded bool
}
// Next returns the next chunk's ID, length and data. It returns io.EOF if there
// are no more chunks. The io.Reader returned becomes stale after the next Next
// call, and should no longer be used.
//
// It is valid to call Next even if all of the previous chunk's data has not
// been read.
func (z *Reader) Next() (chunkID FourCC, chunkLen uint32, chunkData io.Reader, err error) {
if z.err != nil {
return FourCC{}, 0, nil, z.err
}
// Drain the rest of the previous chunk.
if z.chunkLen != 0 {
want := z.chunkLen
var got int64
got, z.err = io.Copy(ioutil.Discard, z.chunkReader)
if z.err == nil && uint32(got) != want {
z.err = errShortChunkData
}
if z.err != nil {
return FourCC{}, 0, nil, z.err
}
}
z.chunkReader = nil
if z.padded {
if z.totalLen == 0 {
z.err = errListSubchunkTooLong
return FourCC{}, 0, nil, z.err
}
z.totalLen--
_, z.err = io.ReadFull(z.r, z.buf[:1])
if z.err != nil {
if z.err == io.EOF {
z.err = errMissingPaddingByte
}
return FourCC{}, 0, nil, z.err
}
}
// We are done if we have no more data.
if z.totalLen == 0 {
z.err = io.EOF
return FourCC{}, 0, nil, z.err
}
// Read the next chunk header.
if z.totalLen < chunkHeaderSize {
z.err = errShortChunkHeader
return FourCC{}, 0, nil, z.err
}
z.totalLen -= chunkHeaderSize
if _, z.err = io.ReadFull(z.r, z.buf[:chunkHeaderSize]); z.err != nil {
if z.err == io.EOF || z.err == io.ErrUnexpectedEOF {
z.err = errShortChunkHeader
}
return FourCC{}, 0, nil, z.err
}
chunkID = FourCC{z.buf[0], z.buf[1], z.buf[2], z.buf[3]}
z.chunkLen = u32(z.buf[4:])
if z.chunkLen > z.totalLen {
z.err = errListSubchunkTooLong
return FourCC{}, 0, nil, z.err
}
z.padded = z.chunkLen&1 == 1
z.chunkReader = &chunkReader{z}
return chunkID, z.chunkLen, z.chunkReader, nil
}
type chunkReader struct {
z *Reader
}
func (c *chunkReader) Read(p []byte) (int, error) {
if c != c.z.chunkReader {
return 0, errStaleReader
}
z := c.z
if z.err != nil {
if z.err == io.EOF {
return 0, errStaleReader
}
return 0, z.err
}
n := int(z.chunkLen)
if n == 0 {
return 0, io.EOF
}
if n < 0 {
// Converting uint32 to int overflowed.
n = math.MaxInt32
}
if n > len(p) {
n = len(p)
}
n, err := z.r.Read(p[:n])
z.totalLen -= uint32(n)
z.chunkLen -= uint32(n)
if err != io.EOF {
z.err = err
}
return n, err
}
|
riff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/riff/example_test.go | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package riff_test
import (
"fmt"
"io"
"io/ioutil"
"log"
"strings"
"golang.org/x/image/riff"
)
func ExampleReader() {
formType, r, err := riff.NewReader(strings.NewReader(data))
if err != nil {
log.Fatal(err)
}
fmt.Printf("RIFF(%s)\n", formType)
if err := dump(r, ".\t"); err != nil {
log.Fatal(err)
}
// Output:
// RIFF(ROOT)
// . ZERO ""
// . ONE "a"
// . LIST(META)
// . . LIST(GOOD)
// . . . ONE "a"
// . . . FIVE "klmno"
// . . ZERO ""
// . . LIST(BAD )
// . . . THRE "def"
// . TWO "bc"
// . LIST(UGLY)
// . . FOUR "ghij"
// . . SIX "pqrstu"
}
func dump(r *riff.Reader, indent string) error {
for {
chunkID, chunkLen, chunkData, err := r.Next()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if chunkID == riff.LIST {
listType, list, err := riff.NewListReader(chunkLen, chunkData)
if err != nil {
return err
}
fmt.Printf("%sLIST(%s)\n", indent, listType)
if err := dump(list, indent+".\t"); err != nil {
return err
}
continue
}
b, err := ioutil.ReadAll(chunkData)
if err != nil {
return err
}
fmt.Printf("%s%s %q\n", indent, chunkID, b)
}
}
func encodeU32(u uint32) string {
return string([]byte{
byte(u >> 0),
byte(u >> 8),
byte(u >> 16),
byte(u >> 24),
})
}
func encode(chunkID, contents string) string {
n := len(contents)
if n&1 == 1 {
contents += "\x00"
}
return chunkID + encodeU32(uint32(n)) + contents
}
func encodeMulti(typ0, typ1 string, chunks ...string) string {
n := 4
for _, c := range chunks {
n += len(c)
}
s := typ0 + encodeU32(uint32(n)) + typ1
for _, c := range chunks {
s += c
}
return s
}
var (
d0 = encode("ZERO", "")
d1 = encode("ONE ", "a")
d2 = encode("TWO ", "bc")
d3 = encode("THRE", "def")
d4 = encode("FOUR", "ghij")
d5 = encode("FIVE", "klmno")
d6 = encode("SIX ", "pqrstu")
l0 = encodeMulti("LIST", "GOOD", d1, d5)
l1 = encodeMulti("LIST", "BAD ", d3)
l2 = encodeMulti("LIST", "UGLY", d4, d6)
l01 = encodeMulti("LIST", "META", l0, d0, l1)
data = encodeMulti("RIFF", "ROOT", d0, d1, l01, d2, l2)
)
|
riff | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/image/riff/riff_test.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package riff
import (
"bytes"
"testing"
)
func encodeU32(u uint32) []byte {
return []byte{
byte(u >> 0),
byte(u >> 8),
byte(u >> 16),
byte(u >> 24),
}
}
func TestShortChunks(t *testing.T) {
// s is a RIFF(ABCD) with allegedly 256 bytes of data (excluding the
// leading 8-byte "RIFF\x00\x01\x00\x00"). The first chunk of that ABCD
// list is an abcd chunk of length m followed by n zeroes.
for _, m := range []uint32{0, 8, 15, 200, 300} {
for _, n := range []int{0, 1, 2, 7} {
s := []byte("RIFF\x00\x01\x00\x00ABCDabcd")
s = append(s, encodeU32(m)...)
s = append(s, make([]byte, n)...)
_, r, err := NewReader(bytes.NewReader(s))
if err != nil {
t.Errorf("m=%d, n=%d: NewReader: %v", m, n, err)
continue
}
_, _, _, err0 := r.Next()
// The total "ABCD" list length is 256 bytes, of which the first 12
// bytes are "ABCDabcd" plus the 4-byte encoding of m. If the
// "abcd" subchunk length (m) plus those 12 bytes is greater than
// the total list length, we have an invalid RIFF, and we expect an
// errListSubchunkTooLong error.
if m+12 > 256 {
if err0 != errListSubchunkTooLong {
t.Errorf("m=%d, n=%d: Next #0: got %v, want %v", m, n, err0, errListSubchunkTooLong)
}
continue
}
// Otherwise, we expect a nil error.
if err0 != nil {
t.Errorf("m=%d, n=%d: Next #0: %v", m, n, err0)
continue
}
_, _, _, err1 := r.Next()
// If m > 0, then m > n, so that "abcd" subchunk doesn't have m
// bytes of data. If m == 0, then that "abcd" subchunk is OK in
// that it has 0 extra bytes of data, but the next subchunk (8 byte
// header plus body) is missing, as we only have n < 8 more bytes.
want := errShortChunkData
if m == 0 {
want = errShortChunkHeader
}
if err1 != want {
t.Errorf("m=%d, n=%d: Next #1: got %v, want %v", m, n, err1, want)
continue
}
}
}
}
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/CONTRIBUTING.md | # Contributing to Go
Go is an open source project.
It is the work of hundreds of contributors. We appreciate your help!
## Filing issues
When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions:
1. What version of Go are you using (`go version`)?
2. What operating system and processor architecture are you using?
3. What did you do?
4. What did you expect to see?
5. What did you see instead?
General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
The gophers there will answer or ask you to file an issue if you've tripped over a bug.
## Contributing code
Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
before sending patches.
Unless otherwise noted, the Go source files are distributed under
the BSD-style license found in the LICENSE file.
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/PATENTS | Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/update.bash | #!/usr/bin/env bash
set -e
rm -rf ./vendor/cmd/go
cp -a $(go env GOROOT)/src/cmd/go vendor/cmd/go
rm -f vendor/cmd/go/alldocs.go vendor/cmd/go/mkalldocs.sh # docs are in wrong place and describe wrong command
cd vendor/cmd/go
patch -p0 < ../../../patch.txt
vers=$(go version | sed 's/^go version //; s/ [A-Z][a-z][a-z].*//')
echo "package version; const version = \"$vers\"" > internal/version/vgo.go
gofmt -w internal
cd ../../..
rm $(find . -name '*.orig')
go build
./vgo version
rm vgo
git add .
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/go.mod | go 1.18
module golang.org/x/vgo
// This dependency is vulnerable to GO-2020-0006.
// The point of this commit is to serve as a test case for
// automated vulnerability scanning of the Go repos.
//
// Using the tour repo because it contains nothing
// important and is not imported by any of our other repos,
// which means any report should be limited to x/tour
// and not affect other users.
//
// Even if people did depend on x/tour, govulncheck would
// correctly identify that no code here calls the vulnerable
// symbols in github.com/miekg/dns. Only less precise
// scanners would suggest that there is a problem.
require github.com/miekg/dns v1.0.0
require (
golang.org/x/crypto v0.1.0 // indirect
golang.org/x/net v0.1.0 // indirect
golang.org/x/sys v0.1.0 // indirect
)
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/README.md | # Versioned Go Command (vgo)
This repository holds a standalone implementation of a version-aware `go` command,
allowing users with a Go 1.10 toolchain to use the new Go 1.11 module support.
The code in this repo is auto-generated from and should behave exactly like
the Go 1.11 `go` command, with two changes:
- It behaves as if the `GO111MODULE` variable defaults to `on`.
- When using a Go 1.10 toolchain, `go` `vet` during `go` `test` is disabled.
## Download/Install
Use `go get -u golang.org/x/vgo`.
You can also manually
git clone the repository to `$GOPATH/src/golang.org/x/vgo`.
## Report Issues / Send Patches
See [CONTRIBUTING.md](CONTRIBUTING.md).
Please file bugs in the main Go issue tracker,
[golang.org/issue](https://golang.org/issue),
and put the prefix `x/vgo:` in the issue title,
or `cmd/go:` if you have confirmed that the same
bug is present in the Go 1.11 module support.
Thank you.
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/go.sum | github.com/miekg/dns v1.0.0 h1:DZ3fdvcFXfWew8XOY+33+MqAcCnqDrGsnt3kK8yf4Hg=
github.com/miekg/dns v1.0.0/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/main.go | // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Vgo is a prototype of what the go command
// might look like with integrated support for package versioning.
//
// Download and install with:
//
// go get -u golang.org/x/vgo
//
// Then run "vgo" instead of "go".
//
// See https://research.swtch.com/vgo-intro for an overview
// and the documents linked at https://research.swtch.com/vgo
// for additional details.
//
// This is still a very early prototype.
// You are likely to run into bugs.
// Please file bugs in the main Go issue tracker,
// https://golang.org/issue,
// and put the prefix `x/vgo:` in the issue title.
//
// Thank you.
package main
import Main "cmd/go"
func main() {
Main.Main()
}
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/LICENSE | Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/codereview.cfg | issuerepo: golang/go
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/patch.txt | diff -u -r ./go11.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go11.go
--- ./go11.go 2018-05-30 20:46:08.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go11.go 2018-02-20 12:11:43.000000000 -0500
@@ -4,7 +4,7 @@
// +build go1.1
-package main
+package Main
// Test that go1.1 tag above is included in builds. main.go refers to this definition.
const go11tag = true
diff -u -r ./go_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go_test.go
--- ./go_test.go 2018-07-12 00:17:57.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go_test.go 2018-07-12 00:09:46.000000000 -0400
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-package main_test
+package Main_test
import (
"bytes"
@@ -120,2 +120,2 @@
testGo = filepath.Join(testTmpDir, "testgo"+exeSuffix)
- args := []string{"build", "-tags", "testgo", "-o", testGo}
+ args := []string{"build", "-tags", "testgo", "-o", testGo, "../../.."}
@@ -867,7 +870,9 @@
tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
}
func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
+ t.Skip("vgo")
+
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
@@ -1342,6 +1389,8 @@
}
func TestMoveHG(t *testing.T) {
+ t.Skip("vgo") // Failing in main branch too: non-hermetic hg configuration?
+
testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
}
@@ -1507,6 +1556,8 @@
}
func TestAccidentalGitCheckout(t *testing.T) {
+ t.Skip("vgo") // Failing in main branch too: https://golang.org/issue/22983
+
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
@@ -2114,6 +2165,8 @@
}
func TestDefaultGOPATH(t *testing.T) {
+ t.Skip("vgo") // Needs a more realistic GOROOT; see RuntimeGoroot below.
+
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
@@ -2172,6 +2225,8 @@
// Issue 4186. go get cannot be used to download packages to $GOROOT.
// Test that without GOPATH set, go get should fail.
func TestGoGetIntoGOROOT(t *testing.T) {
+ t.Skip("vgo")
+
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
@@ -2771,6 +2771,8 @@ func TestTestBuildFailureOutput(t *testing.T) {
}
func TestCoverageFunc(t *testing.T) {
+ t.Skip("vgo")
+
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
@@ -3395,6 +3450,8 @@
}
func TestGoVetWithExternalTests(t *testing.T) {
+ t.Skip("vgo")
+
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
@@ -3404,6 +3461,8 @@
}
func TestGoVetWithTags(t *testing.T) {
+ t.Skip("vgo")
+
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
@@ -3413,6 +3472,8 @@
}
func TestGoVetWithFlagsOn(t *testing.T) {
+ t.Skip("vgo")
+
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
@@ -4754,6 +4815,8 @@
}
func TestExecutableGOROOT(t *testing.T) {
+ t.Skip("vgo")
+
skipIfGccgo(t, "gccgo has no GOROOT")
if runtime.GOOS == "openbsd" {
t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
@@ -4829,6 +4892,8 @@
// Binaries built in the new tree should report the
// new tree when they call runtime.GOROOT.
t.Run("RuntimeGoroot", func(t *testing.T) {
+ t.Skip("vgo") // Needs "new/api" in GOROOT.
+
// Build a working GOROOT the easy way, with symlinks.
testenv.MustHaveSymlink(t)
if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
@@ -4984,6 +5049,8 @@
}
func TestTestRegexps(t *testing.T) {
+ t.Skip("vgo") // fails with Go 1.10 testing package
+
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
@@ -5119,6 +5186,8 @@
}
func TestExecBuildX(t *testing.T) {
+ t.Skip("vgo")
+
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
@@ -5761,6 +5830,8 @@
}
func TestTestVet(t *testing.T) {
+ t.Skip("vgo")
+
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
@@ -5945,6 +6011,8 @@
}
func TestGoTestJSON(t *testing.T) {
+ t.Skip("vgo") // "did not see skip"
+
skipIfGccgo(t, "gccgo does not have standard packages")
tooSlow(t)
@@ -5983,6 +6051,8 @@
}
func TestFailFast(t *testing.T) {
+ t.Skip("vgo") // fails with Go 1.10 testing package
+
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
diff -u -r ./go_unix_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go_unix_test.go
--- ./go_unix_test.go 2018-06-04 09:24:18.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go_unix_test.go 2018-02-20 12:11:43.000000000 -0500
@@ -4,6 +4,6 @@
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-package main_test
+package Main_test
import (
diff -u -r ./go_windows_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go_windows_test.go
--- ./go_windows_test.go 2018-06-04 09:24:18.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/go_windows_test.go 2018-02-20 12:11:43.000000000 -0500
@@ -2,6 +2,6 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-package main
+package Main
import (
diff -u -r ./script_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/script_test.go
--- ./script_test.go 2018-06-04 09:24:18.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/script_test.go 2018-02-20 12:11:43.000000000 -0500
@@ -5,6 +5,6 @@
// Script-driven tests.
// See testdata/script/README for an overview.
-package main_test
+package Main_test
import (
diff -u -r ./internal/base/base.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/base/base.go
--- ./internal/base/base.go 2018-06-04 09:24:18.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/base/base.go 2018-02-23 16:13:50.000000000 -0500
@@ -15,6 +15,7 @@
"log"
"os"
"os/exec"
+ "runtime/debug"
"strings"
"sync"
@@ -86,13 +87,20 @@
os.Exit(exitStatus)
}
+var et = flag.Bool("et", false, "print stack traces with errors")
+
func Fatalf(format string, args ...interface{}) {
Errorf(format, args...)
Exit()
}
func Errorf(format string, args ...interface{}) {
- log.Printf(format, args...)
+ if *et {
+ stack := debug.Stack()
+ log.Printf("%s\n%s", fmt.Sprintf(format, args...), stack)
+ } else {
+ log.Printf(format, args...)
+ }
SetExitStatus(1)
}
diff -u -r ./internal/cfg/cfg.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/cfg/cfg.go
--- ./internal/cfg/cfg.go 2018-07-12 00:17:57.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/cfg/cfg.go 2018-07-12 00:03:05.000000000 -0400
@@ -7,13 +7,14 @@
package cfg
import (
+ "bytes"
"fmt"
"go/build"
+ "io/ioutil"
+ "log"
"os"
"path/filepath"
"runtime"
-
- "cmd/internal/objabi"
)
// These are general "build flags" used by build and other commands.
@@ -90,10 +91,10 @@
GOROOT_FINAL = findGOROOT_FINAL()
// Used in envcmd.MkEnv and build ID computations.
- GOARM = fmt.Sprint(objabi.GOARM)
- GO386 = objabi.GO386
- GOMIPS = objabi.GOMIPS
- GOMIPS64 = objabi.GOMIPS64
+ GOARM, GO386, GOMIPS, GOMIPS64 = objabi()
+
+ // C and C++ compilers
+ CC, CXX = compilers()
)
// Update build context to use our computed GOROOT.
@@ -109,18 +110,75 @@
}
}
-// There is a copy of findGOROOT, isSameDir, and isGOROOT in
-// x/tools/cmd/godoc/goroot.go.
-// Try to keep them in sync for now.
-
-// findGOROOT returns the GOROOT value, using either an explicitly
-// provided environment variable, a GOROOT that contains the current
-// os.Executable value, or else the GOROOT that the binary was built
-// with from runtime.GOROOT().
-//
-// There is a copy of this code in x/tools/cmd/godoc/goroot.go.
+func objabi() (GOARM, GO386, GOMIPS, GOMIPS64 string) {
+ data, err := ioutil.ReadFile(filepath.Join(GOROOT, "src/cmd/internal/objabi/zbootstrap.go"))
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "go objabi: %v\n", err)
+ }
+
+ find := func(key string) string {
+ if env := os.Getenv(key); env != "" {
+ return env
+ }
+ i := bytes.Index(data, []byte("default"+key+" = `"))
+ if i < 0 {
+ if key == "GOMIPS64" { // new in Go 1.11
+ return ""
+ }
+ fmt.Fprintf(os.Stderr, "go objabi: cannot find %s\n", key)
+ os.Exit(2)
+ }
+ line := data[i:]
+ line = line[bytes.IndexByte(line, '`')+1:]
+ return string(line[:bytes.IndexByte(line, '`')])
+ }
+
+ return find("GOARM"), find("GO386"), find("GOMIPS"), find("GOMIPS64")
+}
+
+func compilers() (CC, CXX string) {
+ data, err := ioutil.ReadFile(filepath.Join(GOROOT, "src/cmd/go/internal/cfg/zdefaultcc.go"))
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "go compilers: %v\n", err)
+ }
+
+ find := func(key string) string {
+ if env := os.Getenv(key); env != "" {
+ return env
+ }
+ fi := bytes.Index(data, []byte("Default"+key+"(goos, goarch string)"))
+ if fi < 0 {
+ fmt.Fprintf(os.Stderr, "go compilers: cannot find %s\n", key)
+ os.Exit(2)
+ }
+ i := bytes.Index(data[fi:], []byte("\treturn "))
+ if i < 0 {
+ fmt.Fprintf(os.Stderr, "go compilers: cannot find %s\n", key)
+ os.Exit(2)
+ }
+ line := data[fi+i:]
+ line = line[bytes.IndexByte(line, '"')+1:]
+ return string(line[:bytes.IndexByte(line, '"')])
+ }
+
+ return find("CC"), find("CXX")
+}
+
func findGOROOT() string {
+ goroot := findGOROOT1()
+ _, err := os.Stat(filepath.Join(goroot, "api/go1.10.txt"))
+ if err != nil {
+ log.SetFlags(0)
+ log.Fatalf("go requires Go 1.10 but VGOROOT=%s is not a Go 1.10 source tree", goroot)
+ }
+ return goroot
+}
+
+func findGOROOT1() string {
+ if env := os.Getenv("VGOROOT"); env != "" {
+ return filepath.Clean(env)
+ }
if env := os.Getenv("GOROOT"); env != "" {
return filepath.Clean(env)
}
def := filepath.Clean(runtime.GOROOT())
diff -u -r ./internal/help/help.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/help/help.go
--- ./internal/help/help.go 2018-07-12 00:17:57.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/help/help.go 2018-07-12 00:03:05.000000000 -0400
@@ -72,6 +72,10 @@
var usageTemplate = `Go is a tool for managing Go source code.
+This is vgo, an experimental go command with support for package versioning.
+Even though you are invoking it as vgo, most of the messages printed will
+still say "go", not "vgo". Sorry.
+
Usage:
go command [arguments]
diff -u -r ./internal/version/version.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/version/version.go
--- ./internal/version/version.go 2018-06-04 09:24:18.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/version/version.go 2018-07-10 16:04:55.000000000 -0400
@@ -10,8 +10,9 @@
"runtime"
"cmd/go/internal/base"
+ "cmd/go/internal/work"
)
var CmdVersion = &base.Command{
Run: runVersion,
UsageLine: "version",
@@ -24,5 +27,5 @@
cmd.Usage()
}
- fmt.Printf("go version %s %s/%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH)
+ fmt.Printf("go version %s %s/%s vgo:%s\n", work.RuntimeVersion, runtime.GOOS, runtime.GOARCH, version)
}
diff -u -r ./internal/work/build.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/work/build.go
--- ./internal/work/build.go 2018-07-12 00:17:57.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/work/build.go 2018-07-10 17:04:18.000000000 -0400
@@ -5,9 +5,11 @@
package work
import (
+ "bytes"
"errors"
"fmt"
"go/build"
+ "io/ioutil"
"os"
"os/exec"
"path"
@@ -274,7 +276,25 @@
var pkgsFilter = func(pkgs []*load.Package) []*load.Package { return pkgs }
-var runtimeVersion = runtime.Version()
+var runtimeVersion = getRuntimeVersion()
+var RuntimeVersion = runtimeVersion
+
+func getRuntimeVersion() string {
+ data, err := ioutil.ReadFile(filepath.Join(cfg.GOROOT, "src/runtime/internal/sys/zversion.go"))
+ if err != nil {
+ base.Fatalf("go: %v", err)
+ }
+ i := bytes.Index(data, []byte("TheVersion = `"))
+ if i < 0 {
+ base.Fatalf("go: cannot find TheVersion")
+ }
+ data = data[i+len("TheVersion = `"):]
+ j := bytes.IndexByte(data, '`')
+ if j < 0 {
+ base.Fatalf("go: cannot find TheVersion")
+ }
+ return string(data[:j])
+}
func runBuild(cmd *base.Command, args []string) {
BuildInit()
diff -u -r ./internal/work/buildid.go /home/bcmills/src/golang.org/x/vgo/vendor/cmd/go/internal/work/buildid.go
--- ./internal/work/buildid.go 2018-09-10 17:07:58.954625955 -0400
+++ /home/bcmills/src/golang.org/x/vgo/vendor/cmd/go/internal/work/buildid.go 2018-09-10 17:18:52.954844647 -0400
@@ -18,7 +18,6 @@
"cmd/go/internal/load"
"cmd/go/internal/str"
"cmd/internal/buildid"
- "cmd/internal/objabi"
)
// Build IDs
@@ -135,6 +134,8 @@
return string(dst[:])
}
+var oldVet = false
+
// toolID returns the unique ID to use for the current copy of the
// named tool (asm, compile, cover, link).
//
@@ -167,6 +168,10 @@
// build setups agree on details like $GOROOT and file name paths, but at least the
// tool IDs do not make it impossible.)
func (b *Builder) toolID(name string) string {
+ if name == "vet" && oldVet {
+ return ""
+ }
+
b.id.Lock()
id := b.toolIDCache[name]
b.id.Unlock()
@@ -191,6 +196,10 @@
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
+ if name == "vet" {
+ oldVet = true
+ return ""
+ }
base.Fatalf("%s: %v\n%s%s", desc, err, stdout.Bytes(), stderr.Bytes())
}
@@ -207,11 +216,6 @@
id = f[2]
}
- // For the compiler, add any experiments.
- if name == "compile" {
- id += " " + objabi.Expstring()
- }
-
b.id.Lock()
b.toolIDCache[name] = id
b.id.Unlock()
diff -u -r ./internal/work/exec.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/work/exec.go
--- ./internal/work/exec.go 2018-07-12 00:17:57.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/work/exec.go 2018-07-12 00:03:05.000000000 -0400
@@ -972,7 +972,7 @@
// TODO(rsc,gri): Try to remove this for Go 1.11.
//
// Disabled 2018-04-20. Let's see if we can do without it.
- // vcfg.SucceedOnTypecheckFailure = cfg.CmdName == "test"
+ vcfg.SucceedOnTypecheckFailure = cfg.CmdName == "test"
js, err := json.MarshalIndent(vcfg, "", "\t")
if err != nil {
diff -u -r ./internal/work/gc.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/work/gc.go
--- ./internal/work/gc.go 2018-07-06 16:52:53.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/internal/work/gc.go 2018-06-27 21:01:27.000000000 -0400
@@ -20,7 +20,6 @@
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/str"
- "cmd/internal/objabi"
"crypto/sha1"
)
@@ -167,11 +166,6 @@
}
}
- // TODO: Test and delete these conditions.
- if objabi.Fieldtrack_enabled != 0 || objabi.Preemptibleloops_enabled != 0 || objabi.Clobberdead_enabled != 0 {
- canDashC = false
- }
-
if !canDashC {
return 1
}
diff -u -r ./main.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/main.go
--- ./main.go 2018-07-12 00:17:57.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/main.go 2018-07-10 16:04:55.000000000 -0400
@@ -4,7 +4,7 @@
//go:generate ./mkalldocs.sh
-package main
+package Main
import (
"flag"
@@ -74,7 +74,7 @@
}
}
-func main() {
+func Main() {
_ = go11tag
flag.Usage = base.Usage
flag.Parse()
diff -u -r ./note_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/note_test.go
--- ./note_test.go 2018-07-12 00:14:08.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/note_test.go 2018-07-11 23:25:10.000000000 -0400
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-package main_test
+package Main_test
import (
"bytes"
diff -u -r ./proxy_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/proxy_test.go
--- ./proxy_test.go 2018-07-12 00:14:08.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/proxy_test.go 2018-07-11 23:25:10.000000000 -0400
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-package main_test
+package Main_test
import (
"bytes"
diff -u -r ./vendor_test.go /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/vendor_test.go
--- ./vendor_test.go 2018-07-12 00:14:08.000000000 -0400
+++ /Users/rsc/src/golang.org/x/vgo/vendor/cmd/go/vendor_test.go 2018-07-11 23:25:10.000000000 -0400
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-package main_test
+package Main_test
import (
"bytes"
|
vgo | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vulnerable.go | // Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file exists to keep the github.com/miekg/dns entry in go.mod.
//go:build never
package never
import _ "github.com/miekg/dns"
|
race | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/race/race.go | package race
const Enabled = false
|
singleflight | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/singleflight/singleflight_test.go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package singleflight
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestDo(t *testing.T) {
var g Group
v, err, _ := g.Do("key", func() (interface{}, error) {
return "bar", nil
})
if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want {
t.Errorf("Do = %v; want %v", got, want)
}
if err != nil {
t.Errorf("Do error = %v", err)
}
}
func TestDoErr(t *testing.T) {
var g Group
someErr := errors.New("Some error")
v, err, _ := g.Do("key", func() (interface{}, error) {
return nil, someErr
})
if err != someErr {
t.Errorf("Do error = %v; want someErr %v", err, someErr)
}
if v != nil {
t.Errorf("unexpected non-nil value %#v", v)
}
}
func TestDoDupSuppress(t *testing.T) {
var g Group
var wg1, wg2 sync.WaitGroup
c := make(chan string, 1)
var calls int32
fn := func() (interface{}, error) {
if atomic.AddInt32(&calls, 1) == 1 {
// First invocation.
wg1.Done()
}
v := <-c
c <- v // pump; make available for any future calls
time.Sleep(10 * time.Millisecond) // let more goroutines enter Do
return v, nil
}
const n = 10
wg1.Add(1)
for i := 0; i < n; i++ {
wg1.Add(1)
wg2.Add(1)
go func() {
defer wg2.Done()
wg1.Done()
v, err, _ := g.Do("key", fn)
if err != nil {
t.Errorf("Do error: %v", err)
return
}
if s, _ := v.(string); s != "bar" {
t.Errorf("Do = %T %v; want %q", v, v, "bar")
}
}()
}
wg1.Wait()
// At least one goroutine is in fn now and all of them have at
// least reached the line before the Do.
c <- "bar"
wg2.Wait()
if got := atomic.LoadInt32(&calls); got <= 0 || got >= n {
t.Errorf("number of calls = %d; want over 0 and less than %d", got, n)
}
}
|
singleflight | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/singleflight/singleflight.go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package singleflight provides a duplicate function call suppression
// mechanism.
package singleflight
import "sync"
// call is an in-flight or completed singleflight.Do call
type call struct {
wg sync.WaitGroup
// These fields are written once before the WaitGroup is done
// and are only read after the WaitGroup is done.
val interface{}
err error
// These fields are read and written with the singleflight
// mutex held before the WaitGroup is done, and are read but
// not written after the WaitGroup is done.
dups int
chans []chan<- Result
}
// Group represents a class of work and forms a namespace in
// which units of work can be executed with duplicate suppression.
type Group struct {
mu sync.Mutex // protects m
m map[string]*call // lazily initialized
}
// Result holds the results of Do, so they can be passed
// on a channel.
type Result struct {
Val interface{}
Err error
Shared bool
}
// Do executes and returns the results of the given function, making
// sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results.
// The return value shared indicates whether v was given to multiple callers.
func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
g.mu.Unlock()
c.wg.Wait()
return c.val, c.err, true
}
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
g.doCall(c, key, fn)
return c.val, c.err, c.dups > 0
}
// DoChan is like Do but returns a channel that will receive the
// results when they are ready. The second result is true if the function
// will eventually be called, false if it will not (because there is
// a pending request with this key).
func (g *Group) DoChan(key string, fn func() (interface{}, error)) (<-chan Result, bool) {
ch := make(chan Result, 1)
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
c.chans = append(c.chans, ch)
g.mu.Unlock()
return ch, false
}
c := &call{chans: []chan<- Result{ch}}
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
go g.doCall(c, key, fn)
return ch, true
}
// doCall handles the single call for a key.
func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
c.val, c.err = fn()
c.wg.Done()
g.mu.Lock()
delete(g.m, key)
for _, ch := range c.chans {
ch <- Result{c.val, c.err, c.dups > 0}
}
g.mu.Unlock()
}
// Forget tells the singleflight to forget about a key. Future calls
// to Do for this key will call the function rather than waiting for
// an earlier call to complete.
func (g *Group) Forget(key string) {
g.mu.Lock()
delete(g.m, key)
g.mu.Unlock()
}
|
testenv | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/testenv/testenv_notwin.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !windows
package testenv
import (
"runtime"
)
func hasSymlink() (ok bool, reason string) {
switch runtime.GOOS {
case "android", "nacl", "plan9":
return false, ""
}
return true, ""
}
|
testenv | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/testenv/testenv.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package testenv provides information about what functionality
// is available in different testing environments run by the Go team.
//
// It is an internal package because these details are specific
// to the Go team's test setup (on build.golang.org) and not
// fundamental to tests in general.
package testenv
import (
"errors"
"flag"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
)
// Builder reports the name of the builder running this test
// (for example, "linux-amd64" or "windows-386-gce").
// If the test is not running on the build infrastructure,
// Builder returns the empty string.
func Builder() string {
return os.Getenv("GO_BUILDER_NAME")
}
// HasGoBuild reports whether the current system can build programs with ``go build''
// and then run them with os.StartProcess or exec.Command.
func HasGoBuild() bool {
if os.Getenv("GO_GCFLAGS") != "" {
// It's too much work to require every caller of the go command
// to pass along "-gcflags="+os.Getenv("GO_GCFLAGS").
// For now, if $GO_GCFLAGS is set, report that we simply can't
// run go build.
return false
}
switch runtime.GOOS {
case "android", "nacl":
return false
case "darwin":
if strings.HasPrefix(runtime.GOARCH, "arm") {
return false
}
}
return true
}
// MustHaveGoBuild checks that the current system can build programs with ``go build''
// and then run them with os.StartProcess or exec.Command.
// If not, MustHaveGoBuild calls t.Skip with an explanation.
func MustHaveGoBuild(t testing.TB) {
if os.Getenv("GO_GCFLAGS") != "" {
t.Skipf("skipping test: 'go build' not compatible with setting $GO_GCFLAGS")
}
if !HasGoBuild() {
t.Skipf("skipping test: 'go build' not available on %s/%s", runtime.GOOS, runtime.GOARCH)
}
}
// HasGoRun reports whether the current system can run programs with ``go run.''
func HasGoRun() bool {
// For now, having go run and having go build are the same.
return HasGoBuild()
}
// MustHaveGoRun checks that the current system can run programs with ``go run.''
// If not, MustHaveGoRun calls t.Skip with an explanation.
func MustHaveGoRun(t testing.TB) {
if !HasGoRun() {
t.Skipf("skipping test: 'go run' not available on %s/%s", runtime.GOOS, runtime.GOARCH)
}
}
// GoToolPath reports the path to the Go tool.
// It is a convenience wrapper around GoTool.
// If the tool is unavailable GoToolPath calls t.Skip.
// If the tool should be available and isn't, GoToolPath calls t.Fatal.
func GoToolPath(t testing.TB) string {
MustHaveGoBuild(t)
path, err := GoTool()
if err != nil {
t.Fatal(err)
}
return path
}
// GoTool reports the path to the Go tool.
func GoTool() (string, error) {
if !HasGoBuild() {
return "", errors.New("platform cannot run go tool")
}
var exeSuffix string
if runtime.GOOS == "windows" {
exeSuffix = ".exe"
}
path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
if _, err := os.Stat(path); err == nil {
return path, nil
}
goBin, err := exec.LookPath("go" + exeSuffix)
if err != nil {
return "", errors.New("cannot find go tool: " + err.Error())
}
return goBin, nil
}
// HasExec reports whether the current system can start new processes
// using os.StartProcess or (more commonly) exec.Command.
func HasExec() bool {
switch runtime.GOOS {
case "nacl":
return false
case "darwin":
if strings.HasPrefix(runtime.GOARCH, "arm") {
return false
}
}
return true
}
// HasSrc reports whether the entire source tree is available under GOROOT.
func HasSrc() bool {
switch runtime.GOOS {
case "nacl":
return false
case "darwin":
if strings.HasPrefix(runtime.GOARCH, "arm") {
return false
}
}
return true
}
// MustHaveExec checks that the current system can start new processes
// using os.StartProcess or (more commonly) exec.Command.
// If not, MustHaveExec calls t.Skip with an explanation.
func MustHaveExec(t testing.TB) {
if !HasExec() {
t.Skipf("skipping test: cannot exec subprocess on %s/%s", runtime.GOOS, runtime.GOARCH)
}
}
// HasExternalNetwork reports whether the current system can use
// external (non-localhost) networks.
func HasExternalNetwork() bool {
return !testing.Short()
}
// MustHaveExternalNetwork checks that the current system can use
// external (non-localhost) networks.
// If not, MustHaveExternalNetwork calls t.Skip with an explanation.
func MustHaveExternalNetwork(t testing.TB) {
if testing.Short() {
t.Skipf("skipping test: no external network in -short mode")
}
}
var haveCGO bool
// HasCGO reports whether the current system can use cgo.
func HasCGO() bool {
return haveCGO
}
// MustHaveCGO calls t.Skip if cgo is not available.
func MustHaveCGO(t testing.TB) {
if !haveCGO {
t.Skipf("skipping test: no cgo")
}
}
// HasSymlink reports whether the current system can use os.Symlink.
func HasSymlink() bool {
ok, _ := hasSymlink()
return ok
}
// MustHaveSymlink reports whether the current system can use os.Symlink.
// If not, MustHaveSymlink calls t.Skip with an explanation.
func MustHaveSymlink(t testing.TB) {
ok, reason := hasSymlink()
if !ok {
t.Skipf("skipping test: cannot make symlinks on %s/%s%s", runtime.GOOS, runtime.GOARCH, reason)
}
}
// HasLink reports whether the current system can use os.Link.
func HasLink() bool {
// From Android release M (Marshmallow), hard linking files is blocked
// and an attempt to call link() on a file will return EACCES.
// - https://code.google.com/p/android-developer-preview/issues/detail?id=3150
return runtime.GOOS != "plan9" && runtime.GOOS != "android"
}
// MustHaveLink reports whether the current system can use os.Link.
// If not, MustHaveLink calls t.Skip with an explanation.
func MustHaveLink(t testing.TB) {
if !HasLink() {
t.Skipf("skipping test: hardlinks are not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
}
}
var flaky = flag.Bool("flaky", false, "run known-flaky tests too")
func SkipFlaky(t testing.TB, issue int) {
t.Helper()
if !*flaky {
t.Skipf("skipping known flaky test without the -flaky flag; see golang.org/issue/%d", issue)
}
}
func SkipFlakyNet(t testing.TB) {
t.Helper()
if v, _ := strconv.ParseBool(os.Getenv("GO_BUILDER_FLAKY_NET")); v {
t.Skip("skipping test on builder known to have frequent network failures")
}
}
// CleanCmdEnv will fill cmd.Env with the environment, excluding certain
// variables that could modify the behavior of the Go tools such as
// GODEBUG and GOTRACEBACK.
func CleanCmdEnv(cmd *exec.Cmd) *exec.Cmd {
if cmd.Env != nil {
panic("environment already set")
}
for _, env := range os.Environ() {
// Exclude GODEBUG from the environment to prevent its output
// from breaking tests that are trying to parse other command output.
if strings.HasPrefix(env, "GODEBUG=") {
continue
}
// Exclude GOTRACEBACK for the same reason.
if strings.HasPrefix(env, "GOTRACEBACK=") {
continue
}
cmd.Env = append(cmd.Env, env)
}
return cmd
}
|
testenv | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/testenv/testenv_windows.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package testenv
import (
"io/ioutil"
"os"
"path/filepath"
"sync"
"syscall"
)
var symlinkOnce sync.Once
var winSymlinkErr error
func initWinHasSymlink() {
tmpdir, err := ioutil.TempDir("", "symtest")
if err != nil {
panic("failed to create temp directory: " + err.Error())
}
defer os.RemoveAll(tmpdir)
err = os.Symlink("target", filepath.Join(tmpdir, "symlink"))
if err != nil {
err = err.(*os.LinkError).Err
switch err {
case syscall.EWINDOWS, syscall.ERROR_PRIVILEGE_NOT_HELD:
winSymlinkErr = err
}
}
}
func hasSymlink() (ok bool, reason string) {
symlinkOnce.Do(initWinHasSymlink)
switch winSymlinkErr {
case nil:
return true, ""
case syscall.EWINDOWS:
return false, ": symlinks are not supported on your version of Windows"
case syscall.ERROR_PRIVILEGE_NOT_HELD:
return false, ": you don't have enough privileges to create symlinks"
}
return false, ""
}
|
testenv | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/internal/testenv/testenv_cgo.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build cgo
package testenv
func init() {
haveCGO = true
}
|
browser | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/browser/browser.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package browser provides utilities for interacting with users' browsers.
package browser
import (
"os"
"os/exec"
"runtime"
"time"
)
// Commands returns a list of possible commands to use to open a url.
func Commands() [][]string {
var cmds [][]string
if exe := os.Getenv("BROWSER"); exe != "" {
cmds = append(cmds, []string{exe})
}
switch runtime.GOOS {
case "darwin":
cmds = append(cmds, []string{"/usr/bin/open"})
case "windows":
cmds = append(cmds, []string{"cmd", "/c", "start"})
default:
if os.Getenv("DISPLAY") != "" {
// xdg-open is only for use in a desktop environment.
cmds = append(cmds, []string{"xdg-open"})
}
}
cmds = append(cmds,
[]string{"chrome"},
[]string{"google-chrome"},
[]string{"chromium"},
[]string{"firefox"},
)
return cmds
}
// Open tries to open url in a browser and reports whether it succeeded.
func Open(url string) bool {
for _, args := range Commands() {
cmd := exec.Command(args[0], append(args[1:], url)...)
if cmd.Start() == nil && appearsSuccessful(cmd, 3*time.Second) {
return true
}
}
return false
}
// appearsSuccessful reports whether the command appears to have run successfully.
// If the command runs longer than the timeout, it's deemed successful.
// If the command runs within the timeout, it's deemed successful if it exited cleanly.
func appearsSuccessful(cmd *exec.Cmd, timeout time.Duration) bool {
errc := make(chan error, 1)
go func() {
errc <- cmd.Wait()
}()
select {
case <-time.After(timeout):
return true
case err := <-errc:
return err == nil
}
}
|
test2json | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/test2json_test.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test2json
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"path/filepath"
"reflect"
"strings"
"testing"
"unicode/utf8"
)
var update = flag.Bool("update", false, "rewrite testdata/*.json files")
func TestGolden(t *testing.T) {
files, err := filepath.Glob("testdata/*.test")
if err != nil {
t.Fatal(err)
}
for _, file := range files {
name := strings.TrimSuffix(filepath.Base(file), ".test")
t.Run(name, func(t *testing.T) {
orig, err := ioutil.ReadFile(file)
if err != nil {
t.Fatal(err)
}
// Test one line written to c at a time.
// Assume that's the most likely to be handled correctly.
var buf bytes.Buffer
c := NewConverter(&buf, "", 0)
in := append([]byte{}, orig...)
for _, line := range bytes.SplitAfter(in, []byte("\n")) {
writeAndKill(c, line)
}
c.Close()
if *update {
js := strings.TrimSuffix(file, ".test") + ".json"
t.Logf("rewriting %s", js)
if err := ioutil.WriteFile(js, buf.Bytes(), 0666); err != nil {
t.Fatal(err)
}
return
}
want, err := ioutil.ReadFile(strings.TrimSuffix(file, ".test") + ".json")
if err != nil {
t.Fatal(err)
}
diffJSON(t, buf.Bytes(), want)
if t.Failed() {
// If the line-at-a-time conversion fails, no point testing boundary conditions.
return
}
// Write entire input in bulk.
t.Run("bulk", func(t *testing.T) {
buf.Reset()
c = NewConverter(&buf, "", 0)
in = append([]byte{}, orig...)
writeAndKill(c, in)
c.Close()
diffJSON(t, buf.Bytes(), want)
})
// Write 2 bytes at a time on even boundaries.
t.Run("even2", func(t *testing.T) {
buf.Reset()
c = NewConverter(&buf, "", 0)
in = append([]byte{}, orig...)
for i := 0; i < len(in); i += 2 {
if i+2 <= len(in) {
writeAndKill(c, in[i:i+2])
} else {
writeAndKill(c, in[i:])
}
}
c.Close()
diffJSON(t, buf.Bytes(), want)
})
// Write 2 bytes at a time on odd boundaries.
t.Run("odd2", func(t *testing.T) {
buf.Reset()
c = NewConverter(&buf, "", 0)
in = append([]byte{}, orig...)
if len(in) > 0 {
writeAndKill(c, in[:1])
}
for i := 1; i < len(in); i += 2 {
if i+2 <= len(in) {
writeAndKill(c, in[i:i+2])
} else {
writeAndKill(c, in[i:])
}
}
c.Close()
diffJSON(t, buf.Bytes(), want)
})
// Test with very small output buffers, to check that
// UTF8 sequences are not broken up.
for b := 5; b <= 8; b++ {
t.Run(fmt.Sprintf("tiny%d", b), func(t *testing.T) {
oldIn := inBuffer
oldOut := outBuffer
defer func() {
inBuffer = oldIn
outBuffer = oldOut
}()
inBuffer = 64
outBuffer = b
buf.Reset()
c = NewConverter(&buf, "", 0)
in = append([]byte{}, orig...)
writeAndKill(c, in)
c.Close()
diffJSON(t, buf.Bytes(), want)
})
}
})
}
}
// writeAndKill writes b to w and then fills b with Zs.
// The filling makes sure that if w is holding onto b for
// future use, that future use will have obviously wrong data.
func writeAndKill(w io.Writer, b []byte) {
w.Write(b)
for i := range b {
b[i] = 'Z'
}
}
// diffJSON diffs the stream we have against the stream we want
// and fails the test with a useful message if they don't match.
func diffJSON(t *testing.T, have, want []byte) {
t.Helper()
type event map[string]interface{}
// Parse into events, one per line.
parseEvents := func(b []byte) ([]event, []string) {
t.Helper()
var events []event
var lines []string
for _, line := range bytes.SplitAfter(b, []byte("\n")) {
if len(line) > 0 {
line = bytes.TrimSpace(line)
var e event
err := json.Unmarshal(line, &e)
if err != nil {
t.Errorf("unmarshal %s: %v", b, err)
continue
}
events = append(events, e)
lines = append(lines, string(line))
}
}
return events, lines
}
haveEvents, haveLines := parseEvents(have)
wantEvents, wantLines := parseEvents(want)
if t.Failed() {
return
}
// Make sure the events we have match the events we want.
// At each step we're matching haveEvents[i] against wantEvents[j].
// i and j can move independently due to choices about exactly
// how to break up text in "output" events.
i := 0
j := 0
// Fail reports a failure at the current i,j and stops the test.
// It shows the events around the current positions,
// with the current positions marked.
fail := func() {
var buf bytes.Buffer
show := func(i int, lines []string) {
for k := -2; k < 5; k++ {
marker := ""
if k == 0 {
marker = "» "
}
if 0 <= i+k && i+k < len(lines) {
fmt.Fprintf(&buf, "\t%s%s\n", marker, lines[i+k])
}
}
if i >= len(lines) {
// show marker after end of input
fmt.Fprintf(&buf, "\t» \n")
}
}
fmt.Fprintf(&buf, "have:\n")
show(i, haveLines)
fmt.Fprintf(&buf, "want:\n")
show(j, wantLines)
t.Fatal(buf.String())
}
var outputTest string // current "Test" key in "output" events
var wantOutput, haveOutput string // collected "Output" of those events
// getTest returns the "Test" setting, or "" if it is missing.
getTest := func(e event) string {
s, _ := e["Test"].(string)
return s
}
// checkOutput collects output from the haveEvents for the current outputTest
// and then checks that the collected output matches the wanted output.
checkOutput := func() {
for i < len(haveEvents) && haveEvents[i]["Action"] == "output" && getTest(haveEvents[i]) == outputTest {
haveOutput += haveEvents[i]["Output"].(string)
i++
}
if haveOutput != wantOutput {
t.Errorf("output mismatch for Test=%q:\nhave %q\nwant %q", outputTest, haveOutput, wantOutput)
fail()
}
haveOutput = ""
wantOutput = ""
}
// Walk through wantEvents matching against haveEvents.
for j = range wantEvents {
e := wantEvents[j]
if e["Action"] == "output" && getTest(e) == outputTest {
wantOutput += e["Output"].(string)
continue
}
checkOutput()
if e["Action"] == "output" {
outputTest = getTest(e)
wantOutput += e["Output"].(string)
continue
}
if i >= len(haveEvents) {
t.Errorf("early end of event stream: missing event")
fail()
}
if !reflect.DeepEqual(haveEvents[i], e) {
t.Errorf("events out of sync")
fail()
}
i++
}
checkOutput()
if i < len(haveEvents) {
t.Errorf("extra events in stream")
fail()
}
}
func TestTrimUTF8(t *testing.T) {
s := "hello α ☺ 😂 world" // α is 2-byte, ☺ is 3-byte, 😂 is 4-byte
b := []byte(s)
for i := 0; i < len(s); i++ {
j := trimUTF8(b[:i])
u := string([]rune(s[:j])) + string([]rune(s[j:]))
if u != s {
t.Errorf("trimUTF8(%q) = %d (-%d), not at boundary (split: %q %q)", s[:i], j, i-j, s[:j], s[j:])
}
if utf8.FullRune(b[j:i]) {
t.Errorf("trimUTF8(%q) = %d (-%d), too early (missed: %q)", s[:j], j, i-j, s[j:i])
}
}
}
|
test2json | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/test2json.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package test2json implements conversion of test binary output to JSON.
// It is used by cmd/test2json and cmd/go.
//
// See the cmd/test2json documentation for details of the JSON encoding.
package test2json
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
// Mode controls details of the conversion.
type Mode int
const (
Timestamp Mode = 1 << iota // include Time in events
)
// event is the JSON struct we emit.
type event struct {
Time *time.Time `json:",omitempty"`
Action string
Package string `json:",omitempty"`
Test string `json:",omitempty"`
Elapsed *float64 `json:",omitempty"`
Output *textBytes `json:",omitempty"`
}
// textBytes is a hack to get JSON to emit a []byte as a string
// without actually copying it to a string.
// It implements encoding.TextMarshaler, which returns its text form as a []byte,
// and then json encodes that text form as a string (which was our goal).
type textBytes []byte
func (b textBytes) MarshalText() ([]byte, error) { return b, nil }
// A converter holds the state of a test-to-JSON conversion.
// It implements io.WriteCloser; the caller writes test output in,
// and the converter writes JSON output to w.
type converter struct {
w io.Writer // JSON output stream
pkg string // package to name in events
mode Mode // mode bits
start time.Time // time converter started
testName string // name of current test, for output attribution
report []*event // pending test result reports (nested for subtests)
result string // overall test result if seen
input lineBuffer // input buffer
output lineBuffer // output buffer
}
// inBuffer and outBuffer are the input and output buffer sizes.
// They're variables so that they can be reduced during testing.
//
// The input buffer needs to be able to hold any single test
// directive line we want to recognize, like:
//
// <many spaces> --- PASS: very/nested/s/u/b/t/e/s/t
//
// If anyone reports a test directive line > 4k not working, it will
// be defensible to suggest they restructure their test or test names.
//
// The output buffer must be >= utf8.UTFMax, so that it can
// accumulate any single UTF8 sequence. Lines that fit entirely
// within the output buffer are emitted in single output events.
// Otherwise they are split into multiple events.
// The output buffer size therefore limits the size of the encoding
// of a single JSON output event. 1k seems like a reasonable balance
// between wanting to avoid splitting an output line and not wanting to
// generate enormous output events.
var (
inBuffer = 4096
outBuffer = 1024
)
// NewConverter returns a "test to json" converter.
// Writes on the returned writer are written as JSON to w,
// with minimal delay.
//
// The writes to w are whole JSON events ending in \n,
// so that it is safe to run multiple tests writing to multiple converters
// writing to a single underlying output stream w.
// As long as the underlying output w can handle concurrent writes
// from multiple goroutines, the result will be a JSON stream
// describing the relative ordering of execution in all the concurrent tests.
//
// The mode flag adjusts the behavior of the converter.
// Passing ModeTime includes event timestamps and elapsed times.
//
// The pkg string, if present, specifies the import path to
// report in the JSON stream.
func NewConverter(w io.Writer, pkg string, mode Mode) io.WriteCloser {
c := new(converter)
*c = converter{
w: w,
pkg: pkg,
mode: mode,
start: time.Now(),
input: lineBuffer{
b: make([]byte, 0, inBuffer),
line: c.handleInputLine,
part: c.output.write,
},
output: lineBuffer{
b: make([]byte, 0, outBuffer),
line: c.writeOutputEvent,
part: c.writeOutputEvent,
},
}
return c
}
// Write writes the test input to the converter.
func (c *converter) Write(b []byte) (int, error) {
c.input.write(b)
return len(b), nil
}
var (
bigPass = []byte("PASS\n")
bigFail = []byte("FAIL\n")
updates = [][]byte{
[]byte("=== RUN "),
[]byte("=== PAUSE "),
[]byte("=== CONT "),
}
reports = [][]byte{
[]byte("--- PASS: "),
[]byte("--- FAIL: "),
[]byte("--- SKIP: "),
[]byte("--- BENCH: "),
}
fourSpace = []byte(" ")
skipLinePrefix = []byte("? \t")
skipLineSuffix = []byte("\t[no test files]\n")
)
// handleInputLine handles a single whole test output line.
// It must write the line to c.output but may choose to do so
// before or after emitting other events.
func (c *converter) handleInputLine(line []byte) {
// Final PASS or FAIL.
if bytes.Equal(line, bigPass) || bytes.Equal(line, bigFail) {
c.flushReport(0)
c.output.write(line)
if bytes.Equal(line, bigPass) {
c.result = "pass"
} else {
c.result = "fail"
}
return
}
// Special case for entirely skipped test binary: "? \tpkgname\t[no test files]\n" is only line.
// Report it as plain output but remember to say skip in the final summary.
if bytes.HasPrefix(line, skipLinePrefix) && bytes.HasSuffix(line, skipLineSuffix) && len(c.report) == 0 {
c.result = "skip"
}
// "=== RUN "
// "=== PAUSE "
// "=== CONT "
origLine := line
ok := false
indent := 0
for _, magic := range updates {
if bytes.HasPrefix(line, magic) {
ok = true
break
}
}
if !ok {
// "--- PASS: "
// "--- FAIL: "
// "--- SKIP: "
// "--- BENCH: "
// but possibly indented.
for bytes.HasPrefix(line, fourSpace) {
line = line[4:]
indent++
}
for _, magic := range reports {
if bytes.HasPrefix(line, magic) {
ok = true
break
}
}
}
if !ok {
// Not a special test output line.
c.output.write(origLine)
return
}
// Parse out action and test name.
i := bytes.IndexByte(line, ':') + 1
if i == 0 {
i = len(updates[0])
}
action := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(string(line[4:i])), ":"))
name := strings.TrimSpace(string(line[i:]))
e := &event{Action: action}
if line[0] == '-' { // PASS or FAIL report
// Parse out elapsed time.
if i := strings.Index(name, " ("); i >= 0 {
if strings.HasSuffix(name, "s)") {
t, err := strconv.ParseFloat(name[i+2:len(name)-2], 64)
if err == nil {
if c.mode&Timestamp != 0 {
e.Elapsed = &t
}
}
}
name = name[:i]
}
if len(c.report) < indent {
// Nested deeper than expected.
// Treat this line as plain output.
c.output.write(origLine)
return
}
// Flush reports at this indentation level or deeper.
c.flushReport(indent)
e.Test = name
c.testName = name
c.report = append(c.report, e)
c.output.write(origLine)
return
}
// === update.
// Finish any pending PASS/FAIL reports.
c.flushReport(0)
c.testName = name
if action == "pause" {
// For a pause, we want to write the pause notification before
// delivering the pause event, just so it doesn't look like the test
// is generating output immediately after being paused.
c.output.write(origLine)
}
c.writeEvent(e)
if action != "pause" {
c.output.write(origLine)
}
return
}
// flushReport flushes all pending PASS/FAIL reports at levels >= depth.
func (c *converter) flushReport(depth int) {
c.testName = ""
for len(c.report) > depth {
e := c.report[len(c.report)-1]
c.report = c.report[:len(c.report)-1]
c.writeEvent(e)
}
}
// Close marks the end of the go test output.
// It flushes any pending input and then output (only partial lines at this point)
// and then emits the final overall package-level pass/fail event.
func (c *converter) Close() error {
c.input.flush()
c.output.flush()
e := &event{Action: "fail"}
if c.result != "" {
e.Action = c.result
}
if c.mode&Timestamp != 0 {
dt := time.Since(c.start).Round(1 * time.Millisecond).Seconds()
e.Elapsed = &dt
}
c.writeEvent(e)
return nil
}
// writeOutputEvent writes a single output event with the given bytes.
func (c *converter) writeOutputEvent(out []byte) {
c.writeEvent(&event{
Action: "output",
Output: (*textBytes)(&out),
})
}
// writeEvent writes a single event.
// It adds the package, time (if requested), and test name (if needed).
func (c *converter) writeEvent(e *event) {
e.Package = c.pkg
if c.mode&Timestamp != 0 {
t := time.Now()
e.Time = &t
}
if e.Test == "" {
e.Test = c.testName
}
js, err := json.Marshal(e)
if err != nil {
// Should not happen - event is valid for json.Marshal.
c.w.Write([]byte(fmt.Sprintf("testjson internal error: %v\n", err)))
return
}
js = append(js, '\n')
c.w.Write(js)
}
// A lineBuffer is an I/O buffer that reacts to writes by invoking
// input-processing callbacks on whole lines or (for long lines that
// have been split) line fragments.
//
// It should be initialized with b set to a buffer of length 0 but non-zero capacity,
// and line and part set to the desired input processors.
// The lineBuffer will call line(x) for any whole line x (including the final newline)
// that fits entirely in cap(b). It will handle input lines longer than cap(b) by
// calling part(x) for sections of the line. The line will be split at UTF8 boundaries,
// and the final call to part for a long line includes the final newline.
type lineBuffer struct {
b []byte // buffer
mid bool // whether we're in the middle of a long line
line func([]byte) // line callback
part func([]byte) // partial line callback
}
// write writes b to the buffer.
func (l *lineBuffer) write(b []byte) {
for len(b) > 0 {
// Copy what we can into b.
m := copy(l.b[len(l.b):cap(l.b)], b)
l.b = l.b[:len(l.b)+m]
b = b[m:]
// Process lines in b.
i := 0
for i < len(l.b) {
j := bytes.IndexByte(l.b[i:], '\n')
if j < 0 {
if !l.mid {
if j := bytes.IndexByte(l.b[i:], '\t'); j >= 0 {
if isBenchmarkName(bytes.TrimRight(l.b[i:i+j], " ")) {
l.part(l.b[i : i+j+1])
l.mid = true
i += j + 1
}
}
}
break
}
e := i + j + 1
if l.mid {
// Found the end of a partial line.
l.part(l.b[i:e])
l.mid = false
} else {
// Found a whole line.
l.line(l.b[i:e])
}
i = e
}
// Whatever's left in l.b is a line fragment.
if i == 0 && len(l.b) == cap(l.b) {
// The whole buffer is a fragment.
// Emit it as the beginning (or continuation) of a partial line.
t := trimUTF8(l.b)
l.part(l.b[:t])
l.b = l.b[:copy(l.b, l.b[t:])]
l.mid = true
}
// There's room for more input.
// Slide it down in hope of completing the line.
if i > 0 {
l.b = l.b[:copy(l.b, l.b[i:])]
}
}
}
// flush flushes the line buffer.
func (l *lineBuffer) flush() {
if len(l.b) > 0 {
// Must be a line without a \n, so a partial line.
l.part(l.b)
l.b = l.b[:0]
}
}
var benchmark = []byte("Benchmark")
// isBenchmarkName reports whether b is a valid benchmark name
// that might appear as the first field in a benchmark result line.
func isBenchmarkName(b []byte) bool {
if !bytes.HasPrefix(b, benchmark) {
return false
}
if len(b) == len(benchmark) { // just "Benchmark"
return true
}
r, _ := utf8.DecodeRune(b[len(benchmark):])
return !unicode.IsLower(r)
}
// trimUTF8 returns a length t as close to len(b) as possible such that b[:t]
// does not end in the middle of a possibly-valid UTF-8 sequence.
//
// If a large text buffer must be split before position i at the latest,
// splitting at position trimUTF(b[:i]) avoids splitting a UTF-8 sequence.
func trimUTF8(b []byte) int {
// Scan backward to find non-continuation byte.
for i := 1; i < utf8.UTFMax && i <= len(b); i++ {
if c := b[len(b)-i]; c&0xc0 != 0x80 {
switch {
case c&0xe0 == 0xc0:
if i < 2 {
return len(b) - i
}
case c&0xf0 == 0xe0:
if i < 3 {
return len(b) - i
}
case c&0xf8 == 0xf0:
if i < 4 {
return len(b) - i
}
}
break
}
}
return len(b)
}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/benchshort.test | # This file ends in an early EOF to trigger the Benchmark prefix test,
# which only happens when a benchmark prefix is seen ahead of the \n.
# Normally that's due to the benchmark running and the \n coming later,
# but to avoid questions of timing, we just use a file with no \n at all.
BenchmarkFoo 10000 early EOF |
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/vet.json | {"Action":"run","Test":"TestVet"}
{"Action":"output","Test":"TestVet","Output":"=== RUN TestVet\n"}
{"Action":"output","Test":"TestVet","Output":"=== PAUSE TestVet\n"}
{"Action":"pause","Test":"TestVet"}
{"Action":"run","Test":"TestVetAsm"}
{"Action":"output","Test":"TestVetAsm","Output":"=== RUN TestVetAsm\n"}
{"Action":"output","Test":"TestVetAsm","Output":"=== PAUSE TestVetAsm\n"}
{"Action":"pause","Test":"TestVetAsm"}
{"Action":"run","Test":"TestVetDirs"}
{"Action":"output","Test":"TestVetDirs","Output":"=== RUN TestVetDirs\n"}
{"Action":"output","Test":"TestVetDirs","Output":"=== PAUSE TestVetDirs\n"}
{"Action":"pause","Test":"TestVetDirs"}
{"Action":"run","Test":"TestTags"}
{"Action":"output","Test":"TestTags","Output":"=== RUN TestTags\n"}
{"Action":"output","Test":"TestTags","Output":"=== PAUSE TestTags\n"}
{"Action":"pause","Test":"TestTags"}
{"Action":"run","Test":"TestVetVerbose"}
{"Action":"output","Test":"TestVetVerbose","Output":"=== RUN TestVetVerbose\n"}
{"Action":"output","Test":"TestVetVerbose","Output":"=== PAUSE TestVetVerbose\n"}
{"Action":"pause","Test":"TestVetVerbose"}
{"Action":"cont","Test":"TestVet"}
{"Action":"output","Test":"TestVet","Output":"=== CONT TestVet\n"}
{"Action":"cont","Test":"TestTags"}
{"Action":"output","Test":"TestTags","Output":"=== CONT TestTags\n"}
{"Action":"cont","Test":"TestVetVerbose"}
{"Action":"output","Test":"TestVetVerbose","Output":"=== CONT TestVetVerbose\n"}
{"Action":"run","Test":"TestTags/testtag"}
{"Action":"output","Test":"TestTags/testtag","Output":"=== RUN TestTags/testtag\n"}
{"Action":"output","Test":"TestTags/testtag","Output":"=== PAUSE TestTags/testtag\n"}
{"Action":"pause","Test":"TestTags/testtag"}
{"Action":"cont","Test":"TestVetDirs"}
{"Action":"output","Test":"TestVetDirs","Output":"=== CONT TestVetDirs\n"}
{"Action":"cont","Test":"TestVetAsm"}
{"Action":"output","Test":"TestVetAsm","Output":"=== CONT TestVetAsm\n"}
{"Action":"run","Test":"TestVet/0"}
{"Action":"output","Test":"TestVet/0","Output":"=== RUN TestVet/0\n"}
{"Action":"output","Test":"TestVet/0","Output":"=== PAUSE TestVet/0\n"}
{"Action":"pause","Test":"TestVet/0"}
{"Action":"run","Test":"TestVet/1"}
{"Action":"output","Test":"TestVet/1","Output":"=== RUN TestVet/1\n"}
{"Action":"output","Test":"TestVet/1","Output":"=== PAUSE TestVet/1\n"}
{"Action":"pause","Test":"TestVet/1"}
{"Action":"run","Test":"TestVet/2"}
{"Action":"output","Test":"TestVet/2","Output":"=== RUN TestVet/2\n"}
{"Action":"output","Test":"TestVet/2","Output":"=== PAUSE TestVet/2\n"}
{"Action":"pause","Test":"TestVet/2"}
{"Action":"run","Test":"TestVet/3"}
{"Action":"output","Test":"TestVet/3","Output":"=== RUN TestVet/3\n"}
{"Action":"output","Test":"TestVet/3","Output":"=== PAUSE TestVet/3\n"}
{"Action":"pause","Test":"TestVet/3"}
{"Action":"run","Test":"TestVet/4"}
{"Action":"output","Test":"TestVet/4","Output":"=== RUN TestVet/4\n"}
{"Action":"run","Test":"TestTags/x_testtag_y"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":"=== RUN TestTags/x_testtag_y\n"}
{"Action":"output","Test":"TestVet/4","Output":"=== PAUSE TestVet/4\n"}
{"Action":"pause","Test":"TestVet/4"}
{"Action":"run","Test":"TestVet/5"}
{"Action":"output","Test":"TestVet/5","Output":"=== RUN TestVet/5\n"}
{"Action":"output","Test":"TestVet/5","Output":"=== PAUSE TestVet/5\n"}
{"Action":"pause","Test":"TestVet/5"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":"=== PAUSE TestTags/x_testtag_y\n"}
{"Action":"pause","Test":"TestTags/x_testtag_y"}
{"Action":"run","Test":"TestVet/6"}
{"Action":"output","Test":"TestVet/6","Output":"=== RUN TestVet/6\n"}
{"Action":"run","Test":"TestTags/x,testtag,y"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":"=== RUN TestTags/x,testtag,y\n"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":"=== PAUSE TestTags/x,testtag,y\n"}
{"Action":"pause","Test":"TestTags/x,testtag,y"}
{"Action":"run","Test":"TestVetDirs/testingpkg"}
{"Action":"output","Test":"TestVetDirs/testingpkg","Output":"=== RUN TestVetDirs/testingpkg\n"}
{"Action":"output","Test":"TestVet/6","Output":"=== PAUSE TestVet/6\n"}
{"Action":"pause","Test":"TestVet/6"}
{"Action":"cont","Test":"TestTags/x,testtag,y"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":"=== CONT TestTags/x,testtag,y\n"}
{"Action":"output","Test":"TestVetDirs/testingpkg","Output":"=== PAUSE TestVetDirs/testingpkg\n"}
{"Action":"pause","Test":"TestVetDirs/testingpkg"}
{"Action":"run","Test":"TestVetDirs/divergent"}
{"Action":"output","Test":"TestVetDirs/divergent","Output":"=== RUN TestVetDirs/divergent\n"}
{"Action":"run","Test":"TestVet/7"}
{"Action":"output","Test":"TestVet/7","Output":"=== RUN TestVet/7\n"}
{"Action":"output","Test":"TestVet/7","Output":"=== PAUSE TestVet/7\n"}
{"Action":"pause","Test":"TestVet/7"}
{"Action":"output","Test":"TestVetDirs/divergent","Output":"=== PAUSE TestVetDirs/divergent\n"}
{"Action":"pause","Test":"TestVetDirs/divergent"}
{"Action":"cont","Test":"TestTags/x_testtag_y"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":"=== CONT TestTags/x_testtag_y\n"}
{"Action":"cont","Test":"TestTags/testtag"}
{"Action":"output","Test":"TestTags/testtag","Output":"=== CONT TestTags/testtag\n"}
{"Action":"run","Test":"TestVetDirs/buildtag"}
{"Action":"output","Test":"TestVetDirs/buildtag","Output":"=== RUN TestVetDirs/buildtag\n"}
{"Action":"output","Test":"TestVetDirs/buildtag","Output":"=== PAUSE TestVetDirs/buildtag\n"}
{"Action":"pause","Test":"TestVetDirs/buildtag"}
{"Action":"cont","Test":"TestVet/0"}
{"Action":"output","Test":"TestVet/0","Output":"=== CONT TestVet/0\n"}
{"Action":"cont","Test":"TestVet/4"}
{"Action":"output","Test":"TestVet/4","Output":"=== CONT TestVet/4\n"}
{"Action":"run","Test":"TestVetDirs/incomplete"}
{"Action":"output","Test":"TestVetDirs/incomplete","Output":"=== RUN TestVetDirs/incomplete\n"}
{"Action":"output","Test":"TestVetDirs/incomplete","Output":"=== PAUSE TestVetDirs/incomplete\n"}
{"Action":"pause","Test":"TestVetDirs/incomplete"}
{"Action":"run","Test":"TestVetDirs/cgo"}
{"Action":"output","Test":"TestVetDirs/cgo","Output":"=== RUN TestVetDirs/cgo\n"}
{"Action":"output","Test":"TestVetDirs/cgo","Output":"=== PAUSE TestVetDirs/cgo\n"}
{"Action":"pause","Test":"TestVetDirs/cgo"}
{"Action":"cont","Test":"TestVet/7"}
{"Action":"output","Test":"TestVet/7","Output":"=== CONT TestVet/7\n"}
{"Action":"cont","Test":"TestVet/6"}
{"Action":"output","Test":"TestVet/6","Output":"=== CONT TestVet/6\n"}
{"Action":"output","Test":"TestVetVerbose","Output":"--- PASS: TestVetVerbose (0.04s)\n"}
{"Action":"pass","Test":"TestVetVerbose"}
{"Action":"cont","Test":"TestVet/5"}
{"Action":"output","Test":"TestVet/5","Output":"=== CONT TestVet/5\n"}
{"Action":"cont","Test":"TestVet/3"}
{"Action":"output","Test":"TestVet/3","Output":"=== CONT TestVet/3\n"}
{"Action":"cont","Test":"TestVet/2"}
{"Action":"output","Test":"TestVet/2","Output":"=== CONT TestVet/2\n"}
{"Action":"output","Test":"TestTags","Output":"--- PASS: TestTags (0.00s)\n"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":" --- PASS: TestTags/x_testtag_y (0.04s)\n"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":" \tvet_test.go:187: -tags=x testtag y\n"}
{"Action":"pass","Test":"TestTags/x_testtag_y"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":" --- PASS: TestTags/x,testtag,y (0.04s)\n"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":" \tvet_test.go:187: -tags=x,testtag,y\n"}
{"Action":"pass","Test":"TestTags/x,testtag,y"}
{"Action":"output","Test":"TestTags/testtag","Output":" --- PASS: TestTags/testtag (0.04s)\n"}
{"Action":"output","Test":"TestTags/testtag","Output":" \tvet_test.go:187: -tags=testtag\n"}
{"Action":"pass","Test":"TestTags/testtag"}
{"Action":"pass","Test":"TestTags"}
{"Action":"cont","Test":"TestVet/1"}
{"Action":"output","Test":"TestVet/1","Output":"=== CONT TestVet/1\n"}
{"Action":"cont","Test":"TestVetDirs/testingpkg"}
{"Action":"output","Test":"TestVetDirs/testingpkg","Output":"=== CONT TestVetDirs/testingpkg\n"}
{"Action":"cont","Test":"TestVetDirs/buildtag"}
{"Action":"output","Test":"TestVetDirs/buildtag","Output":"=== CONT TestVetDirs/buildtag\n"}
{"Action":"cont","Test":"TestVetDirs/divergent"}
{"Action":"output","Test":"TestVetDirs/divergent","Output":"=== CONT TestVetDirs/divergent\n"}
{"Action":"cont","Test":"TestVetDirs/incomplete"}
{"Action":"output","Test":"TestVetDirs/incomplete","Output":"=== CONT TestVetDirs/incomplete\n"}
{"Action":"cont","Test":"TestVetDirs/cgo"}
{"Action":"output","Test":"TestVetDirs/cgo","Output":"=== CONT TestVetDirs/cgo\n"}
{"Action":"output","Test":"TestVet","Output":"--- PASS: TestVet (0.39s)\n"}
{"Action":"output","Test":"TestVet/5","Output":" --- PASS: TestVet/5 (0.07s)\n"}
{"Action":"output","Test":"TestVet/5","Output":" \tvet_test.go:114: files: [\"testdata/copylock_func.go\" \"testdata/rangeloop.go\"]\n"}
{"Action":"pass","Test":"TestVet/5"}
{"Action":"output","Test":"TestVet/3","Output":" --- PASS: TestVet/3 (0.07s)\n"}
{"Action":"output","Test":"TestVet/3","Output":" \tvet_test.go:114: files: [\"testdata/composite.go\" \"testdata/nilfunc.go\"]\n"}
{"Action":"pass","Test":"TestVet/3"}
{"Action":"output","Test":"TestVet/6","Output":" --- PASS: TestVet/6 (0.07s)\n"}
{"Action":"output","Test":"TestVet/6","Output":" \tvet_test.go:114: files: [\"testdata/copylock_range.go\" \"testdata/shadow.go\"]\n"}
{"Action":"pass","Test":"TestVet/6"}
{"Action":"output","Test":"TestVet/2","Output":" --- PASS: TestVet/2 (0.07s)\n"}
{"Action":"output","Test":"TestVet/2","Output":" \tvet_test.go:114: files: [\"testdata/bool.go\" \"testdata/method.go\" \"testdata/unused.go\"]\n"}
{"Action":"pass","Test":"TestVet/2"}
{"Action":"output","Test":"TestVet/0","Output":" --- PASS: TestVet/0 (0.13s)\n"}
{"Action":"output","Test":"TestVet/0","Output":" \tvet_test.go:114: files: [\"testdata/assign.go\" \"testdata/httpresponse.go\" \"testdata/structtag.go\"]\n"}
{"Action":"pass","Test":"TestVet/0"}
{"Action":"output","Test":"TestVet/4","Output":" --- PASS: TestVet/4 (0.16s)\n"}
{"Action":"output","Test":"TestVet/4","Output":" \tvet_test.go:114: files: [\"testdata/copylock.go\" \"testdata/print.go\"]\n"}
{"Action":"pass","Test":"TestVet/4"}
{"Action":"output","Test":"TestVet/1","Output":" --- PASS: TestVet/1 (0.07s)\n"}
{"Action":"output","Test":"TestVet/1","Output":" \tvet_test.go:114: files: [\"testdata/atomic.go\" \"testdata/lostcancel.go\" \"testdata/unsafeptr.go\"]\n"}
{"Action":"pass","Test":"TestVet/1"}
{"Action":"output","Test":"TestVet/7","Output":" --- PASS: TestVet/7 (0.19s)\n"}
{"Action":"output","Test":"TestVet/7","Output":" \tvet_test.go:114: files: [\"testdata/deadcode.go\" \"testdata/shift.go\"]\n"}
{"Action":"pass","Test":"TestVet/7"}
{"Action":"pass","Test":"TestVet"}
{"Action":"output","Test":"TestVetDirs","Output":"--- PASS: TestVetDirs (0.01s)\n"}
{"Action":"output","Test":"TestVetDirs/testingpkg","Output":" --- PASS: TestVetDirs/testingpkg (0.06s)\n"}
{"Action":"pass","Test":"TestVetDirs/testingpkg"}
{"Action":"output","Test":"TestVetDirs/divergent","Output":" --- PASS: TestVetDirs/divergent (0.05s)\n"}
{"Action":"pass","Test":"TestVetDirs/divergent"}
{"Action":"output","Test":"TestVetDirs/buildtag","Output":" --- PASS: TestVetDirs/buildtag (0.06s)\n"}
{"Action":"pass","Test":"TestVetDirs/buildtag"}
{"Action":"output","Test":"TestVetDirs/incomplete","Output":" --- PASS: TestVetDirs/incomplete (0.05s)\n"}
{"Action":"pass","Test":"TestVetDirs/incomplete"}
{"Action":"output","Test":"TestVetDirs/cgo","Output":" --- PASS: TestVetDirs/cgo (0.04s)\n"}
{"Action":"pass","Test":"TestVetDirs/cgo"}
{"Action":"pass","Test":"TestVetDirs"}
{"Action":"output","Test":"TestVetAsm","Output":"--- PASS: TestVetAsm (0.75s)\n"}
{"Action":"pass","Test":"TestVetAsm"}
{"Action":"output","Output":"PASS\n"}
{"Action":"output","Output":"ok \tcmd/vet\t(cached)\n"}
{"Action":"pass"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/ascii.json | {"Action":"run","Test":"TestAscii"}
{"Action":"output","Test":"TestAscii","Output":"=== RUN TestAscii\n"}
{"Action":"output","Test":"TestAscii","Output":"I can eat glass, and it doesn't hurt me. I can eat glass, and it doesn't hurt me.\n"}
{"Action":"output","Test":"TestAscii","Output":"I CAN EAT GLASS, AND IT DOESN'T HURT ME. I CAN EAT GLASS, AND IT DOESN'T HURT ME.\n"}
{"Action":"output","Test":"TestAscii","Output":"--- PASS: TestAscii\n"}
{"Action":"output","Test":"TestAscii","Output":" i can eat glass, and it doesn't hurt me. i can eat glass, and it doesn't hurt me.\n"}
{"Action":"output","Test":"TestAscii","Output":" V PNA RNG TYNFF, NAQ VG QBRFA'G UHEG ZR. V PNA RNG TYNFF, NAQ VG QBRFA'G UHEG ZR.\n"}
{"Action":"pass","Test":"TestAscii"}
{"Action":"output","Output":"PASS\n"}
{"Action":"pass"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/bench.json | {"Action":"output","Output":"goos: darwin\n"}
{"Action":"output","Output":"goarch: 386\n"}
{"Action":"output","Output":"BenchmarkFoo-8 \t2000000000\t 0.00 ns/op\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"--- BENCH: BenchmarkFoo-8\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"output","Test":"BenchmarkFoo-8","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"bench","Test":"BenchmarkFoo-8"}
{"Action":"output","Output":"PASS\n"}
{"Action":"output","Output":"ok \tcommand-line-arguments\t0.009s\n"}
{"Action":"pass"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/unicode.test | === RUN TestUnicode
Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα.
私はガラスを食べられます。それは私を傷つけません。私はガラスを食べられます。それは私を傷つけません。
--- PASS: TestUnicode
ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ
אני יכול לאכול זכוכית וזה לא מזיק לי. אני יכול לאכול זכוכית וזה לא מזיק לי.
PASS
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/unicode.json | {"Action":"run","Test":"TestUnicode"}
{"Action":"output","Test":"TestUnicode","Output":"=== RUN TestUnicode\n"}
{"Action":"output","Test":"TestUnicode","Output":"Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα.\n"}
{"Action":"output","Test":"TestUnicode","Output":"私はガラスを食べられます。それは私を傷つけません。私はガラスを食べられます。それは私を傷つけません。\n"}
{"Action":"output","Test":"TestUnicode","Output":"--- PASS: TestUnicode\n"}
{"Action":"output","Test":"TestUnicode","Output":" ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ\n"}
{"Action":"output","Test":"TestUnicode","Output":" אני יכול לאכול זכוכית וזה לא מזיק לי. אני יכול לאכול זכוכית וזה לא מזיק לי.\n"}
{"Action":"pass","Test":"TestUnicode"}
{"Action":"output","Output":"PASS\n"}
{"Action":"pass"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/benchfail.test | --- FAIL: BenchmarkFoo
x_test.go:8: My benchmark
FAIL
FAIL command-line-arguments 0.008s
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/benchfail.json | {"Action":"output","Test":"BenchmarkFoo","Output":"--- FAIL: BenchmarkFoo\n"}
{"Action":"output","Test":"BenchmarkFoo","Output":"\tx_test.go:8: My benchmark\n"}
{"Action":"fail","Test":"BenchmarkFoo"}
{"Action":"output","Output":"FAIL\n"}
{"Action":"output","Output":"FAIL\tcommand-line-arguments\t0.008s\n"}
{"Action":"fail"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/issue23036.test | === RUN TestActualCase
--- FAIL: TestActualCase (0.00s)
foo_test.go:14: Differed.
Expected: MyTest:
--- FAIL: Test output from other tool
Actual: not expected
FAIL
exit status 1
FAIL github.com/org/project/badtest 0.049s
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/smiley.test | === RUN Test☺☹
=== PAUSE Test☺☹
=== RUN Test☺☹Asm
=== PAUSE Test☺☹Asm
=== RUN Test☺☹Dirs
=== PAUSE Test☺☹Dirs
=== RUN TestTags
=== PAUSE TestTags
=== RUN Test☺☹Verbose
=== PAUSE Test☺☹Verbose
=== CONT Test☺☹
=== CONT TestTags
=== CONT Test☺☹Verbose
=== RUN TestTags/testtag
=== PAUSE TestTags/testtag
=== CONT Test☺☹Dirs
=== CONT Test☺☹Asm
=== RUN Test☺☹/0
=== PAUSE Test☺☹/0
=== RUN Test☺☹/1
=== PAUSE Test☺☹/1
=== RUN Test☺☹/2
=== PAUSE Test☺☹/2
=== RUN Test☺☹/3
=== PAUSE Test☺☹/3
=== RUN Test☺☹/4
=== RUN TestTags/x_testtag_y
=== PAUSE Test☺☹/4
=== RUN Test☺☹/5
=== PAUSE Test☺☹/5
=== PAUSE TestTags/x_testtag_y
=== RUN Test☺☹/6
=== RUN TestTags/x,testtag,y
=== PAUSE TestTags/x,testtag,y
=== RUN Test☺☹Dirs/testingpkg
=== PAUSE Test☺☹/6
=== CONT TestTags/x,testtag,y
=== PAUSE Test☺☹Dirs/testingpkg
=== RUN Test☺☹Dirs/divergent
=== RUN Test☺☹/7
=== PAUSE Test☺☹/7
=== PAUSE Test☺☹Dirs/divergent
=== CONT TestTags/x_testtag_y
=== CONT TestTags/testtag
=== RUN Test☺☹Dirs/buildtag
=== PAUSE Test☺☹Dirs/buildtag
=== CONT Test☺☹/0
=== CONT Test☺☹/4
=== RUN Test☺☹Dirs/incomplete
=== PAUSE Test☺☹Dirs/incomplete
=== RUN Test☺☹Dirs/cgo
=== PAUSE Test☺☹Dirs/cgo
=== CONT Test☺☹/7
=== CONT Test☺☹/6
--- PASS: Test☺☹Verbose (0.04s)
=== CONT Test☺☹/5
=== CONT Test☺☹/3
=== CONT Test☺☹/2
--- PASS: TestTags (0.00s)
--- PASS: TestTags/x_testtag_y (0.04s)
vet_test.go:187: -tags=x testtag y
--- PASS: TestTags/x,testtag,y (0.04s)
vet_test.go:187: -tags=x,testtag,y
--- PASS: TestTags/testtag (0.04s)
vet_test.go:187: -tags=testtag
=== CONT Test☺☹/1
=== CONT Test☺☹Dirs/testingpkg
=== CONT Test☺☹Dirs/buildtag
=== CONT Test☺☹Dirs/divergent
=== CONT Test☺☹Dirs/incomplete
=== CONT Test☺☹Dirs/cgo
--- PASS: Test☺☹ (0.39s)
--- PASS: Test☺☹/5 (0.07s)
vet_test.go:114: φιλεσ: ["testdata/copylock_func.go" "testdata/rangeloop.go"]
--- PASS: Test☺☹/3 (0.07s)
vet_test.go:114: φιλεσ: ["testdata/composite.go" "testdata/nilfunc.go"]
--- PASS: Test☺☹/6 (0.07s)
vet_test.go:114: φιλεσ: ["testdata/copylock_range.go" "testdata/shadow.go"]
--- PASS: Test☺☹/2 (0.07s)
vet_test.go:114: φιλεσ: ["testdata/bool.go" "testdata/method.go" "testdata/unused.go"]
--- PASS: Test☺☹/0 (0.13s)
vet_test.go:114: φιλεσ: ["testdata/assign.go" "testdata/httpresponse.go" "testdata/structtag.go"]
--- PASS: Test☺☹/4 (0.16s)
vet_test.go:114: φιλεσ: ["testdata/copylock.go" "testdata/print.go"]
--- PASS: Test☺☹/1 (0.07s)
vet_test.go:114: φιλεσ: ["testdata/atomic.go" "testdata/lostcancel.go" "testdata/unsafeptr.go"]
--- PASS: Test☺☹/7 (0.19s)
vet_test.go:114: φιλεσ: ["testdata/deadcode.go" "testdata/shift.go"]
--- PASS: Test☺☹Dirs (0.01s)
--- PASS: Test☺☹Dirs/testingpkg (0.06s)
--- PASS: Test☺☹Dirs/divergent (0.05s)
--- PASS: Test☺☹Dirs/buildtag (0.06s)
--- PASS: Test☺☹Dirs/incomplete (0.05s)
--- PASS: Test☺☹Dirs/cgo (0.04s)
--- PASS: Test☺☹Asm (0.75s)
PASS
ok cmd/vet (cached)
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/benchshort.json | {"Action":"output","Output":"# This file ends in an early EOF to trigger the Benchmark prefix test,\n"}
{"Action":"output","Output":"# which only happens when a benchmark prefix is seen ahead of the \\n.\n"}
{"Action":"output","Output":"# Normally that's due to the benchmark running and the \\n coming later,\n"}
{"Action":"output","Output":"# but to avoid questions of timing, we just use a file with no \\n at all.\n"}
{"Action":"output","Output":"BenchmarkFoo \t"}
{"Action":"output","Output":"10000 early EOF"}
{"Action":"fail"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/bench.test | goos: darwin
goarch: 386
BenchmarkFoo-8 2000000000 0.00 ns/op
--- BENCH: BenchmarkFoo-8
x_test.go:8: My benchmark
x_test.go:8: My benchmark
x_test.go:8: My benchmark
x_test.go:8: My benchmark
x_test.go:8: My benchmark
x_test.go:8: My benchmark
PASS
ok command-line-arguments 0.009s
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/issue23036.json | {"Action":"run","Test":"TestActualCase"}
{"Action":"output","Test":"TestActualCase","Output":"=== RUN TestActualCase\n"}
{"Action":"output","Test":"TestActualCase","Output":"--- FAIL: TestActualCase (0.00s)\n"}
{"Action":"output","Test":"TestActualCase","Output":" foo_test.go:14: Differed.\n"}
{"Action":"output","Test":"TestActualCase","Output":" Expected: MyTest:\n"}
{"Action":"output","Test":"TestActualCase","Output":" --- FAIL: Test output from other tool\n"}
{"Action":"output","Test":"TestActualCase","Output":" Actual: not expected\n"}
{"Action":"fail","Test":"TestActualCase"}
{"Action":"output","Output":"FAIL\n"}
{"Action":"output","Output":"exit status 1\n"}
{"Action":"output","Output":"FAIL github.com/org/project/badtest 0.049s\n"}
{"Action":"fail"}
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/ascii.test | === RUN TestAscii
I can eat glass, and it doesn't hurt me. I can eat glass, and it doesn't hurt me.
I CAN EAT GLASS, AND IT DOESN'T HURT ME. I CAN EAT GLASS, AND IT DOESN'T HURT ME.
--- PASS: TestAscii
i can eat glass, and it doesn't hurt me. i can eat glass, and it doesn't hurt me.
V PNA RNG TYNFF, NAQ VG QBRFA'G UHEG ZR. V PNA RNG TYNFF, NAQ VG QBRFA'G UHEG ZR.
PASS
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/vet.test | === RUN TestVet
=== PAUSE TestVet
=== RUN TestVetAsm
=== PAUSE TestVetAsm
=== RUN TestVetDirs
=== PAUSE TestVetDirs
=== RUN TestTags
=== PAUSE TestTags
=== RUN TestVetVerbose
=== PAUSE TestVetVerbose
=== CONT TestVet
=== CONT TestTags
=== CONT TestVetVerbose
=== RUN TestTags/testtag
=== PAUSE TestTags/testtag
=== CONT TestVetDirs
=== CONT TestVetAsm
=== RUN TestVet/0
=== PAUSE TestVet/0
=== RUN TestVet/1
=== PAUSE TestVet/1
=== RUN TestVet/2
=== PAUSE TestVet/2
=== RUN TestVet/3
=== PAUSE TestVet/3
=== RUN TestVet/4
=== RUN TestTags/x_testtag_y
=== PAUSE TestVet/4
=== RUN TestVet/5
=== PAUSE TestVet/5
=== PAUSE TestTags/x_testtag_y
=== RUN TestVet/6
=== RUN TestTags/x,testtag,y
=== PAUSE TestTags/x,testtag,y
=== RUN TestVetDirs/testingpkg
=== PAUSE TestVet/6
=== CONT TestTags/x,testtag,y
=== PAUSE TestVetDirs/testingpkg
=== RUN TestVetDirs/divergent
=== RUN TestVet/7
=== PAUSE TestVet/7
=== PAUSE TestVetDirs/divergent
=== CONT TestTags/x_testtag_y
=== CONT TestTags/testtag
=== RUN TestVetDirs/buildtag
=== PAUSE TestVetDirs/buildtag
=== CONT TestVet/0
=== CONT TestVet/4
=== RUN TestVetDirs/incomplete
=== PAUSE TestVetDirs/incomplete
=== RUN TestVetDirs/cgo
=== PAUSE TestVetDirs/cgo
=== CONT TestVet/7
=== CONT TestVet/6
--- PASS: TestVetVerbose (0.04s)
=== CONT TestVet/5
=== CONT TestVet/3
=== CONT TestVet/2
--- PASS: TestTags (0.00s)
--- PASS: TestTags/x_testtag_y (0.04s)
vet_test.go:187: -tags=x testtag y
--- PASS: TestTags/x,testtag,y (0.04s)
vet_test.go:187: -tags=x,testtag,y
--- PASS: TestTags/testtag (0.04s)
vet_test.go:187: -tags=testtag
=== CONT TestVet/1
=== CONT TestVetDirs/testingpkg
=== CONT TestVetDirs/buildtag
=== CONT TestVetDirs/divergent
=== CONT TestVetDirs/incomplete
=== CONT TestVetDirs/cgo
--- PASS: TestVet (0.39s)
--- PASS: TestVet/5 (0.07s)
vet_test.go:114: files: ["testdata/copylock_func.go" "testdata/rangeloop.go"]
--- PASS: TestVet/3 (0.07s)
vet_test.go:114: files: ["testdata/composite.go" "testdata/nilfunc.go"]
--- PASS: TestVet/6 (0.07s)
vet_test.go:114: files: ["testdata/copylock_range.go" "testdata/shadow.go"]
--- PASS: TestVet/2 (0.07s)
vet_test.go:114: files: ["testdata/bool.go" "testdata/method.go" "testdata/unused.go"]
--- PASS: TestVet/0 (0.13s)
vet_test.go:114: files: ["testdata/assign.go" "testdata/httpresponse.go" "testdata/structtag.go"]
--- PASS: TestVet/4 (0.16s)
vet_test.go:114: files: ["testdata/copylock.go" "testdata/print.go"]
--- PASS: TestVet/1 (0.07s)
vet_test.go:114: files: ["testdata/atomic.go" "testdata/lostcancel.go" "testdata/unsafeptr.go"]
--- PASS: TestVet/7 (0.19s)
vet_test.go:114: files: ["testdata/deadcode.go" "testdata/shift.go"]
--- PASS: TestVetDirs (0.01s)
--- PASS: TestVetDirs/testingpkg (0.06s)
--- PASS: TestVetDirs/divergent (0.05s)
--- PASS: TestVetDirs/buildtag (0.06s)
--- PASS: TestVetDirs/incomplete (0.05s)
--- PASS: TestVetDirs/cgo (0.04s)
--- PASS: TestVetAsm (0.75s)
PASS
ok cmd/vet (cached)
|
testdata | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/test2json/testdata/smiley.json | {"Action":"run","Test":"Test☺☹"}
{"Action":"output","Test":"Test☺☹","Output":"=== RUN Test☺☹\n"}
{"Action":"output","Test":"Test☺☹","Output":"=== PAUSE Test☺☹\n"}
{"Action":"pause","Test":"Test☺☹"}
{"Action":"run","Test":"Test☺☹Asm"}
{"Action":"output","Test":"Test☺☹Asm","Output":"=== RUN Test☺☹Asm\n"}
{"Action":"output","Test":"Test☺☹Asm","Output":"=== PAUSE Test☺☹Asm\n"}
{"Action":"pause","Test":"Test☺☹Asm"}
{"Action":"run","Test":"Test☺☹Dirs"}
{"Action":"output","Test":"Test☺☹Dirs","Output":"=== RUN Test☺☹Dirs\n"}
{"Action":"output","Test":"Test☺☹Dirs","Output":"=== PAUSE Test☺☹Dirs\n"}
{"Action":"pause","Test":"Test☺☹Dirs"}
{"Action":"run","Test":"TestTags"}
{"Action":"output","Test":"TestTags","Output":"=== RUN TestTags\n"}
{"Action":"output","Test":"TestTags","Output":"=== PAUSE TestTags\n"}
{"Action":"pause","Test":"TestTags"}
{"Action":"run","Test":"Test☺☹Verbose"}
{"Action":"output","Test":"Test☺☹Verbose","Output":"=== RUN Test☺☹Verbose\n"}
{"Action":"output","Test":"Test☺☹Verbose","Output":"=== PAUSE Test☺☹Verbose\n"}
{"Action":"pause","Test":"Test☺☹Verbose"}
{"Action":"cont","Test":"Test☺☹"}
{"Action":"output","Test":"Test☺☹","Output":"=== CONT Test☺☹\n"}
{"Action":"cont","Test":"TestTags"}
{"Action":"output","Test":"TestTags","Output":"=== CONT TestTags\n"}
{"Action":"cont","Test":"Test☺☹Verbose"}
{"Action":"output","Test":"Test☺☹Verbose","Output":"=== CONT Test☺☹Verbose\n"}
{"Action":"run","Test":"TestTags/testtag"}
{"Action":"output","Test":"TestTags/testtag","Output":"=== RUN TestTags/testtag\n"}
{"Action":"output","Test":"TestTags/testtag","Output":"=== PAUSE TestTags/testtag\n"}
{"Action":"pause","Test":"TestTags/testtag"}
{"Action":"cont","Test":"Test☺☹Dirs"}
{"Action":"output","Test":"Test☺☹Dirs","Output":"=== CONT Test☺☹Dirs\n"}
{"Action":"cont","Test":"Test☺☹Asm"}
{"Action":"output","Test":"Test☺☹Asm","Output":"=== CONT Test☺☹Asm\n"}
{"Action":"run","Test":"Test☺☹/0"}
{"Action":"output","Test":"Test☺☹/0","Output":"=== RUN Test☺☹/0\n"}
{"Action":"output","Test":"Test☺☹/0","Output":"=== PAUSE Test☺☹/0\n"}
{"Action":"pause","Test":"Test☺☹/0"}
{"Action":"run","Test":"Test☺☹/1"}
{"Action":"output","Test":"Test☺☹/1","Output":"=== RUN Test☺☹/1\n"}
{"Action":"output","Test":"Test☺☹/1","Output":"=== PAUSE Test☺☹/1\n"}
{"Action":"pause","Test":"Test☺☹/1"}
{"Action":"run","Test":"Test☺☹/2"}
{"Action":"output","Test":"Test☺☹/2","Output":"=== RUN Test☺☹/2\n"}
{"Action":"output","Test":"Test☺☹/2","Output":"=== PAUSE Test☺☹/2\n"}
{"Action":"pause","Test":"Test☺☹/2"}
{"Action":"run","Test":"Test☺☹/3"}
{"Action":"output","Test":"Test☺☹/3","Output":"=== RUN Test☺☹/3\n"}
{"Action":"output","Test":"Test☺☹/3","Output":"=== PAUSE Test☺☹/3\n"}
{"Action":"pause","Test":"Test☺☹/3"}
{"Action":"run","Test":"Test☺☹/4"}
{"Action":"output","Test":"Test☺☹/4","Output":"=== RUN Test☺☹/4\n"}
{"Action":"run","Test":"TestTags/x_testtag_y"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":"=== RUN TestTags/x_testtag_y\n"}
{"Action":"output","Test":"Test☺☹/4","Output":"=== PAUSE Test☺☹/4\n"}
{"Action":"pause","Test":"Test☺☹/4"}
{"Action":"run","Test":"Test☺☹/5"}
{"Action":"output","Test":"Test☺☹/5","Output":"=== RUN Test☺☹/5\n"}
{"Action":"output","Test":"Test☺☹/5","Output":"=== PAUSE Test☺☹/5\n"}
{"Action":"pause","Test":"Test☺☹/5"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":"=== PAUSE TestTags/x_testtag_y\n"}
{"Action":"pause","Test":"TestTags/x_testtag_y"}
{"Action":"run","Test":"Test☺☹/6"}
{"Action":"output","Test":"Test☺☹/6","Output":"=== RUN Test☺☹/6\n"}
{"Action":"run","Test":"TestTags/x,testtag,y"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":"=== RUN TestTags/x,testtag,y\n"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":"=== PAUSE TestTags/x,testtag,y\n"}
{"Action":"pause","Test":"TestTags/x,testtag,y"}
{"Action":"run","Test":"Test☺☹Dirs/testingpkg"}
{"Action":"output","Test":"Test☺☹Dirs/testingpkg","Output":"=== RUN Test☺☹Dirs/testingpkg\n"}
{"Action":"output","Test":"Test☺☹/6","Output":"=== PAUSE Test☺☹/6\n"}
{"Action":"pause","Test":"Test☺☹/6"}
{"Action":"cont","Test":"TestTags/x,testtag,y"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":"=== CONT TestTags/x,testtag,y\n"}
{"Action":"output","Test":"Test☺☹Dirs/testingpkg","Output":"=== PAUSE Test☺☹Dirs/testingpkg\n"}
{"Action":"pause","Test":"Test☺☹Dirs/testingpkg"}
{"Action":"run","Test":"Test☺☹Dirs/divergent"}
{"Action":"output","Test":"Test☺☹Dirs/divergent","Output":"=== RUN Test☺☹Dirs/divergent\n"}
{"Action":"run","Test":"Test☺☹/7"}
{"Action":"output","Test":"Test☺☹/7","Output":"=== RUN Test☺☹/7\n"}
{"Action":"output","Test":"Test☺☹/7","Output":"=== PAUSE Test☺☹/7\n"}
{"Action":"pause","Test":"Test☺☹/7"}
{"Action":"output","Test":"Test☺☹Dirs/divergent","Output":"=== PAUSE Test☺☹Dirs/divergent\n"}
{"Action":"pause","Test":"Test☺☹Dirs/divergent"}
{"Action":"cont","Test":"TestTags/x_testtag_y"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":"=== CONT TestTags/x_testtag_y\n"}
{"Action":"cont","Test":"TestTags/testtag"}
{"Action":"output","Test":"TestTags/testtag","Output":"=== CONT TestTags/testtag\n"}
{"Action":"run","Test":"Test☺☹Dirs/buildtag"}
{"Action":"output","Test":"Test☺☹Dirs/buildtag","Output":"=== RUN Test☺☹Dirs/buildtag\n"}
{"Action":"output","Test":"Test☺☹Dirs/buildtag","Output":"=== PAUSE Test☺☹Dirs/buildtag\n"}
{"Action":"pause","Test":"Test☺☹Dirs/buildtag"}
{"Action":"cont","Test":"Test☺☹/0"}
{"Action":"output","Test":"Test☺☹/0","Output":"=== CONT Test☺☹/0\n"}
{"Action":"cont","Test":"Test☺☹/4"}
{"Action":"output","Test":"Test☺☹/4","Output":"=== CONT Test☺☹/4\n"}
{"Action":"run","Test":"Test☺☹Dirs/incomplete"}
{"Action":"output","Test":"Test☺☹Dirs/incomplete","Output":"=== RUN Test☺☹Dirs/incomplete\n"}
{"Action":"output","Test":"Test☺☹Dirs/incomplete","Output":"=== PAUSE Test☺☹Dirs/incomplete\n"}
{"Action":"pause","Test":"Test☺☹Dirs/incomplete"}
{"Action":"run","Test":"Test☺☹Dirs/cgo"}
{"Action":"output","Test":"Test☺☹Dirs/cgo","Output":"=== RUN Test☺☹Dirs/cgo\n"}
{"Action":"output","Test":"Test☺☹Dirs/cgo","Output":"=== PAUSE Test☺☹Dirs/cgo\n"}
{"Action":"pause","Test":"Test☺☹Dirs/cgo"}
{"Action":"cont","Test":"Test☺☹/7"}
{"Action":"output","Test":"Test☺☹/7","Output":"=== CONT Test☺☹/7\n"}
{"Action":"cont","Test":"Test☺☹/6"}
{"Action":"output","Test":"Test☺☹/6","Output":"=== CONT Test☺☹/6\n"}
{"Action":"output","Test":"Test☺☹Verbose","Output":"--- PASS: Test☺☹Verbose (0.04s)\n"}
{"Action":"pass","Test":"Test☺☹Verbose"}
{"Action":"cont","Test":"Test☺☹/5"}
{"Action":"output","Test":"Test☺☹/5","Output":"=== CONT Test☺☹/5\n"}
{"Action":"cont","Test":"Test☺☹/3"}
{"Action":"output","Test":"Test☺☹/3","Output":"=== CONT Test☺☹/3\n"}
{"Action":"cont","Test":"Test☺☹/2"}
{"Action":"output","Test":"Test☺☹/2","Output":"=== CONT Test☺☹/2\n"}
{"Action":"output","Test":"TestTags","Output":"--- PASS: TestTags (0.00s)\n"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":" --- PASS: TestTags/x_testtag_y (0.04s)\n"}
{"Action":"output","Test":"TestTags/x_testtag_y","Output":" \tvet_test.go:187: -tags=x testtag y\n"}
{"Action":"pass","Test":"TestTags/x_testtag_y"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":" --- PASS: TestTags/x,testtag,y (0.04s)\n"}
{"Action":"output","Test":"TestTags/x,testtag,y","Output":" \tvet_test.go:187: -tags=x,testtag,y\n"}
{"Action":"pass","Test":"TestTags/x,testtag,y"}
{"Action":"output","Test":"TestTags/testtag","Output":" --- PASS: TestTags/testtag (0.04s)\n"}
{"Action":"output","Test":"TestTags/testtag","Output":" \tvet_test.go:187: -tags=testtag\n"}
{"Action":"pass","Test":"TestTags/testtag"}
{"Action":"pass","Test":"TestTags"}
{"Action":"cont","Test":"Test☺☹/1"}
{"Action":"output","Test":"Test☺☹/1","Output":"=== CONT Test☺☹/1\n"}
{"Action":"cont","Test":"Test☺☹Dirs/testingpkg"}
{"Action":"output","Test":"Test☺☹Dirs/testingpkg","Output":"=== CONT Test☺☹Dirs/testingpkg\n"}
{"Action":"cont","Test":"Test☺☹Dirs/buildtag"}
{"Action":"output","Test":"Test☺☹Dirs/buildtag","Output":"=== CONT Test☺☹Dirs/buildtag\n"}
{"Action":"cont","Test":"Test☺☹Dirs/divergent"}
{"Action":"output","Test":"Test☺☹Dirs/divergent","Output":"=== CONT Test☺☹Dirs/divergent\n"}
{"Action":"cont","Test":"Test☺☹Dirs/incomplete"}
{"Action":"output","Test":"Test☺☹Dirs/incomplete","Output":"=== CONT Test☺☹Dirs/incomplete\n"}
{"Action":"cont","Test":"Test☺☹Dirs/cgo"}
{"Action":"output","Test":"Test☺☹Dirs/cgo","Output":"=== CONT Test☺☹Dirs/cgo\n"}
{"Action":"output","Test":"Test☺☹","Output":"--- PASS: Test☺☹ (0.39s)\n"}
{"Action":"output","Test":"Test☺☹/5","Output":" --- PASS: Test☺☹/5 (0.07s)\n"}
{"Action":"output","Test":"Test☺☹/5","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/copylock_func.go\" \"testdata/rangeloop.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/5"}
{"Action":"output","Test":"Test☺☹/3","Output":" --- PASS: Test☺☹/3 (0.07s)\n"}
{"Action":"output","Test":"Test☺☹/3","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/composite.go\" \"testdata/nilfunc.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/3"}
{"Action":"output","Test":"Test☺☹/6","Output":" --- PASS: Test☺☹/6 (0.07s)\n"}
{"Action":"output","Test":"Test☺☹/6","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/copylock_range.go\" \"testdata/shadow.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/6"}
{"Action":"output","Test":"Test☺☹/2","Output":" --- PASS: Test☺☹/2 (0.07s)\n"}
{"Action":"output","Test":"Test☺☹/2","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/bool.go\" \"testdata/method.go\" \"testdata/unused.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/2"}
{"Action":"output","Test":"Test☺☹/0","Output":" --- PASS: Test☺☹/0 (0.13s)\n"}
{"Action":"output","Test":"Test☺☹/0","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/assign.go\" \"testdata/httpresponse.go\" \"testdata/structtag.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/0"}
{"Action":"output","Test":"Test☺☹/4","Output":" --- PASS: Test☺☹/4 (0.16s)\n"}
{"Action":"output","Test":"Test☺☹/4","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/copylock.go\" \"testdata/print.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/4"}
{"Action":"output","Test":"Test☺☹/1","Output":" --- PASS: Test☺☹/1 (0.07s)\n"}
{"Action":"output","Test":"Test☺☹/1","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/atomic.go\" \"testdata/lostcancel.go\" \"testdata/unsafeptr.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/1"}
{"Action":"output","Test":"Test☺☹/7","Output":" --- PASS: Test☺☹/7 (0.19s)\n"}
{"Action":"output","Test":"Test☺☹/7","Output":" \tvet_test.go:114: φιλεσ: [\"testdata/deadcode.go\" \"testdata/shift.go\"]\n"}
{"Action":"pass","Test":"Test☺☹/7"}
{"Action":"pass","Test":"Test☺☹"}
{"Action":"output","Test":"Test☺☹Dirs","Output":"--- PASS: Test☺☹Dirs (0.01s)\n"}
{"Action":"output","Test":"Test☺☹Dirs/testingpkg","Output":" --- PASS: Test☺☹Dirs/testingpkg (0.06s)\n"}
{"Action":"pass","Test":"Test☺☹Dirs/testingpkg"}
{"Action":"output","Test":"Test☺☹Dirs/divergent","Output":" --- PASS: Test☺☹Dirs/divergent (0.05s)\n"}
{"Action":"pass","Test":"Test☺☹Dirs/divergent"}
{"Action":"output","Test":"Test☺☹Dirs/buildtag","Output":" --- PASS: Test☺☹Dirs/buildtag (0.06s)\n"}
{"Action":"pass","Test":"Test☺☹Dirs/buildtag"}
{"Action":"output","Test":"Test☺☹Dirs/incomplete","Output":" --- PASS: Test☺☹Dirs/incomplete (0.05s)\n"}
{"Action":"pass","Test":"Test☺☹Dirs/incomplete"}
{"Action":"output","Test":"Test☺☹Dirs/cgo","Output":" --- PASS: Test☺☹Dirs/cgo (0.04s)\n"}
{"Action":"pass","Test":"Test☺☹Dirs/cgo"}
{"Action":"pass","Test":"Test☺☹Dirs"}
{"Action":"output","Test":"Test☺☹Asm","Output":"--- PASS: Test☺☹Asm (0.75s)\n"}
{"Action":"pass","Test":"Test☺☹Asm"}
{"Action":"output","Output":"PASS\n"}
{"Action":"output","Output":"ok \tcmd/vet\t(cached)\n"}
{"Action":"pass"}
|
buildid | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/buildid/buildid.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package buildid
import (
"bytes"
"debug/elf"
"fmt"
"io"
"os"
"strconv"
"strings"
)
var (
errBuildIDToolchain = fmt.Errorf("build ID only supported in gc toolchain")
errBuildIDMalformed = fmt.Errorf("malformed object file")
errBuildIDUnknown = fmt.Errorf("lost build ID")
)
var (
bangArch = []byte("!<arch>")
pkgdef = []byte("__.PKGDEF")
goobject = []byte("go object ")
buildid = []byte("build id ")
)
// ReadFile reads the build ID from an archive or executable file.
func ReadFile(name string) (id string, err error) {
f, err := os.Open(name)
if err != nil {
return "", err
}
defer f.Close()
buf := make([]byte, 8)
if _, err := f.ReadAt(buf, 0); err != nil {
return "", err
}
if string(buf) != "!<arch>\n" {
return readBinary(name, f)
}
// Read just enough of the target to fetch the build ID.
// The archive is expected to look like:
//
// !<arch>
// __.PKGDEF 0 0 0 644 7955 `
// go object darwin amd64 devel X:none
// build id "b41e5c45250e25c9fd5e9f9a1de7857ea0d41224"
//
// The variable-sized strings are GOOS, GOARCH, and the experiment list (X:none).
// Reading the first 1024 bytes should be plenty.
data := make([]byte, 1024)
n, err := io.ReadFull(f, data)
if err != nil && n == 0 {
return "", err
}
tryGccgo := func() (string, error) {
return readGccgoArchive(name, f)
}
// Archive header.
for i := 0; ; i++ { // returns during i==3
j := bytes.IndexByte(data, '\n')
if j < 0 {
return tryGccgo()
}
line := data[:j]
data = data[j+1:]
switch i {
case 0:
if !bytes.Equal(line, bangArch) {
return tryGccgo()
}
case 1:
if !bytes.HasPrefix(line, pkgdef) {
return tryGccgo()
}
case 2:
if !bytes.HasPrefix(line, goobject) {
return tryGccgo()
}
case 3:
if !bytes.HasPrefix(line, buildid) {
// Found the object header, just doesn't have a build id line.
// Treat as successful, with empty build id.
return "", nil
}
id, err := strconv.Unquote(string(line[len(buildid):]))
if err != nil {
return tryGccgo()
}
return id, nil
}
}
}
// readGccgoArchive tries to parse the archive as a standard Unix
// archive file, and fetch the build ID from the _buildid.o entry.
// The _buildid.o entry is written by (*Builder).gccgoBuildIDELFFile
// in cmd/go/internal/work/exec.go.
func readGccgoArchive(name string, f *os.File) (string, error) {
bad := func() (string, error) {
return "", &os.PathError{Op: "parse", Path: name, Err: errBuildIDMalformed}
}
off := int64(8)
for {
if _, err := f.Seek(off, io.SeekStart); err != nil {
return "", err
}
// TODO(iant): Make a debug/ar package, and use it
// here and in cmd/link.
var hdr [60]byte
if _, err := io.ReadFull(f, hdr[:]); err != nil {
if err == io.EOF {
// No more entries, no build ID.
return "", nil
}
return "", err
}
off += 60
sizeStr := strings.TrimSpace(string(hdr[48:58]))
size, err := strconv.ParseInt(sizeStr, 0, 64)
if err != nil {
return bad()
}
name := strings.TrimSpace(string(hdr[:16]))
if name == "_buildid.o/" {
sr := io.NewSectionReader(f, off, size)
e, err := elf.NewFile(sr)
if err != nil {
return bad()
}
s := e.Section(".go.buildid")
if s == nil {
return bad()
}
data, err := s.Data()
if err != nil {
return bad()
}
return string(data), nil
}
off += size
if off&1 != 0 {
off++
}
}
}
var (
goBuildPrefix = []byte("\xff Go build ID: \"")
goBuildEnd = []byte("\"\n \xff")
elfPrefix = []byte("\x7fELF")
machoPrefixes = [][]byte{
{0xfe, 0xed, 0xfa, 0xce},
{0xfe, 0xed, 0xfa, 0xcf},
{0xce, 0xfa, 0xed, 0xfe},
{0xcf, 0xfa, 0xed, 0xfe},
}
)
var readSize = 32 * 1024 // changed for testing
// readBinary reads the build ID from a binary.
//
// ELF binaries store the build ID in a proper PT_NOTE section.
//
// Other binary formats are not so flexible. For those, the linker
// stores the build ID as non-instruction bytes at the very beginning
// of the text segment, which should appear near the beginning
// of the file. This is clumsy but fairly portable. Custom locations
// can be added for other binary types as needed, like we did for ELF.
func readBinary(name string, f *os.File) (id string, err error) {
// Read the first 32 kB of the binary file.
// That should be enough to find the build ID.
// In ELF files, the build ID is in the leading headers,
// which are typically less than 4 kB, not to mention 32 kB.
// In Mach-O files, there's no limit, so we have to parse the file.
// On other systems, we're trying to read enough that
// we get the beginning of the text segment in the read.
// The offset where the text segment begins in a hello
// world compiled for each different object format today:
//
// Plan 9: 0x20
// Windows: 0x600
//
data := make([]byte, readSize)
_, err = io.ReadFull(f, data)
if err == io.ErrUnexpectedEOF {
err = nil
}
if err != nil {
return "", err
}
if bytes.HasPrefix(data, elfPrefix) {
return readELF(name, f, data)
}
for _, m := range machoPrefixes {
if bytes.HasPrefix(data, m) {
return readMacho(name, f, data)
}
}
return readRaw(name, data)
}
// readRaw finds the raw build ID stored in text segment data.
func readRaw(name string, data []byte) (id string, err error) {
i := bytes.Index(data, goBuildPrefix)
if i < 0 {
// Missing. Treat as successful but build ID empty.
return "", nil
}
j := bytes.Index(data[i+len(goBuildPrefix):], goBuildEnd)
if j < 0 {
return "", &os.PathError{Op: "parse", Path: name, Err: errBuildIDMalformed}
}
quoted := data[i+len(goBuildPrefix)-1 : i+len(goBuildPrefix)+j+1]
id, err = strconv.Unquote(string(quoted))
if err != nil {
return "", &os.PathError{Op: "parse", Path: name, Err: errBuildIDMalformed}
}
return id, nil
}
|
buildid | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/buildid/rewrite.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package buildid
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
)
// FindAndHash reads all of r and returns the offsets of occurrences of id.
// While reading, findAndHash also computes and returns
// a hash of the content of r, but with occurrences of id replaced by zeros.
// FindAndHash reads bufSize bytes from r at a time.
// If bufSize == 0, FindAndHash uses a reasonable default.
func FindAndHash(r io.Reader, id string, bufSize int) (matches []int64, hash [32]byte, err error) {
if bufSize == 0 {
bufSize = 31 * 1024 // bufSize+little will likely fit in 32 kB
}
if len(id) > bufSize {
return nil, [32]byte{}, fmt.Errorf("buildid.FindAndHash: buffer too small")
}
zeros := make([]byte, len(id))
idBytes := []byte(id)
// The strategy is to read the file through buf, looking for id,
// but we need to worry about what happens if id is broken up
// and returned in parts by two different reads.
// We allocate a tiny buffer (at least len(id)) and a big buffer (bufSize bytes)
// next to each other in memory and then copy the tail of
// one read into the tiny buffer before reading new data into the big buffer.
// The search for id is over the entire tiny+big buffer.
tiny := (len(id) + 127) &^ 127 // round up to 128-aligned
buf := make([]byte, tiny+bufSize)
h := sha256.New()
start := tiny
for offset := int64(0); ; {
// The file offset maintained by the loop corresponds to &buf[tiny].
// buf[start:tiny] is left over from previous iteration.
// After reading n bytes into buf[tiny:], we process buf[start:tiny+n].
n, err := io.ReadFull(r, buf[tiny:])
if err != io.ErrUnexpectedEOF && err != io.EOF && err != nil {
return nil, [32]byte{}, err
}
// Process any matches.
for {
i := bytes.Index(buf[start:tiny+n], idBytes)
if i < 0 {
break
}
matches = append(matches, offset+int64(start+i-tiny))
h.Write(buf[start : start+i])
h.Write(zeros)
start += i + len(id)
}
if n < bufSize {
// Did not fill buffer, must be at end of file.
h.Write(buf[start : tiny+n])
break
}
// Process all but final tiny bytes of buf (bufSize = len(buf)-tiny).
// Note that start > len(buf)-tiny is possible, if the search above
// found an id ending in the final tiny fringe. That's OK.
if start < len(buf)-tiny {
h.Write(buf[start : len(buf)-tiny])
start = len(buf) - tiny
}
// Slide ending tiny-sized fringe to beginning of buffer.
copy(buf[0:], buf[bufSize:])
start -= bufSize
offset += int64(bufSize)
}
h.Sum(hash[:0])
return matches, hash, nil
}
func Rewrite(w io.WriterAt, pos []int64, id string) error {
b := []byte(id)
for _, p := range pos {
if _, err := w.WriteAt(b, p); err != nil {
return err
}
}
return nil
}
|
buildid | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/buildid/buildid_test.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package buildid
import (
"bytes"
"crypto/sha256"
"io/ioutil"
"os"
"reflect"
"testing"
)
const (
expectedID = "abcdefghijklmnopqrstuvwxyz.1234567890123456789012345678901234567890123456789012345678901234"
newID = "bcdefghijklmnopqrstuvwxyza.2345678901234567890123456789012345678901234567890123456789012341"
)
func TestReadFile(t *testing.T) {
var files = []string{
"p.a",
"a.elf",
"a.macho",
"a.pe",
}
f, err := ioutil.TempFile("", "buildid-test-")
if err != nil {
t.Fatal(err)
}
tmp := f.Name()
defer os.Remove(tmp)
f.Close()
for _, f := range files {
id, err := ReadFile("testdata/" + f)
if id != expectedID || err != nil {
t.Errorf("ReadFile(testdata/%s) = %q, %v, want %q, nil", f, id, err, expectedID)
}
old := readSize
readSize = 2048
id, err = ReadFile("testdata/" + f)
readSize = old
if id != expectedID || err != nil {
t.Errorf("ReadFile(testdata/%s) [readSize=2k] = %q, %v, want %q, nil", f, id, err, expectedID)
}
data, err := ioutil.ReadFile("testdata/" + f)
if err != nil {
t.Fatal(err)
}
m, _, err := FindAndHash(bytes.NewReader(data), expectedID, 1024)
if err != nil {
t.Errorf("FindAndHash(testdata/%s): %v", f, err)
continue
}
if err := ioutil.WriteFile(tmp, data, 0666); err != nil {
t.Error(err)
continue
}
tf, err := os.OpenFile(tmp, os.O_WRONLY, 0)
if err != nil {
t.Error(err)
continue
}
err = Rewrite(tf, m, newID)
err2 := tf.Close()
if err != nil {
t.Errorf("Rewrite(testdata/%s): %v", f, err)
continue
}
if err2 != nil {
t.Fatal(err2)
}
id, err = ReadFile(tmp)
if id != newID || err != nil {
t.Errorf("ReadFile(testdata/%s after Rewrite) = %q, %v, want %q, nil", f, id, err, newID)
}
}
}
func TestFindAndHash(t *testing.T) {
buf := make([]byte, 64)
buf2 := make([]byte, 64)
id := make([]byte, 8)
zero := make([]byte, 8)
for i := range id {
id[i] = byte(i)
}
numError := 0
errorf := func(msg string, args ...interface{}) {
t.Errorf(msg, args...)
if numError++; numError > 20 {
t.Logf("stopping after too many errors")
t.FailNow()
}
}
for bufSize := len(id); bufSize <= len(buf); bufSize++ {
for j := range buf {
for k := 0; k < 2*len(id) && j+k < len(buf); k++ {
for i := range buf {
buf[i] = 1
}
copy(buf[j:], id)
copy(buf[j+k:], id)
var m []int64
if j+len(id) <= j+k {
m = append(m, int64(j))
}
if j+k+len(id) <= len(buf) {
m = append(m, int64(j+k))
}
copy(buf2, buf)
for _, p := range m {
copy(buf2[p:], zero)
}
h := sha256.Sum256(buf2)
matches, hash, err := FindAndHash(bytes.NewReader(buf), string(id), bufSize)
if err != nil {
errorf("bufSize=%d j=%d k=%d: findAndHash: %v", bufSize, j, k, err)
continue
}
if !reflect.DeepEqual(matches, m) {
errorf("bufSize=%d j=%d k=%d: findAndHash: matches=%v, want %v", bufSize, j, k, matches, m)
continue
}
if hash != h {
errorf("bufSize=%d j=%d k=%d: findAndHash: matches correct, but hash=%x, want %x", bufSize, j, k, hash, h)
}
}
}
}
}
|
buildid | /home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/internal/buildid/note.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package buildid
import (
"bytes"
"debug/elf"
"debug/macho"
"encoding/binary"
"fmt"
"io"
"os"
)
func readAligned4(r io.Reader, sz int32) ([]byte, error) {
full := (sz + 3) &^ 3
data := make([]byte, full)
_, err := io.ReadFull(r, data)
if err != nil {
return nil, err
}
data = data[:sz]
return data, nil
}
func ReadELFNote(filename, name string, typ int32) ([]byte, error) {
f, err := elf.Open(filename)
if err != nil {
return nil, err
}
for _, sect := range f.Sections {
if sect.Type != elf.SHT_NOTE {
continue
}
r := sect.Open()
for {
var namesize, descsize, noteType int32
err = binary.Read(r, f.ByteOrder, &namesize)
if err != nil {
if err == io.EOF {
break
}
return nil, fmt.Errorf("read namesize failed: %v", err)
}
err = binary.Read(r, f.ByteOrder, &descsize)
if err != nil {
return nil, fmt.Errorf("read descsize failed: %v", err)
}
err = binary.Read(r, f.ByteOrder, ¬eType)
if err != nil {
return nil, fmt.Errorf("read type failed: %v", err)
}
noteName, err := readAligned4(r, namesize)
if err != nil {
return nil, fmt.Errorf("read name failed: %v", err)
}
desc, err := readAligned4(r, descsize)
if err != nil {
return nil, fmt.Errorf("read desc failed: %v", err)
}
if name == string(noteName) && typ == noteType {
return desc, nil
}
}
}
return nil, nil
}
var elfGoNote = []byte("Go\x00\x00")
var elfGNUNote = []byte("GNU\x00")
// The Go build ID is stored in a note described by an ELF PT_NOTE prog
// header. The caller has already opened filename, to get f, and read
// at least 4 kB out, in data.
func readELF(name string, f *os.File, data []byte) (buildid string, err error) {
// Assume the note content is in the data, already read.
// Rewrite the ELF header to set shnum to 0, so that we can pass
// the data to elf.NewFile and it will decode the Prog list but not
// try to read the section headers and the string table from disk.
// That's a waste of I/O when all we care about is the Prog list
// and the one ELF note.
switch elf.Class(data[elf.EI_CLASS]) {
case elf.ELFCLASS32:
data[48] = 0
data[49] = 0
case elf.ELFCLASS64:
data[60] = 0
data[61] = 0
}
const elfGoBuildIDTag = 4
const gnuBuildIDTag = 3
ef, err := elf.NewFile(bytes.NewReader(data))
if err != nil {
return "", &os.PathError{Path: name, Op: "parse", Err: err}
}
var gnu string
for _, p := range ef.Progs {
if p.Type != elf.PT_NOTE || p.Filesz < 16 {
continue
}
var note []byte
if p.Off+p.Filesz < uint64(len(data)) {
note = data[p.Off : p.Off+p.Filesz]
} else {
// For some linkers, such as the Solaris linker,
// the buildid may not be found in data (which
// likely contains the first 16kB of the file)
// or even the first few megabytes of the file
// due to differences in note segment placement;
// in that case, extract the note data manually.
_, err = f.Seek(int64(p.Off), io.SeekStart)
if err != nil {
return "", err
}
note = make([]byte, p.Filesz)
_, err = io.ReadFull(f, note)
if err != nil {
return "", err
}
}
filesz := p.Filesz
off := p.Off
for filesz >= 16 {
nameSize := ef.ByteOrder.Uint32(note)
valSize := ef.ByteOrder.Uint32(note[4:])
tag := ef.ByteOrder.Uint32(note[8:])
nname := note[12:16]
if nameSize == 4 && 16+valSize <= uint32(len(note)) && tag == elfGoBuildIDTag && bytes.Equal(nname, elfGoNote) {
return string(note[16 : 16+valSize]), nil
}
if nameSize == 4 && 16+valSize <= uint32(len(note)) && tag == gnuBuildIDTag && bytes.Equal(nname, elfGNUNote) {
gnu = string(note[16 : 16+valSize])
}
nameSize = (nameSize + 3) &^ 3
valSize = (valSize + 3) &^ 3
notesz := uint64(12 + nameSize + valSize)
if filesz <= notesz {
break
}
off += notesz
align := uint64(p.Align)
alignedOff := (off + align - 1) &^ (align - 1)
notesz += alignedOff - off
off = alignedOff
filesz -= notesz
note = note[notesz:]
}
}
// If we didn't find a Go note, use a GNU note if available.
// This is what gccgo uses.
if gnu != "" {
return gnu, nil
}
// No note. Treat as successful but build ID empty.
return "", nil
}
// The Go build ID is stored at the beginning of the Mach-O __text segment.
// The caller has already opened filename, to get f, and read a few kB out, in data.
// Sadly, that's not guaranteed to hold the note, because there is an arbitrary amount
// of other junk placed in the file ahead of the main text.
func readMacho(name string, f *os.File, data []byte) (buildid string, err error) {
// If the data we want has already been read, don't worry about Mach-O parsing.
// This is both an optimization and a hedge against the Mach-O parsing failing
// in the future due to, for example, the name of the __text section changing.
if b, err := readRaw(name, data); b != "" && err == nil {
return b, err
}
mf, err := macho.NewFile(f)
if err != nil {
return "", &os.PathError{Path: name, Op: "parse", Err: err}
}
sect := mf.Section("__text")
if sect == nil {
// Every binary has a __text section. Something is wrong.
return "", &os.PathError{Path: name, Op: "parse", Err: fmt.Errorf("cannot find __text section")}
}
// It should be in the first few bytes, but read a lot just in case,
// especially given our past problems on OS X with the build ID moving.
// There shouldn't be much difference between reading 4kB and 32kB:
// the hard part is getting to the data, not transferring it.
n := sect.Size
if n > uint64(readSize) {
n = uint64(readSize)
}
buf := make([]byte, n)
if _, err := f.ReadAt(buf, int64(sect.Offset)); err != nil {
return "", err
}
return readRaw(name, buf)
}
|