chore: consolidated dependabot (#12029)

* chore(deps): bump github.com/kovidgoyal/imaging from 1.8.7 to 1.8.19

Bumps [github.com/kovidgoyal/imaging](https://github.com/kovidgoyal/imaging) from 1.8.7 to 1.8.19.
- [Release notes](https://github.com/kovidgoyal/imaging/releases)
- [Commits](https://github.com/kovidgoyal/imaging/compare/v1.8.7...v1.8.19)

---
updated-dependencies:
- dependency-name: github.com/kovidgoyal/imaging
  dependency-version: 1.8.19
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(deps): bump golang.org/x/net from 0.48.0 to 0.49.0

Bumps [golang.org/x/net](https://github.com/golang/net) from 0.48.0 to 0.49.0.
- [Commits](https://github.com/golang/net/compare/v0.48.0...v0.49.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.49.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
# Conflicts:
#	go.mod

* chore(deps-dev): bump @babel/runtime in /services/idp

Bumps [@babel/runtime](https://github.com/babel/babel/tree/HEAD/packages/babel-runtime) from 7.28.2 to 7.28.6.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.28.6/packages/babel-runtime)

---
updated-dependencies:
- dependency-name: "@babel/runtime"
  dependency-version: 7.28.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
Michal Klosanddependabot[bot] authored and GitHub committed 2026-02-18 09:37:09 +01:00
1 parent d70ae42427
commit c0daae28bf
61 files changed
+3355 -325

No files matched your search

+4 -4
View File
@@ -48,7 +48,7 @@ require (
github.com/jellydator/ttlcache/v3 v3.4.0
github.com/jinzhu/now v1.1.5
github.com/justinas/alice v1.2.0
github.com/kovidgoyal/imaging v1.8.7
github.com/kovidgoyal/imaging v1.8.19
github.com/leonelquinteros/gotext v1.7.2
github.com/libregraph/idm v0.5.0
github.com/libregraph/lico v0.66.0
@@ -96,8 +96,8 @@ require (
go.opentelemetry.io/otel/trace v1.39.0
golang.org/x/crypto v0.47.0
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b
golang.org/x/image v0.32.0
golang.org/x/net v0.48.0
golang.org/x/image v0.35.0
golang.org/x/net v0.49.0
golang.org/x/oauth2 v0.34.0
golang.org/x/sync v0.19.0
golang.org/x/term v0.39.0
@@ -236,12 +236,12 @@ require (
github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/juliangruber/go-intersect v1.1.0 // indirect
github.com/kettek/apng v0.0.0-20250827064933-2bb5f5fcf253 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/compress v1.18.2 // indirect
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
github.com/kovidgoyal/go-shm v1.0.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lestrrat-go/blackmagic v1.0.4 // indirect
github.com/lestrrat-go/dsig v1.0.0 // indirect
+8 -8
View File
@@ -571,8 +571,6 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
github.com/kettek/apng v0.0.0-20250827064933-2bb5f5fcf253 h1:ar6YqPcuumkcWgAJHkmda6Q35V3OnpxeTej4iU/QFLA=
github.com/kettek/apng v0.0.0-20250827064933-2bb5f5fcf253/go.mod h1:x78/VRQYKuCftMWS0uK5e+F5RJ7S4gSlESRWI0Prl6Q=
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
@@ -596,8 +594,10 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kovidgoyal/go-parallel v1.1.1 h1:1OzpNjtrUkBPq3UaqrnvOoB2F9RttSt811uiUXyI7ok=
github.com/kovidgoyal/go-parallel v1.1.1/go.mod h1:BJNIbe6+hxyFWv7n6oEDPj3PA5qSw5OCtf0hcVxWJiw=
github.com/kovidgoyal/imaging v1.8.7 h1:QyOBtEslEHG2x7VBoYoMhb3rp60DvUYePtXzva/8OcY=
github.com/kovidgoyal/imaging v1.8.7/go.mod h1:GAbZkbyB86PSfosof5EnS2o6N15yUk9Vy2r61EWy1Wg=
github.com/kovidgoyal/go-shm v1.0.0 h1:HJEel9D1F9YhULvClEHJLawoRSj/1u/EDV7MJbBPgQo=
github.com/kovidgoyal/go-shm v1.0.0/go.mod h1:Yzb80Xf9L3kaoB2RGok9hHwMIt7Oif61kT6t3+VnZds=
github.com/kovidgoyal/imaging v1.8.19 h1:zWJdQqF2tfSKjvoB7XpLRhVGbYsze++M0iaqZ4ZkhNk=
github.com/kovidgoyal/imaging v1.8.19/go.mod h1:I0q8RdoEuyc4G8GFOF9CaluTUHQSf68d6TmsqpvfRI8=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
@@ -1039,8 +1039,8 @@ golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAf
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
golang.org/x/image v0.32.0 h1:6lZQWq75h7L5IWNk0r+SCpUJ6tUVd3v4ZHnbRKLkUDQ=
golang.org/x/image v0.32.0/go.mod h1:/R37rrQmKXtO6tYXAjtDLwQgFLHmhW+V6ayXlxzP2Pc=
golang.org/x/image v0.35.0 h1:LKjiHdgMtO8z7Fh18nGY6KDcoEtVfsgLDPeLyguqb7I=
golang.org/x/image v0.35.0/go.mod h1:MwPLTVgvxSASsxdLzKrl8BRFuyqMyGhLwmC+TO1Sybk=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -1112,8 +1112,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
+1 -1
View File
@@ -119,7 +119,7 @@
"@babel/preset-env": "^7.28.5",
"@babel/preset-react": "^7.27.1",
"@babel/preset-typescript": "^7.27.1",
"@babel/runtime": "^7.28.2",
"@babel/runtime": "^7.28.6",
"@babel/runtime-corejs3": "^7.28.2",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^6.21.0",
+14 -20
View File
@@ -160,8 +160,8 @@ importers:
specifier: ^7.27.1
version: 7.27.1(@babel/core@7.28.6)
'@babel/runtime':
specifier: ^7.28.2
version: 7.28.2
specifier: ^7.28.6
version: 7.28.6
'@babel/runtime-corejs3':
specifier: ^7.28.2
version: 7.28.2
@@ -1104,10 +1104,6 @@ packages:
resolution: {integrity: sha512-FVFaVs2/dZgD3Y9ZD+AKNKjyGKzwu0C54laAXWUXgLcVXcCX6YZ6GhK2cp7FogSN2OA0Fu+QT8dP3FUdo9ShSQ==}
engines: {node: '>=6.9.0'}
'@babel/runtime@7.28.2':
resolution: {integrity: sha512-KHp2IflsnGywDjBWDkR9iEqiWSpc8GIi0lgTT3mOElT0PP1tG26P4tmFI2YvAdzgq9RGyoHZQEIEdZy6Ec5xCA==}
engines: {node: '>=6.9.0'}
'@babel/runtime@7.28.6':
resolution: {integrity: sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==}
engines: {node: '>=6.9.0'}
@@ -7802,8 +7798,6 @@ snapshots:
dependencies:
core-js-pure: 3.44.0
'@babel/runtime@7.28.2': {}
'@babel/runtime@7.28.6': {}
'@babel/template@7.28.6':
@@ -8668,7 +8662,7 @@ snapshots:
'@mui/icons-material@5.18.0(@mui/material@5.18.0(@types/react@17.0.87)(react-dom@17.0.2(react@17.0.2))(react@17.0.2))(@types/react@17.0.87)(react@17.0.2)':
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
'@mui/material': 5.18.0(@types/react@17.0.87)(react-dom@17.0.2(react@17.0.2))(react@17.0.2)
react: 17.0.2
optionalDependencies:
@@ -8676,7 +8670,7 @@ snapshots:
'@mui/material@5.18.0(@types/react@17.0.87)(react-dom@17.0.2(react@17.0.2))(react@17.0.2)':
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
'@mui/core-downloads-tracker': 5.18.0
'@mui/system': 5.18.0(@types/react@17.0.87)(react@17.0.2)
'@mui/types': 7.2.24(@types/react@17.0.87)
@@ -8884,7 +8878,7 @@ snapshots:
'@testing-library/react@12.1.5(@types/react@17.0.87)(react-dom@17.0.2(react@17.0.2))(react@17.0.2)':
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
'@testing-library/dom': 8.20.1
'@types/react-dom': 17.0.26(@types/react@17.0.87)
react: 17.0.2
@@ -9769,7 +9763,7 @@ snapshots:
'@babel/preset-env': 7.28.6(@babel/core@7.28.6)
'@babel/preset-react': 7.27.1(@babel/core@7.28.6)
'@babel/preset-typescript': 7.27.1(@babel/core@7.28.6)
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
babel-plugin-macros: 3.1.0
babel-plugin-transform-react-remove-prop-types: 0.4.24
transitivePeerDependencies:
@@ -11456,7 +11450,7 @@ snapshots:
i18next-browser-languagedetector@7.2.2:
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
i18next-conv@16.0.0:
dependencies:
@@ -11475,7 +11469,7 @@ snapshots:
i18next-parser@9.3.0:
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
broccoli-plugin: 4.0.7
cheerio: 1.0.0
colors: 1.4.0
@@ -11497,11 +11491,11 @@ snapshots:
i18next-resources-to-backend@1.2.1:
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
i18next@23.16.8:
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
iconv-lite@0.6.3:
dependencies:
@@ -13256,7 +13250,7 @@ snapshots:
react-i18next@15.6.1(i18next@23.16.8)(react-dom@17.0.2(react@17.0.2))(react@17.0.2)(typescript@5.9.3):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
html-parse-stringify: 3.0.1
i18next: 23.16.8
react: 17.0.2
@@ -13290,7 +13284,7 @@ snapshots:
react-redux@8.1.3(@types/react-dom@17.0.26(@types/react@17.0.87))(@types/react@17.0.87)(react-dom@17.0.2(react@17.0.2))(react@17.0.2)(redux@4.2.1):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
'@types/hoist-non-react-statics': 3.3.5
'@types/use-sync-external-store': 0.0.3
hoist-non-react-statics: 3.3.2
@@ -13316,7 +13310,7 @@ snapshots:
react-router@5.3.4(react@17.0.2):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
history: 4.10.1
hoist-non-react-statics: 3.3.2
loose-envify: 1.4.0
@@ -13407,7 +13401,7 @@ snapshots:
redux@4.2.1:
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.28.6
redux@5.0.1: {}
+1
View File
@@ -0,0 +1 @@
dist
+2
View File
@@ -0,0 +1,2 @@
builds:
- skip: true
+28
View File
@@ -0,0 +1,28 @@
BSD 3-Clause License
Copyright (c) 2025, Kovid Goyal
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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 HOLDER 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.
+3
View File
@@ -0,0 +1,3 @@
Tools to create and manage shared memory (POSIX Shared memory) across all Unix
variants. Pure Go, no external dependencies. Implements Go versions of
shm_open() and shm_unlink() that interoperate with the libc versions.
+20
View File
@@ -0,0 +1,20 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
import (
"errors"
"fmt"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func Fallocate_simple(fd int, size int64) (err error) {
for {
if err = unix.Fallocate(fd, 0, 0, size); !errors.Is(err, unix.EINTR) {
return
}
}
}
+16
View File
@@ -0,0 +1,16 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build !linux
package shm
import (
"errors"
"fmt"
)
var _ = fmt.Print
func Fallocate_simple(fd int, size int64) (err error) {
return errors.ErrUnsupported
}
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
import os
import subprocess
VERSION = '1.0.0'
def run(*args: str):
cp = subprocess.run(args)
if cp.returncode != 0:
raise SystemExit(cp.returncode)
def main():
try:
ans = input(f'Publish version \033[91m{VERSION}\033[m (y/n): ')
except KeyboardInterrupt:
ans = 'n'
if ans.lower() != 'y':
return
os.environ['GITHUB_TOKEN'] = open(os.path.join(os.environ['PENV'], 'github-token')).read().strip().partition(':')[2]
run('git', 'tag', '-a', 'v' + VERSION, '-m', f'version {VERSION}')
run('git', 'push')
run('goreleaser', 'release', '--clean')
if __name__ == '__main__':
main()
+208
View File
@@ -0,0 +1,208 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
import (
"encoding/binary"
"errors"
"fmt"
"io"
"io/fs"
"os"
"strings"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
var ErrPatternHasSeparator = errors.New("The specified pattern has file path separators in it")
var ErrPatternTooLong = errors.New("The specified pattern for the SHM name is too long")
type ErrNotSupported struct {
err error
}
func (self *ErrNotSupported) Error() string {
return fmt.Sprintf("POSIX shared memory not supported on this platform: with underlying error: %v", self.err)
}
// prefix_and_suffix splits pattern by the last wildcard "*", if applicable,
// returning prefix as the part before "*" and suffix as the part after "*".
func prefix_and_suffix(pattern string) (prefix, suffix string, err error) {
for i := 0; i < len(pattern); i++ {
if os.IsPathSeparator(pattern[i]) {
return "", "", ErrPatternHasSeparator
}
}
if pos := strings.LastIndexByte(pattern, '*'); pos != -1 {
prefix, suffix = pattern[:pos], pattern[pos+1:]
} else {
prefix = pattern
}
return prefix, suffix, nil
}
type MMap interface {
Close() error
Unlink() error
Slice() []byte
Name() string
IsFileSystemBacked() bool
FileSystemName() string
Stat() (fs.FileInfo, error)
Flush() error
Seek(offset int64, whence int) (ret int64, err error)
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
}
type AccessFlags int
const (
READ AccessFlags = iota
WRITE
COPY
)
func mmap(sz int, access AccessFlags, fd int, off int64) ([]byte, error) {
flags := unix.MAP_SHARED
prot := unix.PROT_READ
switch access {
case COPY:
prot |= unix.PROT_WRITE
flags = unix.MAP_PRIVATE
case WRITE:
prot |= unix.PROT_WRITE
}
b, err := unix.Mmap(fd, off, sz, prot, flags)
if err != nil {
return nil, err
}
return b, nil
}
func munmap(s []byte) error {
return unix.Munmap(s)
}
func CreateTemp(pattern string, size uint64) (MMap, error) {
return create_temp(pattern, size)
}
func truncate_or_unlink(ans *os.File, size uint64, unlink func(string) error) (err error) {
fd := int(ans.Fd())
sz := int64(size)
if err = Fallocate_simple(fd, sz); err != nil {
if !errors.Is(err, errors.ErrUnsupported) {
return fmt.Errorf("fallocate() failed on fd from shm_open(%s) with size: %d with error: %w", ans.Name(), size, err)
}
for {
if err = unix.Ftruncate(fd, sz); !errors.Is(err, unix.EINTR) {
break
}
}
}
if err != nil {
_ = ans.Close()
_ = unlink(ans.Name())
return fmt.Errorf("Failed to ftruncate() SHM file %s to size: %d with error: %w", ans.Name(), size, err)
}
return
}
const NUM_BYTES_FOR_SIZE = 4
var ErrRegionTooSmall = errors.New("mmaped region too small")
func WriteWithSize(self MMap, b []byte, at int) error {
if len(self.Slice()) < at+len(b)+NUM_BYTES_FOR_SIZE {
return ErrRegionTooSmall
}
binary.BigEndian.PutUint32(self.Slice()[at:], uint32(len(b)))
copy(self.Slice()[at+NUM_BYTES_FOR_SIZE:], b)
return nil
}
func ReadWithSize(self MMap, at int) ([]byte, error) {
s := self.Slice()[at:]
if len(s) < NUM_BYTES_FOR_SIZE {
return nil, ErrRegionTooSmall
}
size := int(binary.BigEndian.Uint32(self.Slice()[at : at+NUM_BYTES_FOR_SIZE]))
s = s[NUM_BYTES_FOR_SIZE:]
if len(s) < size {
return nil, ErrRegionTooSmall
}
return s[:size], nil
}
func ReadWithSizeAndUnlink(name string, file_callback ...func(fs.FileInfo) error) ([]byte, error) {
mmap, err := Open(name, 0)
if err != nil {
return nil, err
}
if len(file_callback) > 0 {
s, err := mmap.Stat()
if err != nil {
return nil, fmt.Errorf("Failed to stat SHM file with error: %w", err)
}
for _, f := range file_callback {
err = f(s)
if err != nil {
return nil, err
}
}
}
defer func() {
mmap.Close()
_ = mmap.Unlink()
}()
slice, err := ReadWithSize(mmap, 0)
if err != nil {
return nil, err
}
ans := make([]byte, len(slice))
copy(ans, slice)
return ans, nil
}
func Read(self MMap, b []byte) (n int, err error) {
pos, err := self.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
if pos < 0 {
pos = 0
}
s := self.Slice()
sz := int64(len(s))
if pos >= sz {
return 0, io.EOF
}
n = copy(b, s[pos:])
_, err = self.Seek(int64(n), io.SeekCurrent)
return
}
func Write(self MMap, b []byte) (n int, err error) {
if len(b) == 0 {
return 0, nil
}
pos, _ := self.Seek(0, io.SeekCurrent)
if pos < 0 {
pos = 0
}
s := self.Slice()
if pos >= int64(len(s)) {
return 0, io.ErrShortWrite
}
n = copy(s[pos:], b)
if _, err = self.Seek(int64(n), io.SeekCurrent); err != nil {
return n, err
}
if n < len(b) {
return n, io.ErrShortWrite
}
return n, nil
}
+187
View File
@@ -0,0 +1,187 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build linux || netbsd || openbsd || dragonfly
package shm
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
type file_based_mmap struct {
f *os.File
pos int64
region []byte
unlinked bool
special_name string
}
func ShmUnlink(name string) error {
if runtime.GOOS == "openbsd" {
return os.Remove(openbsd_shm_path(name))
}
name = strings.TrimPrefix(name, "/")
return os.Remove(filepath.Join(SHM_DIR, name))
}
func file_mmap(f *os.File, size uint64, access AccessFlags, truncate bool, special_name string) (MMap, error) {
if truncate {
err := truncate_or_unlink(f, size, os.Remove)
if err != nil {
return nil, err
}
}
region, err := mmap(int(size), access, int(f.Fd()), 0)
if err != nil {
f.Close()
os.Remove(f.Name())
return nil, err
}
return &file_based_mmap{f: f, region: region, special_name: special_name}, nil
}
func (self *file_based_mmap) Seek(offset int64, whence int) (ret int64, err error) {
switch whence {
case io.SeekStart:
self.pos = offset
case io.SeekEnd:
self.pos = int64(len(self.region)) + offset
case io.SeekCurrent:
self.pos += offset
}
return self.pos, nil
}
func (self *file_based_mmap) Read(b []byte) (n int, err error) {
return Read(self, b)
}
func (self *file_based_mmap) Write(b []byte) (n int, err error) {
return Write(self, b)
}
func (self *file_based_mmap) Stat() (fs.FileInfo, error) {
return self.f.Stat()
}
func (self *file_based_mmap) Name() string {
if self.special_name != "" {
return self.special_name
}
return filepath.Base(self.f.Name())
}
func (self *file_based_mmap) Flush() error {
return unix.Msync(self.region, unix.MS_SYNC)
}
func (self *file_based_mmap) FileSystemName() string {
return self.f.Name()
}
func (self *file_based_mmap) Slice() []byte {
return self.region
}
func (self *file_based_mmap) Close() (err error) {
if self.region != nil {
self.f.Close()
err = munmap(self.region)
self.region = nil
}
return err
}
func (self *file_based_mmap) Unlink() (err error) {
if self.unlinked {
return nil
}
self.unlinked = true
return os.Remove(self.f.Name())
}
func (self *file_based_mmap) IsFileSystemBacked() bool { return true }
func openbsd_shm_path(name string) string {
hash := sha256.Sum256(UnsafeStringToBytes(name))
return filepath.Join(SHM_DIR, UnsafeBytesToString(hash[:])+".shm")
}
func file_path_from_name(name string) string {
// See https://github.com/openbsd/src/blob/master/lib/libc/gen/shm_open.c
if runtime.GOOS == "openbsd" {
return openbsd_shm_path(name)
}
return filepath.Join(SHM_DIR, name)
}
func create_temp(pattern string, size uint64) (ans MMap, err error) {
special_name := ""
var prefix, suffix string
prefix, suffix, err = prefix_and_suffix(pattern)
if err != nil {
return
}
var f *os.File
try := 0
for {
name := prefix + RandomFilename() + suffix
path := file_path_from_name(name)
f, err = os.OpenFile(path, os.O_EXCL|os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
if errors.Is(err, fs.ErrExist) {
try += 1
if try > 10000 {
return nil, &os.PathError{Op: "createtemp", Path: prefix + "*" + suffix, Err: fs.ErrExist}
}
continue
}
if errors.Is(err, fs.ErrNotExist) {
return nil, &ErrNotSupported{err: err}
}
return
}
break
}
return file_mmap(f, size, WRITE, true, special_name)
}
func open(name string) (*os.File, error) {
ans, err := os.OpenFile(file_path_from_name(name), os.O_RDONLY, 0)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
if _, serr := os.Stat(SHM_DIR); serr != nil && errors.Is(serr, fs.ErrNotExist) {
return nil, &ErrNotSupported{err: serr}
}
}
return nil, err
}
return ans, nil
}
func Open(name string, size uint64) (MMap, error) {
ans, err := open(name)
if err != nil {
return nil, err
}
if size == 0 {
s, err := ans.Stat()
if err != nil {
ans.Close()
return nil, fmt.Errorf("Failed to stat SHM file with error: %w", err)
}
size = uint64(s.Size())
}
return file_mmap(ans, size, READ, false, name)
}
+198
View File
@@ -0,0 +1,198 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build darwin || freebsd
package shm
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"strings"
"unsafe"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
// ByteSliceFromString makes a zero terminated byte slice from the string
func ByteSliceFromString(s string) []byte {
a := make([]byte, len(s)+1)
copy(a, s)
return a
}
func BytePtrFromString(s string) *byte {
a := ByteSliceFromString(s)
return &a[0]
}
func shm_unlink(name string) (err error) {
bname := BytePtrFromString(name)
for {
_, _, errno := unix.Syscall(unix.SYS_SHM_UNLINK, uintptr(unsafe.Pointer(bname)), 0, 0)
if errno != unix.EINTR {
if errno != 0 {
if errno == unix.ENOENT {
err = fs.ErrNotExist
} else {
err = fmt.Errorf("shm_unlink() failed with error: %w", errno)
}
}
break
}
}
return
}
func ShmUnlink(name string) error {
return shm_unlink(name)
}
func shm_open(name string, flags, perm int) (ans *os.File, err error) {
bname := BytePtrFromString(name)
var fd uintptr
var errno unix.Errno
for {
fd, _, errno = unix.Syscall(unix.SYS_SHM_OPEN, uintptr(unsafe.Pointer(bname)), uintptr(flags), uintptr(perm))
if errno != unix.EINTR {
if errno != 0 {
err = fmt.Errorf("shm_open() failed with error: %w", errno)
}
break
}
}
if err == nil {
ans = os.NewFile(fd, name)
}
return
}
type syscall_based_mmap struct {
f *os.File
pos int64
region []byte
unlinked bool
}
func syscall_mmap(f *os.File, size uint64, access AccessFlags, truncate bool) (MMap, error) {
if truncate {
err := truncate_or_unlink(f, size, shm_unlink)
if err != nil {
return nil, fmt.Errorf("truncate failed with error: %w", err)
}
}
region, err := mmap(int(size), access, int(f.Fd()), 0)
if err != nil {
_ = f.Close()
_ = shm_unlink(f.Name())
return nil, fmt.Errorf("mmap failed with error: %w", err)
}
return &syscall_based_mmap{f: f, region: region}, nil
}
func (self *syscall_based_mmap) Name() string {
return self.f.Name()
}
func (self *syscall_based_mmap) Stat() (fs.FileInfo, error) {
return self.f.Stat()
}
func (self *syscall_based_mmap) Flush() error {
return unix.Msync(self.region, unix.MS_SYNC)
}
func (self *syscall_based_mmap) Slice() []byte {
return self.region
}
func (self *syscall_based_mmap) Close() (err error) {
if self.region != nil {
self.f.Close()
munmap(self.region)
self.region = nil
}
return
}
func (self *syscall_based_mmap) Unlink() (err error) {
if self.unlinked {
return nil
}
self.unlinked = true
return shm_unlink(self.Name())
}
func (self *syscall_based_mmap) Seek(offset int64, whence int) (ret int64, err error) {
switch whence {
case io.SeekStart:
self.pos = offset
case io.SeekEnd:
self.pos = int64(len(self.region)) + offset
case io.SeekCurrent:
self.pos += offset
}
return self.pos, nil
}
func (self *syscall_based_mmap) Read(b []byte) (n int, err error) {
return Read(self, b)
}
func (self *syscall_based_mmap) Write(b []byte) (n int, err error) {
return Write(self, b)
}
func (self *syscall_based_mmap) IsFileSystemBacked() bool { return false }
func (self *syscall_based_mmap) FileSystemName() string { return "" }
func create_temp(pattern string, size uint64) (ans MMap, err error) {
var prefix, suffix string
prefix, suffix, err = prefix_and_suffix(pattern)
if err != nil {
return
}
if SHM_REQUIRED_PREFIX != "" && !strings.HasPrefix(pattern, SHM_REQUIRED_PREFIX) {
// FreeBSD requires name to start with /
prefix = SHM_REQUIRED_PREFIX + prefix
}
var f *os.File
try := 0
for {
name := prefix + RandomFilename() + suffix
if len(name) > SHM_NAME_MAX {
return nil, ErrPatternTooLong
}
f, err = shm_open(name, os.O_EXCL|os.O_CREATE|os.O_RDWR, 0600)
if err != nil && (errors.Is(err, fs.ErrExist) || errors.Unwrap(err) == unix.EEXIST) {
try += 1
if try > 10000 {
return nil, &os.PathError{Op: "createtemp", Path: prefix + "*" + suffix, Err: fs.ErrExist}
}
continue
}
break
}
if err != nil {
return nil, err
}
return syscall_mmap(f, size, WRITE, true)
}
func Open(name string, size uint64) (MMap, error) {
ans, err := shm_open(name, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
if size == 0 {
s, err := ans.Stat()
if err != nil {
ans.Close()
return nil, fmt.Errorf("Failed to stat SHM file with error: %w", err)
}
size = uint64(s.Size())
}
return syscall_mmap(ans, size, READ, false)
}
+7
View File
@@ -0,0 +1,7 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
const SHM_NAME_MAX = 30
const SHM_REQUIRED_PREFIX = ""
const SHM_DIR = ""
+12
View File
@@ -0,0 +1,12 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
import (
"fmt"
)
var _ = fmt.Print
// https://www.dragonflybsd.org/cgi/web-man?command=shm_open&section=3
const SHM_DIR = "/var/run/shm"
+7
View File
@@ -0,0 +1,7 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
const SHM_NAME_MAX = 1023
const SHM_REQUIRED_PREFIX = "/"
const SHM_DIR = ""
+11
View File
@@ -0,0 +1,11 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
import (
"fmt"
)
var _ = fmt.Print
const SHM_DIR = "/dev/shm"
+11
View File
@@ -0,0 +1,11 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
import (
"fmt"
)
var _ = fmt.Print
const SHM_DIR = "/var/shm"
+11
View File
@@ -0,0 +1,11 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shm
import (
"fmt"
)
var _ = fmt.Print
const SHM_DIR = "/tmp"
+35
View File
@@ -0,0 +1,35 @@
package shm
import (
"crypto/rand"
"encoding/base32"
"fmt"
not_rand "math/rand/v2"
"strconv"
"unsafe"
)
var _ = fmt.Print
func RandomFilename() string {
b := []byte{0, 0, 0, 0, 0, 0, 0, 0}
_, err := rand.Read(b)
if err != nil {
return strconv.FormatUint(uint64(not_rand.Uint32()), 16)
}
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b)
}
// Unsafely converts s into a byte slice.
// If you modify b, then s will also be modified. This violates the
// property that strings are immutable.
func UnsafeStringToBytes(s string) (b []byte) {
return unsafe.Slice(unsafe.StringData(s), len(s))
}
// Unsafely converts b into a string.
// If you modify b, then s will also be modified. This violates the
// property that strings are immutable.
func UnsafeBytesToString(b []byte) (s string) {
return unsafe.String(unsafe.SliceData(b), len(b))
}
+2 -1
View File
@@ -3,7 +3,8 @@
This is pure Go code that makes working with images actually
useable on top of the Go stdlib. In addition to the usual PNG/JPEG/WebP/TIFF/BMP/GIF
formats that have been supported forever, this package adds support for
animated PNG, animated WebP and all the netPBM image formats.
animated PNG, animated WebP, Google's new "jpegli" JPEG variant
and all the netPBM image formats.
Additionally, this package support color management via ICC profiles and CICP
metadata. Opening non-sRGB images automatically converts them to sRGB, so you
+29 -23
View File
@@ -4,17 +4,20 @@ import (
"image"
"image/color"
"math"
"github.com/kovidgoyal/imaging/nrgba"
)
// Grayscale produces a grayscale version of the image.
func Grayscale(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * dst.Stride
src.Scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
src.Scan(0, y, w, y+1, dst.Pix[i:i+w*4])
for range w {
d := dst.Pix[i : i+3 : i+3]
r := d[0]
g := d[1]
@@ -27,7 +30,7 @@ func Grayscale(img image.Image) *image.NRGBA {
i += 4
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
@@ -35,13 +38,14 @@ func Grayscale(img image.Image) *image.NRGBA {
// Invert produces an inverted (negated) version of the image.
func Invert(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * dst.Stride
src.Scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
src.Scan(0, y, w, y+1, dst.Pix[i:i+w*4])
for range w {
d := dst.Pix[i : i+3 : i+3]
d[0] = 255 - d[0]
d[1] = 255 - d[1]
@@ -49,7 +53,7 @@ func Invert(img image.Image) *image.NRGBA {
i += 4
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
@@ -129,7 +133,7 @@ func AdjustContrast(img image.Image, percentage float64) *image.NRGBA {
lut := make([]uint8, 256)
v := (100.0 + percentage) / 100.0
for i := 0; i < 256; i++ {
for i := range 256 {
switch {
case 0 <= v && v <= 1:
lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*v) * 255.0)
@@ -160,7 +164,7 @@ func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA {
lut := make([]uint8, 256)
shift := 255.0 * percentage / 100.0
for i := 0; i < 256; i++ {
for i := range 256 {
lut[i] = clamp(float64(i) + shift)
}
@@ -182,7 +186,7 @@ func AdjustGamma(img image.Image, gamma float64) *image.NRGBA {
e := 1.0 / math.Max(gamma, 0.0001)
lut := make([]uint8, 256)
for i := 0; i < 256; i++ {
for i := range 256 {
lut[i] = clamp(math.Pow(float64(i)/255.0, e) * 255.0)
}
@@ -236,14 +240,15 @@ func sigmoid(a, b, x float64) float64 {
// adjustLUT applies the given lookup table to the colors of the image.
func adjustLUT(img image.Image, lut []uint8) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
lut = lut[0:256]
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * dst.Stride
src.Scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
src.Scan(0, y, w, y+1, dst.Pix[i:i+w*4])
for range w {
d := dst.Pix[i : i+3 : i+3]
d[0] = lut[d[0]]
d[1] = lut[d[1]]
@@ -251,7 +256,7 @@ func adjustLUT(img image.Image, lut []uint8) *image.NRGBA {
i += 4
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
@@ -273,13 +278,14 @@ func adjustLUT(img image.Image, lut []uint8) *image.NRGBA {
// }
// )
func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * dst.Stride
src.Scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
src.Scan(0, y, w, y+1, dst.Pix[i:i+w*4])
for range w {
d := dst.Pix[i : i+4 : i+4]
r := d[0]
g := d[1]
@@ -293,7 +299,7 @@ func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGB
i += 4
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
+16 -11
View File
@@ -13,7 +13,7 @@ import (
"os"
"time"
"github.com/kettek/apng"
"github.com/kovidgoyal/imaging/apng"
"github.com/kovidgoyal/imaging/prism/meta"
"github.com/kovidgoyal/imaging/prism/meta/gifmeta"
"github.com/kovidgoyal/imaging/webp"
@@ -163,15 +163,20 @@ func (self *Image) populate_from_gif(g *gif.GIF) {
Delay: gifmeta.CalculateFrameDelay(g.Delay[i], min_gap),
}
switch prev_disposal {
case gif.DisposalNone:
case gif.DisposalNone, 0: // 1
frame.ComposeOnto = frame.Number - 1
case gif.DisposalPrevious:
case gif.DisposalPrevious: // 3
frame.ComposeOnto = prev_compose_onto
case gif.DisposalBackground:
// this is in contravention of the GIF spec but browsers and
// gif2apng both do this, so follow them. Test image for this
// is apple.gif
frame.ComposeOnto = frame.Number - 1
case gif.DisposalBackground: // 2
if i > 0 && g.Delay[i-1] == 0 {
// this is in contravention of the GIF spec but browsers and
// gif2apng both do this, so follow them. Test images for this
// are apple.gif and disposal-background-with-delay.gif
frame.ComposeOnto = frame.Number - 1
} else {
// delay present, frame visible, so clear to background as the spec requires
frame.ComposeOnto = 0
}
}
prev_disposal, prev_compose_onto = g.Disposal[i], frame.ComposeOnto
self.Frames = append(self.Frames, &frame)
@@ -460,12 +465,12 @@ func (self *Image) Resize(width, height int, filter ResampleFilter) {
sx := float64(width) / float64(old_width)
sy := float64(height) / float64(old_height)
scaledx := func(x int) int { return int(float64(x) * sx) }
scaledy := func(x int) int { return int(float64(x) * sy) }
scaledy := func(y int) int { return int(float64(y) * sy) }
for i, f := range self.Frames {
if i == 0 {
f.Image = Resize(f.Image, width, height, filter)
f.Image = ResizeWithOpacity(f.Image, width, height, filter, IsOpaque(f.Image))
} else {
f.Image = Resize(f.Image, scaledx(f.Image.Bounds().Dx()), scaledy(f.Image.Bounds().Dy()), filter)
f.Image = ResizeWithOpacity(f.Image, scaledx(f.Image.Bounds().Dx()), scaledy(f.Image.Bounds().Dy()), filter, IsOpaque(f.Image))
f.TopLeft = image.Pt(scaledx(f.TopLeft.X), scaledy(f.TopLeft.Y))
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -46,7 +46,7 @@ func paeth(a, b, c uint8) uint8 {
// cdat is the current row's data, pdat is the previous row's data.
func filterPaeth(cdat, pdat []byte, bytesPerPixel int) {
var a, b, c, pa, pb, pc int
for i := 0; i < bytesPerPixel; i++ {
for i := range bytesPerPixel {
a, c = 0, 0
for j := i; j < len(cdat); j += bytesPerPixel {
b = int(pdat[j])
@@ -20,6 +20,8 @@ import (
"image"
"image/color"
"io"
"github.com/kovidgoyal/imaging/nrgb"
)
// Color type, as per the PNG spec.
@@ -249,7 +251,7 @@ func (d *decoder) parsePLTE(length uint32) error {
switch d.cb {
case cbP1, cbP2, cbP4, cbP8:
d.palette = make(color.Palette, 256)
for i := 0; i < np; i++ {
for i := range np {
d.palette[i] = color.RGBA{d.tmp[3*i+0], d.tmp[3*i+1], d.tmp[3*i+2], 0xff}
}
for i := np; i < 256; i++ {
@@ -319,7 +321,7 @@ func (d *decoder) parsetRNS(length uint32) error {
if len(d.palette) < n {
d.palette = d.palette[:n]
}
for i := 0; i < n; i++ {
for i := range n {
rgba := d.palette[i].(color.RGBA)
d.palette[i] = color.NRGBA{rgba.R, rgba.G, rgba.B, d.tmp[i]}
}
@@ -332,7 +334,9 @@ func (d *decoder) parsetRNS(length uint32) error {
// Read presents one or more IDAT chunks as one continuous stream (minus the
// intermediate chunk headers and footers). If the PNG data looked like:
// ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2
//
// ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2
//
// then this reader presents xxxyy. For well-formed PNG data, the decoder state
// immediately before the first Read call is that d.r is positioned between the
// first IDAT and xxx, and the decoder state immediately after the last Read
@@ -400,7 +404,7 @@ func (d *decoder) decode() (image.Image, error) {
if err != nil {
return nil, err
}
for pass := 0; pass < 7; pass++ {
for pass := range 7 {
imagePass, err := d.readImagePass(r, pass, false)
if err != nil {
return nil, err
@@ -435,7 +439,7 @@ func (d *decoder) readImagePass(r io.Reader, pass int, allocateOnly bool) (image
pixOffset := 0
var (
gray *image.Gray
rgba *image.RGBA
rgb *nrgb.Image
paletted *image.Paletted
nrgba *image.NRGBA
gray16 *image.Gray16
@@ -479,8 +483,8 @@ func (d *decoder) readImagePass(r io.Reader, pass int, allocateOnly bool) (image
nrgba = image.NewNRGBA(image.Rect(0, 0, width, height))
img = nrgba
} else {
rgba = image.NewRGBA(image.Rect(0, 0, width, height))
img = rgba
rgb = nrgb.NewNRGB(image.Rect(0, 0, width, height))
img = rgb
}
case cbP1, cbP2, cbP4, cbP8:
bitsPerPixel = d.depth
@@ -559,7 +563,7 @@ func (d *decoder) readImagePass(r io.Reader, pass int, allocateOnly bool) (image
// The first column has no column to the left of it, so it is a
// special case. We know that the first column exists because we
// check above that width != 0, and so len(cdat) != 0.
for i := 0; i < bytesPerPixel; i++ {
for i := range bytesPerPixel {
cdat[i] += pdat[i] / 2
}
for i := bytesPerPixel; i < len(cdat); i++ {
@@ -686,16 +690,15 @@ func (d *decoder) readImagePass(r io.Reader, pass int, allocateOnly bool) (image
}
pixOffset += nrgba.Stride
} else {
pix, i, j := rgba.Pix, pixOffset, 0
pix, i, j := rgb.Pix, pixOffset, 0
for x := 0; x < width; x++ {
pix[i+0] = cdat[j+0]
pix[i+1] = cdat[j+1]
pix[i+2] = cdat[j+2]
pix[i+3] = 0xff
i += 4
i += 3
j += 3
}
pixOffset += rgba.Stride
pixOffset += rgb.Stride
}
case cbP1:
for x := 0; x < width; x += 8 {
@@ -1146,7 +1149,3 @@ func DecodeConfig(r io.Reader) (image.Config, error) {
Height: d.a.Frames[0].height,
}, nil
}
func init() {
image.RegisterFormat("apng", pngHeader, Decode, DecodeConfig)
}
@@ -281,7 +281,7 @@ func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
// The up filter.
sum := 0
for i := 0; i < n; i++ {
for i := range n {
cdat2[i] = cdat0[i] - pdat[i]
sum += abs8(cdat2[i])
}
@@ -290,7 +290,7 @@ func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
// The Paeth filter.
sum = 0
for i := 0; i < bpp; i++ {
for i := range bpp {
cdat4[i] = cdat0[i] - pdat[i]
sum += abs8(cdat4[i])
}
@@ -308,7 +308,7 @@ func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
// The none filter.
sum = 0
for i := 0; i < n; i++ {
for i := range n {
sum += abs8(cdat0[i])
if sum >= best {
break
@@ -321,7 +321,7 @@ func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
// The sub filter.
sum = 0
for i := 0; i < bpp; i++ {
for i := range bpp {
cdat1[i] = cdat0[i]
sum += abs8(cdat1[i])
}
@@ -339,7 +339,7 @@ func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
// The average filter.
sum = 0
for i := 0; i < bpp; i++ {
for i := range bpp {
cdat3[i] = cdat0[i] - pdat[i]/2
sum += abs8(cdat3[i])
}
+1 -1
View File
@@ -72,7 +72,7 @@ func convolve(img image.Image, kernel []float64, options *ConvolveOptions) *imag
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
for x := 0; x < w; x++ {
for x := range w {
var r, g, b float64
for _, c := range coefs {
ix := x + c.x
+25 -20
View File
@@ -3,6 +3,8 @@ package imaging
import (
"image"
"math"
"github.com/kovidgoyal/imaging/nrgba"
)
func gaussianBlurKernel(x, sigma float64) float64 {
@@ -31,21 +33,22 @@ func Blur(img image.Image, sigma float64) *image.NRGBA {
}
func blurHorizontal(img image.Image, kernel []float64) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
radius := len(kernel) - 1
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, src.w*4)
scanLine := make([]uint8, w*4)
scanLineF := make([]float64, len(scanLine))
for y := start; y < limit; y++ {
src.Scan(0, y, src.w, y+1, scanLine)
src.Scan(0, y, w, y+1, scanLine)
for i, v := range scanLine {
scanLineF[i] = float64(v)
}
for x := 0; x < src.w; x++ {
for x := range w {
minv := max(0, x-radius)
maxv := min(x+radius, src.w-1)
maxv := min(x+radius, w-1)
var r, g, b, a, wsum float64
for ix := minv; ix <= maxv; ix++ {
i := ix * 4
@@ -69,7 +72,7 @@ func blurHorizontal(img image.Image, kernel []float64) *image.NRGBA {
}
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
@@ -77,21 +80,22 @@ func blurHorizontal(img image.Image, kernel []float64) *image.NRGBA {
}
func blurVertical(img image.Image, kernel []float64) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
radius := len(kernel) - 1
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, src.h*4)
scanLine := make([]uint8, h*4)
scanLineF := make([]float64, len(scanLine))
for x := start; x < limit; x++ {
src.Scan(x, 0, x+1, src.h, scanLine)
src.Scan(x, 0, x+1, h, scanLine)
for i, v := range scanLine {
scanLineF[i] = float64(v)
}
for y := 0; y < src.h; y++ {
for y := range h {
minv := max(0, y-radius)
maxv := min(y+radius, src.h-1)
maxv := min(y+radius, h-1)
var r, g, b, a, wsum float64
for iy := minv; iy <= maxv; iy++ {
i := iy * 4
@@ -115,7 +119,7 @@ func blurVertical(img image.Image, kernel []float64) *image.NRGBA {
}
}
}
}, 0, src.w); err != nil {
}, 0, w); err != nil {
panic(err)
}
@@ -133,16 +137,17 @@ func Sharpen(img image.Image, sigma float64) *image.NRGBA {
return Clone(img)
}
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
blurred := Blur(img, sigma)
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, src.w*4)
scanLine := make([]uint8, w*4)
for y := start; y < limit; y++ {
src.Scan(0, y, src.w, y+1, scanLine)
src.Scan(0, y, w, y+1, scanLine)
j := y * dst.Stride
for i := 0; i < src.w*4; i++ {
for i := 0; i < w*4; i++ {
val := int(scanLine[i])<<1 - int(blurred.Pix[j])
if val < 0 {
val = 0
@@ -153,7 +158,7 @@ func Sharpen(img image.Image, sigma float64) *image.NRGBA {
j++
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
+9 -6
View File
@@ -3,6 +3,8 @@ package imaging
import (
"image"
"sync"
"github.com/kovidgoyal/imaging/nrgba"
)
// Histogram returns a normalized histogram of an image.
@@ -14,19 +16,20 @@ func Histogram(img image.Image) [256]float64 {
var histogram [256]float64
var total float64
src := newScanner(img)
if src.w == 0 || src.h == 0 {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
if w == 0 || h == 0 {
return histogram
}
src := nrgba.NewNRGBAScanner(img)
if err := run_in_parallel_over_range(0, func(start, limit int) {
var tmpHistogram [256]float64
var tmpTotal float64
scanLine := make([]uint8, src.w*4)
scanLine := make([]uint8, w*4)
for y := start; y < limit; y++ {
src.Scan(0, y, src.w, y+1, scanLine)
src.Scan(0, y, w, y+1, scanLine)
i := 0
for x := 0; x < src.w; x++ {
for range w {
s := scanLine[i : i+3 : i+3]
r := s[0]
g := s[1]
@@ -43,7 +46,7 @@ func Histogram(img image.Image) [256]float64 {
}
total += tmpTotal
mu.Unlock()
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
+16 -4
View File
@@ -16,6 +16,8 @@ import (
"strings"
"time"
"github.com/kovidgoyal/imaging/apng"
myjpeg "github.com/kovidgoyal/imaging/jpeg"
"github.com/kovidgoyal/imaging/magick"
_ "github.com/kovidgoyal/imaging/netpbm"
"github.com/kovidgoyal/imaging/prism/meta"
@@ -26,7 +28,6 @@ import (
"github.com/kovidgoyal/imaging/types"
"github.com/kovidgoyal/imaging/webp"
"github.com/kettek/apng"
"github.com/rwcarlsen/goexif/exif"
exif_tiff "github.com/rwcarlsen/goexif/tiff"
@@ -178,7 +179,10 @@ func NewDecodeConfig(opts ...DecodeOption) (cfg *decodeConfig) {
func (cfg *decodeConfig) magick_callback(w, h int) (ro magick.RenderOptions) {
ro.AutoOrient = cfg.autoOrientation
if cfg.resize != nil {
ro.ResizeTo.X, ro.ResizeTo.Y = cfg.resize(w, h)
nw, nh := cfg.resize(w, h)
if nw != w || nh != h {
ro.ResizeTo.X, ro.ResizeTo.Y = nw, nh
}
}
ro.Background = cfg.background
ro.ToSRGB = cfg.outputColorspace == SRGB_COLORSPACE
@@ -382,7 +386,15 @@ func decode_all_go(r io.Reader, md *meta.Data, cfg *decodeConfig) (ans *Image, e
ans.Metadata.NumFrames = len(ans.Frames)
ans.Metadata.NumPlays = int(ans.LoopCount)
} else {
img, _, err := image.Decode(r)
var img image.Image
switch md.Format {
case JPEG:
img, err = myjpeg.Decode(r)
case PNG:
img, err = apng.Decode(r)
default:
img, _, err = image.Decode(r)
}
if err != nil {
return nil, err
}
@@ -622,7 +634,7 @@ func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) e
switch format {
case JPEG:
if nrgba, ok := img.(*image.NRGBA); ok && nrgba.Opaque() {
if nrgba, ok := img.(*image.NRGBA); ok && IsOpaque(nrgba) {
rgba := &image.RGBA{
Pix: nrgba.Pix,
Stride: nrgba.Stride,
+245
View File
@@ -0,0 +1,245 @@
// Copyright 2009 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 jpeg
import (
"io"
)
// maxCodeLength is the maximum (inclusive) number of bits in a Huffman code.
const maxCodeLength = 16
// maxNCodes is the maximum (inclusive) number of codes in a Huffman tree.
const maxNCodes = 256
// lutSize is the log-2 size of the Huffman decoder's look-up table.
const lutSize = 8
// huffman is a Huffman decoder, specified in section C.
type huffman struct {
// length is the number of codes in the tree.
nCodes int32
// lut is the look-up table for the next lutSize bits in the bit-stream.
// The high 8 bits of the uint16 are the encoded value. The low 8 bits
// are 1 plus the code length, or 0 if the value is too large to fit in
// lutSize bits.
lut [1 << lutSize]uint16
// vals are the decoded values, sorted by their encoding.
vals [maxNCodes]uint8
// minCodes[i] is the minimum code of length i, or -1 if there are no
// codes of that length.
minCodes [maxCodeLength]int32
// maxCodes[i] is the maximum code of length i, or -1 if there are no
// codes of that length.
maxCodes [maxCodeLength]int32
// valsIndices[i] is the index into vals of minCodes[i].
valsIndices [maxCodeLength]int32
}
// errShortHuffmanData means that an unexpected EOF occurred while decoding
// Huffman data.
var errShortHuffmanData = FormatError("short Huffman data")
// ensureNBits reads bytes from the byte buffer to ensure that d.bits.n is at
// least n. For best performance (avoiding function calls inside hot loops),
// the caller is the one responsible for first checking that d.bits.n < n.
func (d *decoder) ensureNBits(n int32) error {
for {
c, err := d.readByteStuffedByte()
if err != nil {
if err == io.ErrUnexpectedEOF {
return errShortHuffmanData
}
return err
}
d.bits.a = d.bits.a<<8 | uint32(c)
d.bits.n += 8
if d.bits.m == 0 {
d.bits.m = 1 << 7
} else {
d.bits.m <<= 8
}
if d.bits.n >= n {
break
}
}
return nil
}
// receiveExtend is the composition of RECEIVE and EXTEND, specified in section
// F.2.2.1.
func (d *decoder) receiveExtend(t uint8) (int32, error) {
if d.bits.n < int32(t) {
if err := d.ensureNBits(int32(t)); err != nil {
return 0, err
}
}
d.bits.n -= int32(t)
d.bits.m >>= t
s := int32(1) << t
x := int32(d.bits.a>>uint8(d.bits.n)) & (s - 1)
if x < s>>1 {
x += ((-1) << t) + 1
}
return x, nil
}
// processDHT processes a Define Huffman Table marker, and initializes a huffman
// struct from its contents. Specified in section B.2.4.2.
func (d *decoder) processDHT(n int) error {
for n > 0 {
if n < 17 {
return FormatError("DHT has wrong length")
}
if err := d.readFull(d.tmp[:17]); err != nil {
return err
}
tc := d.tmp[0] >> 4
if tc > maxTc {
return FormatError("bad Tc value")
}
th := d.tmp[0] & 0x0f
// The baseline th <= 1 restriction is specified in table B.5.
if th > maxTh || (d.baseline && th > 1) {
return FormatError("bad Th value")
}
h := &d.huff[tc][th]
// Read nCodes and h.vals (and derive h.nCodes).
// nCodes[i] is the number of codes with code length i.
// h.nCodes is the total number of codes.
h.nCodes = 0
var nCodes [maxCodeLength]int32
for i := range nCodes {
nCodes[i] = int32(d.tmp[i+1])
h.nCodes += nCodes[i]
}
if h.nCodes == 0 {
return FormatError("Huffman table has zero length")
}
if h.nCodes > maxNCodes {
return FormatError("Huffman table has excessive length")
}
n -= int(h.nCodes) + 17
if n < 0 {
return FormatError("DHT has wrong length")
}
if err := d.readFull(h.vals[:h.nCodes]); err != nil {
return err
}
// Derive the look-up table.
clear(h.lut[:])
var x, code uint32
for i := range uint32(lutSize) {
code <<= 1
for j := int32(0); j < nCodes[i]; j++ {
// The codeLength is 1+i, so shift code by 8-(1+i) to
// calculate the high bits for every 8-bit sequence
// whose codeLength's high bits matches code.
// The high 8 bits of lutValue are the encoded value.
// The low 8 bits are 1 plus the codeLength.
base := uint8(code << (7 - i))
lutValue := uint16(h.vals[x])<<8 | uint16(2+i)
for k := uint8(0); k < 1<<(7-i); k++ {
h.lut[base|k] = lutValue
}
code++
x++
}
}
// Derive minCodes, maxCodes, and valsIndices.
var c, index int32
for i, n := range nCodes {
if n == 0 {
h.minCodes[i] = -1
h.maxCodes[i] = -1
h.valsIndices[i] = -1
} else {
h.minCodes[i] = c
h.maxCodes[i] = c + n - 1
h.valsIndices[i] = index
c += n
index += n
}
c <<= 1
}
}
return nil
}
// decodeHuffman returns the next Huffman-coded value from the bit-stream,
// decoded according to h.
func (d *decoder) decodeHuffman(h *huffman) (uint8, error) {
if h.nCodes == 0 {
return 0, FormatError("uninitialized Huffman table")
}
if d.bits.n < 8 {
if err := d.ensureNBits(8); err != nil {
if err != errMissingFF00 && err != errShortHuffmanData {
return 0, err
}
// There are no more bytes of data in this segment, but we may still
// be able to read the next symbol out of the previously read bits.
// First, undo the readByte that the ensureNBits call made.
if d.bytes.nUnreadable != 0 {
d.unreadByteStuffedByte()
}
goto slowPath
}
}
if v := h.lut[(d.bits.a>>uint32(d.bits.n-lutSize))&0xff]; v != 0 {
n := (v & 0xff) - 1
d.bits.n -= int32(n)
d.bits.m >>= n
return uint8(v >> 8), nil
}
slowPath:
for i, code := 0, int32(0); i < maxCodeLength; i++ {
if d.bits.n == 0 {
if err := d.ensureNBits(1); err != nil {
return 0, err
}
}
if d.bits.a&d.bits.m != 0 {
code |= 1
}
d.bits.n--
d.bits.m >>= 1
if code <= h.maxCodes[i] {
return h.vals[h.valsIndices[i]+code-h.minCodes[i]], nil
}
code <<= 1
}
return 0, FormatError("bad Huffman code")
}
func (d *decoder) decodeBit() (bool, error) {
if d.bits.n == 0 {
if err := d.ensureNBits(1); err != nil {
return false, err
}
}
ret := d.bits.a&d.bits.m != 0
d.bits.n--
d.bits.m >>= 1
return ret, nil
}
func (d *decoder) decodeBits(n int32) (uint32, error) {
if d.bits.n < n {
if err := d.ensureNBits(n); err != nil {
return 0, err
}
}
ret := d.bits.a >> uint32(d.bits.n-n)
ret &= (1 << uint32(n)) - 1
d.bits.n -= n
d.bits.m >>= uint32(n)
return ret, nil
}
+194
View File
@@ -0,0 +1,194 @@
// Copyright 2009 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 jpeg
// This is a Go translation of idct.c from
//
// http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_IEC_13818-4_2004_Conformance_Testing/Video/verifier/mpeg2decode_960109.tar.gz
//
// which carries the following notice:
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
const blockSize = 64 // A DCT block is 8x8.
type block [blockSize]int32
const (
w1 = 2841 // 2048*sqrt(2)*cos(1*pi/16)
w2 = 2676 // 2048*sqrt(2)*cos(2*pi/16)
w3 = 2408 // 2048*sqrt(2)*cos(3*pi/16)
w5 = 1609 // 2048*sqrt(2)*cos(5*pi/16)
w6 = 1108 // 2048*sqrt(2)*cos(6*pi/16)
w7 = 565 // 2048*sqrt(2)*cos(7*pi/16)
w1pw7 = w1 + w7
w1mw7 = w1 - w7
w2pw6 = w2 + w6
w2mw6 = w2 - w6
w3pw5 = w3 + w5
w3mw5 = w3 - w5
r2 = 181 // 256/sqrt(2)
)
// idct performs a 2-D Inverse Discrete Cosine Transformation.
//
// The input coefficients should already have been multiplied by the
// appropriate quantization table. We use fixed-point computation, with the
// number of bits for the fractional component varying over the intermediate
// stages.
//
// For more on the actual algorithm, see Z. Wang, "Fast algorithms for the
// discrete W transform and for the discrete Fourier transform", IEEE Trans. on
// ASSP, Vol. ASSP- 32, pp. 803-816, Aug. 1984.
func idct(src *block) {
// Horizontal 1-D IDCT.
for y := range 8 {
y8 := y * 8
s := src[y8 : y8+8 : y8+8] // Small cap improves performance, see https://golang.org/issue/27857
// If all the AC components are zero, then the IDCT is trivial.
if s[1] == 0 && s[2] == 0 && s[3] == 0 &&
s[4] == 0 && s[5] == 0 && s[6] == 0 && s[7] == 0 {
dc := s[0] << 3
s[0] = dc
s[1] = dc
s[2] = dc
s[3] = dc
s[4] = dc
s[5] = dc
s[6] = dc
s[7] = dc
continue
}
// Prescale.
x0 := (s[0] << 11) + 128
x1 := s[4] << 11
x2 := s[6]
x3 := s[2]
x4 := s[1]
x5 := s[7]
x6 := s[5]
x7 := s[3]
// Stage 1.
x8 := w7 * (x4 + x5)
x4 = x8 + w1mw7*x4
x5 = x8 - w1pw7*x5
x8 = w3 * (x6 + x7)
x6 = x8 - w3mw5*x6
x7 = x8 - w3pw5*x7
// Stage 2.
x8 = x0 + x1
x0 -= x1
x1 = w6 * (x3 + x2)
x2 = x1 - w2pw6*x2
x3 = x1 + w2mw6*x3
x1 = x4 + x6
x4 -= x6
x6 = x5 + x7
x5 -= x7
// Stage 3.
x7 = x8 + x3
x8 -= x3
x3 = x0 + x2
x0 -= x2
x2 = (r2*(x4+x5) + 128) >> 8
x4 = (r2*(x4-x5) + 128) >> 8
// Stage 4.
s[0] = (x7 + x1) >> 8
s[1] = (x3 + x2) >> 8
s[2] = (x0 + x4) >> 8
s[3] = (x8 + x6) >> 8
s[4] = (x8 - x6) >> 8
s[5] = (x0 - x4) >> 8
s[6] = (x3 - x2) >> 8
s[7] = (x7 - x1) >> 8
}
// Vertical 1-D IDCT.
for x := range 8 {
// Similar to the horizontal 1-D IDCT case, if all the AC components are zero, then the IDCT is trivial.
// However, after performing the horizontal 1-D IDCT, there are typically non-zero AC components, so
// we do not bother to check for the all-zero case.
s := src[x : x+57 : x+57] // Small cap improves performance, see https://golang.org/issue/27857
// Prescale.
y0 := (s[8*0] << 8) + 8192
y1 := s[8*4] << 8
y2 := s[8*6]
y3 := s[8*2]
y4 := s[8*1]
y5 := s[8*7]
y6 := s[8*5]
y7 := s[8*3]
// Stage 1.
y8 := w7*(y4+y5) + 4
y4 = (y8 + w1mw7*y4) >> 3
y5 = (y8 - w1pw7*y5) >> 3
y8 = w3*(y6+y7) + 4
y6 = (y8 - w3mw5*y6) >> 3
y7 = (y8 - w3pw5*y7) >> 3
// Stage 2.
y8 = y0 + y1
y0 -= y1
y1 = w6*(y3+y2) + 4
y2 = (y1 - w2pw6*y2) >> 3
y3 = (y1 + w2mw6*y3) >> 3
y1 = y4 + y6
y4 -= y6
y6 = y5 + y7
y5 -= y7
// Stage 3.
y7 = y8 + y3
y8 -= y3
y3 = y0 + y2
y0 -= y2
y2 = (r2*(y4+y5) + 128) >> 8
y4 = (r2*(y4-y5) + 128) >> 8
// Stage 4.
s[8*0] = (y7 + y1) >> 14
s[8*1] = (y3 + y2) >> 14
s[8*2] = (y0 + y4) >> 14
s[8*3] = (y8 + y6) >> 14
s[8*4] = (y8 - y6) >> 14
s[8*5] = (y0 - y4) >> 14
s[8*6] = (y3 - y2) >> 14
s[8*7] = (y7 - y1) >> 14
}
}
+814
View File
@@ -0,0 +1,814 @@
// Copyright 2009 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 jpeg implements a JPEG image decoder and encoder.
//
// JPEG is defined in ITU-T T.81: https://www.w3.org/Graphics/JPEG/itu-t81.pdf.
package jpeg
import (
"image"
"image/color"
"io"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/imaging/nrgb"
"github.com/kovidgoyal/imaging/nrgba"
)
// A FormatError reports that the input is not a valid JPEG.
type FormatError string
func (e FormatError) Error() string { return "invalid JPEG format: " + string(e) }
// An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.
type UnsupportedError string
func (e UnsupportedError) Error() string { return "unsupported JPEG feature: " + string(e) }
var errUnsupportedSubsamplingRatio = UnsupportedError("luma/chroma subsampling ratio")
// Component specification, specified in section B.2.2.
type component struct {
h int // Horizontal sampling factor.
v int // Vertical sampling factor.
c uint8 // Component identifier.
tq uint8 // Quantization table destination selector.
expand struct{ h, v int } // subsampleRatio for this component
}
const (
dcTable = 0
acTable = 1
maxTc = 1
maxTh = 3
maxTq = 3
maxComponents = 4
)
const (
sof0Marker = 0xc0 // Start Of Frame (Baseline Sequential).
sof1Marker = 0xc1 // Start Of Frame (Extended Sequential).
sof2Marker = 0xc2 // Start Of Frame (Progressive).
dhtMarker = 0xc4 // Define Huffman Table.
rst0Marker = 0xd0 // ReSTart (0).
rst7Marker = 0xd7 // ReSTart (7).
soiMarker = 0xd8 // Start Of Image.
eoiMarker = 0xd9 // End Of Image.
sosMarker = 0xda // Start Of Scan.
dqtMarker = 0xdb // Define Quantization Table.
driMarker = 0xdd // Define Restart Interval.
comMarker = 0xfe // COMment.
// "APPlication specific" markers aren't part of the JPEG spec per se,
// but in practice, their use is described at
// https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html
app0Marker = 0xe0
app14Marker = 0xee
app15Marker = 0xef
)
// See https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
const (
adobeTransformUnknown = 0
adobeTransformYCbCr = 1
adobeTransformYCbCrK = 2
)
// unzig maps from the zig-zag ordering to the natural ordering. For example,
// unzig[3] is the column and row of the fourth element in zig-zag order. The
// value is 16, which means first column (16%8 == 0) and third row (16/8 == 2).
var unzig = [blockSize]int{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
}
// Deprecated: Reader is not used by the [image/jpeg] package and should
// not be used by others. It is kept for compatibility.
type Reader interface {
io.ByteReader
io.Reader
}
// bits holds the unprocessed bits that have been taken from the byte-stream.
// The n least significant bits of a form the unread bits, to be read in MSB to
// LSB order.
type bits struct {
a uint32 // accumulator.
m uint32 // mask. m==1<<(n-1) when n>0, with m==0 when n==0.
n int32 // the number of unread bits in a.
}
type decoder struct {
r io.Reader
bits bits
// bytes is a byte buffer, similar to a bufio.Reader, except that it
// has to be able to unread more than 1 byte, due to byte stuffing.
// Byte stuffing is specified in section F.1.2.3.
bytes struct {
// buf[i:j] are the buffered bytes read from the underlying
// io.Reader that haven't yet been passed further on.
buf [4096]byte
i, j int
// nUnreadable is the number of bytes to back up i after
// overshooting. It can be 0, 1 or 2.
nUnreadable int
}
width, height int
img1 *image.Gray
img3 *image.YCbCr
blackPix []byte
flex bool // uses a non-standard subsampleRatio
force_flex bool // used for testing
maxH, maxV int
blackStride int
ri int // Restart Interval.
nComp int
// As per section 4.5, there are four modes of operation (selected by the
// SOF? markers): sequential DCT, progressive DCT, lossless and
// hierarchical, although this implementation does not support the latter
// two non-DCT modes. Sequential DCT is further split into baseline and
// extended, as per section 4.11.
baseline bool
progressive bool
jfif bool
adobeTransformValid bool
adobeTransform uint8
eobRun uint16 // End-of-Band run, specified in section G.1.2.2.
comp [maxComponents]component
progCoeffs [maxComponents][]block // Saved state between progressive-mode scans.
huff [maxTc + 1][maxTh + 1]huffman
quant [maxTq + 1]block // Quantization tables, in zig-zag order.
tmp [2 * blockSize]byte
}
// fill fills up the d.bytes.buf buffer from the underlying io.Reader. It
// should only be called when there are no unread bytes in d.bytes.
func (d *decoder) fill() error {
if d.bytes.i != d.bytes.j {
panic("jpeg: fill called when unread bytes exist")
}
// Move the last 2 bytes to the start of the buffer, in case we need
// to call unreadByteStuffedByte.
if d.bytes.j > 2 {
d.bytes.buf[0] = d.bytes.buf[d.bytes.j-2]
d.bytes.buf[1] = d.bytes.buf[d.bytes.j-1]
d.bytes.i, d.bytes.j = 2, 2
}
// Fill in the rest of the buffer.
n, err := d.r.Read(d.bytes.buf[d.bytes.j:])
d.bytes.j += n
if n > 0 {
return nil
}
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return err
}
// unreadByteStuffedByte undoes the most recent readByteStuffedByte call,
// giving a byte of data back from d.bits to d.bytes. The Huffman look-up table
// requires at least 8 bits for look-up, which means that Huffman decoding can
// sometimes overshoot and read one or two too many bytes. Two-byte overshoot
// can happen when expecting to read a 0xff 0x00 byte-stuffed byte.
func (d *decoder) unreadByteStuffedByte() {
d.bytes.i -= d.bytes.nUnreadable
d.bytes.nUnreadable = 0
if d.bits.n >= 8 {
d.bits.a >>= 8
d.bits.n -= 8
d.bits.m >>= 8
}
}
// readByte returns the next byte, whether buffered or not buffered. It does
// not care about byte stuffing.
func (d *decoder) readByte() (x byte, err error) {
for d.bytes.i == d.bytes.j {
if err = d.fill(); err != nil {
return 0, err
}
}
x = d.bytes.buf[d.bytes.i]
d.bytes.i++
d.bytes.nUnreadable = 0
return x, nil
}
// errMissingFF00 means that readByteStuffedByte encountered an 0xff byte (a
// marker byte) that wasn't the expected byte-stuffed sequence 0xff, 0x00.
var errMissingFF00 = FormatError("missing 0xff00 sequence")
// readByteStuffedByte is like readByte but is for byte-stuffed Huffman data.
func (d *decoder) readByteStuffedByte() (x byte, err error) {
// Take the fast path if d.bytes.buf contains at least two bytes.
if d.bytes.i+2 <= d.bytes.j {
x = d.bytes.buf[d.bytes.i]
d.bytes.i++
d.bytes.nUnreadable = 1
if x != 0xff {
return x, err
}
if d.bytes.buf[d.bytes.i] != 0x00 {
return 0, errMissingFF00
}
d.bytes.i++
d.bytes.nUnreadable = 2
return 0xff, nil
}
d.bytes.nUnreadable = 0
x, err = d.readByte()
if err != nil {
return 0, err
}
d.bytes.nUnreadable = 1
if x != 0xff {
return x, nil
}
x, err = d.readByte()
if err != nil {
return 0, err
}
d.bytes.nUnreadable = 2
if x != 0x00 {
return 0, errMissingFF00
}
return 0xff, nil
}
// readFull reads exactly len(p) bytes into p. It does not care about byte
// stuffing.
func (d *decoder) readFull(p []byte) error {
// Unread the overshot bytes, if any.
if d.bytes.nUnreadable != 0 {
if d.bits.n >= 8 {
d.unreadByteStuffedByte()
}
d.bytes.nUnreadable = 0
}
for {
n := copy(p, d.bytes.buf[d.bytes.i:d.bytes.j])
p = p[n:]
d.bytes.i += n
if len(p) == 0 {
break
}
if err := d.fill(); err != nil {
return err
}
}
return nil
}
// ignore ignores the next n bytes.
func (d *decoder) ignore(n int) error {
// Unread the overshot bytes, if any.
if d.bytes.nUnreadable != 0 {
if d.bits.n >= 8 {
d.unreadByteStuffedByte()
}
d.bytes.nUnreadable = 0
}
for {
m := min(d.bytes.j-d.bytes.i, n)
d.bytes.i += m
n -= m
if n == 0 {
break
}
if err := d.fill(); err != nil {
return err
}
}
return nil
}
// Specified in section B.2.2.
func (d *decoder) processSOF(n int) error {
if d.nComp != 0 {
return FormatError("multiple SOF markers")
}
switch n {
case 6 + 3*1: // Grayscale image.
d.nComp = 1
case 6 + 3*3: // YCbCr or RGB image.
d.nComp = 3
case 6 + 3*4: // YCbCrK or CMYK image.
d.nComp = 4
default:
return UnsupportedError("number of components")
}
if err := d.readFull(d.tmp[:n]); err != nil {
return err
}
// We only support 8-bit precision.
if d.tmp[0] != 8 {
return UnsupportedError("precision")
}
d.height = int(d.tmp[1])<<8 + int(d.tmp[2])
d.width = int(d.tmp[3])<<8 + int(d.tmp[4])
if int(d.tmp[5]) != d.nComp {
return FormatError("SOF has wrong length")
}
for i := 0; i < d.nComp; i++ {
d.comp[i].c = d.tmp[6+3*i]
// Section B.2.2 states that "the value of C_i shall be different from
// the values of C_1 through C_(i-1)".
for j := 0; j < i; j++ {
if d.comp[i].c == d.comp[j].c {
return FormatError("repeated component identifier")
}
}
d.comp[i].tq = d.tmp[8+3*i]
if d.comp[i].tq > maxTq {
return FormatError("bad Tq value")
}
hv := d.tmp[7+3*i]
h, v := int(hv>>4), int(hv&0x0f)
if h < 1 || 4 < h || v < 1 || 4 < v {
return FormatError("luma/chroma subsampling ratio")
}
if h == 3 || v == 3 {
return errUnsupportedSubsamplingRatio
}
d.maxH, d.maxV = max(d.maxH, h), max(d.maxV, v)
switch d.nComp {
case 1:
// If a JPEG image has only one component, section A.2 says "this data
// is non-interleaved by definition" and section A.2.2 says "[in this
// case...] the order of data units within a scan shall be left-to-right
// and top-to-bottom... regardless of the values of H_1 and V_1". Section
// 4.8.2 also says "[for non-interleaved data], the MCU is defined to be
// one data unit". Similarly, section A.1.1 explains that it is the ratio
// of H_i to max_j(H_j) that matters, and similarly for V. For grayscale
// images, H_1 is the maximum H_j for all components j, so that ratio is
// always 1. The component's (h, v) is effectively always (1, 1): even if
// the nominal (h, v) is (2, 1), a 20x5 image is encoded in three 8x8
// MCUs, not two 16x8 MCUs.
h, v = 1, 1
case 3:
if i == 0 && v == 4 {
return errUnsupportedSubsamplingRatio
}
case 4:
// For 4-component images (either CMYK or YCbCrK), we only support two
// hv vectors: [0x11 0x11 0x11 0x11] and [0x22 0x11 0x11 0x22].
// Theoretically, 4-component JPEG images could mix and match hv values
// but in practice, those two combinations are the only ones in use,
// and it simplifies the applyBlack code below if we can assume that:
// - for CMYK, the C and K channels have full samples, and if the M
// and Y channels subsample, they subsample both horizontally and
// vertically.
// - for YCbCrK, the Y and K channels have full samples.
switch i {
case 0:
if hv != 0x11 && hv != 0x22 {
return errUnsupportedSubsamplingRatio
}
case 1, 2:
if hv != 0x11 {
return errUnsupportedSubsamplingRatio
}
case 3:
if d.comp[0].h != h || d.comp[0].v != v {
return errUnsupportedSubsamplingRatio
}
}
}
d.comp[i].h = h
d.comp[i].v = v
}
if d.nComp == 3 {
for i := range 3 {
if d.maxH%d.comp[i].h != 0 || d.maxV%d.comp[i].v != 0 {
return errUnsupportedSubsamplingRatio
}
}
}
for i := range d.nComp {
d.comp[i].expand.h = d.maxH / d.comp[i].h
d.comp[i].expand.v = d.maxV / d.comp[i].v
}
return nil
}
// Specified in section B.2.4.1.
func (d *decoder) processDQT(n int) error {
loop:
for n > 0 {
n--
x, err := d.readByte()
if err != nil {
return err
}
tq := x & 0x0f
if tq > maxTq {
return FormatError("bad Tq value")
}
switch x >> 4 {
default:
return FormatError("bad Pq value")
case 0:
if n < blockSize {
break loop
}
n -= blockSize
if err := d.readFull(d.tmp[:blockSize]); err != nil {
return err
}
for i := range d.quant[tq] {
d.quant[tq][i] = int32(d.tmp[i])
}
case 1:
if n < 2*blockSize {
break loop
}
n -= 2 * blockSize
if err := d.readFull(d.tmp[:2*blockSize]); err != nil {
return err
}
for i := range d.quant[tq] {
d.quant[tq][i] = int32(d.tmp[2*i])<<8 | int32(d.tmp[2*i+1])
}
}
}
if n != 0 {
return FormatError("DQT has wrong length")
}
return nil
}
// Specified in section B.2.4.4.
func (d *decoder) processDRI(n int) error {
if n != 2 {
return FormatError("DRI has wrong length")
}
if err := d.readFull(d.tmp[:2]); err != nil {
return err
}
d.ri = int(d.tmp[0])<<8 + int(d.tmp[1])
return nil
}
func (d *decoder) processApp0Marker(n int) error {
if n < 5 {
return d.ignore(n)
}
if err := d.readFull(d.tmp[:5]); err != nil {
return err
}
n -= 5
d.jfif = d.tmp[0] == 'J' && d.tmp[1] == 'F' && d.tmp[2] == 'I' && d.tmp[3] == 'F' && d.tmp[4] == '\x00'
if n > 0 {
return d.ignore(n)
}
return nil
}
func (d *decoder) processApp14Marker(n int) error {
if n < 12 {
return d.ignore(n)
}
if err := d.readFull(d.tmp[:12]); err != nil {
return err
}
n -= 12
if d.tmp[0] == 'A' && d.tmp[1] == 'd' && d.tmp[2] == 'o' && d.tmp[3] == 'b' && d.tmp[4] == 'e' {
d.adobeTransformValid = true
d.adobeTransform = d.tmp[11]
}
if n > 0 {
return d.ignore(n)
}
return nil
}
// decode reads a JPEG image from r and returns it as an image.Image.
func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, error) {
d.r = r
// Check for the Start Of Image marker.
if err := d.readFull(d.tmp[:2]); err != nil {
return nil, err
}
if d.tmp[0] != 0xff || d.tmp[1] != soiMarker {
return nil, FormatError("missing SOI marker")
}
// Process the remaining segments until the End Of Image marker.
for {
err := d.readFull(d.tmp[:2])
if err != nil {
return nil, err
}
for d.tmp[0] != 0xff {
// Strictly speaking, this is a format error. However, libjpeg is
// liberal in what it accepts. As of version 9, next_marker in
// jdmarker.c treats this as a warning (JWRN_EXTRANEOUS_DATA) and
// continues to decode the stream. Even before next_marker sees
// extraneous data, jpeg_fill_bit_buffer in jdhuff.c reads as many
// bytes as it can, possibly past the end of a scan's data. It
// effectively puts back any markers that it overscanned (e.g. an
// "\xff\xd9" EOI marker), but it does not put back non-marker data,
// and thus it can silently ignore a small number of extraneous
// non-marker bytes before next_marker has a chance to see them (and
// print a warning).
//
// We are therefore also liberal in what we accept. Extraneous data
// is silently ignored.
//
// This is similar to, but not exactly the same as, the restart
// mechanism within a scan (the RST[0-7] markers).
//
// Note that extraneous 0xff bytes in e.g. SOS data are escaped as
// "\xff\x00", and so are detected a little further down below.
d.tmp[0] = d.tmp[1]
d.tmp[1], err = d.readByte()
if err != nil {
return nil, err
}
}
marker := d.tmp[1]
if marker == 0 {
// Treat "\xff\x00" as extraneous data.
continue
}
for marker == 0xff {
// Section B.1.1.2 says, "Any marker may optionally be preceded by any
// number of fill bytes, which are bytes assigned code X'FF'".
marker, err = d.readByte()
if err != nil {
return nil, err
}
}
if marker == eoiMarker { // End Of Image.
break
}
if rst0Marker <= marker && marker <= rst7Marker {
// Figures B.2 and B.16 of the specification suggest that restart markers should
// only occur between Entropy Coded Segments and not after the final ECS.
// However, some encoders may generate incorrect JPEGs with a final restart
// marker. That restart marker will be seen here instead of inside the processSOS
// method, and is ignored as a harmless error. Restart markers have no extra data,
// so we check for this before we read the 16-bit length of the segment.
continue
}
// Read the 16-bit length of the segment. The value includes the 2 bytes for the
// length itself, so we subtract 2 to get the number of remaining bytes.
if err = d.readFull(d.tmp[:2]); err != nil {
return nil, err
}
n := int(d.tmp[0])<<8 + int(d.tmp[1]) - 2
if n < 0 {
return nil, FormatError("short segment length")
}
switch marker {
case sof0Marker, sof1Marker, sof2Marker:
d.baseline = marker == sof0Marker
d.progressive = marker == sof2Marker
err = d.processSOF(n)
if configOnly && d.jfif {
return nil, err
}
case dhtMarker:
if configOnly {
err = d.ignore(n)
} else {
err = d.processDHT(n)
}
case dqtMarker:
if configOnly {
err = d.ignore(n)
} else {
err = d.processDQT(n)
}
case sosMarker:
if configOnly {
return nil, nil
}
err = d.processSOS(n)
case driMarker:
if configOnly {
err = d.ignore(n)
} else {
err = d.processDRI(n)
}
case app0Marker:
err = d.processApp0Marker(n)
case app14Marker:
err = d.processApp14Marker(n)
default:
if app0Marker <= marker && marker <= app15Marker || marker == comMarker {
err = d.ignore(n)
} else if marker < 0xc0 { // See Table B.1 "Marker code assignments".
err = FormatError("unknown marker")
} else {
err = UnsupportedError("unknown marker")
}
}
if err != nil {
return nil, err
}
}
if d.progressive {
if err := d.reconstructProgressiveImage(); err != nil {
return nil, err
}
}
if d.img1 != nil {
return d.img1, nil
}
if d.img3 != nil {
if d.blackPix != nil {
return d.applyBlack()
} else if d.isRGB() {
return d.convertToRGB()
}
return d.img3, nil
}
return nil, FormatError("missing SOS marker")
}
// applyBlack combines d.img3 and d.blackPix into a CMYK image. The formula
// used depends on whether the JPEG image is stored as CMYK or YCbCrK,
// indicated by the APP14 (Adobe) metadata.
//
// Adobe CMYK JPEG images are inverted, where 255 means no ink instead of full
// ink, so we apply "v = 255 - v" at various points. Note that a double
// inversion is a no-op, so inversions might be implicit in the code below.
func (d *decoder) applyBlack() (image.Image, error) {
if !d.adobeTransformValid {
return nil, UnsupportedError("unknown color model: 4-component JPEG doesn't have Adobe APP14 metadata")
}
// If the 4-component JPEG image isn't explicitly marked as "Unknown (RGB
// or CMYK)" as per
// https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
// we assume that it is YCbCrK. This matches libjpeg's jdapimin.c.
if d.adobeTransform != adobeTransformUnknown {
// Convert the YCbCr part of the YCbCrK to RGB, invert the RGB to get
// CMY, and patch in the original K. The RGB to CMY inversion cancels
// out the 'Adobe inversion' described in the applyBlack doc comment
// above, so in practice, only the fourth channel (black) is inverted.
bounds := d.img3.Bounds()
img := image.NewRGBA(bounds)
src := nrgba.NewNRGBAScanner(d.img3)
w, h := img.Bounds().Dx(), img.Bounds().Dy()
size := w * 4
if err := parallel.Run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * img.Stride
src.Scan(0, y, w, y+1, img.Pix[i:i+size])
}
}, 0, h); err != nil {
panic(err)
}
for iBase, y := 0, bounds.Min.Y; y < bounds.Max.Y; iBase, y = iBase+img.Stride, y+1 {
for i, x := iBase+3, bounds.Min.X; x < bounds.Max.X; i, x = i+4, x+1 {
img.Pix[i] = 255 - d.blackPix[(y-bounds.Min.Y)*d.blackStride+(x-bounds.Min.X)]
}
}
return &image.CMYK{
Pix: img.Pix,
Stride: img.Stride,
Rect: img.Rect,
}, nil
}
// The first three channels (cyan, magenta, yellow) of the CMYK
// were decoded into d.img3, but each channel was decoded into a separate
// []byte slice, and some channels may be subsampled. We interleave the
// separate channels into an image.CMYK's single []byte slice containing 4
// contiguous bytes per pixel.
bounds := d.img3.Bounds()
img := image.NewCMYK(bounds)
translations := [4]struct {
src []byte
stride int
}{
{d.img3.Y, d.img3.YStride},
{d.img3.Cb, d.img3.CStride},
{d.img3.Cr, d.img3.CStride},
{d.blackPix, d.blackStride},
}
for t, translation := range translations {
subsample := d.comp[t].h != d.comp[0].h || d.comp[t].v != d.comp[0].v
for iBase, y := 0, bounds.Min.Y; y < bounds.Max.Y; iBase, y = iBase+img.Stride, y+1 {
sy := y - bounds.Min.Y
if subsample {
sy /= 2
}
for i, x := iBase+t, bounds.Min.X; x < bounds.Max.X; i, x = i+4, x+1 {
sx := x - bounds.Min.X
if subsample {
sx /= 2
}
img.Pix[i] = 255 - translation.src[sy*translation.stride+sx]
}
}
}
return img, nil
}
func (d *decoder) isRGB() bool {
if d.jfif {
return false
}
if d.adobeTransformValid && d.adobeTransform == adobeTransformUnknown {
// https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html#Adobe
// says that 0 means Unknown (and in practice RGB) and 1 means YCbCr.
return true
}
return d.comp[0].c == 'R' && d.comp[1].c == 'G' && d.comp[2].c == 'B'
}
func (d *decoder) convertToRGB() (image.Image, error) {
cScale := d.comp[0].h / d.comp[1].h
bounds := d.img3.Bounds()
img := nrgb.NewNRGB(bounds)
parallel.Run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
po := img.PixOffset(bounds.Min.X, y)
yo := d.img3.YOffset(bounds.Min.X, y)
co := d.img3.COffset(bounds.Min.X, y)
for i, iMax := 0, bounds.Max.X-bounds.Min.X; i < iMax; i++ {
img.Pix[po+3*i+0] = d.img3.Y[yo+i]
img.Pix[po+3*i+1] = d.img3.Cb[co+i/cScale]
img.Pix[po+3*i+2] = d.img3.Cr[co+i/cScale]
}
}
}, bounds.Min.Y, bounds.Max.Y)
return img, nil
}
// Decode reads a JPEG image from r and returns it as an [image.Image].
func Decode(r io.Reader) (image.Image, error) {
var d decoder
return d.decode(r, false)
}
// DecodeConfig returns the color model and dimensions of a JPEG image without
// decoding the entire image.
func DecodeConfig(r io.Reader) (image.Config, error) {
var d decoder
if _, err := d.decode(r, true); err != nil {
return image.Config{}, err
}
switch d.nComp {
case 1:
return image.Config{
ColorModel: color.GrayModel,
Width: d.width,
Height: d.height,
}, nil
case 3:
cm := color.YCbCrModel
if d.isRGB() {
cm = nrgb.Model
}
return image.Config{
ColorModel: cm,
Width: d.width,
Height: d.height,
}, nil
case 4:
return image.Config{
ColorModel: color.CMYKModel,
Width: d.width,
Height: d.height,
}, nil
}
return image.Config{}, FormatError("missing SOF marker")
}
+583
View File
@@ -0,0 +1,583 @@
// 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 jpeg
import (
"image"
)
// makeImg allocates and initializes the destination image.
func (d *decoder) makeImg(mxx, myy int) {
if d.nComp == 1 {
m := image.NewGray(image.Rect(0, 0, 8*mxx, 8*myy))
d.img1 = m.SubImage(image.Rect(0, 0, d.width, d.height)).(*image.Gray)
return
}
subsampleRatio := image.YCbCrSubsampleRatio444
if d.comp[1].h != d.comp[2].h || d.comp[1].v != d.comp[2].v || d.maxH != d.comp[0].h || d.maxV != d.comp[0].v {
d.flex = true
} else {
if d.force_flex {
d.flex = true
} else {
hRatio := d.maxH / d.comp[1].h
vRatio := d.maxV / d.comp[1].v
switch hRatio<<4 | vRatio {
case 0x11:
subsampleRatio = image.YCbCrSubsampleRatio444
case 0x12:
subsampleRatio = image.YCbCrSubsampleRatio440
case 0x21:
subsampleRatio = image.YCbCrSubsampleRatio422
case 0x22:
subsampleRatio = image.YCbCrSubsampleRatio420
case 0x41:
subsampleRatio = image.YCbCrSubsampleRatio411
case 0x42:
subsampleRatio = image.YCbCrSubsampleRatio410
default:
d.flex = true
}
}
}
m := image.NewYCbCr(image.Rect(0, 0, 8*d.maxH*mxx, 8*d.maxV*myy), subsampleRatio)
d.img3 = m.SubImage(image.Rect(0, 0, d.width, d.height)).(*image.YCbCr)
if d.nComp == 4 {
h3, v3 := d.comp[3].h, d.comp[3].v
d.blackPix = make([]byte, 8*h3*mxx*8*v3*myy)
d.blackStride = 8 * h3 * mxx
}
}
// Specified in section B.2.3.
func (d *decoder) processSOS(n int) error {
if d.nComp == 0 {
return FormatError("missing SOF marker")
}
if n < 6 || 4+2*d.nComp < n || n%2 != 0 {
return FormatError("SOS has wrong length")
}
if err := d.readFull(d.tmp[:n]); err != nil {
return err
}
nComp := int(d.tmp[0])
if n != 4+2*nComp {
return FormatError("SOS length inconsistent with number of components")
}
var scan [maxComponents]struct {
compIndex uint8
td uint8 // DC table selector.
ta uint8 // AC table selector.
}
totalHV := 0
for i := range nComp {
cs := d.tmp[1+2*i] // Component selector.
compIndex := -1
for j, comp := range d.comp[:d.nComp] {
if cs == comp.c {
compIndex = j
}
}
if compIndex < 0 {
return FormatError("unknown component selector")
}
scan[i].compIndex = uint8(compIndex)
// Section B.2.3 states that "the value of Cs_j shall be different from
// the values of Cs_1 through Cs_(j-1)". Since we have previously
// verified that a frame's component identifiers (C_i values in section
// B.2.2) are unique, it suffices to check that the implicit indexes
// into d.comp are unique.
for j := range i {
if scan[i].compIndex == scan[j].compIndex {
return FormatError("repeated component selector")
}
}
totalHV += d.comp[compIndex].h * d.comp[compIndex].v
// The baseline t <= 1 restriction is specified in table B.3.
scan[i].td = d.tmp[2+2*i] >> 4
if t := scan[i].td; t > maxTh || (d.baseline && t > 1) {
return FormatError("bad Td value")
}
scan[i].ta = d.tmp[2+2*i] & 0x0f
if t := scan[i].ta; t > maxTh || (d.baseline && t > 1) {
return FormatError("bad Ta value")
}
}
// Section B.2.3 states that if there is more than one component then the
// total H*V values in a scan must be <= 10.
if d.nComp > 1 && totalHV > 10 {
return FormatError("total sampling factors too large")
}
// zigStart and zigEnd are the spectral selection bounds.
// ah and al are the successive approximation high and low values.
// The spec calls these values Ss, Se, Ah and Al.
//
// For progressive JPEGs, these are the two more-or-less independent
// aspects of progression. Spectral selection progression is when not
// all of a block's 64 DCT coefficients are transmitted in one pass.
// For example, three passes could transmit coefficient 0 (the DC
// component), coefficients 1-5, and coefficients 6-63, in zig-zag
// order. Successive approximation is when not all of the bits of a
// band of coefficients are transmitted in one pass. For example,
// three passes could transmit the 6 most significant bits, followed
// by the second-least significant bit, followed by the least
// significant bit.
//
// For sequential JPEGs, these parameters are hard-coded to 0/63/0/0, as
// per table B.3.
zigStart, zigEnd, ah, al := int32(0), int32(blockSize-1), uint32(0), uint32(0)
if d.progressive {
zigStart = int32(d.tmp[1+2*nComp])
zigEnd = int32(d.tmp[2+2*nComp])
ah = uint32(d.tmp[3+2*nComp] >> 4)
al = uint32(d.tmp[3+2*nComp] & 0x0f)
if (zigStart == 0 && zigEnd != 0) || zigStart > zigEnd || blockSize <= zigEnd {
return FormatError("bad spectral selection bounds")
}
if zigStart != 0 && nComp != 1 {
return FormatError("progressive AC coefficients for more than one component")
}
if ah != 0 && ah != al+1 {
return FormatError("bad successive approximation values")
}
}
// mxx and myy are the number of MCUs (Minimum Coded Units) in the image.
h0, v0 := d.comp[0].h, d.comp[0].v // The h and v values from the Y components.
mxx := (d.width + 8*h0 - 1) / (8 * h0)
myy := (d.height + 8*v0 - 1) / (8 * v0)
if d.img1 == nil && d.img3 == nil {
d.makeImg(mxx, myy)
}
if d.progressive {
for i := range nComp {
compIndex := scan[i].compIndex
if d.progCoeffs[compIndex] == nil {
d.progCoeffs[compIndex] = make([]block, mxx*myy*d.comp[compIndex].h*d.comp[compIndex].v)
}
}
}
d.bits = bits{}
mcu, expectedRST := 0, uint8(rst0Marker)
var (
// b is the decoded coefficients, in natural (not zig-zag) order.
b block
dc [maxComponents]int32
// bx and by are the location of the current block, in units of 8x8
// blocks: the third block in the first row has (bx, by) = (2, 0).
bx, by int
blockCount int
)
for my := range myy {
for mx := range mxx {
for i := range nComp {
compIndex := scan[i].compIndex
hi := d.comp[compIndex].h
vi := d.comp[compIndex].v
for j := 0; j < hi*vi; j++ {
// The blocks are traversed one MCU at a time. For 4:2:0 chroma
// subsampling, there are four Y 8x8 blocks in every 16x16 MCU.
//
// For a sequential 32x16 pixel image, the Y blocks visiting order is:
// 0 1 4 5
// 2 3 6 7
//
// For progressive images, the interleaved scans (those with nComp > 1)
// are traversed as above, but non-interleaved scans are traversed left
// to right, top to bottom:
// 0 1 2 3
// 4 5 6 7
// Only DC scans (zigStart == 0) can be interleaved. AC scans must have
// only one component.
//
// To further complicate matters, for non-interleaved scans, there is no
// data for any blocks that are inside the image at the MCU level but
// outside the image at the pixel level. For example, a 24x16 pixel 4:2:0
// progressive image consists of two 16x16 MCUs. The interleaved scans
// will process 8 Y blocks:
// 0 1 4 5
// 2 3 6 7
// The non-interleaved scans will process only 6 Y blocks:
// 0 1 2
// 3 4 5
if nComp != 1 {
bx = hi*mx + j%hi
by = vi*my + j/hi
} else {
q := mxx * hi
bx = blockCount % q
by = blockCount / q
blockCount++
if bx*8 >= d.width || by*8 >= d.height {
continue
}
}
// Load the previous partially decoded coefficients, if applicable.
if d.progressive {
b = d.progCoeffs[compIndex][by*mxx*hi+bx]
} else {
b = block{}
}
if ah != 0 {
if err := d.refine(&b, &d.huff[acTable][scan[i].ta], zigStart, zigEnd, 1<<al); err != nil {
return err
}
} else {
zig := zigStart
if zig == 0 {
zig++
// Decode the DC coefficient, as specified in section F.2.2.1.
value, err := d.decodeHuffman(&d.huff[dcTable][scan[i].td])
if err != nil {
return err
}
if value > 16 {
return UnsupportedError("excessive DC component")
}
dcDelta, err := d.receiveExtend(value)
if err != nil {
return err
}
dc[compIndex] += dcDelta
b[0] = dc[compIndex] << al
}
if zig <= zigEnd && d.eobRun > 0 {
d.eobRun--
} else {
// Decode the AC coefficients, as specified in section F.2.2.2.
huff := &d.huff[acTable][scan[i].ta]
for ; zig <= zigEnd; zig++ {
value, err := d.decodeHuffman(huff)
if err != nil {
return err
}
val0 := value >> 4
val1 := value & 0x0f
if val1 != 0 {
zig += int32(val0)
if zig > zigEnd {
break
}
ac, err := d.receiveExtend(val1)
if err != nil {
return err
}
b[unzig[zig]] = ac << al
} else {
if val0 != 0x0f {
d.eobRun = uint16(1 << val0)
if val0 != 0 {
bits, err := d.decodeBits(int32(val0))
if err != nil {
return err
}
d.eobRun |= uint16(bits)
}
d.eobRun--
break
}
zig += 0x0f
}
}
}
}
if d.progressive {
// Save the coefficients.
d.progCoeffs[compIndex][by*mxx*hi+bx] = b
// At this point, we could call reconstructBlock to dequantize and perform the
// inverse DCT, to save early stages of a progressive image to the *image.YCbCr
// buffers (the whole point of progressive encoding), but in Go, the jpeg.Decode
// function does not return until the entire image is decoded, so we "continue"
// here to avoid wasted computation. Instead, reconstructBlock is called on each
// accumulated block by the reconstructProgressiveImage method after all of the
// SOS markers are processed.
continue
}
d.reconstructBlock(&b, bx, by, int(compIndex))
} // for j
} // for i
mcu++
if d.ri > 0 && mcu%d.ri == 0 && mcu < mxx*myy {
// For well-formed input, the RST[0-7] restart marker follows
// immediately. For corrupt input, call findRST to try to
// resynchronize.
if err := d.readFull(d.tmp[:2]); err != nil {
return err
} else if d.tmp[0] != 0xff || d.tmp[1] != expectedRST {
if err := d.findRST(expectedRST); err != nil {
return err
}
}
expectedRST++
if expectedRST == rst7Marker+1 {
expectedRST = rst0Marker
}
// Reset the Huffman decoder.
d.bits = bits{}
// Reset the DC components, as per section F.2.1.3.1.
dc = [maxComponents]int32{}
// Reset the progressive decoder state, as per section G.1.2.2.
d.eobRun = 0
}
} // for mx
} // for my
return nil
}
// refine decodes a successive approximation refinement block, as specified in
// section G.1.2.
func (d *decoder) refine(b *block, h *huffman, zigStart, zigEnd, delta int32) error {
// Refining a DC component is trivial.
if zigStart == 0 {
if zigEnd != 0 {
panic("unreachable")
}
bit, err := d.decodeBit()
if err != nil {
return err
}
if bit {
b[0] |= delta
}
return nil
}
// Refining AC components is more complicated; see sections G.1.2.2 and G.1.2.3.
zig := zigStart
if d.eobRun == 0 {
loop:
for ; zig <= zigEnd; zig++ {
z := int32(0)
value, err := d.decodeHuffman(h)
if err != nil {
return err
}
val0 := value >> 4
val1 := value & 0x0f
switch val1 {
case 0:
if val0 != 0x0f {
d.eobRun = uint16(1 << val0)
if val0 != 0 {
bits, err := d.decodeBits(int32(val0))
if err != nil {
return err
}
d.eobRun |= uint16(bits)
}
break loop
}
case 1:
z = delta
bit, err := d.decodeBit()
if err != nil {
return err
}
if !bit {
z = -z
}
default:
return FormatError("unexpected Huffman code")
}
zig, err = d.refineNonZeroes(b, zig, zigEnd, int32(val0), delta)
if err != nil {
return err
}
if zig > zigEnd {
return FormatError("too many coefficients")
}
if z != 0 {
b[unzig[zig]] = z
}
}
}
if d.eobRun > 0 {
d.eobRun--
if _, err := d.refineNonZeroes(b, zig, zigEnd, -1, delta); err != nil {
return err
}
}
return nil
}
// refineNonZeroes refines non-zero entries of b in zig-zag order. If nz >= 0,
// the first nz zero entries are skipped over.
func (d *decoder) refineNonZeroes(b *block, zig, zigEnd, nz, delta int32) (int32, error) {
for ; zig <= zigEnd; zig++ {
u := unzig[zig]
if b[u] == 0 {
if nz == 0 {
break
}
nz--
continue
}
bit, err := d.decodeBit()
if err != nil {
return 0, err
}
if !bit {
continue
}
if b[u] >= 0 {
b[u] += delta
} else {
b[u] -= delta
}
}
return zig, nil
}
func (d *decoder) reconstructProgressiveImage() error {
// The h0, mxx, by and bx variables have the same meaning as in the
// processSOS method.
h0 := d.comp[0].h
mxx := (d.width + 8*h0 - 1) / (8 * h0)
for i := 0; i < d.nComp; i++ {
if d.progCoeffs[i] == nil {
continue
}
v := 8 * d.comp[0].v / d.comp[i].v
h := 8 * d.comp[0].h / d.comp[i].h
stride := mxx * d.comp[i].h
for by := 0; by*v < d.height; by++ {
for bx := 0; bx*h < d.width; bx++ {
d.reconstructBlock(&d.progCoeffs[i][by*stride+bx], bx, by, i)
}
}
}
return nil
}
func level_shift(c int32) uint8 {
if c < -128 {
return 0
}
if c > 127 {
return 255
}
return uint8(c + 128)
}
func (d *decoder) storeFlexBlock(b *block, bx, by, compIndex int) {
h, v := d.comp[compIndex].expand.h, d.comp[compIndex].expand.v
dst, stride := []byte(nil), 0
bx, by = bx*h, by*v
switch compIndex {
case 0:
dst, stride = d.img3.Y[8*(by*d.img3.YStride+bx):], d.img3.YStride
case 1:
dst, stride = d.img3.Cb[8*(by*d.img3.CStride+bx):], d.img3.CStride
case 2:
dst, stride = d.img3.Cr[8*(by*d.img3.CStride+bx):], d.img3.CStride
case 3:
dst, stride = d.blackPix[8*(by*d.blackStride+bx):], d.blackStride
}
for y := range 8 {
y8 := y * 8
yv := y * v
for x := range 8 {
val := level_shift(b[y8+x])
xh := x * h
for yy := range v {
for xx := range h {
dst[(yv+yy)*stride+xh+xx] = val
}
}
}
}
}
// reconstructBlock dequantizes, performs the inverse DCT and stores the block
// to the image.
func (d *decoder) reconstructBlock(b *block, bx, by, compIndex int) {
qt := &d.quant[d.comp[compIndex].tq]
for zig := range blockSize {
b[unzig[zig]] *= qt[zig]
}
idct(b)
dst, stride := []byte(nil), 0
if d.nComp == 1 {
dst, stride = d.img1.Pix[8*(by*d.img1.Stride+bx):], d.img1.Stride
} else {
if d.flex {
d.storeFlexBlock(b, bx, by, compIndex)
return
}
switch compIndex {
case 0:
dst, stride = d.img3.Y[8*(by*d.img3.YStride+bx):], d.img3.YStride
case 1:
dst, stride = d.img3.Cb[8*(by*d.img3.CStride+bx):], d.img3.CStride
case 2:
dst, stride = d.img3.Cr[8*(by*d.img3.CStride+bx):], d.img3.CStride
case 3:
dst, stride = d.blackPix[8*(by*d.blackStride+bx):], d.blackStride
}
}
// Level shift by +128, clip to [0, 255], and write to dst.
for y := range 8 {
y8 := y * 8
yStride := y * stride
for x := range 8 {
dst[yStride+x] = level_shift(b[y8+x])
}
}
}
// findRST advances past the next RST restart marker that matches expectedRST.
// Other than I/O errors, it is also an error if we encounter an {0xFF, M}
// two-byte marker sequence where M is not 0x00, 0xFF or the expectedRST.
//
// This is similar to libjpeg's jdmarker.c's next_marker function.
// https://github.com/libjpeg-turbo/libjpeg-turbo/blob/2dfe6c0fe9e18671105e94f7cbf044d4a1d157e6/jdmarker.c#L892-L935
//
// Precondition: d.tmp[:2] holds the next two bytes of JPEG-encoded input
// (input in the d.readFull sense).
func (d *decoder) findRST(expectedRST uint8) error {
for {
// i is the index such that, at the bottom of the loop, we read 2-i
// bytes into d.tmp[i:2], maintaining the invariant that d.tmp[:2]
// holds the next two bytes of JPEG-encoded input. It is either 0 or 1,
// so that each iteration advances by 1 or 2 bytes (or returns).
i := 0
if d.tmp[0] == 0xff {
if d.tmp[1] == expectedRST {
return nil
} else if d.tmp[1] == 0xff {
i = 1
} else if d.tmp[1] != 0x00 {
// libjpeg's jdmarker.c's jpeg_resync_to_restart does something
// fancy here, treating RST markers within two (modulo 8) of
// expectedRST differently from RST markers that are 'more
// distant'. Until we see evidence that recovering from such
// cases is frequent enough to be worth the complexity, we take
// a simpler approach for now. Any marker that's not 0x00, 0xff
// or expectedRST is a fatal FormatError.
return FormatError("bad RST marker")
}
} else if d.tmp[1] == 0xff {
d.tmp[0] = 0xff
i = 1
}
if err := d.readFull(d.tmp[i:2]); err != nil {
return err
}
}
}
+1 -13
View File
@@ -35,19 +35,7 @@ var MagickExe = sync.OnceValue(func() string {
})
var HasMagick = sync.OnceValue(func() bool { return MagickExe() != "magick" })
var TempDirInRAMIfPossible = sync.OnceValue(func() string {
const shm = "/dev/shm"
if s, err := os.Stat(shm); err == nil && s.IsDir() {
tempFile, err := os.CreateTemp(shm, "write_check_*")
if err != nil {
return os.TempDir()
}
tempFile.Close()
os.Remove(tempFile.Name())
return shm
}
return os.TempDir()
})
var TempDirInRAMIfPossible = sync.OnceValue(func() string { return get_temp_dir() })
type ImageFrame struct {
Width, Height, Left, Top int
+26
View File
@@ -0,0 +1,26 @@
//go:build !windows
package magick
import (
"fmt"
"os"
"github.com/kovidgoyal/go-shm"
)
var _ = fmt.Print
func get_temp_dir() string {
if shm.SHM_DIR != "" {
tempFile, err := os.CreateTemp(shm.SHM_DIR, "write_check_*")
if err != nil {
return os.TempDir()
}
tempFile.Close()
os.Remove(tempFile.Name())
return shm.SHM_DIR
}
return os.TempDir()
}
+14
View File
@@ -0,0 +1,14 @@
//go:build windows
package magick
import (
"fmt"
"os"
)
var _ = fmt.Print
func get_temp_dir() string {
return os.TempDir()
}
+114 -32
View File
@@ -225,8 +225,21 @@ func newScannerRGB(img image.Image, opaque_base Color) *scanner_rgb {
return s
}
func (s *scanner_rgb) blend8(d []uint8, a uint8) {
switch a {
case 0:
d[0] = s.opaque_base_uint[0]
d[1] = s.opaque_base_uint[1]
d[2] = s.opaque_base_uint[2]
case 0xff:
default:
blend(d, s.opaque_base, d[0], d[1], d[2], a)
}
}
// scan scans the given rectangular region of the image into dst.
func (s *scanner_rgb) Scan(x1, y1, x2, y2 int, dst []uint8) {
_ = dst[3*(x2-x1)*(y2-y1)-1]
switch img := s.image.(type) {
case *image.NRGBA:
j := 0
@@ -339,39 +352,108 @@ func (s *scanner_rgb) Scan(x1, y1, x2, y2 int, dst []uint8) {
}
case *image.YCbCr:
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
}
for x := x1; x < x2; x++ {
var ic int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
if img.SubsampleRatio == image.YCbCrSubsampleRatio444 {
Y := img.Y[y1*img.YStride:]
Cb := img.Cb[y1*img.CStride:]
Cr := img.Cr[y1*img.CStride:]
for range y2 - y1 {
for x := x1; x < x2; x++ {
d := dst[0:3:3]
d[0], d[1], d[2] = color.YCbCrToRGB(Y[x], Cb[x], Cr[x])
dst = dst[3:]
}
Y, Cb, Cr = Y[img.YStride:], Cb[img.CStride:], Cr[img.CStride:]
}
} else {
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
}
for x := x1; x < x2; x++ {
var ic int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
}
d := dst[j : j+3 : j+3]
d[0], d[1], d[2] = color.YCbCrToRGB(img.Y[iy], img.Cb[ic], img.Cr[ic])
iy++
j += 3
}
}
}
case *image.NYCbCrA:
if img.SubsampleRatio == image.YCbCrSubsampleRatio444 {
Y := img.Y[y1*img.YStride:]
A := img.A[y1*img.AStride:]
Cb := img.Cb[y1*img.CStride:]
Cr := img.Cr[y1*img.CStride:]
for range y2 - y1 {
for x := x1; x < x2; x++ {
d := dst[0:3:3]
d[0], d[1], d[2] = color.YCbCrToRGB(Y[x], Cb[x], Cr[x])
s.blend8(d, A[x])
dst = dst[3:]
}
Y, Cb, Cr = Y[img.YStride:], Cb[img.CStride:], Cr[img.CStride:]
A = A[img.AStride:]
}
} else {
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
ia := (y-img.Rect.Min.Y)*img.AStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
}
for x := x1; x < x2; x++ {
var ic int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
}
d := dst[j : j+3 : j+3]
d[0], d[1], d[2] = color.YCbCrToRGB(img.Y[iy], img.Cb[ic], img.Cr[ic])
s.blend8(d, img.A[ia])
iy++
j += 3
}
d := dst[j : j+3 : j+3]
d[0], d[1], d[2] = color.YCbCrToRGB(img.Y[iy], img.Cb[ic], img.Cr[ic])
iy++
j += 3
}
}
@@ -1,4 +1,4 @@
package imaging
package nrgba
import (
"image"
@@ -36,6 +36,24 @@ func newScanner(img image.Image) *scanner {
return s
}
func reverse4(pix []uint8) {
if len(pix) <= 4 {
return
}
i := 0
j := len(pix) - 4
for i < j {
pi := pix[i : i+4 : i+4]
pj := pix[j : j+4 : j+4]
pi[0], pj[0] = pj[0], pi[0]
pi[1], pj[1] = pj[1], pi[1]
pi[2], pj[2] = pj[2], pi[2]
pi[3], pj[3] = pj[3], pi[3]
i += 4
j -= 4
}
}
func (s *scanner) ReverseRow(img image.Image, row int) {
d := img.(*image.NRGBA)
pos := row * d.Stride
@@ -52,6 +70,7 @@ func (s *scanner) ScanRow(x1, y1, x2, y2 int, img image.Image, row int) {
// scan scans the given rectangular region of the image into dst.
func (s *scanner) Scan(x1, y1, x2, y2 int, dst []uint8) {
_ = dst[4*(x2-x1)*(y2-y1)-1]
switch img := s.image.(type) {
case *nrgb.Image:
if x2 == x1+1 {
@@ -216,42 +235,115 @@ func (s *scanner) Scan(x1, y1, x2, y2 int, dst []uint8) {
}
case *image.YCbCr:
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
if img.SubsampleRatio == image.YCbCrSubsampleRatio444 {
Y := img.Y[y1*img.YStride:]
Cb := img.Cb[y1*img.CStride:]
Cr := img.Cr[y1*img.CStride:]
for range y2 - y1 {
for x := x1; x < x2; x++ {
d := dst[0:4:4]
d[0], d[1], d[2] = color.YCbCrToRGB(Y[x], Cb[x], Cr[x])
d[3] = 255
dst = dst[4:]
}
Y, Cb, Cr = Y[img.YStride:], Cb[img.CStride:], Cr[img.CStride:]
}
} else {
for x := x1; x < x2; x++ {
var ic int
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
case image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
}
d := dst[j : j+4 : j+4]
d[0], d[1], d[2] = color.YCbCrToRGB(img.Y[iy], img.Cb[ic], img.Cr[ic])
d[3] = 0xff
for x := x1; x < x2; x++ {
var ic int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
}
iy++
j += 4
d := dst[j : j+4 : j+4]
d[0], d[1], d[2] = color.YCbCrToRGB(img.Y[iy], img.Cb[ic], img.Cr[ic])
d[3] = 0xff
iy++
j += 4
}
}
}
case *image.NYCbCrA:
if img.SubsampleRatio == image.YCbCrSubsampleRatio444 {
Y := img.Y[y1*img.YStride:]
A := img.A[y1*img.AStride:]
Cb := img.Cb[y1*img.CStride:]
Cr := img.Cr[y1*img.CStride:]
for range y2 - y1 {
for x := x1; x < x2; x++ {
d := dst[0:4:4]
d[0], d[1], d[2] = color.YCbCrToRGB(Y[x], Cb[x], Cr[x])
d[3] = A[x]
dst = dst[4:]
}
Y, Cb, Cr = Y[img.YStride:], Cb[img.CStride:], Cr[img.CStride:]
A = A[img.AStride:]
}
} else {
j := 0
x1 += img.Rect.Min.X
x2 += img.Rect.Min.X
y1 += img.Rect.Min.Y
y2 += img.Rect.Min.Y
hy := img.Rect.Min.Y / 2
hx := img.Rect.Min.X / 2
for y := y1; y < y2; y++ {
iy := (y-img.Rect.Min.Y)*img.YStride + (x1 - img.Rect.Min.X)
ia := (y-img.Rect.Min.Y)*img.AStride + (x1 - img.Rect.Min.X)
var yBase int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio422:
yBase = (y - img.Rect.Min.Y) * img.CStride
case image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440:
yBase = (y/2 - hy) * img.CStride
}
for x := x1; x < x2; x++ {
var ic int
switch img.SubsampleRatio {
case image.YCbCrSubsampleRatio440:
ic = yBase + (x - img.Rect.Min.X)
case image.YCbCrSubsampleRatio422, image.YCbCrSubsampleRatio420:
ic = yBase + (x/2 - hx)
default:
ic = img.COffset(x, y)
}
d := dst[j : j+4 : j+4]
d[0], d[1], d[2] = color.YCbCrToRGB(img.Y[iy], img.Cb[ic], img.Cr[ic])
d[3] = img.A[ia]
iy++
j += 4
}
}
}
+53 -12
View File
@@ -1,6 +1,7 @@
package imaging
import (
"bytes"
"fmt"
"image"
"sync/atomic"
@@ -12,14 +13,15 @@ import (
var _ = fmt.Print
func is_opaque1(pix []uint8, w, h, stride int) bool {
is_opaque := true
parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
is_opaque := atomic.Bool{}
is_opaque.Store(true)
if err := parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
pix := pix[stride*start:]
for range limit - start {
p := pix[0:w:w]
for _, x := range p {
if x != 0xff {
is_opaque = false
is_opaque.Store(false)
return true
}
}
@@ -29,14 +31,16 @@ func is_opaque1(pix []uint8, w, h, stride int) bool {
pix = pix[stride:]
}
return false
}, 0, h)
return is_opaque
}, 0, h); err != nil {
panic(err)
}
return is_opaque.Load()
}
func is_opaque8(pix []uint8, w, h, stride int) bool {
is_opaque := atomic.Bool{}
is_opaque.Store(true)
parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
if err := parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
pix := pix[stride*start:]
for range limit - start {
p := pix[0 : 4*w : 4*w]
@@ -53,14 +57,16 @@ func is_opaque8(pix []uint8, w, h, stride int) bool {
pix = pix[stride:]
}
return false
}, 0, h)
}, 0, h); err != nil {
panic(err)
}
return is_opaque.Load()
}
func is_opaque16(pix []uint8, w, h, stride int) bool {
is_opaque := atomic.Bool{}
is_opaque.Store(true)
parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
if err := parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
pix := pix[stride*start:]
for range limit - start {
p := pix[0 : 8*w : 8*w]
@@ -77,10 +83,22 @@ func is_opaque16(pix []uint8, w, h, stride int) bool {
pix = pix[stride:]
}
return false
}, 0, h)
}, 0, h); err != nil {
panic(err)
}
return is_opaque.Load()
}
func IsOpaqueType(img image.Image) (ans bool) {
switch img.(type) {
case *nrgb.Image, *image.CMYK, *image.YCbCr, *image.Gray, *image.Gray16:
return true
default:
return false
}
}
func IsOpaque(img image.Image) (ans bool) {
type is_opaque interface{ Opaque() bool }
if img.Bounds().Empty() {
@@ -100,13 +118,36 @@ func IsOpaque(img image.Image) (ans bool) {
case *image.NYCbCrA:
return is_opaque1(img.A, img.Bounds().Dx(), img.Bounds().Dy(), img.AStride)
case *image.Paletted:
for _, c := range img.Palette {
bad_colors := make([]uint8, 0, len(img.Palette))
for i, c := range img.Palette {
_, _, _, a := c.RGBA()
if a != 0xffff {
return false
bad_colors = append(bad_colors, uint8(i))
}
}
return true
switch len(bad_colors) {
case 0:
return true
case len(img.Palette):
return false
case 1:
return bytes.IndexByte(img.Pix, bad_colors[0]) < 0
default:
is_opaque := atomic.Bool{}
is_opaque.Store(true)
if err := parallel.Run_in_parallel_to_first_result(0, func(start, limit int, keep_going *atomic.Bool) bool {
for i := start; i < limit && keep_going.Load(); i++ {
if bytes.IndexByte(img.Pix, bad_colors[i]) > -1 {
is_opaque.Store(false)
return true
}
}
return false
}, 0, len(bad_colors)); err != nil {
panic(err)
}
return is_opaque.Load()
}
case is_opaque:
return img.Opaque()
}
+1 -1
View File
@@ -147,7 +147,7 @@ func mlucDecoder(raw []byte) (any, error) {
return nil, fmt.Errorf("mluc tag too small for %d records", count)
}
tag := &MultiLocalizedTag{Strings: make([]LocalizedString, 0, count)}
for i := 0; i < count; i++ {
for i := range count {
base := 16 + i*recordSize
langCode := string(raw[base : base+2])
countryCode := string(raw[base+2 : base+4])
+1 -1
View File
@@ -59,7 +59,7 @@ func ExtractMetadata(r io.Reader) (md *meta.Data, err error) {
soiSegment, err := segReader.ReadSegment()
if err != nil {
if strings.Contains(err.Error(), "invalid marker identifier") {
if q := err.Error(); strings.Contains(q, "invalid marker identifier") || strings.Contains(q, "unrecognised marker type") {
err = nil
}
return nil, err
+3 -2
View File
@@ -5,7 +5,7 @@ import os
import subprocess
VERSION = "1.8.7"
VERSION = "1.8.19"
def run(*args: str):
@@ -22,7 +22,8 @@ def main():
ans = 'n'
if ans.lower() != 'y':
return
os.environ['GITHUB_TOKEN'] = open(os.path.join(os.environ['PENV'], 'github-token')).read().strip().partition(':')[2]
os.environ['GITHUB_TOKEN'] = open(os.path.join(
os.environ['PENV'], 'github-token')).read().strip().partition(':')[2]
run('git', 'tag', '-a', 'v' + version, '-m', f'version {version}')
run('git', 'push')
run('goreleaser', 'release', '--clean')
+162 -30
View File
@@ -3,6 +3,9 @@ package imaging
import (
"image"
"math"
"github.com/kovidgoyal/imaging/nrgb"
"github.com/kovidgoyal/imaging/nrgba"
)
type indexWeight struct {
@@ -47,24 +50,28 @@ func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) [][]indexWei
// Resize resizes the image to the specified width and height using the specified resampling
// filter and returns the transformed image. If one of width or height is 0, the image aspect
// ratio is preserved.
// ratio is preserved. When is_opaque is true, returns a nrgb.Image otherwise
// an image.NRGBA. When the image size is unchanged returns a clone with the
// same image type.
//
// Example:
//
// dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
func Resize(img image.Image, width, height int, filter ResampleFilter) image.Image {
func ResizeWithOpacity(img image.Image, width, height int, filter ResampleFilter, is_opaque bool) image.Image {
dstW, dstH := width, height
if dstW < 0 || dstH < 0 {
return &NRGB{}
if dstW < 0 || dstH < 0 || (dstW == 0 && dstH == 0) {
if is_opaque {
return &NRGB{}
}
return &image.NRGBA{}
}
if dstW == 0 && dstH == 0 {
return &NRGB{}
}
srcW := img.Bounds().Dx()
srcH := img.Bounds().Dy()
if srcW <= 0 || srcH <= 0 {
return &NRGB{}
if is_opaque {
return &NRGB{}
}
return &image.NRGBA{}
}
// If new width or height is 0 then preserve aspect ratio, minimum 1px.
@@ -83,27 +90,79 @@ func Resize(img image.Image, width, height int, filter ResampleFilter) image.Ima
if filter.Support <= 0 {
// Nearest-neighbor special case.
return resizeNearest(img, dstW, dstH)
if is_opaque {
return resizeNearest(img, dstW, dstH)
}
return resizeNearestWithAlpha(img, dstW, dstH)
}
hr := func(img image.Image, dim int) image.Image {
if is_opaque {
return resizeHorizontal(img, dim, filter)
}
return resizeHorizontalWithAlpha(img, dim, filter)
}
vr := func(img image.Image, dim int) image.Image {
if is_opaque {
return resizeVertical(img, dim, filter)
}
return resizeVerticalWithAlpha(img, dim, filter)
}
if srcW != dstW && srcH != dstH {
return resizeVertical(resizeHorizontal(img, dstW, filter), dstH, filter)
return vr(hr(img, dstW), dstH)
}
if srcW != dstW {
return resizeHorizontal(img, dstW, filter)
return hr(img, dstW)
}
return resizeVertical(img, dstH, filter)
return vr(img, dstH)
}
func resizeHorizontal(img image.Image, width int, filter ResampleFilter) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, width, src.h).Add(img.Bounds().Min))
weights := precomputeWeights(width, src.w, filter)
func Resize(img image.Image, width, height int, filter ResampleFilter) image.Image {
return ResizeWithOpacity(img, width, height, filter, false)
}
func resizeHorizontal(img image.Image, width int, filter ResampleFilter) *nrgb.Image {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgb.NewNRGBScanner(img, nrgb.Color{})
dst := nrgb.NewNRGB(image.Rect(0, 0, width, h).Add(img.Bounds().Min))
weights := precomputeWeights(width, w, filter)
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, src.w*4)
scanLine := make([]uint8, w*3)
for y := start; y < limit; y++ {
src.Scan(0, y, src.w, y+1, scanLine)
src.Scan(0, y, w, y+1, scanLine)
j0 := y * dst.Stride
for x := range weights {
var r, g, b float64
for _, w := range weights[x] {
i := w.index * 3
s := scanLine[i : i+3 : i+3]
r += float64(s[0]) * w.weight
g += float64(s[1]) * w.weight
b += float64(s[2]) * w.weight
}
j := j0 + x*3
d := dst.Pix[j : j+3 : j+3]
d[0] = clamp(r)
d[1] = clamp(g)
d[2] = clamp(b)
}
}
}, 0, h); err != nil {
panic(err)
}
return dst
}
func resizeHorizontalWithAlpha(img image.Image, width int, filter ResampleFilter) *image.NRGBA {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, width, h).Add(img.Bounds().Min))
weights := precomputeWeights(width, w, filter)
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, w*4)
for y := start; y < limit; y++ {
src.Scan(0, y, w, y+1, scanLine)
j0 := y * dst.Stride
for x := range weights {
var r, g, b, a float64
@@ -127,20 +186,52 @@ func resizeHorizontal(img image.Image, width int, filter ResampleFilter) *image.
}
}
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
}
func resizeVertical(img image.Image, height int, filter ResampleFilter) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, height).Add(img.Bounds().Min))
weights := precomputeWeights(height, src.h, filter)
func resizeVertical(img image.Image, height int, filter ResampleFilter) *nrgb.Image {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgb.NewNRGBScanner(img, nrgb.Color{})
dst := nrgb.NewNRGB(image.Rect(0, 0, w, height).Add(img.Bounds().Min))
weights := precomputeWeights(height, h, filter)
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, src.h*4)
scanLine := make([]uint8, h*3)
for x := start; x < limit; x++ {
src.Scan(x, 0, x+1, src.h, scanLine)
src.Scan(x, 0, x+1, h, scanLine)
for y := range weights {
var r, g, b float64
for _, w := range weights[y] {
i := w.index * 3
s := scanLine[i : i+3 : i+3]
r += float64(s[0]) * w.weight
g += float64(s[1]) * w.weight
b += float64(s[2]) * w.weight
}
j := y*dst.Stride + x*3
d := dst.Pix[j : j+3 : j+3]
d[0] = clamp(r)
d[1] = clamp(g)
d[2] = clamp(b)
}
}
}, 0, w); err != nil {
panic(err)
}
return dst
}
func resizeVerticalWithAlpha(img image.Image, height int, filter ResampleFilter) *image.NRGBA {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, height).Add(img.Bounds().Min))
weights := precomputeWeights(height, h, filter)
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, h*4)
for x := start; x < limit; x++ {
src.Scan(x, 0, x+1, h, scanLine)
for y := range weights {
var r, g, b, a float64
for _, w := range weights[y] {
@@ -163,20 +254,20 @@ func resizeVertical(img image.Image, height int, filter ResampleFilter) *image.N
}
}
}
}, 0, src.w); err != nil {
}, 0, w); err != nil {
panic(err)
}
return dst
}
// resizeNearest is a fast nearest-neighbor resize, no filtering.
func resizeNearest(img image.Image, width, height int) *image.NRGBA {
func resizeNearestWithAlpha(img image.Image, width, height int) *image.NRGBA {
dst := image.NewNRGBA(image.Rect(0, 0, width, height).Add(img.Bounds().Min))
dx := float64(img.Bounds().Dx()) / float64(width)
dy := float64(img.Bounds().Dy()) / float64(height)
if dx > 1 && dy > 1 {
src := newScanner(img)
src := nrgba.NewNRGBAScanner(img)
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
srcY := int((float64(y) + 0.5) * dy)
@@ -211,6 +302,47 @@ func resizeNearest(img image.Image, width, height int) *image.NRGBA {
return dst
}
func resizeNearest(img image.Image, width, height int) *nrgb.Image {
dst := nrgb.NewNRGB(image.Rect(0, 0, width, height).Add(img.Bounds().Min))
dx := float64(img.Bounds().Dx()) / float64(width)
dy := float64(img.Bounds().Dy()) / float64(height)
if dx > 1 && dy > 1 {
src := nrgb.NewNRGBScanner(img, nrgb.Color{})
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
srcY := int((float64(y) + 0.5) * dy)
dstOff := y * dst.Stride
for x := range width {
srcX := int((float64(x) + 0.5) * dx)
src.Scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+3])
dstOff += 3
}
}
}, 0, height); err != nil {
panic(err)
}
} else {
src := AsNRGB(img)
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
srcY := int((float64(y) + 0.5) * dy)
srcOff0 := srcY * src.Stride
dstOff := y * dst.Stride
for x := range width {
srcX := int((float64(x) + 0.5) * dx)
srcOff := srcOff0 + srcX*3
copy(dst.Pix[dstOff:dstOff+3], src.Pix[srcOff:srcOff+3])
dstOff += 3
}
}
}, 0, height); err != nil {
panic(err)
}
}
return dst
}
// Fit scales down the image using the specified resample filter to fit the specified
// maximum width and height and returns the transformed image.
//
+43 -12
View File
@@ -10,6 +10,7 @@ import (
"slices"
"github.com/kovidgoyal/imaging/nrgb"
"github.com/kovidgoyal/imaging/nrgba"
)
var _ = fmt.Println
@@ -34,30 +35,32 @@ func New(width, height int, fillColor color.Color) *image.NRGBA {
// Clone returns a copy of the given image.
func Clone(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
size := src.w * 4
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
size := w * 4
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * dst.Stride
src.Scan(0, y, src.w, y+1, dst.Pix[i:i+size])
src.Scan(0, y, w, y+1, dst.Pix[i:i+size])
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
}
func ClonePreservingOrigin(img image.Image) *image.NRGBA {
src := newScanner(img)
w, h := img.Bounds().Dx(), img.Bounds().Dy()
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(img.Bounds())
size := src.w * 4
size := w * 4
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
i := y * dst.Stride
src.Scan(0, y, src.w, y+1, dst.Pix[i:i+size])
src.Scan(0, y, w, y+1, dst.Pix[i:i+size])
}
}, 0, src.h); err != nil {
}, 0, h); err != nil {
panic(err)
}
return dst
@@ -306,7 +309,7 @@ func Crop(img image.Image, rect image.Rectangle) *image.NRGBA {
return Clone(img)
}
src := newScanner(img)
src := nrgba.NewNRGBAScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, r.Dx(), r.Dy()))
rowSize := r.Dx() * 4
if err := run_in_parallel_over_range(0, func(start, limit int) {
@@ -349,7 +352,7 @@ func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
return Clone(img)
}
src := newScanner(img)
src := nrgba.NewNRGBAScanner(img)
if err := run_in_parallel_over_range(0, func(start, limit int) {
for y := start; y < limit; y++ {
x1 := interRect.Min.X - pasteRect.Min.X
@@ -403,7 +406,7 @@ func Overlay(background, img image.Image, pos image.Point, opacity float64) *ima
if interRect.Empty() {
return dst
}
src := newScanner(img)
src := nrgba.NewNRGBAScanner(img)
if err := run_in_parallel_over_range(0, func(start, limit int) {
scanLine := make([]uint8, interRect.Dx()*4)
for y := start; y < limit; y++ {
@@ -489,3 +492,31 @@ func PasteOntoBackground(img image.Image, bg color.Color) image.Image {
}
return base
}
// Return contiguous non-premultiplied RGB pixel data for this image with 8 bits per channel
func AsRGBData8(img image.Image) (pix []uint8) {
b := img.Bounds()
n := AsNRGB(img)
if n.Stride == b.Dx()*3 {
return n.Pix
}
pix = make([]uint8, 0, b.Dx()*b.Dy()*3)
for y := range b.Dy() {
pix = append(pix, n.Pix[y*n.Stride:y*(n.Stride+1)]...)
}
return pix
}
// Return contiguous non-premultiplied RGBA pixel data for this image with 8 bits per channel
func AsRGBAData8(img image.Image) (pix []uint8) {
b := img.Bounds()
n := AsNRGBA(img)
if n.Stride == b.Dx()*4 {
return n.Pix
}
pix = make([]uint8, 0, b.Dx()*b.Dy()*4)
for y := range b.Dy() {
pix = append(pix, n.Pix[y*n.Stride:y*(n.Stride+1)]...)
}
return pix
}
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"math"
"github.com/kovidgoyal/imaging/nrgb"
"github.com/kovidgoyal/imaging/nrgba"
"github.com/kovidgoyal/imaging/types"
)
@@ -24,12 +25,12 @@ func ScannerForImage(img image.Image) Scanner {
for _, x := range img.Palette {
_, _, _, a := x.RGBA()
if a < 0xffff {
return NewNRGBAScanner(img)
return nrgba.NewNRGBAScanner(img)
}
}
return nrgb.NewNRGBScanner(img, NRGBColor{})
}
return NewNRGBAScanner(img)
return nrgba.NewNRGBAScanner(img)
}
// FlipH flips the image horizontally (from left to right) and returns the transformed image.
-18
View File
@@ -49,24 +49,6 @@ func clamp(x float64) uint8 {
return 0
}
func reverse4(pix []uint8) {
if len(pix) <= 4 {
return
}
i := 0
j := len(pix) - 4
for i < j {
pi := pix[i : i+4 : i+4]
pj := pix[j : j+4 : j+4]
pi[0], pj[0] = pj[0], pi[0]
pi[1], pj[1] = pj[1], pi[1]
pi[2], pj[2] = pj[2], pi[2]
pi[3], pj[3] = pj[3], pi[3]
i += 4
j -= 4
}
}
func toNRGBA(img image.Image) *image.NRGBA {
if img, ok := img.(*image.NRGBA); ok {
return &image.NRGBA{
+10 -9
View File
@@ -42,7 +42,7 @@ func decodeAnimated(r io.Reader) (*AnimatedWEBP, error) {
}
for {
frame, err := parseFrame(riffReader, vp8xHeader)
frame, err := parseFrame(riffReader)
if err != nil {
if err == io.EOF {
break
@@ -93,7 +93,7 @@ func validateANIMHeader(r *riff.Reader) (ANIMHeader, error) {
return h, nil
}
func parseFrame(r *riff.Reader, h VP8XHeader) (*Frame, error) {
func parseFrame(r *riff.Reader) (*Frame, error) {
fourCC, chunkLen, chunkData, err := r.Next()
if err != nil {
return nil, err
@@ -131,28 +131,29 @@ func parseFrame(r *riff.Reader, h VP8XHeader) (*Frame, error) {
return nil, err
}
}
if subFourCC != fccVP8 && subFourCC != fccVP8L {
return nil, errInvalidFormat
}
var out image.Image
if subFourCC == fccVP8 {
switch subFourCC {
case fccVP8:
i, err = decodeVp8Bitstream(subChunkData, int(subChunkLen))
if err != nil {
return nil, err
}
if alpha != nil && len(alpha) > 0 {
if len(alpha) > 0 {
out = &image.NYCbCrA{
YCbCr: *i,
A: alpha,
AStride: stride,
}
} else {
out = i
}
} else if subFourCC == fccVP8L {
case fccVP8L:
out, err = vp8l.Decode(subChunkData)
if err != nil {
return nil, err
}
default:
return nil, errInvalidFormat
}
return &Frame{
+1 -1
View File
@@ -721,7 +721,7 @@ func Decode(r io.Reader) (img image.Image, err error) {
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
// 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 {
+1 -15
View File
@@ -40,20 +40,6 @@ type int1ϕ int32
// buf[i] += int2ϕ(etc) // buf has type []int2ϕ.
type int2ϕ int32
func fixedMax(x, y int1ϕ) int1ϕ {
if x > y {
return x
}
return y
}
func fixedMin(x, y int1ϕ) int1ϕ {
if x < y {
return x
}
return y
}
func fixedFloor(x int1ϕ) int32 { return int32(x >> ϕ) }
func fixedCeil(x int1ϕ) int32 { return int32((x + fxOneMinusIota) >> ϕ) }
@@ -85,7 +71,7 @@ func (z *Rasterizer) fixedLineTo(bx, by float32) {
width := int32(z.size.X)
for ; y < yMax; y++ {
dy := fixedMin(int1ϕ(y+1)<<ϕ, byϕ) - fixedMax(int1ϕ(y)<<ϕ, ayϕ)
dy := min(int1ϕ(y+1)<<ϕ, byϕ) - max(int1ϕ(y)<<ϕ, ayϕ)
xNext := x + int1ϕ(float32(dy)*dxdy)
if y < 0 {
x = xNext
+1 -15
View File
@@ -11,20 +11,6 @@ import (
"math"
)
func floatingMax(x, y float32) float32 {
if x > y {
return x
}
return y
}
func floatingMin(x, y float32) float32 {
if x < y {
return x
}
return y
}
func floatingFloor(x float32) int32 { return int32(math.Floor(float64(x))) }
func floatingCeil(x float32) int32 { return int32(math.Ceil(float64(x))) }
@@ -53,7 +39,7 @@ func (z *Rasterizer) floatingLineTo(bx, by float32) {
width := int32(z.size.X)
for ; y < yMax; y++ {
dy := floatingMin(float32(y+1), by) - floatingMax(float32(y), ay)
dy := min(float32(y+1), by) - max(float32(y), ay)
// The "float32" in expressions like "float32(foo*bar)" here and below
// look redundant, since foo and bar already have type float32, but are
+2 -2
View File
@@ -34,7 +34,7 @@ import (
// Both implementations of line segmentation rasterization (see raster_fixed.go
// and raster_floating.go) implement the same algorithm (in ideal, infinite
// precision math) but they perform differently in practice. The fixed point
// math version is roughtly 1.25x faster (on GOARCH=amd64) on the benchmarks,
// math version is roughly 1.25x faster (on GOARCH=amd64) on the benchmarks,
// but at sufficiently large scales, the computations will overflow and hence
// show rendering artifacts. The floating point math version has more
// consistent quality over larger scales, but it is significantly slower.
@@ -251,7 +251,7 @@ func (z *Rasterizer) CubeTo(bx, by, cx, cy, dx, dy float32) {
// The reason for the subdivision by n is that I expect the "flatness"
// computation to be semi-expensive (it's done once rather than on each
// potential subdivision) and also because you'll often get fewer subdivisions.
// Taking a circular arc as a simplifying assumption (ie a spherical cow),
// Taking a circular arc as a simplifying assumption (i.e., a spherical cow),
// where I get n, a recursive approach would get 2^⌈lg n⌉, which, if I haven't
// made any horrible mistakes, is expected to be 33% more in the limit.
func devSquared(ax, ay, bx, by, cx, cy float32) float32 {
+1 -1
View File
@@ -4,7 +4,7 @@
package vp8
// This file implements the predicition functions, as specified in chapter 12.
// This file implements the prediction 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
+1 -1
View File
@@ -178,7 +178,7 @@ var unpack = [16][4]uint8{
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.
// Category probabilities 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},
+15
View File
@@ -37,6 +37,15 @@ type priorityWriteSchedulerRFC9218 struct {
// incremental streams or not, when urgency is the same in a given Pop()
// call.
prioritizeIncremental bool
// priorityUpdateBuf is used to buffer the most recent PRIORITY_UPDATE we
// receive per https://www.rfc-editor.org/rfc/rfc9218.html#name-the-priority_update-frame.
priorityUpdateBuf struct {
// streamID being 0 means that the buffer is empty. This is a safe
// assumption as PRIORITY_UPDATE for stream 0 is a PROTOCOL_ERROR.
streamID uint32
priority PriorityParam
}
}
func newPriorityWriteSchedulerRFC9218() WriteScheduler {
@@ -50,6 +59,10 @@ func (ws *priorityWriteSchedulerRFC9218) OpenStream(streamID uint32, opt OpenStr
if ws.streams[streamID].location != nil {
panic(fmt.Errorf("stream %d already opened", streamID))
}
if streamID == ws.priorityUpdateBuf.streamID {
ws.priorityUpdateBuf.streamID = 0
opt.priority = ws.priorityUpdateBuf.priority
}
q := ws.queuePool.get()
ws.streams[streamID] = streamMetadata{
location: q,
@@ -95,6 +108,8 @@ func (ws *priorityWriteSchedulerRFC9218) AdjustStream(streamID uint32, priority
metadata := ws.streams[streamID]
q, u, i := metadata.location, metadata.priority.urgency, metadata.priority.incremental
if q == nil {
ws.priorityUpdateBuf.streamID = streamID
ws.priorityUpdateBuf.priority = priority
return
}
+9 -6
View File
@@ -846,9 +846,6 @@ github.com/juliangruber/go-intersect
# github.com/justinas/alice v1.2.0
## explicit; go 1.12
github.com/justinas/alice
# github.com/kettek/apng v0.0.0-20250827064933-2bb5f5fcf253
## explicit
github.com/kettek/apng
# github.com/kevinburke/ssh_config v1.2.0
## explicit
github.com/kevinburke/ssh_config
@@ -876,13 +873,19 @@ github.com/klauspost/crc32
# github.com/kovidgoyal/go-parallel v1.1.1
## explicit; go 1.23
github.com/kovidgoyal/go-parallel
# github.com/kovidgoyal/imaging v1.8.7
# github.com/kovidgoyal/go-shm v1.0.0
## explicit; go 1.24.0
github.com/kovidgoyal/go-shm
# github.com/kovidgoyal/imaging v1.8.19
## explicit; go 1.24.0
github.com/kovidgoyal/imaging
github.com/kovidgoyal/imaging/apng
github.com/kovidgoyal/imaging/colorconv
github.com/kovidgoyal/imaging/jpeg
github.com/kovidgoyal/imaging/magick
github.com/kovidgoyal/imaging/netpbm
github.com/kovidgoyal/imaging/nrgb
github.com/kovidgoyal/imaging/nrgba
github.com/kovidgoyal/imaging/prism/meta
github.com/kovidgoyal/imaging/prism/meta/autometa
github.com/kovidgoyal/imaging/prism/meta/gifmeta
@@ -2273,7 +2276,7 @@ golang.org/x/exp/slices
golang.org/x/exp/slog
golang.org/x/exp/slog/internal
golang.org/x/exp/slog/internal/buffer
# golang.org/x/image v0.32.0
# golang.org/x/image v0.35.0
## explicit; go 1.24.0
golang.org/x/image/bmp
golang.org/x/image/ccitt
@@ -2294,7 +2297,7 @@ golang.org/x/image/webp
golang.org/x/mod/internal/lazyregexp
golang.org/x/mod/module
golang.org/x/mod/semver
# golang.org/x/net v0.48.0
# golang.org/x/net v0.49.0
## explicit; go 1.24.0
golang.org/x/net/bpf
golang.org/x/net/context