Checkpoint
This commit is contained in:
125 files changed
+59376
No files matched your search
@@ -0,0 +1,73 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// Color555 is a 16-bit RGB555 color.
|
||||
//
|
||||
// The 5 most significant bits are red, the 5 middle bits are green, and the 5 last ones are blue:
|
||||
//
|
||||
// 0RRRRRGG GGGBBBBB
|
||||
type Color555 uint16
|
||||
|
||||
func (c Color555) RGBA() (r, g, b, a uint32) {
|
||||
r = ((uint32(c&0x7c00) >> 10) * 255) / 31
|
||||
r |= r << 8
|
||||
g = ((uint32(c&0x03e0) >> 5) * 255) / 31
|
||||
g |= g << 8
|
||||
b = ((uint32(c&0x001f) >> 0) * 255) / 31
|
||||
b |= b << 8
|
||||
a = 0xFFFF
|
||||
return
|
||||
}
|
||||
|
||||
var Color555Model color.Model = color.ModelFunc(color555Model)
|
||||
|
||||
func color555Model(c color.Color) color.Color {
|
||||
if _, ok := c.(Color565); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA() // 16 bits per channel
|
||||
r = (r & 0xf800) >> 1 // .RRRRR.. ........
|
||||
g = (g & 0xf800) >> 6 // ......GG GGG.....
|
||||
b = (b & 0xf800) >> 11 // ........ ...BBBBB
|
||||
return Color555(r | g | b)
|
||||
}
|
||||
|
||||
type Image555 struct {
|
||||
Pix []byte
|
||||
Rect image.Rectangle
|
||||
Stride int
|
||||
}
|
||||
|
||||
func NewImage555(r image.Rectangle) *Image555 {
|
||||
var (
|
||||
w, h = r.Dx(), r.Dy()
|
||||
size = w * h * 2
|
||||
pix = make([]byte, size)
|
||||
)
|
||||
return &Image555{pix, r, w * 2}
|
||||
}
|
||||
|
||||
func (i *Image555) ColorModel() color.Model { return Color555Model }
|
||||
func (i *Image555) Bounds() image.Rectangle { return i.Rect }
|
||||
|
||||
func (i *Image555) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return Color555(0)
|
||||
}
|
||||
o := y*i.Stride + x*2
|
||||
return Color555(i.Pix[o]) | Color555(i.Pix[o+1])<<8
|
||||
}
|
||||
|
||||
func (i *Image555) Set(x, y int, c color.Color) {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return
|
||||
}
|
||||
o := y*i.Stride + x*2
|
||||
cc := color555Model(c).(Color555)
|
||||
i.Pix[o] = byte(cc)
|
||||
i.Pix[o+1] = byte(cc >> 8)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testsColor555 = []struct {
|
||||
name string
|
||||
test Color555
|
||||
r, g, b uint32
|
||||
}{
|
||||
{"black",
|
||||
Color555(0b000000000000000), 0, 0, 0},
|
||||
{"white",
|
||||
Color555(0b111111111111111), 255, 255, 255},
|
||||
{"red",
|
||||
Color555(0b111110000000000), 255, 0, 0},
|
||||
{"green",
|
||||
Color555(0b000001111100000), 0, 255, 0},
|
||||
{"blue",
|
||||
Color555(0b000001001111011), 0, 156, 222},
|
||||
{"yellow",
|
||||
Color555(0b111111011000001), 255, 180, 8},
|
||||
{"cyan",
|
||||
Color555(0b000001111111111), 0, 255, 255},
|
||||
{"magenta",
|
||||
Color555(0b111110000011111), 255, 0, 255},
|
||||
}
|
||||
|
||||
func TestColor555(t *testing.T) {
|
||||
for _, test := range testsColor555 {
|
||||
t.Run(test.name, func(it *testing.T) {
|
||||
r, g, b, _ := test.test.RGBA()
|
||||
r >>= 8 // undo the premultiplication
|
||||
g >>= 8
|
||||
b >>= 8
|
||||
if r != test.r || g != test.g || b != test.b {
|
||||
it.Errorf("expected %d %d %d, got %d %d %d", test.r, test.g, test.b, r, g, b)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModel555(t *testing.T) {
|
||||
for _, test := range testsColor555 {
|
||||
t.Run(test.name, func(it *testing.T) {
|
||||
c := Color555Model.Convert(color.RGBA{uint8(test.r), uint8(test.g), uint8(test.b), 255})
|
||||
if c != test.test {
|
||||
it.Errorf("expected %#04x, got %#04x", test.test, c)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// Color565 is a 16-bit RGB565 color.
|
||||
//
|
||||
// The 5 most significant bits are red, the 6 middle bits are green, and the 5 last ones are blue:
|
||||
//
|
||||
// RRRRRGGG GGGBBBBB
|
||||
type Color565 uint16
|
||||
|
||||
//func RGB565(r, g, b uint8) Color565 {
|
||||
// return Color565(uint16(r&0xF8)<<8 | uint16(g&0xFC)<<3 | uint16(b>>3))
|
||||
//}
|
||||
|
||||
func (c Color565) RGBA() (r, g, b, a uint32) {
|
||||
r = ((uint32(c&0xf800) >> 11) * 255) / 31
|
||||
r |= r << 8
|
||||
g = ((uint32(c&0x07e0) >> 5) * 255) / 63
|
||||
g |= g << 8
|
||||
b = ((uint32(c&0x001f) >> 0) * 255) / 31
|
||||
b |= b << 8
|
||||
a = 0xFFFF
|
||||
return
|
||||
}
|
||||
|
||||
var Color565Model color.Model = color.ModelFunc(color565Model)
|
||||
|
||||
func color565Model(c color.Color) color.Color {
|
||||
if _, ok := c.(Color565); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA() // 16 bits per channel
|
||||
r = (r & 0xf800) // RRRRR... ........
|
||||
g = (g & 0xfc00) >> 5 // .....GGG GGG.....
|
||||
b = (b & 0xf800) >> 11 // ........ ...BBBBB
|
||||
return Color565(r | g | b)
|
||||
}
|
||||
|
||||
type Image565 struct {
|
||||
Pix []byte
|
||||
Rect image.Rectangle
|
||||
Stride int
|
||||
}
|
||||
|
||||
func NewImage565(r image.Rectangle) *Image565 {
|
||||
var (
|
||||
w, h = r.Dx(), r.Dy()
|
||||
size = w * h * 2
|
||||
pix = make([]byte, size)
|
||||
)
|
||||
return &Image565{pix, r, w * 2}
|
||||
}
|
||||
|
||||
func (i *Image565) ColorModel() color.Model { return Color565Model }
|
||||
func (i *Image565) Bounds() image.Rectangle { return i.Rect }
|
||||
|
||||
func (i *Image565) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return Color565(0)
|
||||
}
|
||||
o := y*i.Stride + x*2
|
||||
return Color565(i.Pix[o]) | Color565(i.Pix[o+1])<<8
|
||||
}
|
||||
|
||||
func (i *Image565) Set(x, y int, c color.Color) {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return
|
||||
}
|
||||
o := y*i.Stride + x*2
|
||||
cc := color565Model(c).(Color565)
|
||||
i.Pix[o] = byte(cc)
|
||||
i.Pix[o+1] = byte(cc >> 8)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testsColor565 = []struct {
|
||||
name string
|
||||
test Color565
|
||||
r, g, b uint32
|
||||
}{
|
||||
{"black",
|
||||
Color565(0b0000000000000000), 0, 0, 0},
|
||||
{"white",
|
||||
Color565(0b1111111111111111), 255, 255, 255},
|
||||
{"red",
|
||||
Color565(0b1111100000000000), 255, 0, 0},
|
||||
{"green",
|
||||
Color565(0b0000011111100000), 0, 255, 0},
|
||||
{"blue",
|
||||
Color565(0b0000010011111100), 0, 157, 230},
|
||||
{"yellow",
|
||||
Color565(0b1111110111000001), 255, 186, 8},
|
||||
{"cyan",
|
||||
Color565(0b0000011111111111), 0, 255, 255},
|
||||
{"magenta",
|
||||
Color565(0b1111100000011111), 255, 0, 255},
|
||||
}
|
||||
|
||||
func TestColor565(t *testing.T) {
|
||||
for _, test := range testsColor565 {
|
||||
t.Run(test.name, func(it *testing.T) {
|
||||
r, g, b, _ := test.test.RGBA()
|
||||
r >>= 8 // undo the premultiplication
|
||||
g >>= 8
|
||||
b >>= 8
|
||||
if r != test.r || g != test.g || b != test.b {
|
||||
it.Errorf("expected %d %d %d, got %d %d %d", test.r, test.g, test.b, r, g, b)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModel565(t *testing.T) {
|
||||
for _, test := range testsColor565 {
|
||||
t.Run(test.name, func(it *testing.T) {
|
||||
c := Color565Model.Convert(color.RGBA{uint8(test.r), uint8(test.g), uint8(test.b), 255})
|
||||
if c != test.test {
|
||||
it.Errorf("expected %#04x, got %#04x", test.test, c)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// ToGrayBits converts a color to a n-bit grayscale color.
|
||||
func ToGrayBits(c color.Color, n uint8) uint16 {
|
||||
r, g, b, _ := c.RGBA()
|
||||
|
||||
if n < 1 {
|
||||
return 0 // no color
|
||||
} else if n > 16 {
|
||||
n = 16 // most that will fit
|
||||
}
|
||||
|
||||
// Shift values to fit n bits.
|
||||
s := 32 - n
|
||||
|
||||
// These coefficients (the fractions 0.299, 0.587 and 0.114) are the same
|
||||
// as those given by the JFIF specification and used by func RGBToYCbCr in
|
||||
// image/color/ycbcr.go.
|
||||
//
|
||||
// Note that 19595 + 38470 + 7471 equals 65536.
|
||||
//
|
||||
// The 28 is 16 + 8 + n. The 16 is the same as used in RGBToYCbCr. The 8 + n is
|
||||
// because the return value is n-bit color, not 16 bit color.
|
||||
return uint16((19595*r + 38470*g + 7471*b + 1<<15) >> s)
|
||||
}
|
||||
|
||||
func IsOn(c color.Color) bool {
|
||||
return ToGrayBits(c, 1) == 1
|
||||
}
|
||||
|
||||
func IsOff(c color.Color) bool {
|
||||
return ToGrayBits(c, 1) == 0
|
||||
}
|
||||
|
||||
// Monochrome is a 1-bit color.
|
||||
type Monochrome uint8
|
||||
|
||||
// Monochrome constants.
|
||||
const (
|
||||
On Monochrome = iota
|
||||
Off
|
||||
)
|
||||
|
||||
func (m Monochrome) RGBA() (r, g, b, a uint32) {
|
||||
if m == 0 {
|
||||
return 0, 0, 0, 0
|
||||
}
|
||||
return 0xffff, 0xffff, 0xffff, 0xffff
|
||||
}
|
||||
|
||||
var MonochromeModel color.Model = color.ModelFunc(monochromeModel)
|
||||
|
||||
func monochromeModel(c color.Color) color.Color {
|
||||
if _, ok := c.(Monochrome); ok {
|
||||
return c
|
||||
}
|
||||
if IsOn(c) {
|
||||
return Monochrome(1)
|
||||
}
|
||||
return Monochrome(0)
|
||||
}
|
||||
|
||||
type MonochromeImage struct {
|
||||
Pix []byte
|
||||
Rect image.Rectangle
|
||||
Stride int
|
||||
}
|
||||
|
||||
func NewMonochromeImage(r image.Rectangle) *MonochromeImage {
|
||||
var (
|
||||
w, h = r.Dx(), r.Dy()
|
||||
size = w * h / 8
|
||||
pix = make([]byte, size)
|
||||
)
|
||||
return &MonochromeImage{pix, r, w / 8}
|
||||
}
|
||||
|
||||
func (i *MonochromeImage) ColorModel() color.Model { return MonochromeModel }
|
||||
func (i *MonochromeImage) Bounds() image.Rectangle { return i.Rect }
|
||||
|
||||
func (i *MonochromeImage) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return Monochrome(0)
|
||||
}
|
||||
o := y*i.Stride + x/8
|
||||
return Monochrome(i.Pix[o] >> (7 - uint(x%8)) & 1)
|
||||
}
|
||||
|
||||
func (i *MonochromeImage) Set(x, y int, c color.Color) {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return
|
||||
}
|
||||
o := y*i.Stride + x/8
|
||||
if IsOn(c) {
|
||||
i.Pix[o] |= 1 << (7 - uint(x%8))
|
||||
} else {
|
||||
i.Pix[o] &^= 1 << (7 - uint(x%8))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// Gray4 represents a 4-bit grayscale color.
|
||||
type Gray4 struct {
|
||||
Y uint8
|
||||
}
|
||||
|
||||
func (c Gray4) RGBA() (r, g, b, a uint32) {
|
||||
y := uint32(c.Y & 0x0f)
|
||||
y |= y << 4
|
||||
y |= y << 8
|
||||
return y, y, y, 0xffff
|
||||
}
|
||||
|
||||
var Gray4Model color.Model = color.ModelFunc(gray4Model)
|
||||
|
||||
func gray4Model(c color.Color) color.Color {
|
||||
if _, ok := c.(Gray4); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA()
|
||||
|
||||
// These coefficients (the fractions 0.299, 0.587 and 0.114) are the same
|
||||
// as those given by the JFIF specification and used by func RGBToYCbCr in
|
||||
// ycbcr.go.
|
||||
//
|
||||
// Note that 19595 + 38470 + 7471 equals 65536.
|
||||
//
|
||||
// The 28 is 16 + 8 + 4. The 16 is the same as used in RGBToYCbCr. The 8 + 4 is
|
||||
// because the return value is 4 bit color, not 16 bit color.
|
||||
y := (19595*r + 38470*g + 7471*b + 1<<15) >> 28
|
||||
|
||||
return Gray4{uint8(y)}
|
||||
}
|
||||
|
||||
// ImageGray4 contains 4-bit grayscale pixels.
|
||||
type ImageGray4 struct {
|
||||
Pix []byte
|
||||
Rect image.Rectangle
|
||||
Stride int
|
||||
}
|
||||
|
||||
func NewImageGray4(r image.Rectangle) *ImageGray4 {
|
||||
var (
|
||||
w, h = r.Dx(), r.Dy()
|
||||
size = w * h / 2
|
||||
pix = make([]byte, size)
|
||||
)
|
||||
return &ImageGray4{pix, r, w / 2}
|
||||
}
|
||||
|
||||
func (i *ImageGray4) ColorModel() color.Model { return Gray4Model }
|
||||
func (i *ImageGray4) Bounds() image.Rectangle { return i.Rect }
|
||||
|
||||
func (i *ImageGray4) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return Gray4{0}
|
||||
}
|
||||
o := (y*i.Stride + x) >> 1
|
||||
if x&1 == 0 { // even x is stored in the high bits
|
||||
return Gray4{i.Pix[o] >> 4}
|
||||
}
|
||||
return Gray4{i.Pix[o] & 0x0f}
|
||||
}
|
||||
|
||||
func (i *ImageGray4) Set(x, y int, c color.Color) {
|
||||
if !(image.Point{x, y}.In(i.Rect)) {
|
||||
return
|
||||
}
|
||||
o := (y*i.Stride + x) >> 1
|
||||
if x&1 == 0 { // even x is stored in the high bits
|
||||
i.Pix[o] = i.Pix[o]&0x0f | c.(Gray4).Y<<4
|
||||
} else {
|
||||
i.Pix[o] = i.Pix[o]&0xf0 | c.(Gray4).Y
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package dsp
|
||||
|
||||
import (
|
||||
"math/cmplx"
|
||||
|
||||
"github.com/maddyblue/go-dsp/fft"
|
||||
"periph.io/x/conn/v3/physic"
|
||||
|
||||
"git.maze.io/go/bragi/internal/audio"
|
||||
)
|
||||
|
||||
// Analyzer for audio signals.
|
||||
type Analyzer struct {
|
||||
signal audio.Complex128
|
||||
}
|
||||
|
||||
type FrequencySpectrum struct {
|
||||
// Store the frequency spectrum values
|
||||
Spectrum []float64
|
||||
|
||||
// Store the frequencies used
|
||||
Frequencies []float64
|
||||
}
|
||||
|
||||
// FrequencySpectrum calculates the frequency spectrum of the signal.
|
||||
func (s *Analyzer) FrequencySpectrum(samples audio.Slice, rate physic.Frequency) (*FrequencySpectrum, error) {
|
||||
// Copy the samples to our complex buffer.
|
||||
length := samples.Len()
|
||||
if len(s.signal) < length {
|
||||
s.signal = make(audio.Complex128, length)
|
||||
} else {
|
||||
s.signal = s.signal[:length]
|
||||
}
|
||||
samples.CopyTo(s.signal)
|
||||
|
||||
// Apply the FFT on the signal to get the frequency components
|
||||
ffft := fft.FFT(s.signal)
|
||||
|
||||
// Compute the two sided spectrum
|
||||
var spectrum2 []float64
|
||||
|
||||
flength := float64(length)
|
||||
for i := range ffft {
|
||||
// Get the absolute value since the fft is a complex value with both real and imaginary parts
|
||||
spectrum2 = append(spectrum2, cmplx.Abs(ffft[i])/flength)
|
||||
}
|
||||
|
||||
// Look at the one sided spectrum
|
||||
spectrum1 := spectrum2[0 : len(spectrum2)/2]
|
||||
|
||||
for i := range spectrum1 {
|
||||
spectrum1[i] = spectrum1[i] * 2
|
||||
}
|
||||
|
||||
var (
|
||||
frequencies []float64
|
||||
spectrumLength = float64(len(spectrum2))
|
||||
scale = rate.Period().Seconds() / spectrumLength
|
||||
)
|
||||
for i := range spectrum1 {
|
||||
// Calculate which frequencies the spectrum contains
|
||||
frequencies = append(frequencies, float64(i)*scale)
|
||||
}
|
||||
|
||||
return &FrequencySpectrum{
|
||||
Spectrum: spectrum1,
|
||||
Frequencies: frequencies,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// Pixel with a particular color, matching the underlying hardware of a
|
||||
// particular display. Each pixel is at least 1 byte in size.
|
||||
// The color format is sRGB (or close to it) in all cases except for 1-bit.
|
||||
type Color interface {
|
||||
RGB888 | RGB565BE | RGB555 | RGB444BE | Monochrome
|
||||
|
||||
BaseColor
|
||||
}
|
||||
|
||||
// BaseColor contains all the methods needed in a color format. This can be used
|
||||
// in display drivers that want to define their own Color type with just the
|
||||
// pixel formats the display supports.
|
||||
type BaseColor interface {
|
||||
color.Color
|
||||
|
||||
// The number of bits when stored.
|
||||
// This means for example that RGB555 (which is still stored as a 16-bit
|
||||
// integer) returns 16, while RGB444 returns 12.
|
||||
BitsPerPixel() int
|
||||
|
||||
// Return the given color in color.RGBA format, which is always sRGB. The
|
||||
// alpha channel is always 255.
|
||||
RGBAColor() color.RGBA
|
||||
}
|
||||
|
||||
// NewColor returns the given color based on the RGB values passed in the
|
||||
// parameters. The input value is assumed to be in sRGB color space.
|
||||
func NewColor[T Color](r, g, b uint8) T {
|
||||
// Ugly cast from color.RGBA to T. The type switch and interface casts are
|
||||
// trivially optimized away after instantiation.
|
||||
var value T
|
||||
switch any(value).(type) {
|
||||
case RGB888:
|
||||
return any(NewRGB888(r, g, b)).(T)
|
||||
case RGB565BE:
|
||||
return any(NewRGB565BE(r, g, b)).(T)
|
||||
case RGB555:
|
||||
return any(NewRGB555(r, g, b)).(T)
|
||||
case RGB444BE:
|
||||
return any(NewRGB444BE(r, g, b)).(T)
|
||||
case Monochrome:
|
||||
return any(NewMonochrome(r, g, b)).(T)
|
||||
default:
|
||||
panic("unknown color format")
|
||||
}
|
||||
}
|
||||
|
||||
// FromColor retusn the given color.
|
||||
func FromColor[T Color](c color.Color) T {
|
||||
var value T
|
||||
switch any(value).(type) {
|
||||
case RGB888:
|
||||
return rgb888Model(c).(T)
|
||||
case RGB565BE:
|
||||
return rgb565BEModel(c).(T)
|
||||
case RGB555:
|
||||
return rgb555Model(c).(T)
|
||||
case RGB444BE:
|
||||
return rgb444BEModel(c).(T)
|
||||
case Monochrome:
|
||||
return monochromeModel(c).(T)
|
||||
default:
|
||||
panic("unknown color format")
|
||||
}
|
||||
}
|
||||
|
||||
// NewLinearColor returns the given color based on the linear RGB values passed
|
||||
// in the parameters. Use this if the RGB values are actually linear colors
|
||||
// (like those that are used in most RGB LEDs) and not when it is in the usual
|
||||
// sRGB color space (which is not linear).
|
||||
//
|
||||
// The input is assumed to be in the linear sRGB color space.
|
||||
func NewLinearColor[T Color](r, g, b uint8) T {
|
||||
r = gammaEncodeTable[r]
|
||||
g = gammaEncodeTable[g]
|
||||
b = gammaEncodeTable[b]
|
||||
return NewColor[T](r, g, b)
|
||||
}
|
||||
|
||||
// RGB888 format, more commonly used in other places (desktop PC displays, CSS,
|
||||
// etc). Less commonly used on embedded displays due to the higher memory usage.
|
||||
type RGB888 struct {
|
||||
R, G, B uint8
|
||||
}
|
||||
|
||||
func NewRGB888(r, g, b uint8) RGB888 {
|
||||
return RGB888{r, g, b}
|
||||
}
|
||||
|
||||
func (c RGB888) BitsPerPixel() int {
|
||||
return 24
|
||||
}
|
||||
|
||||
func (c RGB888) RGBA() (r, g, b, a uint32) {
|
||||
r = uint32(c.R)
|
||||
r |= r << 8
|
||||
g = uint32(c.G)
|
||||
g |= g << 8
|
||||
b = uint32(c.B)
|
||||
b |= b << 8
|
||||
a = 0xffff
|
||||
return
|
||||
}
|
||||
|
||||
func (c RGB888) RGBAColor() color.RGBA {
|
||||
return color.RGBA{
|
||||
R: c.R,
|
||||
G: c.G,
|
||||
B: c.B,
|
||||
A: 255,
|
||||
}
|
||||
}
|
||||
|
||||
// RGB565 as used in many SPI displays. Stored as a big endian value.
|
||||
//
|
||||
// The color format in integer form is gggbbbbb_rrrrrggg on little endian
|
||||
// systems, which is the standard RGB565 format but with the top and bottom
|
||||
// bytes swapped.
|
||||
//
|
||||
// There are a few alternatives to this weird big-endian format, but they're not
|
||||
// great:
|
||||
// - Storing the value in two 8-bit stores (to make the code endian-agnostic)
|
||||
// incurs too much of a performance penalty.
|
||||
// - Swapping the upper and lower bits just before storing. This is still less
|
||||
// efficient than it could be, since colors are usually constructed once and
|
||||
// then reused in many store operations. Doing the swap once instead of many
|
||||
// times for each store is a performance win.
|
||||
type RGB565BE uint16
|
||||
|
||||
func NewRGB565BE(r, g, b uint8) RGB565BE {
|
||||
val := uint16(r&0xF8)<<8 +
|
||||
uint16(g&0xFC)<<3 +
|
||||
uint16(b&0xF8)>>3
|
||||
// Swap endianness (make big endian).
|
||||
// This is done using a single instruction on ARM (rev16).
|
||||
// TODO: this should only be done on little endian systems, but TinyGo
|
||||
// doesn't currently (2023) support big endian systems so it's difficult to
|
||||
// test. Also, big endian systems don't seem fasionable these days.
|
||||
//val = bits.ReverseBytes16(val)
|
||||
return RGB565BE(val)
|
||||
}
|
||||
|
||||
func (c RGB565BE) BitsPerPixel() int {
|
||||
return 16
|
||||
}
|
||||
|
||||
func (c RGB565BE) RGBA() (r, g, b, a uint32) {
|
||||
r = uint32(uint8(c>>12) << 3)
|
||||
r |= (r >> 5)
|
||||
r |= (r << 8)
|
||||
g = uint32(uint8(c>>5) << 2)
|
||||
g |= (g >> 6)
|
||||
g |= (g << 8)
|
||||
b = uint32(uint8(c>>0) << 3)
|
||||
b |= (b >> 5)
|
||||
b |= (b << 8)
|
||||
a = 0xffff
|
||||
return
|
||||
}
|
||||
|
||||
func (c RGB565BE) RGBAColor() color.RGBA {
|
||||
// Note: on ARM, the compiler uses a rev instruction instead of a rev16
|
||||
// instruction. I wonder whether this can be optimized further to use rev16
|
||||
// instead?
|
||||
c = c<<8 | c>>8
|
||||
color := color.RGBA{
|
||||
R: uint8(c>>11) << 3,
|
||||
G: uint8(c>>5) << 2,
|
||||
B: uint8(c) << 3,
|
||||
A: 255,
|
||||
}
|
||||
// Correct color rounding, so that 0xff roundtrips back to 0xff.
|
||||
color.R |= color.R >> 5
|
||||
color.G |= color.G >> 6
|
||||
color.B |= color.B >> 5
|
||||
return color
|
||||
}
|
||||
|
||||
// Color format used on the GameBoy Advance among others.
|
||||
//
|
||||
// Colors are stored as native endian values, with bits 0bbbbbgg_gggrrrrr (red
|
||||
// is least significant, blue is most significant).
|
||||
type RGB555 uint16
|
||||
|
||||
func NewRGB555(r, g, b uint8) RGB555 {
|
||||
return RGB555(r)>>3 | (RGB555(g)>>3)<<5 | (RGB555(b)>>3)<<10
|
||||
}
|
||||
|
||||
func (c RGB555) BitsPerPixel() int {
|
||||
// 15 bits per pixel, but there are 16 bits when stored
|
||||
return 16
|
||||
}
|
||||
|
||||
func (c RGB555) RGBA() (r, g, b, a uint32) {
|
||||
r = uint32(uint8(c>>10) << 3)
|
||||
r |= (r >> 5)
|
||||
r |= (r << 8)
|
||||
g = uint32(uint8(c>>5) << 3)
|
||||
g |= (g >> 5)
|
||||
g |= (g << 8)
|
||||
b = uint32(uint8(c>>0) << 3)
|
||||
b |= (b >> 5)
|
||||
b |= (b << 8)
|
||||
a = 0xffff
|
||||
return
|
||||
}
|
||||
|
||||
func (c RGB555) RGBAColor() color.RGBA {
|
||||
color := color.RGBA{
|
||||
R: uint8(c>>10) << 3,
|
||||
G: uint8(c>>5) << 3,
|
||||
B: uint8(c) << 3,
|
||||
A: 255,
|
||||
}
|
||||
// Correct color rounding, so that 0xff roundtrips back to 0xff.
|
||||
color.R |= color.R >> 5
|
||||
color.G |= color.G >> 5
|
||||
color.B |= color.B >> 5
|
||||
return color
|
||||
}
|
||||
|
||||
// Color format that is supported by the ST7789 for example.
|
||||
// It may be a bit faster to use than RGB565BE on very slow SPI buses.
|
||||
//
|
||||
// The color format is native endian as a uint16 (0000rrrr_ggggbbbb), not big
|
||||
// endian which you might expect. I tried swapping the bytes, but it didn't have
|
||||
// much of a performance impact and made the code harder to read. It is stored
|
||||
// as a 12-bit big endian value in Image[RGB444BE] though.
|
||||
type RGB444BE uint16
|
||||
|
||||
func NewRGB444BE(r, g, b uint8) RGB444BE {
|
||||
return RGB444BE(r>>4)<<8 | RGB444BE(g>>4)<<4 | RGB444BE(b>>4)
|
||||
}
|
||||
|
||||
func (c RGB444BE) BitsPerPixel() int {
|
||||
return 12
|
||||
}
|
||||
|
||||
func (c RGB444BE) RGBA() (r, g, b, a uint32) {
|
||||
r = uint32(c>>8) & 0x0f
|
||||
r |= (r << 4) | (r << 8) | (r << 12)
|
||||
g = uint32(c>>4) & 0x0f
|
||||
g |= (g << 4) | (g << 8) | (g << 12)
|
||||
b = uint32(c>>0) & 0x0f
|
||||
b |= (b << 4) | (b << 8) | (b << 12)
|
||||
a |= 0xffff
|
||||
return
|
||||
}
|
||||
|
||||
func (c RGB444BE) RGBAColor() color.RGBA {
|
||||
color := color.RGBA{
|
||||
R: uint8(c>>8) << 4,
|
||||
G: uint8(c>>4) << 4,
|
||||
B: uint8(c>>0) << 4,
|
||||
A: 255,
|
||||
}
|
||||
// Correct color rounding, so that 0xff roundtrips back to 0xff.
|
||||
color.R |= color.R >> 4
|
||||
color.G |= color.G >> 4
|
||||
color.B |= color.B >> 4
|
||||
return color
|
||||
}
|
||||
|
||||
// Monochrome is a 1-bit color.
|
||||
type Monochrome uint8
|
||||
|
||||
const (
|
||||
Off Monochrome = iota
|
||||
On
|
||||
)
|
||||
|
||||
func NewMonochrome(r, g, b uint8) Monochrome {
|
||||
// Very simple black/white split.
|
||||
// This isn't very accurate (especially for sRGB colors) but is close enough.
|
||||
if int(r)+int(g)+int(b) > 128*3 { // light, convert to white
|
||||
return 1
|
||||
}
|
||||
// dark, convert to black
|
||||
return 0
|
||||
}
|
||||
|
||||
func (c Monochrome) BitsPerPixel() int {
|
||||
return 1
|
||||
}
|
||||
|
||||
func (c Monochrome) RGBA() (r, g, b, a uint32) {
|
||||
if c > 0 {
|
||||
return 0xffff, 0xffff, 0xffff, 0xffff
|
||||
}
|
||||
return 0, 0, 0, 0
|
||||
}
|
||||
|
||||
func (c Monochrome) RGBAColor() color.RGBA {
|
||||
value := uint8(0)
|
||||
if c > 0 {
|
||||
value = 255
|
||||
}
|
||||
return color.RGBA{
|
||||
R: value,
|
||||
G: value,
|
||||
B: value,
|
||||
A: 255,
|
||||
}
|
||||
}
|
||||
|
||||
// Gamma brightness lookup table:
|
||||
// https://victornpb.github.io/gamma-table-generator
|
||||
// gamma = 0.45 steps = 256 range = 0-255
|
||||
var gammaEncodeTable = [256]uint8{
|
||||
0, 21, 28, 34, 39, 43, 46, 50, 53, 56, 59, 61, 64, 66, 68, 70,
|
||||
72, 74, 76, 78, 80, 82, 84, 85, 87, 89, 90, 92, 93, 95, 96, 98,
|
||||
99, 101, 102, 103, 105, 106, 107, 109, 110, 111, 112, 114, 115, 116, 117, 118,
|
||||
119, 120, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
|
||||
136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150,
|
||||
151, 151, 152, 153, 154, 155, 156, 156, 157, 158, 159, 160, 160, 161, 162, 163,
|
||||
164, 164, 165, 166, 167, 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175,
|
||||
175, 176, 177, 178, 178, 179, 180, 180, 181, 182, 182, 183, 184, 184, 185, 186,
|
||||
186, 187, 188, 188, 189, 190, 190, 191, 192, 192, 193, 194, 194, 195, 195, 196,
|
||||
197, 197, 198, 199, 199, 200, 200, 201, 202, 202, 203, 203, 204, 205, 205, 206,
|
||||
206, 207, 207, 208, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 214, 215,
|
||||
215, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 223, 223, 224,
|
||||
224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232,
|
||||
232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, 240,
|
||||
240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248,
|
||||
248, 249, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255, 255,
|
||||
}
|
||||
|
||||
// IsOn checks if the pixel is on or off.
|
||||
func IsOn(c color.Color) bool {
|
||||
return monochromeModel(c) == On
|
||||
}
|
||||
|
||||
// Interface checks
|
||||
var (
|
||||
_ color.Color = (*RGB888)(nil)
|
||||
_ color.Color = (*RGB565BE)(nil)
|
||||
_ color.Color = (*RGB555)(nil)
|
||||
_ color.Color = (*RGB444BE)(nil)
|
||||
_ color.Color = (*Monochrome)(nil)
|
||||
)
|
||||
@@ -0,0 +1,372 @@
|
||||
package pixel
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Image buffer, used for working with the native image format of various
|
||||
// displays. It works a lot like a slice: it can be rescaled while reusing the
|
||||
// underlying buffer and should be passed around by value.
|
||||
type Image[T Color] struct {
|
||||
width int16
|
||||
height int16
|
||||
data unsafe.Pointer
|
||||
}
|
||||
|
||||
// NewImage creates a new image of the given size.
|
||||
func NewImage[T Color](width, height int) Image[T] {
|
||||
if width < 0 || height < 0 || int(int16(width)) != width || int(int16(height)) != height {
|
||||
// The width/height are stored as 16-bit integers and should never be
|
||||
// negative.
|
||||
panic("NewImage: width/height out of bounds")
|
||||
}
|
||||
var zeroColor T
|
||||
var data unsafe.Pointer
|
||||
switch {
|
||||
case zeroColor.BitsPerPixel()%8 == 0:
|
||||
// Typical formats like RGB888 and RGB565.
|
||||
// Each color starts at a whole byte offset from the start.
|
||||
buf := make([]T, width*height)
|
||||
data = unsafe.Pointer(&buf[0])
|
||||
default:
|
||||
// Formats like RGB444 that have 12 bits per pixel.
|
||||
// We access these as bytes, so allocate the buffer as a byte slice.
|
||||
bufBits := width * height * zeroColor.BitsPerPixel()
|
||||
bufBytes := (bufBits + 7) / 8
|
||||
buf := make([]byte, bufBytes)
|
||||
data = unsafe.Pointer(&buf[0])
|
||||
}
|
||||
return Image[T]{
|
||||
width: int16(width),
|
||||
height: int16(height),
|
||||
data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// NewImageFromBytes creates a new image of the given size using an existing data slice of bytes.
|
||||
func NewImageFromBytes[T Color](width, height int, buf []byte) Image[T] {
|
||||
if width < 0 || height < 0 || int(int16(width)) != width || int(int16(height)) != height {
|
||||
// The width/height are stored as 16-bit integers and should never be
|
||||
// negative.
|
||||
panic("NewImageFromBytes: width/height out of bounds")
|
||||
}
|
||||
var zeroColor T
|
||||
var data unsafe.Pointer
|
||||
switch {
|
||||
case zeroColor.BitsPerPixel()%8 == 0:
|
||||
// Typical formats like RGB888 and RGB565.
|
||||
// Each color starts at a whole byte offset from the start.
|
||||
if len(buf) != width*height*int(unsafe.Sizeof(zeroColor)) {
|
||||
panic("NewImageFromBytes: data slice size mismatch")
|
||||
}
|
||||
data = unsafe.Pointer(&buf[0])
|
||||
default:
|
||||
// Formats like RGB444 that have 12 bits per pixel.
|
||||
// We access these as bytes, so allocate the buffer as a byte slice.
|
||||
bufBits := width * height * zeroColor.BitsPerPixel()
|
||||
bufBytes := (bufBits + 7) / 8
|
||||
if len(buf) != bufBytes {
|
||||
panic("NewImageFromBytes: data slice size mismatch")
|
||||
}
|
||||
data = unsafe.Pointer(&buf[0])
|
||||
}
|
||||
return Image[T]{
|
||||
width: int16(width),
|
||||
height: int16(height),
|
||||
data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// NewImageFromImage creates a new image from the provided image.
|
||||
func NewImageFromImage[T Color](src image.Image) Image[T] {
|
||||
var (
|
||||
r = src.Bounds()
|
||||
width = r.Dx()
|
||||
height = r.Dy()
|
||||
dst = NewImage[T](width, height)
|
||||
)
|
||||
draw.Draw(dst, r, src, image.Point{}, draw.Src)
|
||||
return dst
|
||||
}
|
||||
|
||||
// Rescale returns a new Image buffer based on the img buffer.
|
||||
// The contents is undefined after the Rescale operation, and any modification
|
||||
// to the returned image will overwrite the underlying image buffer in undefined
|
||||
// ways. It will panic if width*height is larger than img.Len().
|
||||
func (img Image[T]) Rescale(width, height int) Image[T] {
|
||||
if width*height > img.Len() {
|
||||
panic("Image.Rescale size out of bounds")
|
||||
}
|
||||
return Image[T]{
|
||||
width: int16(width),
|
||||
height: int16(height),
|
||||
data: img.data,
|
||||
}
|
||||
}
|
||||
|
||||
// LimitHeight returns a subimage with the bottom part cut off, as specified by
|
||||
// height.
|
||||
func (img Image[T]) LimitHeight(height int) Image[T] {
|
||||
if height < 0 || height > int(img.height) {
|
||||
panic("Image.LimitHeight: out of bounds")
|
||||
}
|
||||
return Image[T]{
|
||||
width: img.width,
|
||||
height: int16(height),
|
||||
data: img.data,
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of pixels in this image buffer.
|
||||
func (img Image[T]) Len() int {
|
||||
return int(img.width) * int(img.height)
|
||||
}
|
||||
|
||||
// RawBuffer returns a byte slice that can be written directly to the screen
|
||||
// using DrawRGBBitmap8.
|
||||
func (img Image[T]) RawBuffer() []uint8 {
|
||||
var zeroColor T
|
||||
var numBytes int
|
||||
switch {
|
||||
case zeroColor.BitsPerPixel()%8 == 0:
|
||||
// Each color starts at a whole byte offset.
|
||||
numBytes = int(unsafe.Sizeof(zeroColor)) * int(img.width) * int(img.height)
|
||||
default:
|
||||
// Formats like RGB444 that aren't a whole number of bytes.
|
||||
numBits := zeroColor.BitsPerPixel() * int(img.width) * int(img.height)
|
||||
numBytes = (numBits + 7) / 8 // round up (see NewImage)
|
||||
}
|
||||
return unsafe.Slice((*byte)(img.data), numBytes)
|
||||
}
|
||||
|
||||
// Size returns the image size.
|
||||
func (img Image[T]) Size() (int, int) {
|
||||
return int(img.width), int(img.height)
|
||||
}
|
||||
|
||||
func (img Image[T]) setPixel(index int, c T) {
|
||||
var zeroColor T
|
||||
|
||||
switch {
|
||||
case zeroColor.BitsPerPixel() == 1:
|
||||
// Monochrome.
|
||||
offset := index / 8
|
||||
bits := index % 8
|
||||
|
||||
ptr := (*byte)(unsafe.Add(img.data, offset))
|
||||
if c != zeroColor {
|
||||
*((*byte)(ptr)) |= (1 << (7 - uint8(bits)))
|
||||
} else {
|
||||
*((*byte)(ptr)) &^= (1 << (7 - uint8(bits)))
|
||||
}
|
||||
|
||||
return
|
||||
case zeroColor.BitsPerPixel()%8 == 0:
|
||||
// Each color starts at a whole byte offset.
|
||||
// This is the easy case.
|
||||
offset := index * int(unsafe.Sizeof(zeroColor))
|
||||
ptr := unsafe.Add(img.data, offset)
|
||||
*((*T)(ptr)) = c
|
||||
return
|
||||
}
|
||||
|
||||
if c, ok := any(c).(RGB444BE); ok {
|
||||
// Special case for RGB444.
|
||||
bitIndex := index * zeroColor.BitsPerPixel()
|
||||
if bitIndex%8 == 0 {
|
||||
byteOffset := bitIndex / 8
|
||||
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||
ptr[0] = uint8(c >> 4)
|
||||
ptr[1] = ptr[1]&0x0f | uint8(c)<<4 // change top bits
|
||||
} else {
|
||||
byteOffset := bitIndex / 8
|
||||
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||
ptr[0] = ptr[0]&0xf0 | uint8(c>>8) // change bottom bits
|
||||
ptr[1] = uint8(c)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: the code for RGB444 should be generalized to support any bit size.
|
||||
panic("todo: setPixel for odd bits per pixel")
|
||||
}
|
||||
|
||||
// Set sets the pixel at x, y to the given color.
|
||||
// Use FillSolidColor to efficiently fill the entire image buffer.
|
||||
func (img Image[T]) SetPixel(x, y int, c T) {
|
||||
if uint(x) >= uint(int(img.width)) || uint(y) >= uint(int(img.height)) {
|
||||
return
|
||||
}
|
||||
index := y*int(img.width) + x
|
||||
img.setPixel(index, c)
|
||||
}
|
||||
|
||||
// Get returns the color at the given index.
|
||||
func (img Image[T]) GetPixel(x, y int) T {
|
||||
var zeroColor T
|
||||
if uint(x) >= uint(int(img.width)) || uint(y) >= uint(int(img.height)) {
|
||||
return zeroColor
|
||||
}
|
||||
index := y*int(img.width) + x // index into img.data
|
||||
|
||||
switch {
|
||||
case zeroColor.BitsPerPixel() == 1:
|
||||
// Monochrome.
|
||||
var c Monochrome
|
||||
offset := index / 8
|
||||
bits := index % 8
|
||||
ptr := (*byte)(unsafe.Add(img.data, offset))
|
||||
c = Monochrome((*ptr >> (7 - uint8(bits))) & 0x1)
|
||||
return any(c).(T)
|
||||
case zeroColor.BitsPerPixel()%8 == 0:
|
||||
// Colors like RGB565, RGB888, etc.
|
||||
offset := index * int(unsafe.Sizeof(zeroColor))
|
||||
ptr := unsafe.Add(img.data, offset)
|
||||
return *((*T)(ptr))
|
||||
}
|
||||
|
||||
if _, ok := any(zeroColor).(RGB444BE); ok {
|
||||
// Special case for RGB444 that isn't stored in a neat byte multiple.
|
||||
bitIndex := index * zeroColor.BitsPerPixel()
|
||||
var c RGB444BE
|
||||
if bitIndex%8 == 0 {
|
||||
byteOffset := bitIndex / 8
|
||||
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||
c |= RGB444BE(ptr[0]) << 4
|
||||
c |= RGB444BE(ptr[1] >> 4) // load top bits
|
||||
} else {
|
||||
byteOffset := bitIndex / 8
|
||||
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
|
||||
c |= RGB444BE(ptr[0]&0x0f) << 8 // load bottom bits
|
||||
c |= RGB444BE(ptr[1])
|
||||
}
|
||||
return any(c).(T)
|
||||
}
|
||||
|
||||
// TODO: generalize the above code.
|
||||
panic("todo: Image.Get for odd bits per pixel")
|
||||
}
|
||||
|
||||
// FillSolidColor fills the entire image with the given color.
|
||||
// This may be faster than setting individual pixels.
|
||||
func (img Image[T]) FillSolidColor(color T) {
|
||||
var zeroColor T
|
||||
|
||||
switch {
|
||||
case zeroColor.BitsPerPixel() == 1:
|
||||
// Monochrome.
|
||||
var colorByte uint8
|
||||
if color != zeroColor {
|
||||
colorByte = 0xff
|
||||
}
|
||||
numBytes := int(img.width) * int(img.height) / 8
|
||||
for i := 0; i < numBytes; i++ {
|
||||
// TODO: this can be optimized a lot.
|
||||
// - The store can be done as a 32-bit integer, after checking for
|
||||
// alignment.
|
||||
// - Perhaps the loop can be unrolled to improve copy performance.
|
||||
ptr := (*byte)(unsafe.Add(img.data, i))
|
||||
*((*byte)(ptr)) = colorByte
|
||||
}
|
||||
return
|
||||
|
||||
case zeroColor.BitsPerPixel()%8 == 0:
|
||||
// Fast pass for colors of 8, 16, 24, etc bytes in size.
|
||||
ptr := img.data
|
||||
for i := 0; i < img.Len(); i++ {
|
||||
// TODO: this can be optimized a lot.
|
||||
// - The store can be done as a 32-bit integer, after checking for
|
||||
// alignment.
|
||||
// - Perhaps the loop can be unrolled to improve copy performance.
|
||||
*(*T)(ptr) = color
|
||||
ptr = unsafe.Add(ptr, unsafe.Sizeof(zeroColor))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Special case for RGB444.
|
||||
if c, ok := any(color).(RGB444BE); ok {
|
||||
// RGB444 can be stored in a more optimized way, by storing two colors
|
||||
// at a time instead of setting each color individually. This avoids
|
||||
// loading and masking the old color bits for the half-bytes.
|
||||
var buf [3]uint8
|
||||
buf[0] = uint8(c >> 4)
|
||||
buf[1] = uint8(c)<<4 | uint8(c>>8)
|
||||
buf[2] = uint8(c)
|
||||
rawBuf := unsafe.Slice((*[3]byte)(img.data), img.Len()/2)
|
||||
for i := 0; i < len(rawBuf); i++ {
|
||||
rawBuf[i] = buf
|
||||
}
|
||||
if img.Len()%2 != 0 {
|
||||
// The image contains an uneven number of pixels.
|
||||
// This is uncommon, but it can happen and we have to handle it.
|
||||
img.setPixel(img.Len()-1, color)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Fallback for other color formats.
|
||||
for i := 0; i < img.Len(); i++ {
|
||||
img.setPixel(i, color)
|
||||
}
|
||||
}
|
||||
|
||||
// At implements the draw.Image interface.
|
||||
func (img Image[T]) At(x, y int) color.Color {
|
||||
return img.GetPixel(x, y)
|
||||
}
|
||||
|
||||
// Set implements the draw.Image interface.
|
||||
func (img Image[T]) Set(x, y int, c color.Color) {
|
||||
var value T
|
||||
switch any(value).(type) {
|
||||
case RGB888:
|
||||
img.SetPixel(x, y, rgb888Model(c).(T))
|
||||
case RGB565BE:
|
||||
img.SetPixel(x, y, rgb565BEModel(c).(T))
|
||||
case RGB555:
|
||||
img.SetPixel(x, y, rgb555Model(c).(T))
|
||||
case RGB444BE:
|
||||
img.SetPixel(x, y, rgb444BEModel(c).(T))
|
||||
case Monochrome:
|
||||
img.SetPixel(x, y, monochromeModel(c).(T))
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// Bounds returns the image bounding box.
|
||||
func (img Image[T]) Bounds() image.Rectangle {
|
||||
return image.Rect(0, 0, int(img.width), int(img.height))
|
||||
}
|
||||
|
||||
// ColorModel returns the image color model.
|
||||
func (img Image[T]) ColorModel() color.Model {
|
||||
// Ugly cast from color.RGBA to T. The type switch and interface casts are
|
||||
// trivially optimized away after instantiation.
|
||||
var value T
|
||||
switch any(value).(type) {
|
||||
case RGB888:
|
||||
return RGB888Model
|
||||
case RGB565BE:
|
||||
return RGB565BEModel
|
||||
case RGB555:
|
||||
return RGB555Model
|
||||
case RGB444BE:
|
||||
return RGB444BEModel
|
||||
case Monochrome:
|
||||
return MonochromeModel
|
||||
default:
|
||||
panic("unknown color format")
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the image buffer.
|
||||
func (img *Image[T]) Clear() {
|
||||
var zeroColor T
|
||||
img.FillSolidColor(zeroColor)
|
||||
}
|
||||
|
||||
var _ draw.Image = (*Image[RGB888])(nil)
|
||||
@@ -0,0 +1,55 @@
|
||||
package pixel
|
||||
|
||||
import "image/color"
|
||||
|
||||
var (
|
||||
RGB888Model color.Model = color.ModelFunc(rgb888Model)
|
||||
RGB565BEModel color.Model = color.ModelFunc(rgb565BEModel)
|
||||
RGB555Model color.Model = color.ModelFunc(rgb555Model)
|
||||
RGB444BEModel color.Model = color.ModelFunc(rgb444BEModel)
|
||||
MonochromeModel color.Model = color.ModelFunc(monochromeModel)
|
||||
)
|
||||
|
||||
func rgb888Model(c color.Color) color.Color {
|
||||
if _, ok := c.(RGB888); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA()
|
||||
return RGB888{
|
||||
R: uint8(r >> 8),
|
||||
G: uint8(g >> 8),
|
||||
B: uint8(b >> 8),
|
||||
}
|
||||
}
|
||||
|
||||
func rgb565BEModel(c color.Color) color.Color {
|
||||
if _, ok := c.(RGB565BE); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA()
|
||||
return RGB565BE(uint16((r>>8)&0xF8)<<8 + uint16((g>>8)&0xFC)<<3 + uint16((b>>8)&0xF8)>>3)
|
||||
}
|
||||
|
||||
func rgb555Model(c color.Color) color.Color {
|
||||
if _, ok := c.(RGB555); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA()
|
||||
return RGB555(r>>11) | RGB555(g>>11)<<5 | RGB555(b>>11)<<10
|
||||
}
|
||||
|
||||
func rgb444BEModel(c color.Color) color.Color {
|
||||
if _, ok := c.(RGB444BE); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA()
|
||||
return RGB444BE(r>>12)<<8 | RGB444BE(g>>12)<<4 | RGB444BE(b>>12)
|
||||
}
|
||||
|
||||
func monochromeModel(c color.Color) color.Color {
|
||||
if _, ok := c.(Monochrome); ok {
|
||||
return c
|
||||
}
|
||||
r, g, b, _ := c.RGBA()
|
||||
return NewMonochrome(uint8(r>>8), uint8(g>>8), uint8(b>>8))
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Copyright (C) 2007-2008 Jean-Marc Valin
|
||||
// Copyright (C) 2008 Thorvald Natvig
|
||||
// Copyright (C) 2013 Oov
|
||||
//
|
||||
// Arbitrary resampling code
|
||||
//
|
||||
// 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. The name of the author may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
|
||||
|
||||
package resample
|
||||
|
||||
type kaiserTable struct {
|
||||
table []float64
|
||||
oversample int
|
||||
}
|
||||
|
||||
type quality struct {
|
||||
baseLength int
|
||||
oversample int
|
||||
downsampleBandwidth float64
|
||||
upsampleBandwidth float64
|
||||
table *kaiserTable
|
||||
}
|
||||
|
||||
var (
|
||||
kaiser12 = kaiserTable{
|
||||
table: []float64{
|
||||
0.99859849, 1.00000000, 0.99859849, 0.99440475, 0.98745105, 0.97779076,
|
||||
0.96549770, 0.95066529, 0.93340547, 0.91384741, 0.89213598, 0.86843014,
|
||||
0.84290116, 0.81573067, 0.78710866, 0.75723148, 0.72629970, 0.69451601,
|
||||
0.66208321, 0.62920216, 0.59606986, 0.56287762, 0.52980938, 0.49704014,
|
||||
0.46473455, 0.43304576, 0.40211431, 0.37206735, 0.34301800, 0.31506490,
|
||||
0.28829195, 0.26276832, 0.23854851, 0.21567274, 0.19416736, 0.17404546,
|
||||
0.15530766, 0.13794294, 0.12192957, 0.10723616, 0.09382272, 0.08164178,
|
||||
0.07063950, 0.06075685, 0.05193064, 0.04409466, 0.03718069, 0.03111947,
|
||||
0.02584161, 0.02127838, 0.01736250, 0.01402878, 0.01121463, 0.00886058,
|
||||
0.00691064, 0.00531256, 0.00401805, 0.00298291, 0.00216702, 0.00153438,
|
||||
0.00105297, 0.00069463, 0.00043489, 0.00025272, 0.00013031, 0.0000527734,
|
||||
0.00001000, 0.00000000},
|
||||
oversample: 64,
|
||||
}
|
||||
|
||||
kaiser10 = kaiserTable{
|
||||
table: []float64{
|
||||
0.99537781, 1.00000000, 0.99537781, 0.98162644, 0.95908712, 0.92831446,
|
||||
0.89005583, 0.84522401, 0.79486424, 0.74011713, 0.68217934, 0.62226347,
|
||||
0.56155915, 0.50119680, 0.44221549, 0.38553619, 0.33194107, 0.28205962,
|
||||
0.23636152, 0.19515633, 0.15859932, 0.12670280, 0.09935205, 0.07632451,
|
||||
0.05731132, 0.04193980, 0.02979584, 0.02044510, 0.01345224, 0.00839739,
|
||||
0.00488951, 0.00257636, 0.00115101, 0.00035515, 0.00000000, 0.00000000},
|
||||
oversample: 32,
|
||||
}
|
||||
|
||||
kaiser8 = kaiserTable{
|
||||
table: []float64{
|
||||
0.99635258, 1.00000000, 0.99635258, 0.98548012, 0.96759014, 0.94302200,
|
||||
0.91223751, 0.87580811, 0.83439927, 0.78875245, 0.73966538, 0.68797126,
|
||||
0.63451750, 0.58014482, 0.52566725, 0.47185369, 0.41941150, 0.36897272,
|
||||
0.32108304, 0.27619388, 0.23465776, 0.19672670, 0.16255380, 0.13219758,
|
||||
0.10562887, 0.08273982, 0.06335451, 0.04724088, 0.03412321, 0.02369490,
|
||||
0.01563093, 0.00959968, 0.00527363, 0.00233883, 0.00050000, 0.00000000},
|
||||
oversample: 32,
|
||||
}
|
||||
|
||||
kaiser6 = kaiserTable{
|
||||
table: []float64{
|
||||
0.99733006, 1.00000000, 0.99733006, 0.98935595, 0.97618418, 0.95799003,
|
||||
0.93501423, 0.90755855, 0.87598009, 0.84068475, 0.80211977, 0.76076565,
|
||||
0.71712752, 0.67172623, 0.62508937, 0.57774224, 0.53019925, 0.48295561,
|
||||
0.43647969, 0.39120616, 0.34752997, 0.30580127, 0.26632152, 0.22934058,
|
||||
0.19505503, 0.16360756, 0.13508755, 0.10953262, 0.08693120, 0.06722600,
|
||||
0.05031820, 0.03607231, 0.02432151, 0.01487334, 0.00752000, 0.00000000},
|
||||
oversample: 32,
|
||||
}
|
||||
|
||||
qualityMap = []quality{
|
||||
// Q0
|
||||
quality{
|
||||
baseLength: 8,
|
||||
oversample: 4,
|
||||
downsampleBandwidth: 0.830,
|
||||
upsampleBandwidth: 0.860,
|
||||
table: &kaiser6,
|
||||
},
|
||||
// Q1
|
||||
quality{
|
||||
baseLength: 16,
|
||||
oversample: 4,
|
||||
downsampleBandwidth: 0.850,
|
||||
upsampleBandwidth: 0.880,
|
||||
table: &kaiser6,
|
||||
},
|
||||
// Q2
|
||||
quality{
|
||||
baseLength: 32,
|
||||
oversample: 4,
|
||||
downsampleBandwidth: 0.882,
|
||||
upsampleBandwidth: 0.910,
|
||||
table: &kaiser6,
|
||||
},
|
||||
// Q3
|
||||
quality{
|
||||
baseLength: 48,
|
||||
oversample: 8,
|
||||
downsampleBandwidth: 0.895,
|
||||
upsampleBandwidth: 0.917,
|
||||
table: &kaiser8,
|
||||
},
|
||||
// Q4
|
||||
quality{
|
||||
baseLength: 64,
|
||||
oversample: 8,
|
||||
downsampleBandwidth: 0.921,
|
||||
upsampleBandwidth: 0.940,
|
||||
table: &kaiser8,
|
||||
},
|
||||
// Q5
|
||||
quality{
|
||||
baseLength: 80,
|
||||
oversample: 16,
|
||||
downsampleBandwidth: 0.922,
|
||||
upsampleBandwidth: 0.940,
|
||||
table: &kaiser10,
|
||||
},
|
||||
// Q6
|
||||
quality{
|
||||
baseLength: 96,
|
||||
oversample: 16,
|
||||
downsampleBandwidth: 0.940,
|
||||
upsampleBandwidth: 0.945,
|
||||
table: &kaiser10,
|
||||
},
|
||||
// Q7
|
||||
quality{
|
||||
baseLength: 128,
|
||||
oversample: 16,
|
||||
downsampleBandwidth: 0.950,
|
||||
upsampleBandwidth: 0.950,
|
||||
table: &kaiser10,
|
||||
},
|
||||
// Q8
|
||||
quality{
|
||||
baseLength: 160,
|
||||
oversample: 16,
|
||||
downsampleBandwidth: 0.960,
|
||||
upsampleBandwidth: 0.960,
|
||||
table: &kaiser10,
|
||||
},
|
||||
// Q9
|
||||
quality{
|
||||
baseLength: 192,
|
||||
oversample: 32,
|
||||
downsampleBandwidth: 0.968,
|
||||
upsampleBandwidth: 0.968,
|
||||
table: &kaiser12,
|
||||
},
|
||||
// Q10
|
||||
quality{
|
||||
baseLength: 256,
|
||||
oversample: 32,
|
||||
downsampleBandwidth: 0.975,
|
||||
upsampleBandwidth: 0.975,
|
||||
table: &kaiser12,
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,544 @@
|
||||
// Copyright (C) 2007-2008 Jean-Marc Valin
|
||||
// Copyright (C) 2008 Thorvald Natvig
|
||||
// Copyright (C) 2013 Oov
|
||||
//
|
||||
// Arbitrary resampling code
|
||||
//
|
||||
// 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. The name of the author may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
|
||||
|
||||
// Package resampler implements audio resampler.
|
||||
//
|
||||
// This is a port of the Opus-tools( http://git.xiph.org/?p=opus-tools.git ) audio resampler to the pure Go.
|
||||
package resample
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
const bufferSize = 160
|
||||
|
||||
type channelState struct {
|
||||
lastSample int
|
||||
sampFracNum int
|
||||
magicSamples int
|
||||
mem []float64
|
||||
}
|
||||
|
||||
type Resampler struct {
|
||||
numRate int
|
||||
denRate int
|
||||
|
||||
quality *quality
|
||||
filtLen int
|
||||
intAdvance int
|
||||
fracAdvance int
|
||||
cutoff float64
|
||||
oversample int
|
||||
|
||||
initialised bool
|
||||
started bool
|
||||
skipZeros bool
|
||||
|
||||
channels []channelState
|
||||
sincTable []float64
|
||||
resampler func(channelIndex int, in []float64, out []float64) int
|
||||
}
|
||||
|
||||
func Resample64(in []float64, inSampleRate int, out []float64, outSampleRate int, quality int) (read int, written int) {
|
||||
return NewWithSkipZeros(1, inSampleRate, outSampleRate, quality).ProcessFloat64(0, in, out)
|
||||
}
|
||||
|
||||
func Resample32(in []float32, inSampleRate int, out []float32, outSampleRate int, quality int) (read int, written int) {
|
||||
return NewWithSkipZeros(1, inSampleRate, outSampleRate, quality).ProcessFloat32(0, in, out)
|
||||
}
|
||||
|
||||
func New(channels int, inSampleRate, outSampleRate int, quality int) *Resampler {
|
||||
if channels < 1 {
|
||||
panic("you must have at least one channel")
|
||||
}
|
||||
r := &Resampler{
|
||||
cutoff: 1.0,
|
||||
channels: make([]channelState, channels),
|
||||
}
|
||||
|
||||
r.setQuality(quality)
|
||||
r.setSampleRate(inSampleRate, outSampleRate)
|
||||
r.updateFilter()
|
||||
r.initialised = true
|
||||
return r
|
||||
}
|
||||
|
||||
func NewWithSkipZeros(channels int, inSampleRate, outSampleRate int, quality int) *Resampler {
|
||||
r := New(channels, inSampleRate, outSampleRate, quality)
|
||||
r.skipZeros = true
|
||||
return r
|
||||
}
|
||||
|
||||
// cannot change quality on running in now implementation.
|
||||
func (r *Resampler) setQuality(q int) {
|
||||
if q < 0 || q > 10 {
|
||||
panic("invalid quality value")
|
||||
}
|
||||
|
||||
if r.quality == &qualityMap[q] {
|
||||
return
|
||||
}
|
||||
r.quality = &qualityMap[q]
|
||||
if r.initialised {
|
||||
r.updateFilter()
|
||||
}
|
||||
}
|
||||
|
||||
func imin(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
} else {
|
||||
return b
|
||||
}
|
||||
}
|
||||
|
||||
// cannot change sample on running in now implementation.
|
||||
func (r *Resampler) setSampleRate(in int, out int) {
|
||||
ratioNum := in
|
||||
ratioDen := out
|
||||
|
||||
// FIXME: This is terribly inefficient, but who cares (at least for now)?
|
||||
for fact := 2; fact <= imin(ratioNum, ratioDen); fact++ {
|
||||
for (ratioNum%fact == 0) && (ratioDen%fact == 0) {
|
||||
ratioNum /= fact
|
||||
ratioDen /= fact
|
||||
}
|
||||
}
|
||||
|
||||
if r.numRate == ratioNum && r.denRate == ratioDen {
|
||||
return
|
||||
}
|
||||
|
||||
if r.denRate > 0 {
|
||||
for i := range r.channels {
|
||||
ch := &r.channels[i]
|
||||
ch.sampFracNum = ch.sampFracNum * ratioDen / r.denRate
|
||||
// Safety net
|
||||
if ch.sampFracNum >= ratioDen {
|
||||
ch.sampFracNum = ratioDen - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r.numRate = ratioNum
|
||||
r.denRate = ratioDen
|
||||
|
||||
if r.initialised {
|
||||
r.updateFilter()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Resampler) ProcessFloat64(channelIndex int, in []float64, out []float64) (read int, written int) {
|
||||
if r.skipZeros {
|
||||
for i := range r.channels {
|
||||
r.channels[i].lastSample = r.InputLatency()
|
||||
}
|
||||
r.skipZeros = false
|
||||
}
|
||||
|
||||
ch := &r.channels[channelIndex]
|
||||
x := ch.mem
|
||||
filtOffs := r.filtLen - 1
|
||||
iLen, oLen, xLen := len(in), len(out), len(x)-filtOffs
|
||||
read, written = iLen, oLen
|
||||
|
||||
if ch.magicSamples != 0 {
|
||||
oLen -= r.magic(channelIndex, out)
|
||||
}
|
||||
|
||||
if ch.magicSamples == 0 {
|
||||
for iLen != 0 && oLen != 0 {
|
||||
ichunk, ochunk := imin(xLen, iLen), 0
|
||||
if in != nil {
|
||||
copy(x[filtOffs:], in[:ichunk])
|
||||
} else {
|
||||
for j := filtOffs; j < ichunk+filtOffs; j++ {
|
||||
x[j] = 0
|
||||
}
|
||||
}
|
||||
ichunk, ochunk = r.processNative(channelIndex, ichunk, out)
|
||||
iLen -= ichunk
|
||||
oLen -= ochunk
|
||||
out = out[ochunk:]
|
||||
if in != nil {
|
||||
in = in[ichunk:]
|
||||
}
|
||||
}
|
||||
}
|
||||
read -= iLen
|
||||
written -= oLen
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resampler) ProcessFloat32(channelIndex int, in []float32, out []float32) (read int, written int) {
|
||||
const stackSize = 1024
|
||||
var stack [stackSize]float64
|
||||
|
||||
if r.skipZeros {
|
||||
for i := range r.channels {
|
||||
r.channels[i].lastSample = r.InputLatency()
|
||||
}
|
||||
r.skipZeros = false
|
||||
}
|
||||
|
||||
ch := &r.channels[channelIndex]
|
||||
x := ch.mem
|
||||
filtOffs := r.filtLen - 1
|
||||
iLen, oLen := len(in), len(out)
|
||||
xLen, yLen := len(x)-filtOffs, stackSize
|
||||
read, written = iLen, oLen
|
||||
|
||||
if ch.magicSamples != 0 {
|
||||
m := r.magic(channelIndex, stack[:imin(yLen, oLen)])
|
||||
oLen -= m
|
||||
for i, s := range stack[:m] {
|
||||
out[i] = float32(s)
|
||||
}
|
||||
out = out[m:]
|
||||
}
|
||||
|
||||
if ch.magicSamples == 0 {
|
||||
for iLen != 0 && oLen != 0 {
|
||||
ichunk, ochunk := imin(xLen, iLen), imin(yLen, oLen)
|
||||
if in != nil {
|
||||
for i, s := range in[:ichunk] {
|
||||
x[filtOffs+i] = float64(s)
|
||||
}
|
||||
} else {
|
||||
for j := filtOffs; j < ichunk+filtOffs; j++ {
|
||||
x[j] = 0
|
||||
}
|
||||
}
|
||||
ichunk, ochunk = r.processNative(channelIndex, ichunk, stack[:ochunk])
|
||||
iLen -= ichunk
|
||||
oLen -= ochunk
|
||||
for i, s := range stack[:ochunk] {
|
||||
out[i] = float32(s)
|
||||
}
|
||||
out = out[ochunk:]
|
||||
if in != nil {
|
||||
in = in[ichunk:]
|
||||
}
|
||||
}
|
||||
}
|
||||
read -= iLen
|
||||
written -= oLen
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resampler) processNative(channelIndex int, inLen int, out []float64) (inLenRet int, outLenRet int) {
|
||||
ch := &r.channels[channelIndex]
|
||||
r.started = true
|
||||
|
||||
outLenRet = r.resampler(channelIndex, ch.mem[:inLen], out)
|
||||
if ch.lastSample < inLen {
|
||||
inLenRet = ch.lastSample
|
||||
} else {
|
||||
inLenRet = inLen
|
||||
}
|
||||
ch.lastSample -= inLenRet
|
||||
copy(ch.mem, ch.mem[inLenRet:inLenRet+r.filtLen-1])
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resampler) magic(channelIndex int, out []float64) (outWritten int) {
|
||||
ch := &r.channels[channelIndex]
|
||||
n := r.filtLen - 1
|
||||
|
||||
inLen, outLen := r.processNative(channelIndex, ch.magicSamples, out)
|
||||
|
||||
ch.magicSamples -= inLen
|
||||
|
||||
// If we couldn't process all "magic" input samples, save the rest for next time
|
||||
if ch.magicSamples != 0 {
|
||||
copy(ch.mem[n:n+ch.magicSamples], ch.mem[n+inLen:])
|
||||
}
|
||||
return outLen
|
||||
}
|
||||
|
||||
func computeFunc(x float64, windowFunc *kaiserTable) float64 {
|
||||
y := x * float64(windowFunc.oversample)
|
||||
ind := int(math.Floor(y))
|
||||
frac := y - float64(ind)
|
||||
fracx2 := frac * frac
|
||||
fracx3 := fracx2 * frac
|
||||
fracx2mul0_5 := 0.5 * fracx2
|
||||
fracx3mul0_16 := 0.1666666667 * fracx3
|
||||
// Compute interpolation coefficients. I'm not sure whether this corresponds to cubic interpolation but I know it's MMSE-optimal on a sinc
|
||||
i3 := -0.1666666667*frac + fracx3mul0_16
|
||||
i2 := frac + fracx2mul0_5 - 0.5*fracx3
|
||||
// interp[2] = 1.f - 0.5f*frac - frac*frac + 0.5f*frac*frac*frac;
|
||||
i0 := -0.3333333333*frac + fracx2mul0_5 - fracx3mul0_16
|
||||
// Just to make sure we don't have rounding problems
|
||||
i1 := 1.0 - i3 - i2 - i0
|
||||
return i0*windowFunc.table[ind] + i1*windowFunc.table[ind+1] + i2*windowFunc.table[ind+2] + i3*windowFunc.table[ind+3]
|
||||
}
|
||||
|
||||
// The slow way of computing a sinc for the table. Should improve that some day
|
||||
func sinc(cutoff float64, x float64, n float64, windowFunc *kaiserTable) float64 {
|
||||
xabs := math.Abs(x)
|
||||
if xabs < 1e-6 {
|
||||
return cutoff
|
||||
} else if xabs > 0.5*n {
|
||||
return 0
|
||||
}
|
||||
// FIXME: Can it really be any slower than this?
|
||||
xx := x * cutoff * math.Pi
|
||||
return cutoff * math.Sin(xx) / xx * computeFunc(2.0*xabs/n, windowFunc)
|
||||
}
|
||||
|
||||
func (r *Resampler) resamplerBasicDirect(channelIndex int, in []float64, out []float64) int {
|
||||
ch := &r.channels[channelIndex]
|
||||
n := r.filtLen
|
||||
outSample := 0
|
||||
lastSample := ch.lastSample
|
||||
sampFracNum := ch.sampFracNum
|
||||
sincTable := r.sincTable
|
||||
intAdvance := r.intAdvance
|
||||
fracAdvance := r.fracAdvance
|
||||
denRate := r.denRate
|
||||
|
||||
for lastSample < len(in) && outSample < len(out) {
|
||||
sinct := sincTable[sampFracNum*n : sampFracNum*n+n]
|
||||
var sum float64
|
||||
for j, s := range in[lastSample : lastSample+n] {
|
||||
sum += sinct[j] * s
|
||||
}
|
||||
|
||||
out[outSample] = sum
|
||||
outSample++
|
||||
lastSample += intAdvance
|
||||
sampFracNum += fracAdvance
|
||||
if sampFracNum >= denRate {
|
||||
sampFracNum -= denRate
|
||||
lastSample++
|
||||
}
|
||||
}
|
||||
ch.lastSample = lastSample
|
||||
ch.sampFracNum = sampFracNum
|
||||
return outSample
|
||||
}
|
||||
|
||||
func cubicCoef(frac float64) (float64, float64, float64, float64) {
|
||||
fracx2 := frac * frac
|
||||
fracx3 := fracx2 * frac
|
||||
fracx2mul0_5 := 0.5 * fracx2
|
||||
fracx3mul0_16 := 0.1666666667 * fracx3
|
||||
// Compute interpolation coefficients. I'm not sure whether this corresponds to cubic interpolation but I know it's MMSE-optimal on a sinc
|
||||
i0 := -0.1666666667*frac + fracx3mul0_16
|
||||
i1 := frac + fracx2mul0_5 - 0.5*fracx3
|
||||
// interp[2] = 1.f - 0.5f*frac - frac*frac + 0.5f*frac*frac*frac;
|
||||
i3 := -0.3333333333*frac + fracx2mul0_5 - fracx3mul0_16
|
||||
// Just to make sure we don't have rounding problems
|
||||
i2 := 1.0 - i0 - i1 - i3
|
||||
return i0, i1, i2, i3
|
||||
}
|
||||
|
||||
func (r *Resampler) resamplerBasicInterpolate(channelIndex int, in []float64, out []float64) int {
|
||||
ch := &r.channels[channelIndex]
|
||||
n := r.filtLen
|
||||
outSample := 0
|
||||
lastSample := ch.lastSample
|
||||
sampFracNum := ch.sampFracNum
|
||||
intAdvance := r.intAdvance
|
||||
fracAdvance := r.fracAdvance
|
||||
denRate := r.denRate
|
||||
|
||||
for lastSample < len(in) && outSample < len(out) {
|
||||
offset := sampFracNum * r.oversample / r.denRate
|
||||
frac := float64((sampFracNum*r.oversample)%r.denRate) / float64(r.denRate)
|
||||
var accum0, accum1, accum2, accum3 float64
|
||||
for j, s := range in[lastSample : lastSample+n] {
|
||||
t := 4 + (j+1)*r.oversample - offset
|
||||
accum0 += s * r.sincTable[t-2]
|
||||
accum1 += s * r.sincTable[t-1]
|
||||
accum2 += s * r.sincTable[t]
|
||||
accum3 += s * r.sincTable[t+1]
|
||||
}
|
||||
i0, i1, i2, i3 := cubicCoef(frac)
|
||||
out[outSample] = i0*accum0 + i1*accum1 + i2*accum2 + i3*accum3
|
||||
outSample++
|
||||
lastSample += intAdvance
|
||||
sampFracNum += fracAdvance
|
||||
if sampFracNum >= denRate {
|
||||
sampFracNum -= denRate
|
||||
lastSample++
|
||||
}
|
||||
}
|
||||
ch.lastSample = lastSample
|
||||
ch.sampFracNum = sampFracNum
|
||||
return outSample
|
||||
}
|
||||
|
||||
func (r *Resampler) updateFilter() {
|
||||
oldLength := r.filtLen
|
||||
r.oversample = r.quality.oversample
|
||||
r.filtLen = r.quality.baseLength
|
||||
|
||||
if r.numRate > r.denRate {
|
||||
// down-sampling
|
||||
r.cutoff = r.quality.downsampleBandwidth * float64(r.denRate) / float64(r.numRate)
|
||||
// FIXME: divide the numerator and denominator by a certain amount if they're too large
|
||||
r.filtLen = r.filtLen * r.numRate / r.denRate
|
||||
// Round up to make sure we have a multiple of 8
|
||||
r.filtLen = ((r.filtLen - 1) & (^int(0x7))) + 8
|
||||
if r.denRate<<1 < r.numRate {
|
||||
r.oversample >>= 1
|
||||
}
|
||||
if r.denRate<<2 < r.numRate {
|
||||
r.oversample >>= 1
|
||||
}
|
||||
if r.denRate<<3 < r.numRate {
|
||||
r.oversample >>= 1
|
||||
}
|
||||
if r.denRate<<4 < r.numRate {
|
||||
r.oversample >>= 1
|
||||
}
|
||||
if r.oversample < 1 {
|
||||
r.oversample = 1
|
||||
}
|
||||
} else {
|
||||
// up-sampling
|
||||
r.cutoff = r.quality.upsampleBandwidth
|
||||
}
|
||||
|
||||
// Choose the resampling type that requires the least amount of memory
|
||||
if r.denRate <= 16*(r.oversample+8) {
|
||||
if r.sincTable == nil || len(r.sincTable) < r.filtLen*r.denRate {
|
||||
r.sincTable = make([]float64, r.filtLen*r.denRate)
|
||||
}
|
||||
for i := 0; i < r.denRate; i++ {
|
||||
for j := 0; j < r.filtLen; j++ {
|
||||
r.sincTable[i*r.filtLen+j] = sinc(
|
||||
r.cutoff,
|
||||
float64(j-(r.filtLen>>1)+1)-float64(i)/float64(r.denRate),
|
||||
float64(r.filtLen),
|
||||
r.quality.table,
|
||||
)
|
||||
}
|
||||
}
|
||||
r.resampler = r.resamplerBasicDirect
|
||||
} else {
|
||||
if r.sincTable == nil || len(r.sincTable) < r.filtLen*r.oversample+8 {
|
||||
r.sincTable = make([]float64, r.filtLen*r.oversample+8)
|
||||
}
|
||||
for i := -4; i < r.oversample*r.filtLen+4; i++ {
|
||||
r.sincTable[i+4] = sinc(
|
||||
r.cutoff,
|
||||
float64(i)/float64(r.oversample)-float64(r.filtLen>>1),
|
||||
float64(r.filtLen),
|
||||
r.quality.table,
|
||||
)
|
||||
}
|
||||
r.resampler = r.resamplerBasicInterpolate
|
||||
}
|
||||
|
||||
r.intAdvance = r.numRate / r.denRate
|
||||
r.fracAdvance = r.numRate % r.denRate
|
||||
|
||||
// Here's the place where we update the filter memory to take into account
|
||||
// the change in filter length. It's probably the messiest part of the code
|
||||
// due to handling of lots of corner cases.
|
||||
switch {
|
||||
case r.channels[0].mem == nil || !r.started:
|
||||
size := r.filtLen - 1 + bufferSize
|
||||
for i := range r.channels {
|
||||
r.channels[i].mem = make([]float64, size)
|
||||
}
|
||||
case r.filtLen > oldLength:
|
||||
panic("not implemented")
|
||||
// Increase the filter length
|
||||
// oldAllocSize := len(r.mem) / len(r.channels)
|
||||
// if r.filtLen-1+r.bufferSize > oldAllocSize {
|
||||
// m := make([]float64, (r.filtLen-1+r.bufferSize)*len(r.channels))
|
||||
// copy(m, r.mem)
|
||||
// r.mem = m
|
||||
// }
|
||||
for i := len(r.channels) - 1; i >= 0; i-- {
|
||||
// spx_int32_t j;
|
||||
// spx_uint32_t olen = old_length;
|
||||
// /*if (st->magic_samples[i])*/
|
||||
// {
|
||||
// /* Try and remove the magic samples as if nothing had happened */
|
||||
//
|
||||
// /* FIXME: This is wrong but for now we need it to avoid going over the array bounds */
|
||||
// olen = old_length + 2*st->magic_samples[i];
|
||||
// for (j=old_length-2+st->magic_samples[i];j>=0;j--)
|
||||
// st->mem[i*st->mem_alloc_size+j+st->magic_samples[i]] = st->mem[i*old_alloc_size+j];
|
||||
// for (j=0;j<st->magic_samples[i];j++)
|
||||
// st->mem[i*st->mem_alloc_size+j] = 0;
|
||||
// st->magic_samples[i] = 0;
|
||||
// }
|
||||
// if (st->filt_len > olen)
|
||||
// {
|
||||
// /* If the new filter length is still bigger than the "augmented" length */
|
||||
// /* Copy data going backward */
|
||||
// for (j=0;j<olen-1;j++)
|
||||
// st->mem[i*st->mem_alloc_size+(st->filt_len-2-j)] = st->mem[i*st->mem_alloc_size+(olen-2-j)];
|
||||
// /* Then put zeros for lack of anything better */
|
||||
// for (;j<st->filt_len-1;j++)
|
||||
// st->mem[i*st->mem_alloc_size+(st->filt_len-2-j)] = 0;
|
||||
// /* Adjust last_sample */
|
||||
// st->last_sample[i] += (st->filt_len - olen)/2;
|
||||
// } else {
|
||||
// /* Put back some of the magic! */
|
||||
// st->magic_samples[i] = (olen - st->filt_len)/2;
|
||||
// for (j=0;j<st->filt_len-1+st->magic_samples[i];j++)
|
||||
// st->mem[i*st->mem_alloc_size+j] = st->mem[i*st->mem_alloc_size+j+st->magic_samples[i]];
|
||||
// }
|
||||
}
|
||||
case r.filtLen < oldLength:
|
||||
panic("not implemented")
|
||||
// spx_uint32_t i;
|
||||
// /* Reduce filter length, this a bit tricky. We need to store some of the memory as "magic"
|
||||
// samples so they can be used directly as input the next time(s) */
|
||||
// for (i=0;i<st->nb_channels;i++)
|
||||
// {
|
||||
// spx_uint32_t j;
|
||||
// spx_uint32_t old_magic = st->magic_samples[i];
|
||||
// st->magic_samples[i] = (old_length - st->filt_len)/2;
|
||||
// /* We must copy some of the memory that's no longer used */
|
||||
// /* Copy data going backward */
|
||||
// for (j=0;j<st->filt_len-1+st->magic_samples[i]+old_magic;j++)
|
||||
// st->mem[i*st->mem_alloc_size+j] = st->mem[i*st->mem_alloc_size+j+st->magic_samples[i]];
|
||||
// st->magic_samples[i] += old_magic;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Resampler) InputLatency() int {
|
||||
return r.filtLen >> 1
|
||||
}
|
||||
|
||||
func (r *Resampler) OutputLatency() int {
|
||||
return ((r.filtLen>>1)*r.denRate + (r.numRate >> 1)) / r.numRate
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package resample
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
wave = []float64{
|
||||
//-1 to 1 (16 samples)
|
||||
-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
//1 to -1 (16 samples)
|
||||
1, 0.75, 0.5, 0.25, 0, -0.25, -0.5, -0.75, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
}
|
||||
)
|
||||
|
||||
func resample64(t *testing.T, inSamplerate, outSamplerate, q int) []float64 {
|
||||
r := New(1, inSamplerate, outSamplerate, q)
|
||||
t.Log("samplerate:", "in:", inSamplerate, "out:", outSamplerate)
|
||||
t.Log("latency:", "in:", r.InputLatency(), "out:", r.OutputLatency())
|
||||
|
||||
in := make([]float64, inSamplerate/100)
|
||||
out := make([]float64, outSamplerate/100)
|
||||
|
||||
copy(in, wave)
|
||||
read, written := r.ProcessFloat64(0, in, out)
|
||||
t.Log("read:", read)
|
||||
t.Log("written:", written)
|
||||
|
||||
s := ""
|
||||
out = out[r.OutputLatency():][:(32*outSamplerate)/inSamplerate]
|
||||
for _, v := range out {
|
||||
s += fmt.Sprintf("%0.3f ", v)
|
||||
}
|
||||
t.Log("wave:", s)
|
||||
return out
|
||||
}
|
||||
|
||||
func resample32(t *testing.T, inSamplerate, outSamplerate, q int) []float32 {
|
||||
r := New(1, inSamplerate, outSamplerate, q)
|
||||
t.Log("samplerate:", "in:", inSamplerate, "out:", outSamplerate)
|
||||
t.Log("latency:", "in:", r.InputLatency(), "out:", r.OutputLatency())
|
||||
|
||||
in := make([]float32, inSamplerate/100)
|
||||
out := make([]float32, outSamplerate/100)
|
||||
for i, s := range wave {
|
||||
in[i] = float32(s)
|
||||
}
|
||||
|
||||
read, written := r.ProcessFloat32(0, in, out)
|
||||
t.Log("read:", read)
|
||||
t.Log("written:", written)
|
||||
|
||||
s := ""
|
||||
out = out[r.OutputLatency():][:(32*outSamplerate)/inSamplerate]
|
||||
for _, v := range out {
|
||||
s += fmt.Sprintf("%0.3f ", v)
|
||||
}
|
||||
t.Log("wave:", s)
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSame64(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample64(t, 48000, 48000, q)
|
||||
if math.Abs(out[8]-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(out[24] - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSame32(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample32(t, 48000, 48000, q)
|
||||
if math.Abs(float64(out[8])-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(float64(out[24]) - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectDownSampling64(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample64(t, 48000, 24000, q)
|
||||
if math.Abs(out[4]-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(out[12] - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectDownSampling32(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample32(t, 48000, 24000, q)
|
||||
if math.Abs(float64(out[4])-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(float64(out[12]) - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUpSampling64(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample64(t, 24000, 48000, q)
|
||||
if math.Abs(out[16]-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(out[48] - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectUpSampling32(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample32(t, 24000, 48000, q)
|
||||
if math.Abs(float64(out[16])-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(float64(out[48]) - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpolateDownSampling64(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample64(t, 48000, 23999, q)
|
||||
if math.Abs(out[4]-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(out[12] - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpolateDownSampling32(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample32(t, 48000, 23999, q)
|
||||
if math.Abs(float64(out[4])-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(float64(out[12]) - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpolateUpSampling64(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample64(t, 23999, 48000, q)
|
||||
if math.Abs(out[16]-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(out[48] - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpolateUpSampling32(t *testing.T) {
|
||||
for q := 0; q < 11; q++ {
|
||||
out := resample32(t, 23999, 48000, q)
|
||||
if math.Abs(float64(out[16])-1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
if math.Abs(float64(out[48]) - -1.0) > 0.1 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user