Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:29:41 +01:00
1 parent 85a9ec684c
commit c5d6137fab
160 files changed
+76293 -387

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
package audio
import (
"math"
"math/cmplx"
"github.com/BeatGlow/beatglow/internal/calc"
"gonum.org/v1/gonum/dsp/fourier"
)
// FrequencySpectrumAnalyzer structure to hold analysis parameters
type FrequencySpectrumAnalyzer struct {
SampleRate float64
BitDepth int
NumBins int
MinFrequency float64
MaxFrequency float64
avgSamples []float64
coefficients []complex128
bins []float64
}
// dBFS calculates dBFS for the given amplitude value
func dBFS(amplitude float64) float64 {
if amplitude == 0 {
return -math.Inf(1) // -Infinity for silence
}
return 20 * math.Log10(amplitude)
}
func normalize(values []float64) {
var max float64
for _, v := range values {
if v = math.Abs(v); v > max {
max = v
}
}
if max == 0 {
return
}
for i := range values {
values[i] /= max
}
}
// AnalyzeFrequencySpectrum performs the FFT and returns the energy levels in dBFS for each frequency bin
func (a *FrequencySpectrumAnalyzer) AnalyzeFrequencySpectrum(buffer *Buffer) []float64 {
samples := len(buffer.Samples[0])
//if len(a.avgSamples) != samples {
a.avgSamples = make([]float64, samples)
a.coefficients = make([]complex128, samples/2+1)
//}
channels := len(buffer.Samples)
if channels == 1 {
for i, sample := range buffer.Samples[0] {
a.avgSamples[i] = float64(sample)
}
} else {
for i := range buffer.Samples[0] {
a.avgSamples[i] = float64(buffer.Samples[0][i]+buffer.Samples[1][i]) / 2
}
}
// Apply windowing function
//normalize(a.avgSamples)
//calc.Hamming(a.avgSamples, a.avgSamples)
calc.Hann(a.avgSamples, a.avgSamples)
// Perform FFT on the signal
fft := fourier.NewFFT(samples)
fft.Coefficients(a.coefficients, a.avgSamples)
// Calculate the energy levels in dBFS for each frequency bin
var (
frequencyBinSize = a.SampleRate / float64(samples)
minBin = int(math.Round(a.MinFrequency / frequencyBinSize))
maxBin = int(math.Round(a.MaxFrequency / frequencyBinSize))
)
// Make sure the minimum bin is not lower than 0, and the maximum bin doesn't exceed half of the buffer size
if minBin < 0 {
minBin = 0
}
if maxBin > samples/2 {
maxBin = samples / 2
}
//if len(a.bins) != a.NumBins {
a.bins = make([]float64, a.NumBins)
//}
// Compute dBFS levels for the selected frequency range
for i := 0; i < a.NumBins; i++ {
var (
// Calculate the frequency range for this bin
frequencyScale = (a.MaxFrequency - a.MinFrequency) / float64(a.NumBins)
frequencyStart = a.MinFrequency + float64(i)*frequencyScale
frequencyEnd = a.MinFrequency + float64(i+1)*frequencyScale
// Determine the FFT bin range corresponding to the frequency range of this bin
startBin = int((frequencyStart / frequencyBinSize) + .5)
endBin = int((frequencyEnd / frequencyBinSize) + .5)
)
// Ensure the bins are within the valid range
if startBin < 0 {
startBin = 0
}
if endBin > samples/2 {
endBin = samples / 2
}
// Average the magnitudes of the FFT bins in this range and accumulate the result
var totalAmplitude float64
var count int
for bin := startBin; bin < endBin; bin++ {
x := a.coefficients[bin]
//amplitude := real(x)*real(x) + imag(x)*imag(x) // math.Hypot(real(x), imag(x))
amplitude := math.Min(cmplx.Abs(x), 1.0)
totalAmplitude += amplitude
count++
}
// Calculate the average dBFS for this frequency bin
if count > 0 {
a.bins[i] = math.Min((totalAmplitude/float64(count))*10, 1.0)
}
}
return a.bins
}
+97
View File
@@ -0,0 +1,97 @@
package audio
import "math"
// Float is all floating point number types (and Samples).
type Float interface {
~float32 | ~float64
}
// Clamp a sample in [-1..+1].
func Clamp[T Float](sample T) T {
if sample < -1 {
return -1
}
if sample > +1 {
return +1
}
return sample
}
// Abs a slice of values.
func Abs[T Float](values []T) {
for i, v := range values {
values[i] = T(math.Abs(float64(v)))
}
}
// Mean of values.
func Mean[T Float](values []T) T {
if len(values) == 0 {
return 0
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, v := range values {
var (
x = float64(v)
i int
)
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return T(sum / float64(len(values)))
}
// RMS calculates the root mean square of values.
func RMS[T Float](values []T) T {
if len(values) == 0 {
return 0
}
var squares float64
for _, v := range values {
squares += float64(v) * float64(v)
}
return T(math.Sqrt(squares / float64(len(values))))
}
// Sum of values.
func Sum[T Float](values []T) T {
if len(values) == 0 {
return 0
}
var sum T
for _, v := range values {
sum += v
}
return sum
}
// SQNR is the signal-to-quantization-noise ratio.
func SQNR(bits int) float64 {
return 20 * math.Log10(math.Pow(2, float64(bits)))
}
+241
View File
@@ -0,0 +1,241 @@
package audio
import (
"encoding/binary"
"io"
"math"
"github.com/sirupsen/logrus"
)
// Sample is a type alias for float64.
type Sample float64
// Format is the format of a Buffer or another audio source.
type Format interface {
// BitsPerSample is the number of bits per sample.
BitsPerSample() int
// Order is the byte order.
Order() binary.ByteOrder
// DecodeFromBytes reads one sample from b. No bounds checking is performed on b!
DecodeFromBytes(b []byte) Sample
// EncodeToBytes writes on sample to b.
EncodeToBytes(b []byte, s Sample)
}
type pcmFormat uint8
const (
Int8 pcmFormat = iota
Int16
Int16BE
Int32
Int32BE
Float32
Float32BE
Float64
Float64BE
)
func makeFormat(bits int) pcmFormat {
switch bits {
case 8:
return Int8
case 16:
return Int16
case 32:
return Int32
default:
return Int16
}
}
var pcmfFormatBitsPerSample = map[pcmFormat]int{
Int8: 8,
Int16: 16,
Int16BE: 16,
Int32: 32,
Int32BE: 32,
Float32: 32,
Float32BE: 32,
Float64: 64,
Float64BE: 64,
}
func (f pcmFormat) BitsPerSample() int {
if v, ok := pcmfFormatBitsPerSample[f]; ok {
return v
}
return 0
}
func (f pcmFormat) Order() binary.ByteOrder {
if f%2 == 0 {
return binary.BigEndian
}
return binary.LittleEndian
}
func (f pcmFormat) DecodeFromBytes(b []byte) Sample {
order := f.Order()
switch f {
case Int8:
return Sample(int8(b[0])) / math.MaxInt8
case Int16, Int16BE:
return Sample(int16(order.Uint16(b))) / math.MaxInt16
case Int32, Int32BE:
return Sample(int32(order.Uint32(b))) / math.MaxInt32
case Float32, Float32BE:
return Sample(math.Float32frombits(order.Uint32(b)))
case Float64, Float64BE:
return Sample(math.Float64frombits(order.Uint64(b)))
default:
return 0
}
}
func (f pcmFormat) EncodeToBytes(b []byte, s Sample) {
order := f.Order()
switch f {
case Int8:
b[0] = byte(int8(s * math.MaxInt8))
case Int16, Int16BE:
order.PutUint16(b, uint16(int16(s*math.MaxInt16)))
case Int32, Int32BE:
order.PutUint32(b, uint32(int32(s*math.MaxInt32)))
case Float32, Float32BE:
order.PutUint32(b, math.Float32bits(float32(s)))
case Float64, Float64BE:
order.PutUint64(b, math.Float64bits(float64(s)))
}
}
var pcmFormatNames = map[pcmFormat]string{
Int8: "8-bit signed PCM",
Int16: "16-bit signed PCM",
Int16BE: "16-bit signed PCM (BE)",
Int32: "32-bit signed PCM",
Int32BE: "32-bit signed PCM (BE)",
Float32: "32-bit floating piont PCM",
Float32BE: "32-bit floating point PCM (BE)",
Float64: "64-bit floating point PCM",
Float64BE: "64-bit floating point PCM (BE)",
}
func (f pcmFormat) String() string {
if s, ok := pcmFormatNames[f]; ok {
return s
}
return "unknown"
}
// Buffer of audio samples, only supports mono and stereo samples.
type Buffer struct {
Format Format
Rate Rate
Samples [][]Sample
buf []byte
}
func NewBuffer(format Format, rate Rate, n, channels int) *Buffer {
if channels < 1 {
channels = 1
}
if channels > 2 {
channels = 2
}
logrus.WithFields(logrus.Fields{
"channels": channels,
"rate": rate,
"format": format,
"samples": n,
}).Debug("new audio buffer")
samples := make([][]Sample, channels)
for channel := 0; channel < channels; channel++ {
samples[channel] = make([]Sample, n)
}
return &Buffer{
Format: format,
Rate: rate,
Samples: samples,
}
}
// DecodeFrom decodes samples read from r.
func (b *Buffer) DecodeFrom(r io.Reader) (n int, err error) {
if s, ok := r.(SamplesReader); ok {
// Use the SamplesReader interface, if available.
return s.ReadSamples(b.Samples)
}
var (
channels = len(b.Samples)
samples = len(b.Samples[0])
bitsPerSample = b.Format.BitsPerSample()
bytesPerSample = bitsPerSample / 8
bytesRequired = channels * samples * bytesPerSample
)
// Resize buffer, if required.
if len(b.buf) < bytesRequired {
b.buf = make([]byte, bytesRequired)
} else {
b.buf = b.buf[:bytesRequired]
}
// Read raw bytes.
if _, err = io.ReadFull(r, b.buf); err != nil {
return
}
// Convert bytes to samples, deinterleave multi channel audio.
var o, c int
for i, l := 0, bytesRequired/bytesPerSample; i < l; i++ {
b.Samples[0][c] = b.Format.DecodeFromBytes(b.buf[o : o+bytesPerSample])
c = (c + 1) % channels
o = o + bytesPerSample
}
return bytesRequired / bytesPerSample, nil
}
// ToMono converts the buffer to mono. If the buffer is already mono, it returns the buffer.
func (b *Buffer) ToMono() *Buffer {
if len(b.Samples) == 1 {
return b
}
// Convert stereo buffer to mono.
o := NewBuffer(b.Format, b.Rate, len(b.Samples[0]), 2)
for i := range o.Samples[0] {
o.Samples[0][i] = (b.Samples[0][i] + b.Samples[1][i]) / 2
}
return o
}
// ToStereo converts the buffer to stereo. If the buffer is already stereo, it returns the buffer.
func (b *Buffer) ToStereo() *Buffer {
if len(b.Samples) == 2 {
return b
}
// Convert mono buffer to stereo.
o := NewBuffer(b.Format, b.Rate, len(b.Samples[0]), 1)
copy(o.Samples[0], b.Samples[0])
copy(o.Samples[1], b.Samples[0])
return o
}
type BufferProcessor interface {
ProcessBuffer(buffer *Buffer)
}
type Processor interface {
ProcessSamples(samples [][]Sample)
}
+23
View File
@@ -0,0 +1,23 @@
package audio
import "testing"
func TestFormatBitsPerSample(t *testing.T) {
testCases := []struct {
Test Format
Want int
}{
{Int8, 8},
{Int16, 16},
{Int16BE, 16},
{Int32, 32},
{Int32BE, 32},
}
for _, test := range testCases {
t.Run(test.Test.(pcmFormat).String(), func(it *testing.T) {
if v := test.Test.BitsPerSample(); v != test.Want {
it.Errorf("expected %d bits per sample, got %d", test.Want, v)
}
})
}
}
+147
View File
@@ -0,0 +1,147 @@
package audio
import (
"errors"
"fmt"
"io"
"os"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/config"
)
func init() {
Register("file", openReader)
Register("fifo", openReader)
}
// Source of audio samples.
type Source interface {
io.Reader
String() string
// Channels is the number of channels.
Channels() int
// Format of the source.
Format() Format
// SampleRate of the source.
SampleRate() Rate
}
// NotFound signals the reader type can not be found.
type NotFound struct {
Type string
}
func (err NotFound) Error() string {
return fmt.Sprintf("audio source %q not available", err.Type)
}
// SourceOpener can open an audio stream source.
type SourceOpener func(config.Audio) (Source, error)
var drivers = make(map[string]SourceOpener)
func Register(name string, opener SourceOpener) {
if _, dupe := drivers[name]; dupe {
panic(fmt.Sprintf("audio source %q already registered", name))
}
drivers[name] = opener
}
func NewSource(config config.Audio) (Source, error) {
opener, ok := drivers[config.Type]
if ok {
return opener(config)
}
return nil, NotFound{Type: config.Type}
}
type ReaderSource struct {
io.ReadCloser
// Name of the reader (path).
Name string
// Ch is the number of channels.
Ch int
// Format is the audio format.
Fmt Format
// Rate is the sample rate.
Rate Rate
// Opener is a function that can be called if the reader is closed.
Opener func() (io.ReadCloser, error)
}
func openReader(config config.Audio) (Source, error) {
var (
ch = config.Channels
bits = config.Bits
rate = Rate(config.Rate)
)
if ch == 0 {
ch = 2
}
if bits == 0 {
bits = 16
}
if rate == 0 {
rate = 44100
}
return &ReaderSource{
Name: config.Path,
Ch: ch,
Fmt: makeFormat(bits),
Rate: rate,
Opener: func() (io.ReadCloser, error) {
return os.Open(config.Path)
},
}, nil
}
func (s *ReaderSource) String() string {
return "reader:" + s.Name
}
func (s *ReaderSource) Channels() int {
return s.Ch
}
func (s *ReaderSource) Format() Format {
return s.Fmt
}
func (s *ReaderSource) SampleRate() Rate {
return s.Rate
}
func (r *ReaderSource) Read(b []byte) (int, error) {
var err error
if r.ReadCloser == nil {
if r.ReadCloser, err = r.Opener(); err != nil {
return 0, err
}
}
var n int
if n, err = r.ReadCloser.Read(b); err != nil {
logrus.WithError(err).Warn("source failed to read; closing")
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
_ = r.ReadCloser.Close()
r.ReadCloser = nil
}
}
return n, err
}
type SamplesReader interface {
// ReadSamples reads samples, it returns the number of samples read.
ReadSamples(samples [][]Sample) (int, error)
}
+54
View File
@@ -0,0 +1,54 @@
package audio
import (
"context"
"time"
"github.com/sirupsen/logrus"
)
const streamDoubleBufferSize = 16
type StreamCancelFunc func()
// Stream reads from a source using a buffer size of n samples.
func Stream(source Source, n int) (<-chan *Buffer, StreamCancelFunc) {
channel := make(chan *Buffer, streamDoubleBufferSize)
ctx, cancel := context.WithCancel(context.Background())
go stream(ctx, channel, source, n)
return channel, StreamCancelFunc(cancel)
}
func stream(ctx context.Context, stream chan<- *Buffer, source Source, n int) {
defer close(stream)
buffers := make([]*Buffer, streamDoubleBufferSize)
for i := 0; i < streamDoubleBufferSize; i++ {
buffers[i] = NewBuffer(source.Format(), source.SampleRate(), n, source.Channels())
}
var bufferPos int
for {
select {
case <-ctx.Done():
return
default:
}
buffer := buffers[bufferPos]
bufferPos = (bufferPos + 1) % streamDoubleBufferSize
if _, err := buffer.DecodeFrom(source); err != nil {
logrus.WithError(err).WithField("source", source).Warn("decode audio failed")
time.Sleep(time.Second)
continue
}
select {
case <-ctx.Done():
return
case stream <- buffer:
default:
logrus.WithField("source", source).Trace("buffer overrun, host too slow?")
}
}
}
+60
View File
@@ -0,0 +1,60 @@
package audio
import (
"fmt"
"strconv"
"time"
)
// Rate is the sampling rate.
type Rate int
// Frequency is the sampling frequency.
func (r Rate) Frequency() Frequency {
return 1 / Frequency(r)
}
// Duration of n samples at this rate.
func (r Rate) Duration(n int) time.Duration {
return time.Second * time.Duration(n) / time.Duration(r)
}
// Number of sample during duration d.
func (r Rate) Samples(d time.Duration) int {
return int(d * time.Duration(r) / time.Second)
}
func (r Rate) String() string {
return strconv.FormatInt(int64(r), 10)
}
// Frequency is a type alias for float64.
type Frequency float64
const (
Hz Frequency = 1
KHz Frequency = 1e3
MHz Frequency = 1e6
GHz Frequency = 1e9
THz Frequency = 1e12
)
func (f Frequency) String() string {
switch {
case f > THz:
return fmt.Sprintf("%gTHz", f/THz)
case f > GHz:
return fmt.Sprintf("%gGHz", f/GHz)
case f > MHz:
return fmt.Sprintf("%gMHz", f/MHz)
case f > KHz:
return fmt.Sprintf("%gkHz", f/KHz)
default:
return fmt.Sprintf("%gHz", f)
}
}
// Rate is the sampling rate for this frequency.
func (r Frequency) Rate() Rate {
return Rate(1 / r)
}
+147
View File
@@ -0,0 +1,147 @@
package ui
import (
"bytes"
"image"
"image/color"
"image/png"
"time"
"github.com/nfnt/resize"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/ui/widget"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
_ "embed" // Embed binary files
)
var (
logoBG = color.RGBA{R: 0x11, G: 0xff, B: 0xe3, A: 0xff}
logoFG = color.RGBA{R: 0x8a, G: 0x00, B: 0xc4, A: 0xff}
)
// Boot renders the boot splash.
func Boot(dst display.Display) error {
logrus.WithField("display", dst).Info("Welcome to BeatGlow!")
var (
styles = StylesFor(dst.ColorModel())
bounds = dst.Bounds()
width = bounds.Dx()
height = bounds.Dy()
canvas = image.NewRGBA(bounds)
)
logrus.Infof("styles: %#+v", styles)
draw.Draw(canvas, bounds, styles.Boot.Background, image.Point{}, draw.Src)
if err := dst.Refresh(); err != nil {
return err
}
fontSize := 24.0
switch {
case height >= 64:
fontSize = 36.0
case height >= 128:
fontSize = 48.0
}
font := styles.Boot.Font.WithPointSize(fontSize)
logoTextWidth, logoTextHeight := font.MeasureText("beatglow")
logoText := widget.NewText(image.Point{}, font, image.NewUniform(styles.Boot.Foreground), "beatglow")
logoText.Position = bounds.Size()
logoText.Position.X /= 2
logoText.Position.Y /= 2
logoText.Position.X -= logoTextWidth / 2
logoText.Position.Y -= logoTextHeight / 2
logoText.Render(dst)
border := bounds
border.Max.X--
border.Max.Y--
draw.Rectangle(dst, border, color.White)
if err := dst.Refresh(); err != nil {
return err
}
time.Sleep(250 * time.Millisecond)
var (
logoTextStep image.Point
logoTextStop image.Point
logoLoveMaxX uint
logoLoveMaxY uint
logoLovePosition image.Point
logoLoveCenterX bool
logoLoveCenterY bool
)
switch {
case width == 256 && height == 64:
// Side by side
logoTextStep = image.Pt(-1, 0)
logoTextStop = image.Pt(2, logoText.Position.Y)
logoLoveMaxX = uint(width) / 2
logoLoveMaxY = uint(height)
logoLovePosition = image.Pt((width/4)*3, height/2) // center right
logoLoveCenterX = true
default:
// Scroll up
logoTextStep = image.Pt(0, -1)
logoTextStop = image.Pt(logoText.Position.X, 0)
logoLoveMaxX = uint(width)
logoLoveMaxY = uint(height / 2)
logoLovePosition = image.Pt(width/2, (height/4)*3) // bottom
logoLoveCenterY = true
}
ticker := time.NewTicker(10 * time.Millisecond)
for ; !logoText.Position.Eq(logoTextStop); logoText.Position = logoText.Position.Add(logoTextStep) {
draw.Draw(canvas, bounds, styles.Boot.Background, image.Point{}, draw.Src) // clear canvas
logoText.Render(canvas) // render logo
draw.Draw(dst, bounds, canvas, image.Point{}, draw.Src) // canvas to display
dst.Refresh() // display refresh
<-ticker.C
}
ticker.Stop()
logrus.Info("BeatGlow 💖 Volumio")
logoLove := resize.Thumbnail(logoLoveMaxX, logoLoveMaxY, logoVolumio, resize.Lanczos3)
//draw.Draw(canvas, bounds, image.NewUniform(color.Black), image.Point{}, draw.Src)
if logoLoveCenterX {
logoLovePosition.X -= logoLove.Bounds().Dx() / 2
}
if logoLoveCenterY {
logoLovePosition.Y -= logoLove.Bounds().Dy() / 2
}
draw.Draw(canvas, bounds.Add(logoLovePosition), logoLove, image.Point{}, draw.Src)
draw.Draw(dst, bounds, canvas, image.Point{}, draw.Src)
if err := dst.Refresh(); err != nil {
return err
}
time.Sleep(1 * time.Second)
return nil
}
func mustDecodePNG(b []byte) image.Image {
i, err := png.Decode(bytes.NewBuffer(b))
if err != nil {
panic(err)
}
return i
}
var (
logoVolumio = mustDecodePNG(logoVolumioPNG)
logoMoode = mustDecodePNG(logoMoodePNG)
)
//go:embed asset/logo-volumio.png
var logoVolumioPNG []byte
//go:embed asset/logo-moode.png
var logoMoodePNG []byte
+113
View File
@@ -0,0 +1,113 @@
package visual
import (
"math/cmplx"
"github.com/BeatGlow/beatglow/audio"
"github.com/BeatGlow/beatglow/draw"
"github.com/BeatGlow/beatglow/draw/pixel"
"github.com/BeatGlow/beatglow/internal/calc"
"github.com/BeatGlow/display"
"gonum.org/v1/gonum/dsp/fourier"
)
type Analyzer struct {
display display.Display
canvas *draw.Canvas
rate audio.Rate
step int
fft *fourier.FFT
complex []complex128
samples []float64
levels []float64
}
func NewAnalyzer(display display.Display, rate audio.Rate, step int) *Analyzer {
return &Analyzer{
display: display,
canvas: draw.NewCanvas(display),
rate: rate,
step: step,
levels: make([]float64, display.Bounds().Dx()),
}
}
func (a *Analyzer) ProcessBuffer(buffer *audio.Buffer) {
a.frequencySpectrum(buffer.ToMono().Samples[0], a.rate, a.step)
}
func (a *Analyzer) Halt() error {
return nil
}
func (Analyzer) Type() string {
return "visual:analyzer"
}
func (a *Analyzer) Render() error {
//a.display.Clear()
for x, level := range a.levels {
h := int(56*level + .5)
draw.Line(a.display, pixel.On, x, 56-h, x+1, 56)
}
return a.display.Refresh()
}
func (a *Analyzer) resize(n int) {
if s := n/2 + 1; len(a.complex) != s {
a.fft = fourier.NewFFT(n)
a.samples = make([]float64, n)
a.complex = make([]complex128, s)
}
}
func (a *Analyzer) convert(samples []audio.Sample) {
for i, v := range samples {
a.samples[i] = float64(v)
}
}
func (a *Analyzer) frequencySpectrum(samples []audio.Sample, rate audio.Rate, step int) error {
n := len(samples)
a.resize(n)
a.convert(samples)
a.fft.Coefficients(a.complex, a.samples)
/*
if err := transform(csamples); err != nil {
return nil, err
}
*/
/*
fmt.Printf("%d: %#+v", len(a.complex), a.complex)
freqSamplingStep := float64(rate) / float64(n)
scaleStep := float64(step) / freqSamplingStep
freqLimit := float64(rate) / 2.0
for i := 0.0; i*freqSamplingStep <= freqLimit; i += scaleStep {
//result[int(i*freqSamplingStep)] = math.Abs(real(a.complex[int(i)])) // cmplx.Abs(a.complex[int(i)])
a.levels[int(i*freqSamplingStep)] = cmplx.Abs(a.complex[int(i)])
}
*/
for i := 0; i < a.display.Bounds().Size().X; i++ {
o := i << 1
a.levels[i] = (cmplx.Abs(a.complex[o]) + cmplx.Abs(a.complex[o+1])) / 2
}
calc.Hamming(a.levels, a.levels)
a.normalizeSpectrum()
return nil
}
func (a *Analyzer) normalizeSpectrum() {
max := calc.Max(a.levels)
if max > 0 {
for i := range a.levels {
a.levels[i] /= max
}
}
}
+88
View File
@@ -0,0 +1,88 @@
package visual
import (
"image"
"github.com/nfnt/resize"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
_ "embed"
)
type Art struct {
display display.Display
styles ui.Styles
player player.Player
size uint
track *player.Track
icon image.Image
}
func NewArt(display display.Display, player player.Player) *Art {
size := uint(display.Bounds().Dx())
icon := resize.Thumbnail(size, size, ui.MustDecodePNG(recordPNG), resize.Lanczos3)
return &Art{
display: display,
styles: ui.StylesFor(display.ColorModel()),
player: player,
size: size,
icon: icon,
}
}
func (Art) Halt() error {
return nil
}
func (Art) Type() string {
return "art"
}
func (v *Art) Render() error {
logrus.WithField("visual", "art").Debugf("render %s", v.display.Bounds())
return v.display.Refresh()
}
func (v *Art) TrackChanged(track *player.Track) {
logrus.WithField("visual", "art").Debug("track changed")
v.track = track
v.display.Clear()
draw.Draw(v.display, v.display.Bounds(), v.icon, image.Point{}, draw.Src)
if track != nil {
go v.request(track)
}
}
func (v *Art) request(track *player.Track) {
log := logrus.WithFields(logrus.Fields{
"visual": "art",
"player": v.player.Type(),
})
p, ok := v.player.(player.AlbumArt)
if ok {
log.Debug("requesting album art")
var i image.Image
if i, ok = p.AlbumArt(track); ok {
thumbnail := resize.Thumbnail(v.size, v.size, i, resize.Lanczos2)
logrus.WithField("visual", "playing").Debugf("track album art %s", thumbnail.Bounds().Size())
centered := v.display.Bounds().Size().Sub(thumbnail.Bounds().Size())
centered.X /= 2
centered.Y /= 2
draw.Draw(v.display, thumbnail.Bounds().Add(centered), thumbnail, image.Point{}, draw.Src)
} else {
log.Debug("track album art unavailable")
}
} else {
log.Debug("player doesn't support album art")
}
}
//go:embed asset/record.png
var recordPNG []byte
+50
View File
@@ -0,0 +1,50 @@
package visual
import (
"fmt"
"image"
"math/rand"
"time"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/font"
"github.com/BeatGlow/display"
)
type Offline struct {
since time.Time
display display.Display
styles ui.Styles
x, y int
w, h int
dx, dy bool
}
func NewOffline(display display.Display) *Offline {
size := display.Bounds().Size()
return &Offline{
since: time.Now(),
display: display,
styles: ui.StylesFor(display.ColorModel()),
w: size.X - 3,
h: size.Y - 3,
x: rand.Int() % (size.X - 3),
y: rand.Int() % (size.Y - 3),
}
}
func (Offline) Halt() error {
return nil
}
func (Offline) Type() string {
return "offline"
}
func (v *Offline) Render() error {
v.display.Clear()
since := (time.Since(v.since) / time.Second) * time.Second
font.MicroGrotesk.Draw(v.display, image.Point{1, 24}, image.NewUniform(v.styles.Boot.Foreground), "Player offline!")
font.Monaco.Draw(v.display, image.Point{1, 40}, image.NewUniform(v.styles.Boot.Foreground), fmt.Sprintf("for %s", since))
return v.display.Refresh()
}
+196
View File
@@ -0,0 +1,196 @@
package visual
import (
"fmt"
"image"
"path/filepath"
"strings"
"time"
"github.com/BeatGlow/beatglow/draw"
"github.com/BeatGlow/beatglow/draw/pixel"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/sirupsen/logrus"
)
const (
playingTitleY = 12
playingArtistY = 30
)
type Playing struct {
display display.Display
canvas *draw.Canvas
bounds image.Rectangle
styles ui.Styles
status struct {
player *player.Status
track *player.Track
}
scroll *draw.Scroller
}
func NewPlaying(display display.Display) *Playing {
size := display.Bounds().Size()
styles := ui.StylesFor(display.ColorModel())
v := &Playing{
display: display,
canvas: draw.NewCanvas(display).SetStyle(styles.Track),
bounds: display.Bounds(),
styles: styles,
}
// Setup font sizes
v.styles.Track.Font.SetPointSize(24)
v.styles.Progress.Font.SetPointSize(9)
// Setup scroller
v.scroll = draw.NewScroller(display, size.X, true)
v.scroll.Canvas.SetStyle(v.styles.Track)
// Player offline text
v.Update(nil)
return v
}
func (Playing) Halt() error {
return nil
}
func (Playing) Type() string {
return "playing"
}
func (v *Playing) Render() error {
v.display.Clear()
var (
rows = [...]int{
0, // warnings (?)
12, // title
30, // artist
55, // status
43, // progress
}
/*
fonts = [...]*font.Font{
font.Monaco.WithPointSize(8),
font.MicroGrotesk.WithPointSize(16),
font.MicroGrotesk.WithPointSize(12),
font.Monaco.WithPointSize(8),
}
/*
fonts = [...]*font.Font{
font.Fixed5x7,
font.Unifont,
font.Fixed5x7,
font.Fixed5x7,
}
*/
)
v.scroll.Advance()
var (
bounds = v.display.Bounds()
width = bounds.Dx()
status = v.status.player
track = v.status.track
)
if status != nil {
var (
format = "Dunno"
elapsedText = "--:-- / --:--"
progress float64
)
if track != nil {
elapsedText = fmt.Sprintf("%s / %s", hms(status.Elapsed), hms(track.Duration))
progress = float64(status.Elapsed) / float64(track.Duration)
}
if status.Format.Encoding != "" {
format = strings.ToUpper(status.Format.Encoding)
} else if track != nil && track.Path != "" {
format = strings.ToUpper(filepath.Ext(track.Path)[1:])
}
//format += fmt.Sprintf("-%d", status.Format.BitRate)
v.canvas.WithStyle(v.styles.Progress, func() {
v.canvas.Text(1, 0, format)
v.canvas.Text(40, 0, elapsedText)
v.canvas.WithGradient(width-120-2, 8, func() {
v.canvas.Progess(120, 0, width-120-2, progress)
})
})
if status.Paused {
draw.Sprite(v.display, pixel.On, 1, rows[3], pauseSprite)
} else {
draw.Sprite(v.display, pixel.On, 1, rows[3], playSprite)
}
}
return v.display.Refresh()
}
func (v *Playing) TrackChanged(track *player.Track) {
logrus.WithField("visual", "playing").Debug("track changed")
if track == nil {
v.scroll.SetDirection(0)
} else {
v.scroll.SetDirection(+1)
switch {
case track.Artist != "" && track.Title != "":
v.scroll.Text(0, playingTitleY, fmt.Sprintf("%s - %s", track.Artist, track.Title))
case track.Title != "":
v.scroll.Text(0, playingTitleY, fmt.Sprintf("Unknown Artist - %s", track.Title))
case track.Artist != "":
v.scroll.Text(0, playingTitleY, fmt.Sprintf("%s - Unknown", track.Title))
default:
v.scroll.Text(0, playingTitleY, "Unknown")
}
}
v.scroll.Reset()
v.status.track = track
}
func (v *Playing) StatusChanged(status *player.Status) {
logrus.WithField("visual", "playing").Debug("status changed")
v.status.player = status
}
func hms(d time.Duration) string {
var (
v = int(d / time.Second)
h = v / 3600
m = (v - h*3600) / 60
s = (v - m*60)
)
if h == 0 {
return fmt.Sprintf("%02d:%02d", m, s)
}
return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
}
func (v *Playing) Update(status *player.Status) {
v.status.player = status
if status == nil {
v.scroll.Text(0, playingTitleY, "Player is offline")
}
}
var (
playSprite = []byte{8, 8, 0x00, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00}
pauseSprite = []byte{8, 8, 0x00, 0x7F, 0x7F, 0x00, 0x00, 0x7F, 0x7F, 0x00}
repeatSprite = []byte{8, 8, 0x00, 0x79, 0x7B, 0x63, 0x63, 0x63, 0x6F, 0x2F}
volumeSprite = []byte{8, 8, 0x00, 0x18, 0x18, 0x3C, 0x7E, 0xFF, 0x00, 0x00}
)
+11
View File
@@ -0,0 +1,11 @@
package visual
import (
"github.com/BeatGlow/beatglow/hardware"
)
type Visual interface {
hardware.Driver
Render() error
}
+273
View File
@@ -0,0 +1,273 @@
package visual
var vumeterBackground = [2][]uint8{{
0x80, /* = width */
0x40, /* = height */
0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xa8, 0xb8, 0x00, 0xf8, 0x88, 0xf8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xf8, 0x00, 0xf8, 0x88, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa8, 0xa8,
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x88, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xa8, 0xb8, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa8, 0xa8, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0x00,
0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0x00, 0xe0, 0xe0, 0xe0,
0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00,
0xc0, 0x40, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x09, 0x09, 0x0f, 0x00,
0x0f, 0x09, 0x09, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x04, 0x04, 0x04,
0xf8, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x04, 0x04, 0xfc, 0x04, 0x04, 0x00,
0x00, 0xfc, 0x44, 0x44, 0x44, 0x38, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x04,
0x04, 0xfc, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x24,
0x24, 0x24, 0x00, 0x00, 0x3c, 0xc0, 0x00, 0xc0, 0x3c, 0x00, 0x00, 0xfc, 0x24, 0x24, 0x24, 0x00,
0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01,
0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x22, 0x22, 0x1c,
0x00, 0x7e, 0x4a, 0x4a, 0x42, 0x00, 0x7c, 0x12, 0x12, 0x7c, 0x00, 0x7e, 0x08, 0x08, 0x76, 0x00,
}, {
0x80, /* = width */
0x40, /* = height */
0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xa8, 0xb8, 0x00, 0xf8, 0x88, 0xf8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xf8, 0x00, 0xf8, 0x88, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa8, 0xa8,
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x88, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xa8, 0xb8, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa8, 0xa8, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xc0, 0xc0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0x00,
0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0x00, 0xe0, 0xe0, 0xe0,
0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00,
0xc0, 0x40, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x09, 0x09, 0x0f, 0x00,
0x0f, 0x09, 0x09, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x04, 0x04, 0x04,
0xf8, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x04, 0x04, 0xfc, 0x04, 0x04, 0x00,
0x00, 0xfc, 0x44, 0x44, 0x44, 0x38, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x04,
0x04, 0xfc, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x24,
0x24, 0x24, 0x00, 0x00, 0x3c, 0xc0, 0x00, 0xc0, 0x3c, 0x00, 0x00, 0xfc, 0x24, 0x24, 0x24, 0x00,
0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01,
0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x22, 0x22, 0x1c,
0x00, 0x7e, 0x4a, 0x4a, 0x42, 0x00, 0x7c, 0x12, 0x12, 0x7c, 0x00, 0x7e, 0x08, 0x08, 0x76, 0x00,
}}
var vumeterBackgroundVU = [2][]uint8{{
0x80, /* = width */
0x40, /* = height */
0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xf0, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x50,
0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x50, 0xf0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x78, 0x41, 0x41, 0x41, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x41, 0x40, 0x79, 0x41, 0x41, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x79,
0x41, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x79, 0x01, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x79,
0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x61, 0x79, 0x61, 0x60, 0x60,
0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x61, 0x79, 0x01,
0xc0, 0x4e, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x42, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x02, 0x82, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x42, 0x42, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0xc2, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0xc2, 0x02, 0xc2, 0x42, 0xce, 0x00, 0xc0, 0x40, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x05, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00,
0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x10, 0x2f, 0x50, 0xa0, 0x50, 0x2f, 0x10, 0x0f, 0x00,
0x00, 0x3f, 0x40, 0xbf, 0xa0, 0xa0, 0xa0, 0xbf, 0x40, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x22, 0x22, 0x3e,
0x00, 0x7e, 0x52, 0x52, 0x42, 0x00, 0x7e, 0x12, 0x12, 0x7e, 0x00, 0x7e, 0x08, 0x08, 0x76, 0x00,
}, {
0x80, /* = width */
0x40, /* = height */
0x04, 0x04, 0x1f, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04,
0x50, 0x50, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50,
0x50, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x00, 0xf0, 0x10, 0xf0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xd0, 0x50, 0x70, 0x00, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x79, 0x61, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60,
0x60, 0x60, 0x61, 0x79, 0x61, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60,
0x79, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x01, 0x79, 0x41, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41,
0x79, 0x41, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x60, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x40, 0x79, 0x41, 0x41,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x41, 0x41, 0x41, 0x78, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0xc0, 0x40, 0xce, 0x02, 0xc2, 0x42, 0xc2, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0xc2, 0x42, 0x42, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0xc2, 0x02, 0x82, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x42, 0x42, 0xc2, 0x06, 0xc2, 0x42, 0xc2, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xc2, 0x4e, 0xc0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x07, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x05, 0x05, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x04, 0x07,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00,
0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0xf8, 0x04, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x10, 0x2f, 0x50, 0xa0, 0x50, 0x2f, 0x10, 0x0f, 0x00,
0x00, 0x3f, 0x40, 0xbf, 0xa0, 0xa0, 0xa0, 0xbf, 0x40, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x7e, 0x22, 0x22, 0x3e, 0x00, 0x7e, 0x52, 0x52, 0x42, 0x00, 0x7e, 0x12, 0x12, 0x7e, 0x00,
0x7e, 0x08, 0x08, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}}
+67
View File
@@ -0,0 +1,67 @@
package app
import (
"image"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/display"
)
type Layout interface {
String() string
// Widgets used by this screen.
Widgets() []Widget
}
type Context interface {
// Display is the display driver.
Display() display.Display
// Player is the music player.
Player() player.Player
// Track is the current track playing.
Track() *player.Track
}
type Widget interface {
String() string
// Bounds is the bounding box.
Bounds() image.Rectangle
// Move the drawable to a new position on the screen.
Move(image.Point) Widget
// Resize changes the widget's size.
Resize(image.Point) Widget
// Hide the drawable.
Hide(Context) Widget
// Show the drawable.
Show(Context) Widget
// IsVisible checks if the drawable is visible.
IsVisible() bool
Refresh(Context) Widget
}
type RotaryInputHandler interface {
HandleRotary(delta int)
}
type ButtonInputHandler interface {
HandleButtonPress()
HandleButtonLongPress()
}
type StatusChangeHandler interface {
StatusChanged(*player.Status)
}
type TrackChangeHandler interface {
TrackChanged(*player.Track)
}
+76
View File
@@ -0,0 +1,76 @@
package app
import (
"image"
"image/color"
"image/draw"
"github.com/BeatGlow/display/pixel"
)
// BufferFor creates a new image buffer for the provided display matching its color model.
func BufferFor(ctx Context, size image.Point) draw.Image {
switch ctx.Display().ColorModel() {
case pixel.MonoModel:
return pixel.NewMonoImage(size.X, size.Y)
case pixel.Gray2Model:
return pixel.NewGray2Image(size.X, size.Y)
case pixel.Gray4Model:
return pixel.NewGray4Image(size.X, size.Y)
case pixel.CRGB15Model:
return pixel.NewCRGB15Image(size.X, size.Y)
case pixel.CRGB16Model:
return pixel.NewCRGB16Image(size.X, size.Y)
default:
return nil
}
}
type clearer interface {
Clear()
}
// ImageCopy copies an image over dst.
func ImageCopy(dst draw.Image, src image.Image) {
draw.Draw(dst, dst.Bounds(), src, image.Point{}, draw.Src)
}
// ImageCopyBounds copies an image over dst bounded by r.
func ImageCopyBounds(dst draw.Image, src image.Image, r image.Rectangle) {
draw.Draw(dst, r, src, image.Point{}, draw.Src)
}
// Clear an image.
func ImageClear(dst draw.Image) {
if c, ok := dst.(clearer); ok {
c.Clear()
return
}
ImageFill(dst, color.Black)
}
type filler interface {
Fill(color.Color)
}
// Fill an imagre with a single color.
func ImageFill(dst draw.Image, c color.Color) {
if f, ok := dst.(filler); ok {
f.Fill(c)
return
}
var src image.Image
switch c {
case color.Black:
src = image.Black
case color.White:
src = image.White
case color.Transparent:
src = image.Transparent
default:
src = image.NewUniform(c)
}
draw.Draw(dst, dst.Bounds(), src, image.Point{}, draw.Src)
}
+87
View File
@@ -0,0 +1,87 @@
package layout
import (
"fmt"
"image"
"strings"
"time"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/widget"
"github.com/BeatGlow/beatglow/player"
)
const (
formatTextPlaceholder = "None"
durationTextPlaceholder = "--:-- / --:--"
trackTextPlaceholder = "No track playing..."
)
type playing struct {
formatText string
formatWidget *widget.Text
durationText string
durationWidget *widget.Text
trackText string
trackWidget *widget.Text
artWidget *widget.Image
}
func Playing(ctx app.Context) app.Layout {
bounds := ctx.Display().Bounds()
layout := &playing{
formatText: formatTextPlaceholder,
formatWidget: widget.NewText(image.Pt(2+len(formatTextPlaceholder)*8, 12)),
durationText: durationTextPlaceholder,
durationWidget: widget.NewText(image.Pt(2+len(durationTextPlaceholder)*8, 12)),
trackText: trackTextPlaceholder,
trackWidget: widget.NewText(image.Pt(bounds.Dx()-bounds.Dy(), bounds.Dy()-12-16)),
artWidget: widget.NewImage(image.Pt(bounds.Dy(), bounds.Dy())),
}
layout.formatWidget.
Bind(&layout.formatText).
Move(image.Pt(0, 0))
layout.durationWidget.
Bind(&layout.durationText).
Move(layout.formatWidget.Bounds().Min.Add(image.Pt(8, 0)))
layout.trackWidget.
Bind(&layout.trackText).
Move(image.Pt(0, 12))
layout.artWidget.
Move(image.Pt(bounds.Dx()-bounds.Dy(), 0))
return layout
}
func (playing) String() string {
return "playing"
}
func (layout *playing) Widgets() []app.Widget {
return []app.Widget{
layout.formatWidget,
layout.durationWidget,
layout.trackWidget,
layout.artWidget,
}
}
func (layout *playing) TrackChanged(track *player.Track) {
if track == nil {
layout.formatText = formatTextPlaceholder
layout.durationText = durationTextPlaceholder
layout.trackText = trackTextPlaceholder
} else {
layout.trackText = track.Artist + " - " + track.Title
layout.formatText = strings.ToUpper(track.Format)
layout.durationText = fmt.Sprintf("00:00 / %s", formatDuration(track.Duration))
}
}
func formatDuration(d time.Duration) string {
h := int(d / time.Hour)
d -= time.Duration(h) * time.Hour
m := int(d / time.Minute)
return fmt.Sprintf("%02d:%02d", h, m)
}
+264
View File
@@ -0,0 +1,264 @@
package app
import (
"image"
"image/color"
"image/draw"
"github.com/BeatGlow/beatglow/ui/font"
"github.com/BeatGlow/display/pixel"
)
var (
// DefaultTheme is the default theme per color model.
DefaultTheme = &Theme{
Mono: &defaultMonoThemeStyles,
Gray: &defaultGrayThemeStyles,
Color: &defaultColorThemeStyles,
}
// UserTheme can be set to override styles.
UserTheme *Theme
)
var (
defaultMonoObjectStyle = ObjectStyle{
BackgroundColor: pixel.Off,
ForegroundColor: pixel.On,
BorderColor: pixel.On,
}
defaultMonoThemeStyles = Styles{
Window: defaultMonoObjectStyle,
Progress: defaultMonoObjectStyle.WithBorder(1),
Image: defaultMonoObjectStyle,
Graph: defaultMonoObjectStyle,
Text: TextStyle{
ObjectStyle: defaultMonoObjectStyle.WithMargin(1),
Font: font.SmoochSans,
},
}
defaultGrayObjectStyle = ObjectStyle{
Background: image.Black,
ForegroundColor: color.White,
BorderColor: color.Gray{Y: 0x7F},
}
defaultGrayThemeStyles = Styles{
Window: defaultGrayObjectStyle,
Progress: defaultGrayObjectStyle.WithBorder(1),
Image: defaultGrayObjectStyle,
Graph: defaultGrayObjectStyle,
Text: TextStyle{
ObjectStyle: defaultGrayObjectStyle.WithMargin(1),
Font: font.SmoochSans,
},
}
defaultColorObjectStyle = ObjectStyle{
BackgroundColor: color.RGBA{R: 0xB0, G: 0x26, B: 0xFF, A: 0xFF},
ForegroundColor: color.RGBA{R: 0x01, G: 0xFB, B: 0xC1, A: 0xFF},
BorderColor: color.RGBA{R: 0x1D, G: 0xEA, B: 0xA1, A: 0xFF},
}
defaultColorThemeStyles = Styles{
Window: defaultColorObjectStyle,
Progress: defaultColorObjectStyle.WithBorder(1).Inverse(),
Image: defaultColorObjectStyle,
Graph: defaultColorObjectStyle,
Text: TextStyle{
ObjectStyle: defaultColorObjectStyle.WithMargin(1),
Font: font.SmoochSans,
},
}
)
type Theme struct {
Mono *Styles
Gray *Styles
Color *Styles
}
type Styles struct {
Window ObjectStyle
Progress ObjectStyle
Text TextStyle
Image ObjectStyle
Graph ObjectStyle
}
func StylesFor(ctx Context) *Styles {
theme := UserTheme
if theme == nil {
// Use the default theme.
theme = DefaultTheme
} else {
// Make sure all color models have a theme defined.
if theme.Mono == nil {
theme.Mono = DefaultTheme.Mono
}
if theme.Gray == nil {
theme.Gray = DefaultTheme.Gray
}
if theme.Color == nil {
theme.Color = DefaultTheme.Color
}
}
model := ctx.Display().ColorModel()
switch model {
case pixel.MonoModel:
return theme.Mono
case pixel.Gray2Model, pixel.Gray4Model, color.GrayModel, color.Gray16Model:
return theme.Gray
default:
return theme.Color
}
}
type ObjectStyle struct {
// Background image or color.
Background image.Image
BackgroundColor color.Color
// Foreground image (mask) or color.
Foreground image.Image
ForegroundColor color.Color
// Margin around the object.
Margin Edge
// Padding inside the object.
Padding Edge
// Border around the object.
Border Edge
BorderColor color.Color
// Stroke size for lines etc.
Stroke int
}
func (s ObjectStyle) Inverse() ObjectStyle {
i := new(ObjectStyle)
*i = s
i.Background, i.Foreground = i.Foreground, i.Background
i.BackgroundColor, i.ForegroundColor = i.ForegroundColor, i.BackgroundColor
return *i
}
func (s ObjectStyle) WithBorder(size ...int) ObjectStyle {
i := new(ObjectStyle)
*i = s
switch len(size) {
case 0:
return s
case 1:
i.Border = Edge{size[0], size[0], size[0], size[0]}
case 2:
i.Border = Edge{size[0], size[0], size[1], size[1]}
case 3:
i.Border = Edge{size[0], size[1], size[2], size[2]}
default:
i.Border = Edge{size[0], size[1], size[2], size[3]}
}
return *i
}
func (s ObjectStyle) WithMargin(size ...int) ObjectStyle {
i := new(ObjectStyle)
*i = s
switch len(size) {
case 0:
return s
case 1:
i.Margin = Edge{size[0], size[0], size[0], size[0]}
case 2:
i.Margin = Edge{size[0], size[0], size[1], size[1]}
case 3:
i.Margin = Edge{size[0], size[1], size[2], size[2]}
default:
i.Margin = Edge{size[0], size[1], size[2], size[3]}
}
return *i
}
func (s ObjectStyle) WithPadding(size ...int) ObjectStyle {
i := new(ObjectStyle)
*i = s
switch len(size) {
case 0:
return s
case 1:
i.Padding = Edge{size[0], size[0], size[0], size[0]}
case 2:
i.Padding = Edge{size[0], size[0], size[1], size[1]}
case 3:
i.Padding = Edge{size[0], size[1], size[2], size[2]}
default:
i.Padding = Edge{size[0], size[1], size[2], size[3]}
}
return *i
}
// boundedImage translates (x, y) coorindates to coordinats relative to View.Min; if
// writes are outside of View, they are ignored.
type boundedImage struct {
draw.Image
View image.Rectangle
}
func (i boundedImage) At(x, y int) color.Color {
if !(image.Point{X: x, Y: y}).In(i.View.Sub(i.View.Min)) {
return color.Transparent
}
return i.Image.At(x+i.View.Min.X, y+i.View.Min.Y)
}
func (i boundedImage) Set(x, y int, c color.Color) {
if !(image.Point{X: x, Y: y}).In(i.View.Sub(i.View.Min)) {
return
}
i.Image.Set(x+i.View.Min.X, y+i.View.Min.Y, c)
}
func (i boundedImage) Bounds() image.Rectangle {
return i.View
}
// Outer returns an image that draws into i's outer region (inside the border).
func (s ObjectStyle) Outer(i draw.Image) draw.Image {
bounds := i.Bounds()
bounds.Min.X += s.Margin.Left + s.Border.Left
bounds.Min.Y += s.Margin.Top + s.Border.Top
bounds.Max.X -= s.Margin.Right + s.Border.Right
bounds.Max.Y -= s.Margin.Bottom + s.Border.Bottom
return boundedImage{i, bounds}
}
// Inner returns an image that draws into i's inner region.
func (s ObjectStyle) Inner(i draw.Image) draw.Image {
bounded := s.Outer(i).(boundedImage)
bounded.View.Min.X += s.Padding.Left
bounded.View.Min.Y += s.Padding.Top
bounded.View.Max.X -= s.Padding.Right
bounded.View.Max.Y -= s.Padding.Bottom
return bounded
}
type TextStyle struct {
ObjectStyle
Font *font.Font
}
type Edge struct {
Left int
Right int
Top int
Bottom int
}
func (edge Edge) Size() image.Point {
return image.Point{
X: edge.Left + edge.Right,
Y: edge.Top + edge.Bottom,
}
}
+126
View File
@@ -0,0 +1,126 @@
package widget
import (
"image"
"sync"
"sync/atomic"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/draw"
"github.com/BeatGlow/beatglow/internal/safe"
)
type Base struct {
bounds safe.Rectangle
widget atomic.Pointer[app.Widget]
mu sync.RWMutex
buffer draw.Image
hidden bool
styles app.Styles
changed atomic.Bool
}
func (b *Base) Extend(w app.Widget) {
if widget := b.widget.Load(); widget != nil {
return
}
b.widget.Store(&w)
b.changed.Store(true)
}
func (b *Base) super() app.Widget {
if widget := b.widget.Load(); widget != nil {
return *widget
}
return nil
}
func (b *Base) Bounds() image.Rectangle {
return b.bounds.Load()
}
func (b *Base) Move(p image.Point) app.Widget {
bounds := b.bounds.Load()
b.bounds.Store(image.Rectangle{
Min: p,
Max: bounds.Size(),
})
return b.super()
}
func (b *Base) Resize(size image.Point) app.Widget {
bounds := b.bounds.Load()
bounds.Max = bounds.Min.Add(size)
b.bounds.Store(bounds)
return b.super()
}
func (b *Base) Hide(ctx app.Context) app.Widget {
if !b.IsVisible() {
return b.super()
}
b.mu.Lock()
b.hidden = true
b.mu.Unlock()
b.changed.Store(true)
if widget := b.super(); widget != nil {
widget.Refresh(ctx)
}
return b.super()
}
func (b *Base) Show(ctx app.Context) app.Widget {
if b.IsVisible() {
return b.super()
}
b.mu.Lock()
b.hidden = false
b.mu.Unlock()
b.changed.Store(true)
if widget := b.super(); widget != nil {
widget.Refresh(ctx)
}
return b.super()
}
func (b *Base) IsVisible() bool {
b.mu.RLock()
visible := !b.hidden
b.mu.RUnlock()
return visible
}
func (b *Base) Styles() app.Styles {
b.mu.RLock()
styles := b.styles
b.mu.RUnlock()
return styles
}
func (b *Base) SetStyles(styles app.Styles) app.Widget {
b.mu.Lock()
b.styles = styles
b.mu.Unlock()
b.changed.Store(true)
return b.super()
}
func (b *Base) Render(ctx app.Context) app.Widget {
if !b.changed.CompareAndSwap(true, false) {
return b.super()
}
if b.buffer == nil {
b.buffer = app.BufferFor(ctx, b.Bounds().Size())
}
return b.super()
}
+49
View File
@@ -0,0 +1,49 @@
package widget
import (
"image"
"github.com/BeatGlow/beatglow/app"
)
type Image struct {
Base
image image.Image
}
func NewImage(size image.Point) *Image {
w := new(Image)
w.Extend(w)
w.Resize(size)
return w
}
func (w *Image) String() string {
return "image:" + w.image.Bounds().String()
}
func (w *Image) Update(image image.Image) app.Widget {
w.mu.Lock()
w.image = image
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Image) Refresh(ctx app.Context) app.Widget {
if !w.IsVisible() {
return w
}
if !w.changed.CompareAndSwap(true, false) {
return w
}
w.mu.RLock()
app.ImageCopyBounds(ctx.Display(), w.image, w.Bounds())
w.mu.RUnlock()
return w
}
var _ app.Widget = (*Image)(nil)
+70
View File
@@ -0,0 +1,70 @@
package widget
import (
"image"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/display/draw"
)
type Object struct {
active bool
width int
height int
pos image.Point
style app.ObjectStyle
canvas draw.Image
changed bool
}
func MakeObject(ctx app.Context, position image.Point, width, height int, style app.ObjectStyle) Object {
return Object{
width: width,
height: height,
pos: position,
style: style,
canvas: app.BufferFor(ctx, width, height),
changed: true,
}
}
func (w *Object) Bounds() image.Rectangle {
return image.Rect(0, 0, w.width, w.height)
}
func (w *Object) Position() image.Point {
return w.pos
}
func (w *Object) IsActive() bool {
return w.active
}
func (w *Object) Render() draw.Image {
if w.changed {
// Clear entire buffer.
app.ImageClear(w.canvas)
var (
bounds = w.canvas.Bounds()
outer = w.style.Outer(w.canvas)
)
// Background draws into outer region.
if w.style.Background != nil {
app.ImageCopy(outer, w.style.Background)
} else {
app.ImageFill(outer, w.style.BackgroundColor)
}
// Draw border
draw.Box(w.canvas, image.Rect(0, 0, bounds.Max.X, w.style.Border.Top), w.style.BorderColor)
draw.Box(w.canvas, image.Rect(0, bounds.Max.Y-w.style.Border.Bottom, bounds.Max.X, bounds.Max.Y), w.style.BorderColor)
draw.Box(w.canvas, image.Rect(0, 0, w.style.Border.Left, bounds.Max.Y), w.style.BorderColor)
draw.Box(w.canvas, image.Rect(bounds.Max.X-w.style.Border.Right, 0, bounds.Max.X, bounds.Max.Y), w.style.BorderColor)
// After redrawing mark the object as unchanged.
w.changed = false
}
return w.canvas
}
+109
View File
@@ -0,0 +1,109 @@
package widget
import (
"fmt"
"image"
"github.com/BeatGlow/beatglow/app"
)
type Text struct {
Base
text string
bind *string
}
func NewText(size image.Point) *Text {
w := new(Text)
w.Extend(w)
w.Resize(size)
return w
}
func (w *Text) String() string {
if w.bind != nil {
return fmt.Sprintf("text:%p", w.bind)
}
return fmt.Sprintf("text:%q", w.text)
}
func (w *Text) SetStyle(style app.TextStyle) app.Widget {
styles := w.Styles()
styles.Text = style
_ = w.SetStyles(styles)
return w
}
func (w *Text) Bind(text *string) app.Widget {
w.mu.Lock()
w.text = "--- intentionally set to garbage ---"
w.bind = text
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Text) Update(text string) app.Widget {
w.mu.Lock()
w.text = text
w.bind = nil
w.mu.Unlock()
width, height := w.styles.Text.Font.MeasureText(w.text)
bounds := w.bounds.Load()
bounds.Max = bounds.Min.Add(image.Pt(width, height))
w.bounds.Store(bounds)
w.changed.Store(true)
return w
}
func (w *Text) Refresh(ctx app.Context) app.Widget {
if !w.IsVisible() {
return w
}
if !w.changed.CompareAndSwap(true, false) {
// Only bail if our bound value hasn't changed.
if w.bind == nil || (w.text == *w.bind) {
return w
}
}
var (
resize bool
bounds image.Rectangle
)
if w.bind != nil {
w.text = *w.bind
}
width, height := w.styles.Text.Font.MeasureText(w.text)
bounds = w.bounds.Load()
size := bounds.Size()
if resize = (size.X != width || size.Y != height); resize {
bounds.Max = bounds.Min.Add(image.Pt(width, height))
}
if w.buffer == nil || !resize {
w.buffer = app.BufferFor(ctx, bounds.Size())
}
if w.styles.Text.Background != nil {
app.ImageCopy(w.buffer, w.styles.Text.Background)
} else {
app.ImageFill(w.buffer, w.styles.Text.BackgroundColor)
}
inner := w.styles.Text.Inner(w.buffer)
if w.styles.Text.Foreground != nil {
w.styles.Text.Font.Draw(inner, image.Point{}, w.styles.Text.Foreground, w.text)
} else {
w.styles.Text.Font.Draw(inner, image.Point{}, image.NewUniform(w.styles.Text.ForegroundColor), w.text)
}
app.ImageCopyBounds(ctx.Display(), w.buffer, w.Bounds())
return w
}
var _ app.Widget = (*Text)(nil)
@@ -9,8 +9,8 @@ import (
) )
const ( const (
configFileBase = "harmon.conf" configFileBase = "beatglow.conf"
configFileBaseAlt = "harmon.cfg" configFileBaseAlt = "beatglow.cfg"
) )
func findConfigFile() string { func findConfigFile() string {
+20
View File
@@ -0,0 +1,20 @@
package main
import (
"context"
"github.com/urfave/cli/v3"
)
var installCommand = &cli.Command{
Name: "install",
Usage: "Install BeatGlow for your local player",
Action: installFunc,
Flags: []cli.Flag{
&cli.StringFlag{Name: "player", Usage: "Player type", Value: "auto"},
},
}
func installFunc(ctx context.Context, cmd *cli.Command) error {
return nil
}
+6 -6
View File
@@ -9,17 +9,16 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
"go.maze.io/harmon" harmon "github.com/BeatGlow/beatglow"
"go.maze.io/harmon/config" "github.com/BeatGlow/beatglow/config"
_ "go.maze.io/harmon/hardware/display/all" // Display drivers _ "github.com/BeatGlow/beatglow/player/all" // Player drivers
_ "go.maze.io/harmon/player/all" // Player drivers
) )
func main() { func main() {
cmd := &cli.Command{ cmd := &cli.Command{
Name: "harmon", Name: "beatglow",
Usage: "Harmon is a playful music player frontend", Usage: "BeatGlow is a playful music player frontend",
Action: runFunc, Action: runFunc,
Flags: []cli.Flag{ Flags: []cli.Flag{
&cli.StringFlag{Name: "config", Usage: "configuration file path"}, &cli.StringFlag{Name: "config", Usage: "configuration file path"},
@@ -28,6 +27,7 @@ func main() {
}, },
Commands: []*cli.Command{ Commands: []*cli.Command{
scanCommand, scanCommand,
installCommand,
}, },
} }
File renamed without changes.
+28
View File
@@ -0,0 +1,28 @@
package main
import (
"periph.io/x/host/v3"
"github.com/BeatGlow/BeatGlow/config"
"github.com/BeatGlow/BeatGlow/hardware"
"github.com/BeatGlow/BeatGlow/ui"
)
func main() {
if _, err := host.Init(); err != nil {
panic(err)
}
output, err := hardware.Display(&config.DisplayConfig{
Mode: "SPI",
Type: "SSD1322",
Reset: "GPIO25",
DC: "GPIO24",
})
if err != nil {
panic(err)
}
if err = ui.Boot(output); err != nil {
panic(err)
}
}
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"fmt"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/beatglow/player/mpd"
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetLevel(logrus.TraceLevel)
p, err := mpd.New("localhost:6600", "")
if err != nil {
panic(err)
}
defer p.Halt()
events, err := p.Events()
if err != nil {
panic(err)
}
for event := range events {
fmt.Println("event: ", event)
switch event.(type) {
case player.ConnectedEvent:
fmt.Println("connected, requesting playlist...")
tracks, err := p.Playlist()
if err != nil {
panic(err)
}
fmt.Printf("%d tracks:\n", len(tracks))
for _, track := range tracks {
fmt.Println(" ", track.ID, track)
}
return
}
}
}
+43 -7
View File
@@ -1,12 +1,16 @@
// Package config contains the configuration structure and parser. // Package config contains the configuration structure and parser.
package config package config
import "image"
// Config structure. // Config structure.
type Config struct { type Config struct {
Display Display `hcl:"display,block"` Display Display `hcl:"display,block"`
Input Input `hcl:"input,block"` Input Input `hcl:"input,block"`
Audio Audio `hcl:"audio,block"` Audio Audio `hcl:"audio,block"`
Mixer Mixer `hcl:"mixer,block"`
Player Player `hcl:"player,block"` Player Player `hcl:"player,block"`
Screen Screen `hcl:"screen,block"`
} }
// Display configuration for OLED and TFT screens. // Display configuration for OLED and TFT screens.
@@ -15,7 +19,7 @@ type Display struct {
Main *DisplayConfig `hcl:"main,block"` Main *DisplayConfig `hcl:"main,block"`
Left *DisplayConfig `hcl:"left,block"` Left *DisplayConfig `hcl:"left,block"`
Right *DisplayConfig `hcl:"right,block"` Right *DisplayConfig `hcl:"right,block"`
Color *DisplayConfig `hcl:"color,block"` Meta *DisplayConfig `hcl:"meta,block"`
} }
// DisplayConfig is the configuration for one display. // DisplayConfig is the configuration for one display.
@@ -84,12 +88,19 @@ type Encoder struct {
// Audio source provides PCM samples. // Audio source provides PCM samples.
type Audio struct { type Audio struct {
Type string `hcl:"type"` Type string `hcl:"type"`
Path string `hcl:"path,optional"` Path string `hcl:"path,optional"`
Host string `hcl:"host,optional"` Host string `hcl:"host,optional"`
Rate float64 `hcl:"rate,optional"` Rate int `hcl:"rate,optional"`
Channels int `hcl:"channels,optional"` Channels int `hcl:"channels,optional"`
Bits int `hcl:"bits,optional"` Bits int `hcl:"bits,optional"`
BigEndian bool `hcl:"be,optional"`
Delay string `hcl:"delay,optional"`
}
type Mixer struct {
Type string `hcl:"type"`
Card int `hcl:"card,optional"`
} }
// Player controls the audio. // Player controls the audio.
@@ -98,3 +109,28 @@ type Player struct {
Host string `hcl:"host,optional"` Host string `hcl:"host,optional"`
Password string `hcl:"password,optional"` Password string `hcl:"password,optional"`
} }
type Screen struct {
Playing *ScreenPlaying `hcl:"playing,block"`
Spectrum *ScreenSpectrum `hcl:"spectrum,block"`
VUMeter *ScreenVUMeter `hcl:"vumeter,block"`
}
type ScreenPlaying struct {
Track *Style `hcl:"track,block"`
Format *Style `hcl:"format,block"`
Spectrum *ScreenSpectrum `hcl:"spectrum,block"`
}
type ScreenSpectrum struct {
Style *Style `hcl:"style"`
MinFrequency int `hcl:"min,optional"`
MaxFrequency int `hcl:"max,optional"`
Hold int `hcl:"hold,optional"`
Window string `hcl:"window,optional"`
Waterfall bool `hcl:"waterfall,optional"`
Move image.Point
}
type ScreenVUMeter struct {
Style *Style `hcl:"style"`
}
+77
View File
@@ -0,0 +1,77 @@
package config
import (
"image/color"
"strings"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/font"
"github.com/mazznoer/csscolorparser"
"github.com/sirupsen/logrus"
)
type Style struct {
Color string `hcl:"color,optional"`
Font string `hcl:"font,optional"`
FontSize float64 `hcl:"font_size,optional"`
Hinting string `hcl:"hinting,optional"`
DPI float64 `hcl:"dpi,optional"`
}
// Apply styles; errors are logged but don't override styles, so we don't break visuals.
func (s Style) Apply(style *ui.Style) {
if s.Color != "" {
c, err := csscolorparser.Parse(s.Color)
if err != nil {
logrus.WithError(err).WithField("color", s.Color).Warn("invalid color name")
} else {
r, g, b, a := c.RGBA255()
style.Foreground = color.RGBA{r, g, b, a}
}
}
if s.Font != "" {
switch s.Font {
case "monteserrat":
style.Font = font.Montserrat
case "monaco":
style.Font = font.Monaco
case "mairy":
style.Font = font.MairyBlackItalic
case "microgrotesk":
style.Font = font.MicroGrotesk
default:
f, err := font.New(s.Font)
if err != nil {
logrus.WithError(err).WithField("font", s.Font).Warn("font failed to load")
} else {
attr := style.Font.Attr()
style.Font = f
style.Font.SetDPI(attr.DPI)
style.Font.SetHinting(attr.Hinting)
style.Font.SetLineSpacing(attr.LineSpacing)
style.Font.SetPointSize(attr.PointSize)
}
}
}
if s.FontSize > 0 {
style.Font.SetPointSize(s.FontSize)
}
if s.DPI > 0 {
style.Font.SetDPI(s.DPI)
}
switch strings.ToLower(s.Hinting) {
case "": // use default
case "none", "no", "false":
style.Font.SetHinting(font.HintingNone)
case "vertical":
style.Font.SetHinting(font.HintingVertical)
case "full", "yes":
style.Font.SetHinting(font.HintingFull)
default:
logrus.WithField("hinting", s.Hinting).Warn("font hinting invalid")
}
}
+13
View File
@@ -0,0 +1,13 @@
package context
import "github.com/BeatGlow/beatglow/player"
// Context for screens.
type Context interface {
// Contrast returns the current contrast level.
Contrast() uint8
SetContrast(uint8)
// Player is our current player.
Player() player.Player
}
+349 -132
View File
@@ -1,4 +1,4 @@
package harmon package beatglow
import ( import (
"context" "context"
@@ -10,50 +10,64 @@ import (
"time" "time"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"periph.io/x/conn/v3/physic"
"periph.io/x/host/v3" "periph.io/x/host/v3"
"go.maze.io/harmon/audio" "github.com/BeatGlow/audio"
"go.maze.io/harmon/config" "github.com/BeatGlow/beatglow/config"
"go.maze.io/harmon/hardware" "github.com/BeatGlow/beatglow/hardware"
"go.maze.io/harmon/hardware/display" "github.com/BeatGlow/beatglow/hardware/input"
"go.maze.io/harmon/internal/pixel" "github.com/BeatGlow/beatglow/player"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/sound"
"go.maze.io/harmon/visual" "github.com/BeatGlow/beatglow/ui"
"go.maze.io/harmon/visual/screensaver" "github.com/BeatGlow/beatglow/ui/screen"
"github.com/BeatGlow/display"
) )
const defaultFPS = 20 const defaultFPS = 20
type Controller struct { type Controller struct {
// Left, right and color displays. // Main and meta display.
Main hardware.Display Main display.Display
Left hardware.Display Full display.Display
Right hardware.Display Meta display.Display
Color hardware.Display
// Player. // Player.
Player player.Player Player player.Player
AlbumArt player.AlbumArt AlbumArt player.AlbumArt
// Audio source. // Audio source.
Audio audio.Stream Audio sound.Source
// Stream of audio samples. // Inputs.
Stream audio.Stream encoder input.Encoder
// Visual effects. // Volume level.
visual struct { volume int
current visual.Visual
offline *visual.Offline // Observers
screensaver *screensaver.Stars observe struct {
vumeterLeft *visual.VUMeter track *player.Track
vumeterRight *visual.VUMeter trackChanged []player.TrackObserver
status *player.Status
statusChanged []player.StatusObserver
} }
fps time.Duration // Screens.
connected bool screen struct {
playing bool priority ui.Screen
priorityUntil time.Time
active ui.Screen
boot ui.Screen
playing ui.Screen
volume ui.Screen
stereoSpectrum ui.Screen
stereoWaterfall ui.Screen
carousel []ui.Screen
carouselIndex uint
}
fps time.Duration
state *State
} }
func NewController(config *config.Config) (*Controller, error) { func NewController(config *config.Config) (*Controller, error) {
@@ -73,12 +87,15 @@ func NewController(config *config.Config) (*Controller, error) {
log.WithField("driver", driver.String()).Debug("host driver loaded") log.WithField("driver", driver.String()).Debug("host driver loaded")
} }
c := &Controller{} c := &Controller{
state: new(State),
volume: -1,
}
if err = c.loadAudio(config.Audio); err != nil { if err = c.loadAudio(config.Audio); err != nil {
c.teardown() c.teardown()
return nil, err return nil, err
} }
if err = c.loadDisplays(config.Display); err != nil { if err = c.loadDisplays(config.Display, config.Screen); err != nil {
c.teardown() c.teardown()
return nil, err return nil, err
} }
@@ -107,19 +124,25 @@ func (c *Controller) loadPlayer(config config.Player) (err error) {
c.log().Warn("player doesn't support album art... sad :-(") c.log().Warn("player doesn't support album art... sad :-(")
} }
} }
c.screen.volume = screen.Volume(c.Player, c.Main)
c.observer(c.screen.volume)
return return
} }
func (c *Controller) loadAudio(config config.Audio) (err error) { func (c *Controller) loadAudio(config config.Audio) (err error) {
c.Audio, err = audio.New(config) if c.Audio, err = sound.New(config); err != nil {
return
}
return return
} }
func (c *Controller) loadDisplays(config config.Display) (err error) { func (c *Controller) loadDisplays(displayConfig config.Display, screenConfig config.Screen) (err error) {
log := c.log() log := c.log()
if c.fps = time.Second / time.Duration(config.FPS); c.fps <= 0 { if c.fps = time.Second / time.Duration(displayConfig.FPS); c.fps <= 0 {
config.FPS = defaultFPS displayConfig.FPS = defaultFPS
log.WithFields(logrus.Fields{ log.WithFields(logrus.Fields{
"fps": defaultFPS, "fps": defaultFPS,
"rate": c.fps, "rate": c.fps,
@@ -127,74 +150,118 @@ func (c *Controller) loadDisplays(config config.Display) (err error) {
c.fps = time.Second / defaultFPS c.fps = time.Second / defaultFPS
} else { } else {
log.WithFields(logrus.Fields{ log.WithFields(logrus.Fields{
"fps": config.FPS, "fps": displayConfig.FPS,
"rate": c.fps, "rate": c.fps,
}).Debug("setting frame rate") }).Debug("setting frame rate")
} }
if config.Main != nil { if displayConfig.Main != nil {
if c.Main, err = display.Load(*config.Main); err != nil { // Single display
if c.Main, err = hardware.Display(displayConfig.Main); err != nil {
return fmt.Errorf("error loading main display driver: %w", err) return fmt.Errorf("error loading main display driver: %w", err)
} }
size := c.Main.Size()
c.Left = display.MakeView(c.Main, image.Rect(0, 0, size.X/2, size.Y)) } else if displayConfig.Left == nil {
c.Right = display.MakeView(c.Main, image.Rect(size.X/2, 0, size.X, size.Y))
} else if config.Left == nil {
return errors.New("missing main or left block in display configuration") return errors.New("missing main or left block in display configuration")
} else if config.Right == nil {
} else if displayConfig.Right == nil {
return errors.New("missing main or right block in display configuration") return errors.New("missing main or right block in display configuration")
} else { } else {
if c.Left, err = display.Load(*config.Left); err != nil { // Dual displays
var left, right display.Display
if left, err = hardware.Display(displayConfig.Left); err != nil {
return fmt.Errorf("error loading left display driver: %w", err) return fmt.Errorf("error loading left display driver: %w", err)
} else if err = c.Left.Fill(pixel.On); err != nil { } else if err = left.Refresh(); err != nil {
return err return err
} }
if c.Right, err = display.Load(*config.Right); err != nil { if right, err = hardware.Display(displayConfig.Right); err != nil {
return fmt.Errorf("error loading right display driver: %w", err) return fmt.Errorf("error loading right display driver: %w", err)
} else if err = c.Right.Fill(pixel.Off); err != nil { } else if err = right.Refresh(); err != nil {
return err return err
} }
c.Main = display.NewCombined(c.Left, c.Right)
// Merge into virtual display
c.Main = hardware.NewCombined(left, right)
} }
/*
if c.Color, err = display.Load(config.Color); err != nil { var (
return fmt.Errorf("error loading color display driver: %w", err) bounds = c.Main.Bounds()
} else if err = c.Color.Fill(pixel.Off); err != nil { size = bounds.Size()
left34 = image.Rect(0, 0, (size.X/4)*3, size.Y)
right14 = image.Rect((size.X/4)*3, 0, size.X, size.Y)
)
c.Full = c.Main
if displayConfig.Meta == nil {
// Split the screen
c.Meta = hardware.MakeView(c.Main, right14)
c.Main = hardware.MakeView(c.Main, left34)
} else {
if c.Meta, err = hardware.Display(displayConfig.Meta); err != nil {
return fmt.Errorf("error loading meta display driver: %w", err)
} else if err = c.Meta.Refresh(); err != nil {
return err return err
} }
*/ }
log.WithField("type", c.Main.Type()).Info("configured main display") log.WithField("type", c.Main).Info("configured main display")
log.WithField("type", c.Left.Type()).Info("configured left display") log.WithField("type", c.Meta).Info("configured meta display")
log.WithField("type", c.Right.Type()).Info("configured right display")
rate := c.Audio.SampleRate() / physic.Frequency(config.FPS) // Load screens and observers
c.visual.screensaver = screensaver.NewStars(c.Main, 12) spectrumConfig := new(config.ScreenSpectrum)
c.visual.offline = visual.NewOffline(c.Left, c.Right, nil) waterfallConfig := new(config.ScreenSpectrum)
c.visual.vumeterLeft = visual.NewVUMeter(c.Left, rate, 1, c.Audio.Channels()) if screenConfig.Spectrum != nil {
c.visual.vumeterRight = visual.NewVUMeter(c.Right, rate, 2, c.Audio.Channels()) *spectrumConfig = *screenConfig.Spectrum
*waterfallConfig = *screenConfig.Spectrum
}
spectrumConfig.Waterfall = false
waterfallConfig.Waterfall = true
// Splash screen c.screen.boot = screen.Boot(c.Full)
/* c.screen.playing = screen.Playing(c.Main, c.Meta, screenConfig.Playing)
if err = display.DrawImage(c.Color, 40, 40, "harmon.png"); err != nil { c.screen.stereoSpectrum = screen.StereoSpectrum(c.Full, spectrumConfig)
return fmt.Errorf("error loading splash screen: %w", err) c.screen.stereoWaterfall = screen.StereoSpectrum(c.Full, waterfallConfig)
} c.observer(c.screen.playing)
display.DrawText(c.Color, 1, 1, display.Font8x16, "Harmon") c.observer(c.screen.stereoSpectrum)
for y := 0; y < 240; y++ { c.observer(c.screen.stereoWaterfall)
for x := 0; x < 240; x++ {
c.Color.Set(x, y, randomColor()) // Set active screen.
} c.screen.active = c.screen.playing
} c.screen.playing.SetVisible(true)
if err = c.Color.Refresh(); err != nil {
return err // Available screens for carousel.
} c.screen.carousel = []ui.Screen{
*/ c.screen.playing,
c.screen.stereoSpectrum,
c.screen.stereoWaterfall,
}
// Set priority screen for the boot splash.
//c.screen.priority = c.screen.boot
c.screen.priorityUntil = time.Now().Add(time.Second)
return return
} }
func (c *Controller) loadInputs(config config.Input) (err error) { func (c *Controller) loadInputs(config config.Input) (err error) {
return if c.encoder, err = input.NewEncoder(config.Encoder); err != nil {
return
}
return nil
}
func (c *Controller) observer(o interface{}) {
log := c.log()
if o, ok := o.(player.TrackObserver); ok {
log.WithField("observer", o).Debug("adding track change observer")
c.observe.trackChanged = append(c.observe.trackChanged, o)
}
if o, ok := o.(player.StatusObserver); ok {
log.WithField("observer", o).Debug("adding status change observer")
c.observe.statusChanged = append(c.observe.statusChanged, o)
}
} }
func randomColor() color.RGBA { func randomColor() color.RGBA {
@@ -214,16 +281,13 @@ func (c *Controller) teardown() {
log.Debug("halt player") log.Debug("halt player")
} }
if c.Audio != nil { if c.Audio != nil {
log.WithError(c.Audio.Halt()).Debug("halt audio") //log.WithError(c.Audio.Halt()).Debug("halt audio")
} }
if c.Left != nil { if c.Main != nil {
log.WithError(c.Left.Halt()).Debug("halt left screen") log.WithError(c.Main.Close()).Debug("halt main screen")
} }
if c.Right != nil { if c.Meta != nil {
log.WithError(c.Right.Halt()).Debug("halt right screen") log.WithError(c.Meta.Close()).Debug("halt meta screen")
}
if c.Color != nil {
log.WithError(c.Color.Halt()).Debug("halt color screen")
} }
} }
@@ -235,10 +299,16 @@ func (c *Controller) Run(ctx context.Context) error {
return err return err
} }
inputEvents, err := c.encoder.Events()
if err != nil {
return err
}
var ( var (
fps = time.NewTicker(c.fps) fps = time.NewTicker(c.fps)
update = time.NewTicker(25 * time.Millisecond) update = time.NewTicker(time.Second)
rate = int(time.Second / c.fps) rate = int(time.Second / c.fps)
frames int
) )
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
@@ -246,41 +316,34 @@ func (c *Controller) Run(ctx context.Context) error {
"rate_display": c.fps, "rate_display": c.fps,
"rate_sample": c.Audio.SampleRate(), "rate_sample": c.Audio.SampleRate(),
}).Debug("opening audio stream") }).Debug("opening audio stream")
var (
samples = c.Audio.Samples(int(c.Audio.SampleRate() / physic.Frequency(rate) / physic.Hertz))
last time.Time
frames int
)
defer fps.Stop() defer fps.Stop()
defer update.Stop() defer update.Stop()
go c.processSound(ctx)
c.log().WithFields(logrus.Fields{ c.log().WithFields(logrus.Fields{
"rate": c.Audio.SampleRate(), "rate": c.Audio.SampleRate(),
"fps": rate, "fps": rate,
"rate_fps": c.Audio.SampleRate() / physic.Frequency(rate), }).Info("BeatGlow controller running...")
}).Info("Harmon controller running...")
// Main house keeping loop, processes player and input updates, as well as video frames.
for { for {
select { select {
case event := <-playerEvents: case event := <-playerEvents:
c.handlePlayer(event) c.handlePlayer(event)
case <-fps.C: case now := <-fps.C:
frames++ frames++
c.handleFrame() c.handleFrame(now)
case now := <-update.C: case <-update.C:
if logrus.GetLevel() >= logrus.DebugLevel { // Display the frame rate in the debug log.
if now.Sub(last) > time.Second { c.log().WithField("fps", frames).Debug("frame rate")
c.log().WithField("fps", frames).Debug("frame rate") frames = 0
last = now
frames = 0
}
}
case samples := <-samples: case event := <-inputEvents:
c.handleSamples(samples) // Handle input events.
c.handleInput(event)
case <-ctx.Done(): case <-ctx.Done():
return ctx.Err() return ctx.Err()
@@ -288,6 +351,53 @@ func (c *Controller) Run(ctx context.Context) error {
} }
} }
func (c *Controller) handleFrame(t time.Time) {
var widgets []ui.Widget
if c.screen.priority != nil {
if t.After(c.screen.priorityUntil) {
c.log().Debug("priorty screen expired; closing")
c.screen.priority = nil
c.screen.active.SetVisible(true)
} else {
c.log().Trace("priorty screen is active")
widgets = c.screen.priority.Widgets()
}
}
if widgets == nil {
widgets = c.screen.active.Widgets()
}
var refresh bool
for _, widget := range widgets {
if changed := widget.Render(false); changed {
refresh = true
}
}
if refresh {
if err := c.Main.Refresh(); err != nil {
c.log().WithError(err).Error("main refresh failed")
}
if err := c.Meta.Refresh(); err != nil {
c.log().WithError(err).Error("meta refresh failed")
}
}
}
func (c *Controller) handleScreen(name string) {
previous := c.screen.active
switch name {
case "boot":
c.screen.active = c.screen.boot
case "playing":
c.screen.active = c.screen.playing
}
if previous != c.screen.active {
previous.SetVisible(false)
c.screen.active.SetVisible(true)
}
}
func (c *Controller) handlePlayer(event player.Event) { func (c *Controller) handlePlayer(event player.Event) {
log := c.log().WithField("from", "player") log := c.log().WithField("from", "player")
log.WithFields(logrus.Fields{ log.WithFields(logrus.Fields{
@@ -297,48 +407,155 @@ func (c *Controller) handlePlayer(event player.Event) {
switch event := event.(type) { switch event := event.(type) {
case player.ConnectedEvent: case player.ConnectedEvent:
log.Info("player connected") log.Info("player connected")
c.connected = true c.state = &State{Connected: true}
c.handleStatus(nil)
case player.DisconnectedEvent: case player.DisconnectedEvent:
log.Warn("player disconnected") log.Warn("player disconnected")
c.connected = false c.state = &State{}
c.playing = false c.handleStatus(nil)
case player.PlayEvent: case player.PlayEvent:
log.WithField("track", event.Track).Info("now playing") c.handleTrack(event.Track)
case player.StatusEvent: case player.StatusEvent:
log.WithField("state", event.Status).Trace("player status") c.handleStatus(event.Status)
c.playing = event.Status.Playing
default: default:
log.WithField("event", event).Warn("unhandled event") log.WithField("event", event).Warn("unhandled event")
} }
} }
func (c *Controller) handleFrame() { func (c *Controller) handleStatus(status *player.Status) {
log := c.log() //log := c.log().WithField("from", "player")
if c.connected { for _, o := range c.observe.statusChanged {
if c.playing { o.StatusChanged(status)
if err := c.visual.vumeterLeft.Render(); err != nil { }
log.WithError(err).Warn("left vumeter render failed") c.observe.status = status
}
if err := c.visual.vumeterRight.Render(); err != nil { if status != nil {
log.WithError(err).Warn("right vumeter render failed") if c.state.Connected {
} if c.volume != -1 && c.volume != status.Volume {
} else { c.log().WithFields(logrus.Fields{"old": c.volume, "new": status.Volume}).Debug("volume change, showing volume screen")
if err := c.visual.screensaver.Refresh(); err != nil { c.volume = status.Volume
log.WithError(err).Warn("screensaver render failed") c.screen.active.SetVisible(false)
c.screen.priority = c.screen.volume
c.screen.priority.SetVisible(true)
c.screen.priorityUntil = time.Now().Add(5 * time.Second)
} }
c.volume = status.Volume
} }
} else { c.handleTrack(status.Track)
if err := c.visual.offline.Render(); err != nil {
log.WithError(err).Warn("offline render failed")
}
} }
} }
func (c *Controller) handleSamples(samples audio.Buffer) { func (c *Controller) handleTrack(track *player.Track) {
c.visual.vumeterLeft.Process(samples) log := c.log().WithField("from", "player")
c.visual.vumeterRight.Process(samples)
if !c.observe.track.Eq(track) {
log.WithField("track", track).Info("track changed")
for _, o := range c.observe.trackChanged {
o.TrackChanged(c.Player, track)
}
}
c.observe.track = track
}
func (c *Controller) processSound(ctx context.Context) {
var (
channels = c.Audio.Channels()
buffer = make(audio.Buffer[float64], channels)
)
for channel := 0; channel < channels; channel++ {
buffer[channel] = make([]float64, 1024)
}
for {
n, err := c.Audio.ReadBuffer(buffer)
if err != nil {
c.log().WithError(err).Warn("reading samples failed; retrying")
time.Sleep(time.Second)
continue
}
c.log().WithField("samples", n).Trace("read samples")
c.handleSamples(buffer)
}
}
func (c *Controller) handleSamples(buffer audio.Buffer[float64]) {
log := c.log().WithFields(logrus.Fields{
"channels": buffer.Channels(),
"samples": buffer.Samples(),
"screen": c.screen.active,
})
if c.screen.active == nil {
log.Trace("no active screen, discarding samples")
return
}
if processor, ok := c.screen.active.(sound.Processor); ok {
log.Trace("active screen processing samples")
processor.ProcessBuffer(buffer)
} else {
log.Trace("active screen doesn't process samples, discarding samples")
}
}
func (c *Controller) handleInput(event hardware.InputEvent) {
log := c.log()
switch event := event.(type) {
case hardware.RotaryEvent:
if c.observe.status != nil && c.state.Connected {
log.WithField("delta", event.Delta).Debug("update volume")
if err := c.Player.ChangeVolume(event.Delta); err != nil {
log.WithError(err).Warn("failed to adjust volume")
}
} else {
log.WithField("delta", event.Delta).Debug("ignored volume adjustment: player is not connected")
}
case hardware.RotaryPressEvent:
if c.screen.priority == nil {
c.screen.active.SetVisible(false)
c.screen.carouselIndex = (c.screen.carouselIndex + 1) % uint(len(c.screen.carousel))
c.screen.active = c.screen.carousel[c.screen.carouselIndex]
c.screen.active.SetVisible(true)
log.WithField("screen", c.screen.active).Info("switching active screen")
}
case hardware.RotaryLongPressEvent:
if c.state != nil && c.state.Connected {
if err := c.Player.ToggleMute(); err != nil {
log.WithError(err).Warn("mute toggle failed")
}
}
default:
log.WithField("event", event).Debug("unhandled input")
}
}
type State struct {
Connected bool
Playing bool
PlayingSince time.Time
Track *player.Track
}
func (a *State) Eq(b *State) bool {
if a == nil {
return false
}
if b == nil {
return true
}
if a.Connected != b.Connected {
return true
}
if a.Playing != b.Playing {
return true
}
return false
} }
+163
View File
@@ -0,0 +1,163 @@
package draw
import (
"image"
"image/color"
"image/draw"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/font"
"github.com/BeatGlow/display/pixel"
)
type Canvas struct {
Image Image
Style ui.Style
}
func NewCanvas(dst Image) *Canvas {
return &Canvas{
Image: dst,
Style: ui.Style{
Background: image.NewUniform(pixel.Off),
Foreground: pixel.On,
Gradient: ui.Rainbow(),
Font: font.MicroGrotesk,
},
}
}
func (c Canvas) FilledRectangle(x, y, w, h int) {
/*
for py := y; py < y+h; py++ {
for px := x; px < x+w; px++ {
c.Image.Set(px, py, c.Style.Background.At(px, py))
}
}
*/
draw.Draw(c.Image, image.Rect(x, y, x+w, y+h), c.Style.Background, image.Point{}, draw.Src)
}
func (c Canvas) Progess(x, y, w int, progress float64) {
Rectangle(c.Image, c.Style.Foreground, x, y, w, 8)
if fill := int(float64(w-2)*progress + .5); fill > 0 {
c.FilledRectangle(x+1, y+1, fill, 7)
}
}
func (c Canvas) Text(x, y int, text string) {
//c.Font.Print(c.Image, c.Stroke, x, y, text)
c.Style.Font.Draw(c.Image, image.Pt(x, y), image.NewUniform(c.Style.Foreground), text)
}
func (c *Canvas) SetStyle(style ui.Style) *Canvas {
c.Style = style
return c
}
func (c *Canvas) WithStyle(style ui.Style, cb func()) {
oldStyle := c.Style
c.Style = style
cb()
c.Style = oldStyle
}
func (c *Canvas) WithBackground(p image.Image, cb func()) {
oldBackground := c.Style.Background
c.Style.Background = p
cb()
c.Style.Background = oldBackground
}
func (c *Canvas) WithFont(font *font.Font, cb func()) {
oldFont := c.Style.Font
c.Style.Font = font
cb()
c.Style.Font = oldFont
}
func (c *Canvas) WithGradient(w, h int, cb func()) {
gradient := image.NewRGBA(image.Rect(0, 0, w, h))
for x := 0; x < w; x++ {
col := c.Style.Gradient.At(float64(x) / float64(w))
for y := 0; y < h; y++ {
gradient.Set(x, y, col)
}
}
c.WithBackground(gradient, cb)
}
type Paint struct {
Color color.Color
Pattern
}
func (p Paint) At(x, y int) color.Color {
if p.Pattern == nil {
return p.Color
}
return p.Pattern.At(x, y)
}
func (p Paint) Bounds() image.Rectangle {
return image.Rectangle{image.Point{-1e9, -1e9}, image.Point{1e9, 1e9}}
}
func (p Paint) ColorModel() color.Model {
switch p.Color.(type) {
case pixel.Mono:
return pixel.MonoModel
case pixel.Gray2:
return pixel.Gray2Model
case pixel.Gray4:
return pixel.Gray4Model
case pixel.CRGB15:
return pixel.CRGB15Model
case pixel.CRGB16:
return pixel.CRGB16Model
case color.Gray:
return color.GrayModel
case color.RGBA:
return color.RGBAModel
case color.NRGBA:
return color.NRGBAModel
default:
return color.RGBAModel
}
}
type Pattern interface {
At(x, y int) color.Color
}
type PatternFunc func(x, y int) color.Color
func (f PatternFunc) At(x, y int) color.Color { return f(x, y) }
// Solid pattern.
type Solid struct {
color.Color
}
func (p Solid) At(x, y int) color.Color {
return p.Color
}
type Alternate struct {
A, B color.Color
X bool
Y bool
}
func (p Alternate) At(x, y int) color.Color {
if p.X && p.Y && x%2 == 0 && y%2 == 1 {
return p.A
}
if p.X && x%2 == 0 {
return p.A
}
if p.Y && y%2 == 1 {
return p.A
}
return p.B
}
+163
View File
@@ -0,0 +1,163 @@
// Package draw contains screen drawing routines.
package draw
import (
"image"
"image/color"
"image/draw"
)
// Image is a type alias for the Go package.
type Image = draw.Image
// Line draws a line from (x0, y0) to (x1, y1).
func Line(dst Image, c color.Color, x0, y0, x1, y1 int) {
PolyLine(dst, c, image.Point{X: x0, Y: y0}, image.Point{X: x1, Y: y1})
}
// PolyLine draws a multi point line between the specified points.
func PolyLine(dst Image, c color.Color, points ...image.Point) {
if l := len(points); l < 1 {
return
} else if l == 1 {
points = append(points, points[0])
}
for i, l := 0, len(points)-1; i < l; i++ {
a, b := points[i], points[i+1]
bresenham(dst, c, a.X, a.Y, b.X, b.Y)
}
}
// Rectangle draws an empty rectangle.
func Rectangle(dst Image, c color.Color, x, y, w, h int) {
Line(dst, c, x+0, y+0, x+w, y+0)
Line(dst, c, x+w, y+0, x+w, y+h)
Line(dst, c, x+0, y+h, x+w, y+h)
Line(dst, c, x+0, y+0, x+0, y+h)
}
// FilledRectangle draws a filled rectangle from (x, y) to (x + w, y + h).
func FilledRectangle(dst Image, c color.Color, x, y, w, h int) {
for dy := 0; dy < h; dy++ {
Line(dst, c, x, y+dy, x+w, y+dy)
}
}
// Generalized with integer
func bresenham(dst Image, c color.Color, x1, y1, x2, y2 int) {
var dx, dy, e, slope int
// Because drawing p1 -> p2 is equivalent to draw p2 -> p1,
// I sort points in x-axis order to handle only half of possible cases.
if x1 > x2 {
x1, y1, x2, y2 = x2, y2, x1, y1
}
dx, dy = x2-x1, y2-y1
// Because point is x-axis ordered, dx cannot be negative
if dy < 0 {
dy = -dy
}
switch {
// Is line a point ?
case x1 == x2 && y1 == y2:
dst.Set(x1, y1, c)
// Is line an horizontal ?
case y1 == y2:
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
}
dst.Set(x1, y1, c)
// Is line a vertical ?
case x1 == x2:
if y1 > y2 {
y1, y2 = y2, y1
}
for ; dy != 0; dy-- {
dst.Set(x1, y1, c)
y1++
}
dst.Set(x1, y1, c)
// Is line a diagonal ?
case dx == dy:
if y1 < y2 {
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
y1++
}
} else {
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
y1--
}
}
dst.Set(x1, y1, c)
// wider than high ?
case dx > dy:
if y1 < y2 {
// BresenhamDxXRYD(img, x1, y1, x2, y2, col)
dy, e, slope = 2*dy, dx, 2*dx
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
e -= dy
if e < 0 {
y1++
e += slope
}
}
} else {
// BresenhamDxXRYU(img, x1, y1, x2, y2, col)
dy, e, slope = 2*dy, dx, 2*dx
for ; dx != 0; dx-- {
dst.Set(x1, y1, c)
x1++
e -= dy
if e < 0 {
y1--
e += slope
}
}
}
dst.Set(x2, y2, c)
// higher than wide.
default:
if y1 < y2 {
// BresenhamDyXRYD(img, x1, y1, x2, y2, col)
dx, e, slope = 2*dx, dy, 2*dy
for ; dy != 0; dy-- {
dst.Set(x1, y1, c)
y1++
e -= dx
if e < 0 {
x1++
e += slope
}
}
} else {
// BresenhamDyXRYU(img, x1, y1, x2, y2, col)
dx, e, slope = 2*dx, dy, 2*dy
for ; dy != 0; dy-- {
dst.Set(x1, y1, c)
y1--
e -= dx
if e < 0 {
x1++
e += slope
}
}
}
dst.Set(x2, y2, c)
}
}
+27
View File
@@ -0,0 +1,27 @@
package draw
import (
"image/color"
"image/draw"
"math"
)
func Progress(dst Image, c color.Color, x, y, w int, progress float64) {
Rectangle(dst, c, x, y, w, 8)
if fill := int(math.Round(float64(w) * progress)); fill > 0 {
FilledRectangle(dst, c, x+1, y+1, fill, 6)
}
}
func Sprite(dst draw.Image, c color.Color, x, y int, sprite []uint8) {
w, h, data := sprite[0], sprite[1], sprite[2:]
for dy := 0; dy < int(h); dy++ {
for dx := 0; dx < int(w); dx++ {
byteOffset := int(dy/8)*int(w) + dx
bitOffset := dy % 8
if data[byteOffset]&(1<<bitOffset) != 0 {
dst.Set(x+dx, y+dy, c)
}
}
}
}
+87
View File
@@ -0,0 +1,87 @@
package font
import (
"image"
"image/color"
"image/draw"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
// Font is a bitmap font.
type Font struct {
GlyphWith int
GlyphHeight int
Spacing int
glyphs map[rune][]uint16
glyphsV bool
}
func (f *Font) render(out draw.Image, c color.Color, x, y int, pixels []uint16) int {
if f.glyphsV {
for i, bits := range pixels {
for j := 0; j < f.GlyphWith; j++ {
if bits&(1<<j) != 0 {
out.Set(x+(f.GlyphWith-j-1), y+i, c)
}
}
}
} else {
for dx := 0; dx < f.GlyphWith; dx++ {
for dy := 0; dy < f.GlyphHeight; dy++ {
if pixels[dx]&(1<<dy) != 0 {
out.Set(x+dx, y+dy, c)
}
}
}
}
return f.GlyphWith + f.Spacing
}
func (r *Font) Measure(text string) image.Point {
switch size := len(text); size {
case 0:
return image.Point{}
case 1:
return image.Point{X: r.GlyphWith, Y: r.GlyphHeight}
default:
return image.Point{X: r.GlyphWith*size + r.Spacing*size - r.Spacing, Y: r.GlyphHeight}
}
}
func (f *Font) PrintChar(dst draw.Image, c color.Color, x, y int, r rune) int {
if b := dst.Bounds(); !image.Pt(x, y).In(b) {
// Fast path for out of bounds.
return f.GlyphWith + f.Spacing
}
if r == ' ' {
// Fast path for spaces.
return f.GlyphWith + f.Spacing
}
if pixels, ok := f.glyphs[r]; ok {
return f.render(dst, c, x, y, pixels)
} else if r == '?' {
// Glyph was a question mark, but we don't have it, treat it as a space.
return f.PrintChar(dst, c, x, y, ' ')
}
return f.PrintChar(dst, c, x, y, normalizeRune(r))
}
func (f *Font) Print(dst draw.Image, c color.Color, x, y int, text string) {
for _, r := range []rune(text) {
x += f.PrintChar(dst, c, x, y, r)
}
}
func normalizeRune(r rune) rune {
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
result, _, err := transform.String(t, string(r))
if err != nil {
return '?'
}
return []rune(result)[0]
}
+385
View File
@@ -0,0 +1,385 @@
package font
// Fixed4x6 font
var Fixed4x6 = &Font{
GlyphWith: 4,
GlyphHeight: 6,
Spacing: 1,
glyphsV: true,
glyphs: fixed4x4Map,
}
// Fixed5x7 font
var Fixed5x7 = &Font{
GlyphWith: 5,
GlyphHeight: 7,
Spacing: 3,
glyphs: fixed5x7Map,
}
var (
fixed4x4Map = map[rune][]uint16{
0x00: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x00
0x01: {0x20, 0x50, 0x70, 0x50, 0x20, 0x00}, // 0x01
0x02: {0x20, 0x70, 0x50, 0x70, 0x20, 0x00}, // 0x02
0x03: {0x00, 0x50, 0x70, 0x70, 0x20, 0x00}, // 0x03
0x04: {0x00, 0x20, 0x70, 0x70, 0x20, 0x00}, // 0x04
0x05: {0x20, 0x70, 0x70, 0x20, 0x70, 0x00}, // 0x05
0x06: {0x20, 0x20, 0x70, 0x20, 0x70, 0x00}, // 0x06
0x07: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x07
0x08: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x08
0x09: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x09
0x0A: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x0A
0x0B: {0x00, 0x30, 0x10, 0x60, 0x60, 0x00}, // 0x0B
0x0C: {0x20, 0x50, 0x20, 0x70, 0x20, 0x00}, // 0x0C
0x0D: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x0D
0x0E: {0x20, 0x30, 0x50, 0x10, 0x20, 0x00}, // 0x0E
0x0F: {0x20, 0x70, 0x50, 0x70, 0x20, 0x00}, // 0x0F
0x10: {0x40, 0x60, 0x70, 0x60, 0x40, 0x00}, // 0x10
0x11: {0x10, 0x30, 0x70, 0x30, 0x10, 0x00}, // 0x11
0x12: {0x20, 0x70, 0x20, 0x70, 0x20, 0x00}, // 0x12
0x13: {0x50, 0x50, 0x50, 0x00, 0x50, 0x00}, // 0x13
0x14: {0x00, 0x10, 0x20, 0x20, 0x20, 0x20}, // 0x14
0x15: {0x20, 0x20, 0x20, 0x20, 0x40, 0x00}, // 0x15
0x16: {0x00, 0x00, 0x00, 0x00, 0x70, 0x00}, // 0x16
0x17: {0x20, 0x70, 0x20, 0x70, 0x20, 0x70}, // 0x17
0x18: {0x20, 0x70, 0x20, 0x20, 0x20, 0x00}, // 0x18
0x19: {0x20, 0x20, 0x20, 0x70, 0x20, 0x00}, // 0x19
0x1A: {0x00, 0x20, 0xF0, 0x20, 0x00, 0x00}, // 0x1A
0x1B: {0x00, 0x40, 0xF0, 0x40, 0x00, 0x00}, // 0x1B
0x1C: {0x00, 0x00, 0x40, 0x70, 0x00, 0x00}, // 0x1C
0x1D: {0x00, 0x50, 0x70, 0x50, 0x00, 0x00}, // 0x1D
0x1E: {0x00, 0x20, 0x70, 0x70, 0x00, 0x00}, // 0x1E
0x1F: {0x00, 0x70, 0x70, 0x20, 0x00, 0x00}, // 0x1F
0x20: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0x20
0x21: {0x20, 0x20, 0x20, 0x00, 0x20, 0x00}, // 0x21
0x22: {0x50, 0x50, 0x00, 0x00, 0x00, 0x00}, // 0x22
0x23: {0x50, 0x70, 0x50, 0x70, 0x50, 0x00}, // 0x23
0x24: {0x20, 0x30, 0x60, 0x30, 0x60, 0x20}, // 0x24
0x25: {0x40, 0x10, 0x20, 0x40, 0x10, 0x00}, // 0x25
0x26: {0x20, 0x50, 0x30, 0x50, 0x70, 0x00}, // 0x26
0x27: {0x60, 0x40, 0x00, 0x00, 0x00, 0x00}, // 0x27
0x28: {0x20, 0x40, 0x40, 0x40, 0x20, 0x00}, // 0x28
0x29: {0x40, 0x20, 0x20, 0x20, 0x40, 0x00}, // 0x29
0x2A: {0x50, 0x20, 0x70, 0x20, 0x50, 0x00}, // 0x2A
0x2B: {0x00, 0x20, 0x70, 0x20, 0x00, 0x00}, // 0x2B
0x2C: {0x00, 0x00, 0x00, 0x00, 0x60, 0x40}, // 0x2C
0x2D: {0x00, 0x00, 0x70, 0x00, 0x00, 0x00}, // 0x2D
0x2E: {0x00, 0x00, 0x00, 0x00, 0x20, 0x00}, // 0x2E
0x2F: {0x10, 0x10, 0x20, 0x40, 0x40, 0x00}, // 0x2F
0x30: {0x30, 0x50, 0x50, 0x50, 0x60, 0x00}, // 0x30
0x31: {0x20, 0x60, 0x20, 0x20, 0x70, 0x00}, // 0x31
0x32: {0x60, 0x10, 0x20, 0x40, 0x70, 0x00}, // 0x32
0x33: {0x60, 0x10, 0x20, 0x10, 0x60, 0x00}, // 0x33
0x34: {0x10, 0x50, 0x70, 0x10, 0x10, 0x00}, // 0x34
0x35: {0x70, 0x40, 0x60, 0x10, 0x60, 0x00}, // 0x35
0x36: {0x20, 0x40, 0x60, 0x50, 0x20, 0x00}, // 0x36
0x37: {0x70, 0x10, 0x30, 0x20, 0x20, 0x00}, // 0x37
0x38: {0x20, 0x50, 0x20, 0x50, 0x20, 0x00}, // 0x38
0x39: {0x20, 0x50, 0x30, 0x10, 0x20, 0x00}, // 0x39
0x3A: {0x00, 0x00, 0x20, 0x00, 0x20, 0x00}, // 0x3A
0x3B: {0x00, 0x00, 0x20, 0x00, 0x60, 0x40}, // 0x3B
0x3C: {0x10, 0x20, 0x40, 0x20, 0x10, 0x00}, // 0x3C
0x3D: {0x00, 0x00, 0x70, 0x00, 0x70, 0x00}, // 0x3D
0x3E: {0x40, 0x20, 0x10, 0x20, 0x40, 0x00}, // 0x3E
0x3F: {0x60, 0x10, 0x20, 0x00, 0x20, 0x00}, // 0x3F
0x40: {0x70, 0x50, 0x50, 0x40, 0x70, 0x00}, // 0x40
0x41: {0x20, 0x50, 0x70, 0x50, 0x50, 0x00}, // 0x41
0x42: {0x60, 0x50, 0x60, 0x50, 0x60, 0x00}, // 0x42
0x43: {0x30, 0x40, 0x40, 0x40, 0x30, 0x00}, // 0x43
0x44: {0x60, 0x50, 0x50, 0x50, 0x60, 0x00}, // 0x44
0x45: {0x70, 0x40, 0x60, 0x40, 0x70, 0x00}, // 0x45
0x46: {0x70, 0x40, 0x60, 0x40, 0x40, 0x00}, // 0x46
0x47: {0x30, 0x40, 0x50, 0x50, 0x30, 0x00}, // 0x47
0x48: {0x50, 0x50, 0x70, 0x50, 0x50, 0x00}, // 0x48
0x49: {0x70, 0x20, 0x20, 0x20, 0x70, 0x00}, // 0x49
0x4A: {0x10, 0x10, 0x10, 0x50, 0x20, 0x00}, // 0x4A
0x4B: {0x50, 0x50, 0x60, 0x50, 0x50, 0x00}, // 0x4B
0x4C: {0x40, 0x40, 0x40, 0x40, 0x70, 0x00}, // 0x4C
0x4D: {0x50, 0x70, 0x70, 0x50, 0x50, 0x00}, // 0x4D
0x4E: {0x50, 0x70, 0x50, 0x50, 0x50, 0x00}, // 0x4E
0x4F: {0x20, 0x50, 0x50, 0x50, 0x20, 0x00}, // 0x4F
0x50: {0x60, 0x50, 0x60, 0x40, 0x40, 0x00}, // 0x50
0x51: {0x20, 0x50, 0x50, 0x70, 0x30, 0x00}, // 0x51
0x52: {0x60, 0x50, 0x60, 0x50, 0x50, 0x00}, // 0x52
0x53: {0x30, 0x40, 0x70, 0x10, 0x60, 0x00}, // 0x53
0x54: {0x70, 0x20, 0x20, 0x20, 0x20, 0x00}, // 0x54
0x55: {0x50, 0x50, 0x50, 0x50, 0x70, 0x00}, // 0x55
0x56: {0x50, 0x50, 0x50, 0x50, 0x20, 0x00}, // 0x56
0x57: {0x50, 0x50, 0x70, 0x70, 0x50, 0x00}, // 0x57
0x58: {0x50, 0x50, 0x20, 0x50, 0x50, 0x00}, // 0x58
0x59: {0x50, 0x50, 0x20, 0x20, 0x20, 0x00}, // 0x59
0x5A: {0x70, 0x10, 0x20, 0x40, 0x70, 0x00}, // 0x5A
0x5B: {0x60, 0x40, 0x40, 0x40, 0x60, 0x00}, // 0x5B
0x5C: {0x40, 0x40, 0x20, 0x10, 0x10, 0x00}, // 0x5C
0x5D: {0x60, 0x20, 0x20, 0x20, 0x60, 0x00}, // 0x5D
0x5E: {0x20, 0x50, 0x00, 0x00, 0x00, 0x00}, // 0x5E
0x5F: {0x00, 0x00, 0x00, 0x00, 0x00, 0xF0}, // 0x5F
0x60: {0x60, 0x20, 0x00, 0x00, 0x00, 0x00}, // 0x60
0x61: {0x00, 0x00, 0x30, 0x50, 0x70, 0x00}, // 0x61
0x62: {0x40, 0x40, 0x60, 0x50, 0x60, 0x00}, // 0x62
0x63: {0x00, 0x00, 0x30, 0x40, 0x30, 0x00}, // 0x63
0x64: {0x10, 0x10, 0x30, 0x50, 0x30, 0x00}, // 0x64
0x65: {0x00, 0x00, 0x70, 0x60, 0x30, 0x00}, // 0x65
0x66: {0x10, 0x20, 0x70, 0x20, 0x20, 0x00}, // 0x66
0x67: {0x00, 0x00, 0x70, 0x50, 0x10, 0x70}, // 0x67
0x68: {0x40, 0x40, 0x60, 0x50, 0x50, 0x00}, // 0x68
0x69: {0x20, 0x00, 0x20, 0x20, 0x20, 0x00}, // 0x69
0x6A: {0x20, 0x00, 0x20, 0x20, 0x20, 0x60}, // 0x6A
0x6B: {0x40, 0x40, 0x50, 0x60, 0x50, 0x00}, // 0x6B
0x6C: {0x20, 0x20, 0x20, 0x20, 0x20, 0x00}, // 0x6C
0x6D: {0x00, 0x00, 0x70, 0x70, 0x50, 0x00}, // 0x6D
0x6E: {0x00, 0x00, 0x60, 0x50, 0x50, 0x00}, // 0x6E
0x6F: {0x00, 0x00, 0x20, 0x50, 0x20, 0x00}, // 0x6F
0x70: {0x00, 0x00, 0x60, 0x50, 0x60, 0x40}, // 0x70
0x71: {0x00, 0x00, 0x30, 0x50, 0x30, 0x10}, // 0x71
0x72: {0x00, 0x00, 0x60, 0x40, 0x40, 0x00}, // 0x72
0x73: {0x00, 0x00, 0x30, 0x20, 0x60, 0x00}, // 0x73
0x74: {0x00, 0x20, 0x70, 0x20, 0x30, 0x00}, // 0x74
0x75: {0x00, 0x00, 0x50, 0x50, 0x70, 0x00}, // 0x75
0x76: {0x00, 0x00, 0x50, 0x50, 0x20, 0x00}, // 0x76
0x77: {0x00, 0x00, 0x50, 0x70, 0x70, 0x00}, // 0x77
0x78: {0x00, 0x00, 0x50, 0x20, 0x50, 0x00}, // 0x78
0x79: {0x00, 0x00, 0x50, 0x50, 0x20, 0x40}, // 0x79
0x7A: {0x00, 0x00, 0x60, 0x20, 0x30, 0x00}, // 0x7A
0x7B: {0x30, 0x20, 0x60, 0x20, 0x30, 0x00}, // 0x7B
0x7C: {0x20, 0x20, 0x20, 0x20, 0x20, 0x00}, // 0x7C
0x7D: {0x60, 0x20, 0x30, 0x20, 0x60, 0x00}, // 0x7D
0x7E: {0x50, 0xA0, 0x00, 0x00, 0x00, 0x00}, // 0x7E
0x7F: {0x00, 0x20, 0x50, 0x70, 0x00, 0x00}, // 0x7F
0x80: {0x30, 0x40, 0x40, 0x70, 0x20, 0x40}, // 0x80
0x81: {0x50, 0x00, 0x50, 0x50, 0x30, 0x00}, // 0x81
0x82: {0x10, 0x20, 0x70, 0x60, 0x30, 0x00}, // 0x82
0x83: {0x20, 0x50, 0x30, 0x50, 0x70, 0x00}, // 0x83
0x84: {0x50, 0x00, 0x30, 0x50, 0x70, 0x00}, // 0x84
0x85: {0x40, 0x20, 0x30, 0x50, 0x70, 0x00}, // 0x85
0x86: {0x20, 0x00, 0x30, 0x50, 0x70, 0x00}, // 0x86
0x87: {0x00, 0x70, 0x40, 0x70, 0x20, 0x60}, // 0x87
0x88: {0x20, 0x50, 0x70, 0x60, 0x30, 0x00}, // 0x88
0x89: {0x50, 0x00, 0x70, 0x60, 0x30, 0x00}, // 0x89
0x8A: {0x40, 0x20, 0x70, 0x60, 0x30, 0x00}, // 0x8A
0x8B: {0x50, 0x00, 0x20, 0x20, 0x20, 0x00}, // 0x8B
0x8C: {0x20, 0x50, 0x00, 0x20, 0x20, 0x00}, // 0x8C
0x8D: {0x40, 0x20, 0x00, 0x20, 0x20, 0x00}, // 0x8D
0x8E: {0x50, 0x20, 0x50, 0x70, 0x50, 0x00}, // 0x8E
0x8F: {0x20, 0x20, 0x50, 0x70, 0x50, 0x00}, // 0x8F
0x90: {0x10, 0x20, 0x70, 0x60, 0x70, 0x00}, // 0x90
0x91: {0x00, 0x00, 0x30, 0x70, 0x60, 0x00}, // 0x91
0x92: {0x30, 0x60, 0x70, 0x60, 0x70, 0x00}, // 0x92
0x93: {0x20, 0x50, 0x20, 0x50, 0x20, 0x00}, // 0x93
0x94: {0x50, 0x00, 0x20, 0x50, 0x20, 0x00}, // 0x94
0x95: {0x40, 0x20, 0x20, 0x50, 0x20, 0x00}, // 0x95
0x96: {0x20, 0x50, 0x00, 0x50, 0x70, 0x00}, // 0x96
0x97: {0x40, 0x20, 0x50, 0x50, 0x70, 0x00}, // 0x97
0x98: {0x50, 0x00, 0x50, 0x50, 0x20, 0x40}, // 0x98
0x99: {0x50, 0x20, 0x50, 0x50, 0x20, 0x00}, // 0x99
0x9A: {0x50, 0x00, 0x50, 0x50, 0x70, 0x00}, // 0x9A
0x9B: {0x20, 0x70, 0x40, 0x70, 0x20, 0x00}, // 0x9B
0x9C: {0x10, 0x20, 0x70, 0x20, 0x70, 0x00}, // 0x9C
0x9D: {0x50, 0x70, 0x20, 0x70, 0x20, 0x00}, // 0x9D
0x9E: {0x00, 0x60, 0x60, 0x50, 0x50, 0x00}, // 0x9E
0x9F: {0x30, 0x20, 0x30, 0x20, 0x60, 0x00}, // 0x9F
0xA0: {0x10, 0x20, 0x30, 0x50, 0x70, 0x00}, // 0xA0
0xA1: {0x10, 0x20, 0x00, 0x20, 0x20, 0x00}, // 0xA1
0xA2: {0x10, 0x20, 0x70, 0x50, 0x70, 0x00}, // 0xA2
0xA3: {0x10, 0x20, 0x00, 0x50, 0x70, 0x00}, // 0xA3
0xA4: {0x70, 0x00, 0x70, 0x50, 0x50, 0x00}, // 0xA4
0xA5: {0x70, 0x00, 0x50, 0x70, 0x50, 0x00}, // 0xA5
0xA6: {0x30, 0x50, 0x70, 0x00, 0x70, 0x00}, // 0xA6
0xA7: {0x20, 0x50, 0x20, 0x00, 0x70, 0x00}, // 0xA7
0xA8: {0x20, 0x00, 0x20, 0x40, 0x30, 0x00}, // 0xA8
0xA9: {0x00, 0x70, 0x40, 0x40, 0x00, 0x00}, // 0xA9
0xAA: {0x00, 0xE0, 0x20, 0x20, 0x00, 0x00}, // 0xAA
0xAB: {0x40, 0x50, 0x20, 0x50, 0x30, 0x00}, // 0xAB
0xAC: {0x40, 0x50, 0x20, 0x70, 0x10, 0x00}, // 0xAC
0xAD: {0x20, 0x00, 0x20, 0x20, 0x20, 0x00}, // 0xAD
0xAE: {0x00, 0x50, 0xA0, 0x50, 0x00, 0x00}, // 0xAE
0xAF: {0x00, 0xA0, 0x50, 0xA0, 0x00, 0x00}, // 0xAF
0xB0: {0x40, 0x10, 0x40, 0x10, 0x40, 0x10}, // 0xB0
0xB1: {0x50, 0xA0, 0x50, 0xA0, 0x50, 0xA0}, // 0xB1
0xB2: {0xB0, 0xE0, 0xB0, 0xE0, 0xB0, 0xE0}, // 0xB2
0xB3: {0x20, 0x20, 0x20, 0x20, 0x20, 0x20}, // 0xB3
0xB4: {0x20, 0x20, 0xE0, 0x20, 0x20, 0x20}, // 0xB4
0xB5: {0x20, 0xE0, 0x20, 0xE0, 0x20, 0x20}, // 0xB5
0xB6: {0x50, 0x50, 0xD0, 0x50, 0x50, 0x50}, // 0xB6
0xB7: {0x00, 0x00, 0xF0, 0x50, 0x50, 0x50}, // 0xB7
0xB8: {0x00, 0xE0, 0x20, 0xE0, 0x20, 0x20}, // 0xB8
0xB9: {0x50, 0xD0, 0x10, 0xD0, 0x50, 0x50}, // 0xB9
0xBA: {0x50, 0x50, 0x50, 0x50, 0x50, 0x50}, // 0xBA
0xBB: {0x00, 0xF0, 0x10, 0xD0, 0x50, 0x50}, // 0xBB
0xBC: {0x50, 0xD0, 0x10, 0xF0, 0x00, 0x00}, // 0xBC
0xBD: {0x50, 0x50, 0xF0, 0x00, 0x00, 0x00}, // 0xBD
0xBE: {0x20, 0xE0, 0x20, 0xE0, 0x00, 0x00}, // 0xBE
0xBF: {0x00, 0x00, 0xE0, 0x20, 0x20, 0x20}, // 0xBF
0xC0: {0x20, 0x20, 0x30, 0x00, 0x00, 0x00}, // 0xC0
0xC1: {0x20, 0x20, 0xF0, 0x00, 0x00, 0x00}, // 0xC1
0xC2: {0x00, 0x00, 0xF0, 0x20, 0x20, 0x20}, // 0xC2
0xC3: {0x20, 0x20, 0x30, 0x20, 0x20, 0x20}, // 0xC3
0xC4: {0x00, 0x00, 0xF0, 0x00, 0x00, 0x00}, // 0xC4
0xC5: {0x20, 0x20, 0xF0, 0x20, 0x20, 0x20}, // 0xC5
0xC6: {0x20, 0x30, 0x20, 0x30, 0x20, 0x20}, // 0xC6
0xC7: {0x50, 0x50, 0x50, 0x50, 0x50, 0x50}, // 0xC7
0xC8: {0x50, 0x50, 0x40, 0x70, 0x00, 0x00}, // 0xC8
0xC9: {0x00, 0x70, 0x40, 0x50, 0x50, 0x50}, // 0xC9
0xCA: {0x50, 0xD0, 0x00, 0xF0, 0x00, 0x00}, // 0xCA
0xCB: {0x00, 0xF0, 0x00, 0xD0, 0x50, 0x50}, // 0xCB
0xCC: {0x50, 0x50, 0x40, 0x50, 0x50, 0x50}, // 0xCC
0xCD: {0x00, 0xF0, 0x00, 0xF0, 0x00, 0x00}, // 0xCD
0xCE: {0x50, 0xD0, 0x00, 0xD0, 0x50, 0x50}, // 0xCE
0xCF: {0x20, 0xF0, 0x00, 0xF0, 0x00, 0x00}, // 0xCF
0xD0: {0x50, 0x50, 0xF0, 0x00, 0x00, 0x00}, // 0xD0
0xD1: {0x00, 0xF0, 0x00, 0xF0, 0x20, 0x20}, // 0xD1
0xD2: {0x00, 0x00, 0xF0, 0x50, 0x50, 0x50}, // 0xD2
0xD3: {0x50, 0x50, 0x70, 0x00, 0x00, 0x00}, // 0xD3
0xD4: {0x20, 0x30, 0x20, 0x30, 0x00, 0x00}, // 0xD4
0xD5: {0x00, 0x30, 0x20, 0x30, 0x20, 0x20}, // 0xD5
0xD6: {0x00, 0x00, 0x70, 0x50, 0x50, 0x50}, // 0xD6
0xD7: {0x50, 0x50, 0xD0, 0x50, 0x50, 0x50}, // 0xD7
0xD8: {0x20, 0xF0, 0x00, 0xF0, 0x20, 0x20}, // 0xD8
0xD9: {0x20, 0x20, 0xE0, 0x00, 0x00, 0x00}, // 0xD9
0xDA: {0x00, 0x00, 0x30, 0x20, 0x20, 0x20}, // 0xDA
0xDB: {0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0}, // 0xDB
0xDC: {0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0}, // 0xDC
0xDD: {0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0}, // 0xDD
0xDE: {0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, // 0xDE
0xDF: {0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00}, // 0xDF
0xE0: {0x00, 0x00, 0x70, 0x60, 0x70, 0x00}, // 0xE0
0xE1: {0x20, 0x50, 0x60, 0x50, 0x60, 0x40}, // 0xE1
0xE2: {0x70, 0x50, 0x40, 0x40, 0x40, 0x00}, // 0xE2
0xE3: {0x70, 0x50, 0x50, 0x50, 0x50, 0x00}, // 0xE3
0xE4: {0x70, 0x40, 0x20, 0x40, 0x70, 0x00}, // 0xE4
0xE5: {0x00, 0x00, 0x30, 0x50, 0x20, 0x00}, // 0xE5
0xE6: {0x00, 0x00, 0x50, 0x50, 0x70, 0x40}, // 0xE6
0xE7: {0x00, 0x10, 0x60, 0x20, 0x20, 0x00}, // 0xE7
0xE8: {0x70, 0x20, 0x50, 0x20, 0x70, 0x00}, // 0xE8
0xE9: {0x20, 0x50, 0x70, 0x50, 0x20, 0x00}, // 0xE9
0xEA: {0x00, 0x20, 0x50, 0x50, 0x50, 0x00}, // 0xEA
0xEB: {0x30, 0x40, 0x20, 0x50, 0x20, 0x00}, // 0xEB
0xEC: {0x00, 0x00, 0x70, 0x50, 0x70, 0x00}, // 0xEC
0xED: {0x20, 0x70, 0x50, 0x70, 0x20, 0x00}, // 0xED
0xEE: {0x30, 0x40, 0x70, 0x40, 0x30, 0x00}, // 0xEE
0xEF: {0x20, 0x50, 0x50, 0x50, 0x50, 0x00}, // 0xEF
0xF0: {0x70, 0x00, 0x70, 0x00, 0x70, 0x00}, // 0xF0
0xF1: {0x20, 0x70, 0x20, 0x00, 0x70, 0x00}, // 0xF1
0xF2: {0x60, 0x10, 0x60, 0x00, 0x70, 0x00}, // 0xF2
0xF3: {0x30, 0x40, 0x30, 0x00, 0x70, 0x00}, // 0xF3
0xF4: {0x00, 0x10, 0x20, 0x20, 0x20, 0x20}, // 0xF4
0xF5: {0x20, 0x20, 0x20, 0x20, 0x40, 0x00}, // 0xF5
0xF6: {0x20, 0x00, 0x70, 0x00, 0x20, 0x00}, // 0xF6
0xF7: {0x00, 0x50, 0xA0, 0x50, 0xA0, 0x00}, // 0xF7
0xF8: {0x20, 0x50, 0x20, 0x00, 0x00, 0x00}, // 0xF8
0xF9: {0x00, 0x20, 0x70, 0x20, 0x00, 0x00}, // 0xF9
0xFA: {0x00, 0x00, 0x20, 0x00, 0x00, 0x00}, // 0xFA
0xFB: {0x30, 0x20, 0x20, 0x60, 0x20, 0x00}, // 0xFB
0xFC: {0x70, 0x50, 0x50, 0x00, 0x00, 0x00}, // 0xFC
0xFD: {0x60, 0x20, 0x40, 0x60, 0x00, 0x00}, // 0xFD
0xFE: {0x00, 0x00, 0x60, 0x60, 0x00, 0x00}, // 0xFE
0xFF: {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0xFF
}
fixed5x7Map = map[rune][]uint16{
' ': {0x00, 0x00, 0x00, 0x00, 0x00}, // (space)
'!': {0x00, 0x00, 0x5F, 0x00, 0x00}, // !
'"': {0x00, 0x07, 0x00, 0x07, 0x00}, // "
'#': {0x14, 0x7F, 0x14, 0x7F, 0x14}, // #
'$': {0x24, 0x2A, 0x7F, 0x2A, 0x12}, // $
'%': {0x23, 0x13, 0x08, 0x64, 0x62}, // %
'&': {0x36, 0x49, 0x55, 0x22, 0x50}, // &
'\'': {0x00, 0x05, 0x03, 0x00, 0x00}, // '
'(': {0x00, 0x1C, 0x22, 0x41, 0x00}, // (
')': {0x00, 0x41, 0x22, 0x1C, 0x00}, // )
'*': {0x08, 0x2A, 0x1C, 0x2A, 0x08}, // *
'+': {0x08, 0x08, 0x3E, 0x08, 0x08}, // +
',': {0x00, 0x50, 0x30, 0x00, 0x00}, // ,
'-': {0x08, 0x08, 0x08, 0x08, 0x08}, // -
'.': {0x00, 0x60, 0x60, 0x00, 0x00}, // .
'/': {0x20, 0x10, 0x08, 0x04, 0x02}, // /
'0': {0x3E, 0x51, 0x49, 0x45, 0x3E}, // 0
'1': {0x00, 0x42, 0x7F, 0x40, 0x00}, // 1
'2': {0x42, 0x61, 0x51, 0x49, 0x46}, // 2
'3': {0x21, 0x41, 0x45, 0x4B, 0x31}, // 3
'4': {0x18, 0x14, 0x12, 0x7F, 0x10}, // 4
'5': {0x27, 0x45, 0x45, 0x45, 0x39}, // 5
'6': {0x3C, 0x4A, 0x49, 0x49, 0x30}, // 6
'7': {0x01, 0x71, 0x09, 0x05, 0x03}, // 7
'8': {0x36, 0x49, 0x49, 0x49, 0x36}, // 8
'9': {0x06, 0x49, 0x49, 0x29, 0x1E}, // 9
':': {0x00, 0x36, 0x36, 0x00, 0x00}, // :
';': {0x00, 0x56, 0x36, 0x00, 0x00}, // ;
'<': {0x00, 0x08, 0x14, 0x22, 0x41}, // <
'=': {0x14, 0x14, 0x14, 0x14, 0x14}, // =
'>': {0x41, 0x22, 0x14, 0x08, 0x00}, // >
'?': {0x02, 0x01, 0x51, 0x09, 0x06}, // ?
'@': {0x32, 0x49, 0x79, 0x41, 0x3E}, // @
'A': {0x7E, 0x11, 0x11, 0x11, 0x7E}, // A
'B': {0x7F, 0x49, 0x49, 0x49, 0x36}, // B
'C': {0x3E, 0x41, 0x41, 0x41, 0x22}, // C
'D': {0x7F, 0x41, 0x41, 0x22, 0x1C}, // D
'E': {0x7F, 0x49, 0x49, 0x49, 0x41}, // E
'F': {0x7F, 0x09, 0x09, 0x01, 0x01}, // F
'G': {0x3E, 0x41, 0x41, 0x51, 0x32}, // G
'H': {0x7F, 0x08, 0x08, 0x08, 0x7F}, // H
'I': {0x00, 0x41, 0x7F, 0x41, 0x00}, // I
'J': {0x20, 0x40, 0x41, 0x3F, 0x01}, // J
'K': {0x7F, 0x08, 0x14, 0x22, 0x41}, // K
'L': {0x7F, 0x40, 0x40, 0x40, 0x40}, // L
'M': {0x7F, 0x02, 0x04, 0x02, 0x7F}, // M
'N': {0x7F, 0x04, 0x08, 0x10, 0x7F}, // N
'O': {0x3E, 0x41, 0x41, 0x41, 0x3E}, // O
'P': {0x7F, 0x09, 0x09, 0x09, 0x06}, // P
'Q': {0x3E, 0x41, 0x51, 0x21, 0x5E}, // Q
'R': {0x7F, 0x09, 0x19, 0x29, 0x46}, // R
'S': {0x46, 0x49, 0x49, 0x49, 0x31}, // S
'T': {0x01, 0x01, 0x7F, 0x01, 0x01}, // T
'U': {0x3F, 0x40, 0x40, 0x40, 0x3F}, // U
'V': {0x1F, 0x20, 0x40, 0x20, 0x1F}, // V
'W': {0x7F, 0x20, 0x18, 0x20, 0x7F}, // W
'X': {0x63, 0x14, 0x08, 0x14, 0x63}, // X
'Y': {0x03, 0x04, 0x78, 0x04, 0x03}, // Y
'Z': {0x61, 0x51, 0x49, 0x45, 0x43}, // Z
'Ä': {0x7D, 0x12, 0x12, 0x7D, 0x00}, // Ä
'Ö': {0x3D, 0x42, 0x42, 0x42, 0x3D}, // Ö
'Ü': {0x3D, 0x40, 0x40, 0x40, 0x3D}, // Ü
'[': {0x00, 0x00, 0x7F, 0x41, 0x41}, // [
'\\': {0x02, 0x04, 0x08, 0x10, 0x20}, // "\"
']': {0x41, 0x41, 0x7F, 0x00, 0x00}, // ]
'^': {0x04, 0x02, 0x01, 0x02, 0x04}, // ^
'_': {0x40, 0x40, 0x40, 0x40, 0x40}, // _
'`': {0x00, 0x01, 0x02, 0x04, 0x00}, // `
'a': {0x20, 0x54, 0x54, 0x54, 0x78}, // a
'b': {0x7F, 0x48, 0x44, 0x44, 0x38}, // b
'c': {0x38, 0x44, 0x44, 0x44, 0x20}, // c
'd': {0x38, 0x44, 0x44, 0x48, 0x7F}, // d
'e': {0x38, 0x54, 0x54, 0x54, 0x18}, // e
'f': {0x08, 0x7E, 0x09, 0x01, 0x02}, // f
'g': {0x08, 0x14, 0x54, 0x54, 0x3C}, // g
'h': {0x7F, 0x08, 0x04, 0x04, 0x78}, // h
'i': {0x00, 0x44, 0x7D, 0x40, 0x00}, // i
'j': {0x20, 0x40, 0x44, 0x3D, 0x00}, // j
'k': {0x00, 0x7F, 0x10, 0x28, 0x44}, // k
'l': {0x00, 0x41, 0x7F, 0x40, 0x00}, // l
'm': {0x7C, 0x04, 0x18, 0x04, 0x78}, // m
'n': {0x7C, 0x08, 0x04, 0x04, 0x78}, // n
'o': {0x38, 0x44, 0x44, 0x44, 0x38}, // o
'p': {0x7C, 0x14, 0x14, 0x14, 0x08}, // p
'q': {0x08, 0x14, 0x14, 0x18, 0x7C}, // q
'r': {0x7C, 0x08, 0x04, 0x04, 0x08}, // r
's': {0x48, 0x54, 0x54, 0x54, 0x20}, // s
't': {0x04, 0x3F, 0x44, 0x40, 0x20}, // t
'u': {0x3C, 0x40, 0x40, 0x20, 0x7C}, // u
'v': {0x1C, 0x20, 0x40, 0x20, 0x1C}, // v
'w': {0x3C, 0x40, 0x30, 0x40, 0x3C}, // w
'x': {0x44, 0x28, 0x10, 0x28, 0x44}, // x
'y': {0x0C, 0x50, 0x50, 0x50, 0x3C}, // y
'z': {0x44, 0x64, 0x54, 0x4C, 0x44}, // z
'ä': {0x20, 0x55, 0x54, 0x55, 0x78}, // ä
'ö': {0x3A, 0x44, 0x44, 0x3A, 0x00}, // ö
'ü': {0x3A, 0x40, 0x40, 0x3A, 0x00}, // ü
'{': {0x00, 0x08, 0x36, 0x41, 0x00}, // {
'|': {0x00, 0x00, 0x7F, 0x00, 0x00}, // |
'}': {0x00, 0x41, 0x36, 0x08, 0x00}, // }
'€': {0x14, 0x3E, 0x55, 0x41, 0x22}, // €
'†': {0x08, 0x08, 0x2A, 0x1C, 0x08}, // -> (ALT + 0134) †
'‡': {0x08, 0x1C, 0x2A, 0x08, 0x08}, // <- (ALT + 0135) ‡
'°': {0x00, 0x00, 0x07, 0x05, 0x07}, // °
}
)
File diff suppressed because it is too large. Load diff
+232
View File
@@ -0,0 +1,232 @@
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 {
Monochrome | RGB444 | RGB565
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 Monochrome:
return any(NewMonochrome(r, g, b)).(T)
case RGB444:
return any(NewRGB444(r, g, b)).(T)
case RGB565:
return any(NewRGB565(r, g, b)).(T)
/*
case RGB555:
return any(NewRGB555(r, g, b)).(T)
case RGB888:
return any(NewRGB888(r, g, b)).(T)
*/
default:
panic("unknown color format")
}
}
// 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)
}
// Monochrome color.
type Monochrome uint8
// Monochrome color names.
const (
Off Monochrome = iota
On
)
func NewMonochrome(r, g, b uint8) Monochrome {
if ToGrayBits(color.RGBA{r, g, b, 0xff}, 1) == 1 {
return On
}
return Off
}
func (Monochrome) BitsPerPixel() int {
return 1
}
func (c Monochrome) RGBA() (r, g, b, a uint32) {
if c == 0 {
return 0, 0, 0, 0
}
return 0xffff, 0xffff, 0xffff, 0xffff
}
func (c Monochrome) RGBAColor() color.RGBA {
if c == 0 {
return color.RGBA{}
}
return color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}
}
func IsOn(c color.Color) bool {
if _, ok := c.(Monochrome); ok {
return c == On
}
return ToGrayBits(c, 1) == 1
}
// 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[RGB444] though.
type RGB444 uint16
func NewRGB444(r, g, b uint8) RGB444 {
return RGB444(r>>4)<<8 | RGB444(g>>4)<<4 | RGB444(b>>4)
}
func (c RGB444) BitsPerPixel() int {
return 12
}
func (c RGB444) 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 RGB444) 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
}
// RGB565 color.
type RGB565 uint16
func NewRGB565(r, g, b uint8) RGB565 {
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 RGB565(val)
}
// FromColor retusn the given color.
func FromColor[T Color](c color.Color) T {
var value T
switch any(value).(type) {
case Monochrome:
return monochromeModel(c).(T)
case RGB444:
return rgb444Model(c).(T)
case RGB565:
return rgb565Model(c).(T)
/*
case RGB555:
return rgb555Model(c).(T)
case RGB888:
return rgb888Model(c).(T)
*/
default:
panic("unknown color format")
}
}
func (c RGB565) BitsPerPixel() int {
return 16
}
func (c RGB565) 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 RGB565) 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
}
+476
View File
@@ -0,0 +1,476 @@
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).(RGB444); 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).(RGB444); ok {
// Special case for RGB444 that isn't stored in a neat byte multiple.
bitIndex := index * zeroColor.BitsPerPixel()
var c RGB444
if bitIndex%8 == 0 {
byteOffset := bitIndex / 8
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
c |= RGB444(ptr[0]) << 4
c |= RGB444(ptr[1] >> 4) // load top bits
} else {
byteOffset := bitIndex / 8
ptr := (*[2]byte)(unsafe.Add(img.data, byteOffset))
c |= RGB444(ptr[0]&0x0f) << 8 // load bottom bits
c |= RGB444(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).(RGB444); 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 Monochrome:
img.SetPixel(x, y, monochromeModel(c).(T))
case RGB444:
img.SetPixel(x, y, rgb444Model(c).(T))
case RGB565:
img.SetPixel(x, y, rgb565Model(c).(T))
/*
case RGB888:
img.SetPixel(x, y, rgb888Model(c).(T))
case RGB555:
img.SetPixel(x, y, rgb555Model(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 Monochrome:
return MonochromeModel
case RGB444:
return RGB444Model
case RGB565:
return RGB565Model
/*
case RGB888:
return RGB888Model
case RGB555:
return RGB555Model
*/
default:
panic("unknown color format")
}
}
// Clear the image buffer.
func (img *Image[T]) Clear() {
var zeroColor T
img.FillSolidColor(zeroColor)
}
// VerticalLSB is a 1 bit (black and white) image.
//
// Each byte is 8 vertical pixels. Each stride is a horizontal band of 8
// pixels high with LSB first. So the first byte represents the following
// pixels, with lowest bit being the top left pixel.
//
// 0 x x x x x x x
// 1 x x x x x x x
// 2 x x x x x x x
// 3 x x x x x x x
// 4 x x x x x x x
// 5 x x x x x x x
// 6 x x x x x x x
// 7 x x x x x x x
//
// It is designed specifically to work with SSD1306 OLED display controller.
type VerticalLSB struct {
// Pix holds the image's pixels, as vertically LSB-first packed bitmap. It
// can be passed directly to ssd1306.Dev.Write()
Pix []byte
// Stride is the Pix stride (in bytes) between vertically adjacent 8 pixels
// horizontal bands.
Stride int
// Rect is the image's bounds.
Rect image.Rectangle
}
// NewVerticalLSB returns an initialized VerticalLSB instance.
func NewVerticalLSB(r image.Rectangle) *VerticalLSB {
w := r.Dx()
// Round down.
minY := r.Min.Y &^ 7
// Round up.
maxY := (r.Max.Y + 7) & ^7
bands := (maxY - minY) / 8
return &VerticalLSB{Pix: make([]byte, w*bands), Stride: w, Rect: r}
}
// ColorModel implements image.Image.
func (i *VerticalLSB) ColorModel() color.Model {
return MonochromeModel
}
// Bounds implements image.Image.
func (i *VerticalLSB) Bounds() image.Rectangle {
return i.Rect
}
// At implements image.Image.
func (i *VerticalLSB) At(x, y int) color.Color {
return i.BitAt(x, y)
}
// BitAt is the optimized version of At().
func (i *VerticalLSB) BitAt(x, y int) Monochrome {
if !(image.Point{x, y}.In(i.Rect)) {
return Off
}
offset, mask := i.PixOffset(x, y)
if i.Pix[offset]&mask != 0 {
return On
}
return Off
}
// Opaque scans the entire image and reports whether it is fully opaque.
func (i *VerticalLSB) Opaque() bool {
return true
}
// PixOffset returns the index of the first element of Pix that corresponds to
// the pixel at (x, y) and the corresponding mask.
func (i *VerticalLSB) PixOffset(x, y int) (int, byte) {
// Adjust band.
minY := i.Rect.Min.Y &^ 7
pY := (y - minY)
offset := pY/8*i.Stride + (x - i.Rect.Min.X)
bit := uint(pY & 7)
return offset, 1 << bit
}
// Set implements draw.Image
func (i *VerticalLSB) Set(x, y int, c color.Color) {
if ToGrayBits(c, 1) == 0 {
i.SetBit(x, y, Off)
}
i.SetBit(x, y, On)
}
// SetBit is the optimized version of Set().
func (i *VerticalLSB) SetBit(x, y int, b Monochrome) {
if !(image.Point{x, y}.In(i.Rect)) {
return
}
offset, mask := i.PixOffset(x, y)
if b == On {
i.Pix[offset] |= mask
} else {
i.Pix[offset] &^= mask
}
}
+33
View File
@@ -0,0 +1,33 @@
package pixel
import "image/color"
var (
MonochromeModel color.Model = color.ModelFunc(monochromeModel)
RGB444Model color.Model = color.ModelFunc(rgb444Model)
RGB565Model color.Model = color.ModelFunc(rgb565Model)
)
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))
}
func rgb444Model(c color.Color) color.Color {
if _, ok := c.(RGB444); ok {
return c
}
r, g, b, _ := c.RGBA()
return RGB444(r>>12)<<8 | RGB444(g>>12)<<4 | RGB444(b>>12)
}
func rgb565Model(c color.Color) color.Color {
if _, ok := c.(RGB565); ok {
return c
}
r, g, b, _ := c.RGBA()
return RGB565(uint16((r>>8)&0xF8)<<8 + uint16((g>>8)&0xFC)<<3 + uint16((b>>8)&0xF8)>>3)
}
+152
View File
@@ -0,0 +1,152 @@
package draw
import (
"image"
"image/color"
"image/draw"
"github.com/BeatGlow/beatglow/draw/pixel"
"github.com/sirupsen/logrus"
)
type Scroller struct {
Canvas *Canvas
Width int
Wrap bool
origin image.Point
buff image.Image
scroll int
scrollDir int
scrollWidth int
scrollRequired bool
}
func NewScroller(dst Image, width int, wrap bool) *Scroller {
return &Scroller{
Canvas: NewCanvas(dst),
Width: width,
Wrap: wrap,
scrollDir: +1,
}
}
func (s *Scroller) log() *logrus.Entry {
return logrus.WithField("draw", "scroller")
}
func (s *Scroller) Text(x, y int, text string) {
if text == "" {
s.buff = nil
return
}
width, height := s.Canvas.Style.Font.MeasureText(text)
if s.Wrap && width >= s.Canvas.Image.Bounds().Size().X-x {
width += 42 // 3 * (s.Canvas.Font.GlyphWith + s.Canvas.Font.Spacing)
}
buff := pixel.NewImage[pixel.Monochrome](width, height)
logrus.Printf("scroll color: %#+v", s.Canvas.Style.Foreground)
s.Canvas.Style.Font.Draw(buff, image.Point{}, image.NewUniform(s.Canvas.Style.Foreground), text)
s.scrollRequired = width > (s.Canvas.Image.Bounds().Size().X - x)
if s.Wrap && s.scrollRequired {
s.buff = wrapAround{buff, image.Pt(width, height)}
} else {
s.buff = buff
}
s.origin = image.Pt(x, y)
s.scrollWidth = width
s.log().WithFields(logrus.Fields{
"width": width,
"height": height,
"origin": s.origin,
"scroll": s.scrollRequired,
}).Debug("scroll write text")
}
func (s *Scroller) Advance() {
if s.buff == nil {
return
}
var (
log = s.log()
r image.Rectangle
sp image.Point
)
if s.scrollRequired {
log = log.WithFields(logrus.Fields{
"scroll": s.scroll,
"scroll_new": s.scroll + s.scrollDir,
})
s.scroll += s.scrollDir
if s.scroll > s.scrollWidth {
s.scroll = 0
} else if s.scroll < -s.scrollWidth {
s.scroll = 0
}
// Copy the visible part of the buffer.
r = image.Rectangle{
Min: s.origin,
Max: s.origin.Add(image.Point{X: s.Width, Y: s.buff.Bounds().Dy()}),
}
sp = image.Point{X: s.scroll}
log.WithFields(logrus.Fields{
"bounds": r,
"origin": sp,
}).Trace("scroller advance")
} else {
// Just copy the whole buffered image.
r = image.Rectangle{
Min: s.origin,
Max: s.origin.Add(s.buff.Bounds().Size()),
}
log.WithFields(logrus.Fields{
"bounds": r,
"origin": sp,
}).Trace("scroller advance (static)")
}
draw.Draw(s.Canvas.Image, r, s.buff, sp, draw.Src)
}
func (s *Scroller) Reset() {
s.scroll = 0
}
func (s *Scroller) SetDirection(dir int) {
if dir < 0 {
dir = -1
}
if dir > 0 {
dir = 1
}
s.scrollDir = dir
}
type wrapAround struct {
image.Image
Size image.Point
}
func (i wrapAround) At(x, y int) color.Color {
for x < 0 {
x += i.Size.X
}
for x >= i.Size.X {
x -= i.Size.X
}
return i.Image.At(x, y)
}
func (i wrapAround) Bounds() image.Rectangle {
b := i.Image.Bounds()
b.Min.X -= i.Size.X
b.Max.X += i.Size.X
return b
}
+15
View File
@@ -0,0 +1,15 @@
package draw
import (
"image/color"
"github.com/BeatGlow/beatglow/draw/font"
)
// Text draws text using the specified font and color.
func Text(dst Image, font *font.Font, color color.Color, x, y int, text string) {
if font == nil {
return
}
font.Print(dst, color, x, y, text)
}
+124
View File
@@ -0,0 +1,124 @@
package hardware
import (
"image"
"image/color"
"github.com/BeatGlow/display"
)
type Combined struct {
displays []display.Display
size image.Point
stride int
}
func NewCombined(displays ...display.Display) display.Display {
s := displays[0].Bounds().Size()
d := &Combined{
displays: displays,
size: s,
stride: s.X,
}
return d
}
func (d *Combined) At(x, y int) color.Color {
if x < 0 || y < 0 || y >= d.size.Y {
return color.Black
}
for _, display := range d.displays {
if x < d.size.X {
return display.At(x, y)
}
x -= d.stride
}
return color.Black
}
func (d *Combined) Close() error {
var err error
for _, p := range d.displays {
if err1 := p.Close(); err1 != nil && err != nil {
err = err1
}
}
return err
}
func (d *Combined) Clear() {
for _, p := range d.displays {
p.Clear()
}
}
func (d *Combined) Fill(c color.Color) {
for _, p := range d.displays {
p.Fill(c)
}
}
func (d *Combined) SetContrast(level uint8) error {
for _, p := range d.displays {
if err := p.SetContrast(level); err != nil {
return err
}
}
return nil
}
func (d *Combined) SetRotation(rotation display.Rotation) error {
for _, p := range d.displays {
if err := p.SetRotation(rotation); err != nil {
return err
}
}
return nil
}
func (d *Combined) Show(show bool) error {
for _, p := range d.displays {
if err := p.Show(show); err != nil {
return err
}
}
return nil
}
func (d *Combined) Bounds() image.Rectangle {
return image.Rectangle{Max: d.Size()}
}
func (d *Combined) ColorModel() color.Model {
return d.displays[0].ColorModel()
}
func (d *Combined) Refresh() error {
for _, p := range d.displays {
if err := p.Refresh(); err != nil {
return err
}
}
return nil
}
func (d *Combined) Set(x, y int, c color.Color) {
if x < 0 || y < 0 || y >= d.size.Y {
return
}
for _, p := range d.displays {
if x < d.size.X {
p.Set(x, y, c)
return
}
x -= d.stride
}
}
func (d *Combined) Size() image.Point {
return image.Point{X: d.stride * len(d.displays), Y: d.size.Y}
}
func (Combined) Type() string {
return "combined"
}
+90 -19
View File
@@ -1,32 +1,103 @@
package hardware package hardware
import ( import (
"image" "errors"
"image/color" "fmt"
"image/draw" "log"
"strconv"
"strings"
"periph.io/x/conn/v3/gpio/gpioreg"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/display"
) )
// Display driver. func Display(config *config.DisplayConfig) (display.Display, error) {
type Display interface { log.Printf("display: %#+v", config)
Driver var (
conn display.Conn
err error
)
switch strings.ToUpper(config.Mode) {
case "", "I2C", "I²C":
var (
addr uint64
bus = -1
)
if addr, err = strconv.ParseUint(config.Address, 16, 16); err != nil {
return nil, fmt.Errorf("invalid display addr %q: %w", config.Address, err)
}
if config.Bus != "" {
if bus, err = strconv.Atoi(config.Bus); err != nil {
return nil, fmt.Errorf("invalid bus %q: %w", config.Bus, err)
}
}
conn, err = display.OpenI2C(&display.I2CConfig{
Addr: uint8(addr),
Device: bus,
Reset: gpioreg.ByName(config.Reset),
})
// PowerSave puts the display to sleep. case "SPI":
PowerSave(on bool) error conn, err = display.OpenSPI(&display.SPIConfig{
Reset: gpioreg.ByName(config.Reset),
DC: gpioreg.ByName(config.DC),
})
// Draw an image on the display. default:
Draw(r image.Rectangle, src image.Image, sp image.Point) error return nil, fmt.Errorf("display: unknown mode %q", config.Mode)
}
if err != nil {
return nil, err
}
// Size of the display. var options = &display.Config{
Size() image.Point Reset: gpioreg.ByName(config.Reset),
Backlight: gpioreg.ByName(config.BL),
}
// Clear the display buffer. if options.Width, options.Height, err = parseSize(config.Size); err != nil {
Clear() _ = conn.Close()
return nil, fmt.Errorf("display: invalid size %q: %w", config.Size, err)
}
// Fill with one color. switch strings.ToUpper(config.Type) {
Fill(color.Color) error case "SH1106":
return display.SH1106(conn, options)
case "SSD1322":
return display.SSD1322(conn, options)
case "ST7735":
return display.ST7735(conn, options)
case "ST7789":
return display.ST7789(conn, options)
default:
_ = conn.Close()
return nil, fmt.Errorf("display: unknown type %q", config.Type)
}
}
// Refresh the display. func parseSize(size string) (width, height int, err error) {
Refresh() error if size == "" {
return
}
draw.Image i := strings.IndexByte(size, 'x')
if i == -1 {
return 0, 0, errors.New("invalid size format; expected WxH, Wx or xH")
} else if i == 0 {
height, err = strconv.Atoi(size[1:])
return
} else if i == len(size)-1 {
width, err = strconv.Atoi(size[:len(size)-1])
return
}
if width, err = strconv.Atoi(size[:i]); err != nil {
return
}
if height, err = strconv.Atoi(size[i+1:]); err != nil {
return
}
return
} }
+27 -1
View File
@@ -1,12 +1,16 @@
package hardware package hardware
import "time" import (
"fmt"
"time"
)
type Input interface { type Input interface {
Events() <-chan InputEvent Events() <-chan InputEvent
} }
type InputEvent interface { type InputEvent interface {
String() string
} }
type ( type (
@@ -19,10 +23,32 @@ type (
RotaryPressEvent struct { RotaryPressEvent struct {
Time time.Time Time time.Time
Input Input Input Input
Code int
} }
RotaryLongPressEvent struct { RotaryLongPressEvent struct {
Time time.Time Time time.Time
Input Input Input Input
Code int
} }
) )
func (e RotaryEvent) String() string {
return fmt.Sprintf("rotary event delta=%d", e.Delta)
}
type RotaryHandler interface {
Rotary(event RotaryEvent)
}
func (e RotaryPressEvent) String() string {
return "rotary press"
}
type RotaryPressHandler interface {
RotaryPress(event RotaryPressEvent)
}
func (e RotaryLongPressEvent) String() string {
return "rotary long press"
}
+6 -2
View File
@@ -2,12 +2,16 @@ package input
import ( import (
"fmt" "fmt"
"time"
"go.maze.io/harmon/config"
"go.maze.io/harmon/hardware"
"periph.io/x/conn/v3/gpio" "periph.io/x/conn/v3/gpio"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/beatglow/hardware"
) )
var LongPressDuration = 450 * time.Millisecond
type Encoder interface { type Encoder interface {
hardware.Driver hardware.Driver
+79 -28
View File
@@ -3,14 +3,15 @@ package input
import ( import (
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.maze.io/harmon/hardware"
"periph.io/x/conn/v3/gpio" "github.com/BeatGlow/beatglow/hardware"
) )
const ( const (
@@ -20,28 +21,57 @@ const (
) )
type devInputEncoder struct { type devInputEncoder struct {
path string path string
click gpio.PinIn button *linuxButton
rotary *linuxRotary
} }
func newDevInputEncoder(click string) (enc Encoder, err error) { func newDevInputEncoder(click string) (enc Encoder, err error) {
e := new(devInputEncoder)
if e.click, err = hardware.LookupPin(click); err != nil {
return
}
var ps []*linuxPheripheral var ps []*linuxPheripheral
if ps, err = linuxPheripherals(); err != nil { if ps, err = linuxPheripherals(); err != nil {
return return
} }
var (
rotary *linuxRotary
button *linuxButton
)
for _, p := range ps { for _, p := range ps {
if strings.HasPrefix(p.name, "rotary@") { switch {
e.path = p.path case strings.HasPrefix(p.name, "rotary@"):
return e, nil rotary = &linuxRotary{p: p}
case strings.HasPrefix(p.name, "button@") && (click == "" || strings.HasSuffix(p.name, "@"+click)):
button = &linuxButton{p: p}
} }
} }
return nil, errors.New("no rotary encoders found in " + procInputDevices)
if rotary == nil {
return nil, errors.New("no rotary encoder found, is the rotary_encoder dtoveraly loaded?")
}
if button == nil {
return nil, errors.New("no button found, is the gpio-key dtoverlay loaded?")
}
return &devInputEncoder{
button: button,
rotary: rotary,
}, nil
}
func (e devInputEncoder) Halt() error {
return nil
}
func (e devInputEncoder) Type() string {
return e.path
}
func (e devInputEncoder) Events() (<-chan hardware.InputEvent, error) {
events := make(chan hardware.InputEvent, 8)
go e.rotary.readEvents(events)
go e.button.readEvents(events)
return events, nil
} }
type linuxPheripheral struct { type linuxPheripheral struct {
@@ -146,6 +176,10 @@ type linuxInputEvent struct {
Value int32 Value int32
} }
func (e linuxInputEvent) String() string {
return fmt.Sprintf("time=%s type=%#04x code=%#04x value=%d", e.Time(), e.Type, e.Code, e.Value)
}
func (e linuxInputEvent) Time() time.Time { func (e linuxInputEvent) Time() time.Time {
return time.Unix(int64(e.Secs), int64(e.USecs)) return time.Unix(int64(e.Secs), int64(e.USecs))
} }
@@ -180,38 +214,47 @@ func (s *linuxButton) Name() string {
return s.p.name return s.p.name
} }
func (s *linuxButton) Events() (<-chan Event, error) { func (s *linuxButton) Events() (<-chan hardware.InputEvent, error) {
log := logrus. log := logrus.
WithField("input", "button"). WithField("input", "button").
WithField("path", s.p.path) WithField("path", s.p.path)
log.Debug("opening linux button source") log.Debug("opening linux button source")
events := make(chan Event) events := make(chan hardware.InputEvent)
go s.readEvents(events) go s.readEvents(events)
return events, nil return events, nil
} }
func (s *linuxButton) readEvents(events chan<- Event) { func (s *linuxButton) readEvents(events chan<- hardware.InputEvent) {
defer close(events) defer close(events)
log := logrus. log := logrus.
WithField("input", "button"). WithField("input", "button").
WithField("path", s.p.path) WithField("path", s.p.path)
var last time.Time
err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error { err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error {
log.WithField("data", ev).Debug("button event")
if ev.Code == 0 { if ev.Code == 0 {
return nil // not sure what this is return nil // Ignore
} }
var pressed bool log.WithField("data", ev).Trace("button event")
if ev.Value == 1 {
pressed = true var event hardware.InputEvent
switch ev.Value {
case 0: // Released
if ev.Time().Sub(last) > LongPressDuration {
event = hardware.RotaryLongPressEvent{Time: ev.Time()}
} else {
event = hardware.RotaryPressEvent{Time: ev.Time()}
}
case 1: // Pressed
last = ev.Time()
return nil
} }
select { select {
case events <- NewButtonEvent(s, pressed): case events <- event:
default: default:
log.Warn("dropping event") log.Warn("dropping event")
} }
@@ -235,18 +278,18 @@ func (s *linuxRotary) Name() string {
return s.p.name return s.p.name
} }
func (s *linuxRotary) Events() (<-chan Event, error) { func (s *linuxRotary) Events() (<-chan hardware.InputEvent, error) {
log := logrus. log := logrus.
WithField("input", "rotary"). WithField("input", "rotary").
WithField("path", s.p.path) WithField("path", s.p.path)
log.Debug("opening linux rotary source") log.Debug("opening linux rotary source")
events := make(chan Event) events := make(chan hardware.InputEvent)
go s.readEvents(events) go s.readEvents(events)
return events, nil return events, nil
} }
func (s *linuxRotary) readEvents(events chan<- Event) { func (s *linuxRotary) readEvents(events chan<- hardware.InputEvent) {
defer close(events) defer close(events)
log := logrus. log := logrus.
@@ -254,10 +297,18 @@ func (s *linuxRotary) readEvents(events chan<- Event) {
WithField("path", s.p.path) WithField("path", s.p.path)
err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error { err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error {
log.WithField("data", ev).Debug("rotary event") if ev.Value == 0 {
return nil // Ignore
}
log.WithField("data", ev).Trace("rotary event")
event := hardware.RotaryEvent{
Time: ev.Time(),
Delta: int(ev.Value),
}
select { select {
case events <- NewRotaryEvent(s, int(ev.Value), ev.Value == 0): case events <- event:
default: default:
log.Warn("dropping event") log.Warn("dropping event")
} }
+70
View File
@@ -0,0 +1,70 @@
package hardware
import (
"fmt"
"image"
"image/color"
"github.com/BeatGlow/display"
)
// View is a (partial) view on the display.
type View struct {
display.Display
Window image.Rectangle
}
func MakeView(display display.Display, window image.Rectangle) View {
return View{
Display: display,
Window: window,
}
}
func (d View) Bounds() image.Rectangle {
return d.Window.Sub(d.Window.Min)
}
func (d View) Clear() {
if d.Window.Eq(d.Display.Bounds()) {
d.Display.Clear()
return
}
for y := d.Window.Min.Y; y < d.Window.Max.Y; y++ {
for x := d.Window.Min.X; x < d.Window.Max.X; x++ {
d.Display.Set(x, y, color.Transparent)
}
}
}
// Close doesn't do anything.
func (View) Close() error {
return nil
}
func (d View) Type() string {
return fmt.Sprintf("view:%s:%s", d.Display, d.Window)
}
func (d View) Size() image.Point {
return d.Window.Size()
}
func (d View) At(x, y int) color.Color {
if x < 0 || y < 0 || x >= d.Window.Dx() || y >= d.Window.Dy() {
return d.Display.ColorModel().Convert(color.Black)
}
x += d.Window.Min.X
y += d.Window.Min.Y
return d.Display.At(x, y)
}
func (d View) Set(x, y int, c color.Color) {
if x < 0 || y < 0 || x >= d.Window.Dx() || y >= d.Window.Dy() {
return
}
x += d.Window.Min.X
y += d.Window.Min.Y
d.Display.Set(x, y, c)
}
+26 -4
View File
@@ -32,6 +32,28 @@ type Number interface {
Integer | Float Integer | Float
} }
// Min of values.
func Min[T Number](data []T) T {
var min T
for _, v := range data {
if v < min {
min = v
}
}
return min
}
// Max of values.
func Max[T Number](data []T) T {
var max T
for _, v := range data {
if v > max {
max = v
}
}
return max
}
// Sum of values. // Sum of values.
func Sum[T Number](data []T) T { func Sum[T Number](data []T) T {
if len(data) == 0 { if len(data) == 0 {
@@ -124,7 +146,7 @@ func MeanOffset[T Number](data []T, start, offset int) float64 {
} }
// RMS is the root mean square of values. // RMS is the root mean square of values.
func RMS[T Number](data []T) float64 { func RMS[T Number](data []T) T {
if len(data) == 0 { if len(data) == 0 {
return 0 return 0
} }
@@ -134,11 +156,11 @@ func RMS[T Number](data []T) float64 {
squares += float64(v) * float64(v) squares += float64(v) * float64(v)
} }
return math.Sqrt(squares / float64(len(data))) return T(math.Sqrt(squares / float64(len(data))))
} }
// RMSOffset is the root mean square of values every offset. // RMSOffset is the root mean square of values every offset.
func RMSOffset[T Number](data []T, start, offset int) float64 { func RMSOffset[T Number](data []T, start, offset int) T {
if len(data)/offset == 0 { if len(data)/offset == 0 {
return 0 return 0
} }
@@ -148,7 +170,7 @@ func RMSOffset[T Number](data []T, start, offset int) float64 {
squares += float64(data[i]) * float64(data[i]) squares += float64(data[i]) * float64(data[i])
} }
return math.Sqrt(squares / float64(len(data)/offset)) return T(math.Sqrt(squares / float64(len(data)/offset)))
} }
func Eq(a, b, epsilon float32) bool { func Eq(a, b, epsilon float32) bool {
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"math" "math"
"testing" "testing"
"go.maze.io/harmon/internal/calc" "github.com/BeatGlow/beatglow/internal/calc"
) )
func TestMean(t *testing.T) { func TestMean(t *testing.T) {
+49
View File
@@ -0,0 +1,49 @@
package calc
import "math"
// Hann modifies seq in place by the Hann window and returns the result.
// See https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
// and https://www.recordingblogs.com/wiki/hann-window for details.
//
// The Hann window is a high-resolution window.
//
// The sequence weights are
//
// w[k] = 0.5*(1 - cos(2*π*k/(N-1))),
//
// for k=0,1,...,N-1 where N is the length of the window.
//
// Spectral leakage parameters: ΔF_0 = 4, ΔF_0.5 = 1.5, K = 2, ɣ_max = -31.5, β = -6.
func Hann(dst, src []float64) {
k := 2 * math.Pi / float64(len(src)-1)
for i := range src {
dst[i] = src[i] * (0.5 * (1 - math.Cos(k*float64(i))))
}
}
// Hamming modifies seq in place by the Hamming window and returns the result.
// See https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
// and https://www.recordingblogs.com/wiki/hamming-window for details.
//
// The Hamming window is a high-resolution window. Among K=2 windows it has
// the highest ɣ_max.
//
// The sequence weights are
//
// w[k] = 25/46 - 21/46 * cos(2*π*k/(N-1)),
//
// for k=0,1,...,N-1 where N is the length of the window.
//
// Spectral leakage parameters: ΔF_0 = 4, ΔF_0.5 = 1.33, K = 2, ɣ_max = -42, β = -5.37.
func Hamming(dst, src []float64) {
const (
a0 = 0.54
a1 = 0.46
)
k := 2 * math.Pi / float64(len(src)-1)
for i := range src {
dst[i] = src[i] * (a0 - a1*math.Cos(k*float64(i)))
}
}
+26
View File
@@ -0,0 +1,26 @@
package fourier
import "unsafe"
// ToComplex converts a slice of float64 into a slice of complex128, where the input
// slice's values are set as the real part of the complex numbers
//
// In Go, a complex number is a pair of two float numbers. This means that converting a
// float number to a complex number only makes it necessary to assign the (float's) value as
// the real part of the complex number, leaving the imaginary as zero.
//
// This particular function leverages that by creating a float slice of twice the size as the inputs, and
// placing each element of the input on every second slot. Finally, it casts this float slice as a complex slice,
// using an unsafe approach to prioritize performance.
func ToComplex(x []float64) []complex128 {
var (
length = len(x)
out = make([]float64, length*2)
)
for i, j := 0, 0; i < len(x); i, j = i+1, (i+1)*2 {
out[j] = x[i]
}
return (*(*[]complex128)(unsafe.Pointer(&out)))[:length]
}
+147
View File
@@ -0,0 +1,147 @@
package fourier
import (
"math"
"github.com/BeatGlow/BeatGlow/internal/dsp/fourier/window"
)
const (
tau = 2 * math.Pi
// DefaultMagnitudeThreshold describes the default value where a certain
// frequency is strong enough to be considered relevant to the spectrum filter.
DefaultMagnitudeThreshold = 10
)
// FrequencyPower denotes a single frequency and its magnitude in a Fast
// Fourier Transform of a signal.
type FrequencyPower struct {
Freq int
Mag float64
}
// Apply applies a Fast Fourier Transform (FFT) on a slice of float64 `data`,
// with sample rate `sampleRate`. It returns a slice of FrequencyPower.
func Apply(sampleRate int, data []float64, w window.Window) []FrequencyPower {
var (
ln = len(data)
magnitudes = make([]FrequencyPower, 0, (ln/2)-1)
)
// apply a window function to the values
if w != nil && len(w) == ln {
w.Apply(data)
}
// apply a fast Fourier transform on the data; exclude index 0, no 0Hz-freq results
spectrum := FFT(ToComplex(data))
for i := 1; i < ln/2; i++ {
freqReal := real(spectrum[i])
freqImag := imag(spectrum[i])
// map the magnitude for each frequency bin to the corresponding value in the map
// using math.Sqrt(re*re + im*im) is faster than using math.Hypot(re, im)
// see fft_test.go for details
magnitudes = append(
magnitudes,
FrequencyPower{
Freq: i * sampleRate / ln,
Mag: math.Sqrt(freqReal*freqReal + freqImag*freqImag),
},
)
}
return magnitudes
}
// FFT applies a Fast Fourier Transform to the input slice of complex128 values, to
// retrieve the frequency spectrum of a digital signal.
func FFT(value []complex128) []complex128 {
var (
valueLen = len(value)
factors = GetRadix2Factors(valueLen)
temp = make([]complex128, valueLen) // temp
)
value = ReorderData(value)
// stage increases by a power of two
for stage := 2; stage <= valueLen; stage <<= 1 {
var (
blocks = valueLen / stage
stage2Value = stage / 2
)
// iterate through each item in the batch, increasing by the stage value
for batchIdx := 0; batchIdx < valueLen; batchIdx += stage {
if stage == 2 { // "first stage" scenario
var (
reorderIdx = value[batchIdx]
reorderNext = value[batchIdx+1]
)
temp[batchIdx] = reorderIdx + reorderNext
temp[batchIdx+1] = reorderIdx - reorderNext
continue
}
for iter := 0; iter < stage2Value; iter++ {
var (
idx = iter + batchIdx
idx2 = idx + stage2Value
reorderIdx = value[idx]
factorized = value[idx2] * factors[blocks*iter]
)
temp[idx] = reorderIdx + factorized
temp[idx2] = reorderIdx - factorized
}
}
value, temp = temp, value
}
return value
}
// IFFT returns the Inverse Fast Fourier Transform of a given complex128 slice.
func IFFT(value []complex128) []complex128 {
var (
ln = len(value)
output = make([]complex128, ln)
factor = complex(float64(ln), 0)
)
// Reverse inputs, which is calculated with modulo factor, hence value[0] as an outlier
output[0] = value[0]
for i, j := 1, ln-1; i < ln; i, j = i+1, j-1 {
output[i] = value[j]
}
output = FFT(output)
for i := range output {
output[i] /= factor
}
return output
}
// Convolve returns the convolution of x ∗ y, applied to the complex128 slice x.
func Convolve(x, y []complex128) []complex128 {
if len(x) != len(y) {
return nil
}
x = FFT(x)
y = FFT(y)
for i := 0; i < len(x); i++ {
x[i] *= y[i]
}
return IFFT(x)
}
+58
View File
@@ -0,0 +1,58 @@
package fourier
// Log2Types is a type constraint interface to scope the allowed types to
// call the Log2 function.
type Log2Types interface {
uint | uint16 | uint32 | uint64 | int | int16 | int32 | int64
}
// Log2 returns the log base 2 of v, matching the input to precomputed
// values to achieve the fastest performance possible.
//
// If the input is not present, then its log2 value is computed with a fast
// bit-shifting technique.
//
// from: http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
func Log2[T Log2Types](v T) T {
switch v {
case 0, 1:
return 0
case 2:
return 1
case 4:
return 2
case 8:
return 3
case 16:
return 4
case 32:
return 5
case 64:
return 6
case 128:
return 7
case 256:
return 8
case 512:
return 9
case 1024:
return 10
case 2048:
return 11
case 4096:
return 12
case 8192:
return 13
default:
return log2(v)
}
}
func log2[T Log2Types](v T) T {
var r T
for v >>= 1; v != 0; v >>= 1 {
r++
}
return r
}
+45
View File
@@ -0,0 +1,45 @@
package fourier
import "math"
const (
firstCur = 2048
firstPrev = 1024
)
// GetRadix2Factors is temporarily public, could become private at a later point.
func GetRadix2Factors(inputLen int) []complex128 {
if factors, ok := radix2Factors[inputLen]; ok {
return factors
}
for factor, prev := firstCur, firstPrev; factor <= inputLen; factor, prev = factor<<1, factor {
if _, ok := radix2Factors[factor]; !ok {
radix2Factors[factor] = make([]complex128, factor)
for n, j := 0, 0; n < factor; n, j = n+2, j+1 {
radix2Factors[factor][n] = radix2Factors[prev][j]
}
for n := 1; n < factor; n += 2 {
v := -tau / float64(factor) * float64(n)
radix2Factors[factor][n] = complex(
math.Cos(v), math.Sin(v),
)
}
}
}
return radix2Factors[inputLen]
}
var radix2Factors = map[int][]complex128{
4: {1 + 0i, 0 - 1i, -1 + 0i, 0 + 1i},
8: {1 + 0i, 0.7071067811865476 - 0.7071067811865475i, 0 - 1i, -0.7071067811865475 - 0.7071067811865476i, -1 + 0i, -0.7071067811865477 + 0.7071067811865475i, 0 + 1i, 0.7071067811865475 + 0.7071067811865477i},
16: {1 + 0i, 0.9238795325112867 - 0.3826834323650898i, 0.7071067811865476 - 0.7071067811865475i, 0.38268343236508984 - 0.9238795325112867i, 0 - 1i, -0.3826834323650897 - 0.9238795325112867i, -0.7071067811865475 - 0.7071067811865476i, -0.9238795325112867 - 0.38268343236508984i, -1 + 0i, -0.9238795325112868 + 0.38268343236508967i, -0.7071067811865477 + 0.7071067811865475i, -0.38268343236509034 + 0.9238795325112865i, 0 + 1i, 0.38268343236509 + 0.9238795325112866i, 0.7071067811865475 + 0.7071067811865477i, 0.9238795325112865 + 0.3826834323650904i},
32: {1 + 0i, 0.9807852804032304 - 0.19509032201612825i, 0.9238795325112867 - 0.3826834323650898i, 0.8314696123025453 - 0.5555702330196022i, 0.7071067811865476 - 0.7071067811865475i, 0.5555702330196023 - 0.8314696123025452i, 0.38268343236508984 - 0.9238795325112867i, 0.1950903220161283 - 0.9807852804032304i, 0 - 1i, -0.1950903220161282 - 0.9807852804032304i, -0.3826834323650897 - 0.9238795325112867i, -0.555570233019602 - 0.8314696123025453i, -0.7071067811865475 - 0.7071067811865476i, -0.8314696123025453 - 0.5555702330196021i, -0.9238795325112867 - 0.38268343236508984i, -0.9807852804032303 - 0.19509032201612858i, -1 + 0i, -0.9807852804032304 + 0.19509032201612836i, -0.9238795325112868 + 0.38268343236508967i, -0.8314696123025453 + 0.555570233019602i, -0.7071067811865477 + 0.7071067811865475i, -0.5555702330196022 + 0.8314696123025453i, -0.38268343236509034 + 0.9238795325112865i, -0.19509032201612866 + 0.9807852804032303i, 0 + 1i, 0.19509032201612828 + 0.9807852804032304i, 0.38268343236509 + 0.9238795325112866i, 0.5555702330196018 + 0.8314696123025455i, 0.7071067811865475 + 0.7071067811865477i, 0.8314696123025453 + 0.5555702330196022i, 0.9238795325112865 + 0.3826834323650904i, 0.9807852804032303 + 0.19509032201612872i},
64: {1 + 0i, 0.9951847266721968 - 0.0980171403295606i, 0.9807852804032304 - 0.19509032201612825i, 0.9569403357322088 - 0.29028467725446233i, 0.9238795325112867 - 0.3826834323650898i, 0.881921264348355 - 0.47139673682599764i, 0.8314696123025453 - 0.5555702330196022i, 0.773010453362737 - 0.6343932841636455i, 0.7071067811865476 - 0.7071067811865475i, 0.6343932841636456 - 0.7730104533627369i, 0.5555702330196023 - 0.8314696123025452i, 0.4713967368259978 - 0.8819212643483549i, 0.38268343236508984 - 0.9238795325112867i, 0.29028467725446233 - 0.9569403357322089i, 0.1950903220161283 - 0.9807852804032304i, 0.09801714032956077 - 0.9951847266721968i, 0 - 1i, -0.09801714032956066 - 0.9951847266721968i, -0.1950903220161282 - 0.9807852804032304i, -0.2902846772544622 - 0.9569403357322089i, -0.3826834323650897 - 0.9238795325112867i, -0.4713967368259977 - 0.8819212643483549i, -0.555570233019602 - 0.8314696123025453i, -0.6343932841636453 - 0.7730104533627371i, -0.7071067811865475 - 0.7071067811865476i, -0.773010453362737 - 0.6343932841636455i, -0.8314696123025453 - 0.5555702330196021i, -0.8819212643483549 - 0.4713967368259978i, -0.9238795325112867 - 0.38268343236508984i, -0.9569403357322088 - 0.29028467725446233i, -0.9807852804032303 - 0.19509032201612858i, -0.9951847266721968 - 0.09801714032956084i, -1 + 0i, -0.9951847266721968 + 0.09801714032956059i, -0.9807852804032304 + 0.19509032201612836i, -0.9569403357322089 + 0.29028467725446216i, -0.9238795325112868 + 0.38268343236508967i, -0.881921264348355 + 0.47139673682599764i, -0.8314696123025453 + 0.555570233019602i, -0.7730104533627371 + 0.6343932841636453i, -0.7071067811865477 + 0.7071067811865475i, -0.6343932841636459 + 0.7730104533627367i, -0.5555702330196022 + 0.8314696123025453i, -0.47139673682599786 + 0.8819212643483548i, -0.38268343236509034 + 0.9238795325112865i, -0.2902846772544624 + 0.9569403357322088i, -0.19509032201612866 + 0.9807852804032303i, -0.09801714032956045 + 0.9951847266721968i, 0 + 1i, 0.09801714032956009 + 0.9951847266721969i, 0.19509032201612828 + 0.9807852804032304i, 0.2902846772544621 + 0.9569403357322089i, 0.38268343236509 + 0.9238795325112866i, 0.4713967368259976 + 0.881921264348355i, 0.5555702330196018 + 0.8314696123025455i, 0.6343932841636456 + 0.7730104533627369i, 0.7071067811865475 + 0.7071067811865477i, 0.7730104533627367 + 0.6343932841636459i, 0.8314696123025453 + 0.5555702330196022i, 0.8819212643483548 + 0.4713967368259979i, 0.9238795325112865 + 0.3826834323650904i, 0.9569403357322088 + 0.29028467725446244i, 0.9807852804032303 + 0.19509032201612872i, 0.9951847266721968 + 0.09801714032956052i},
128: {1 + 0i, 0.9987954562051724 - 0.049067674327418015i, 0.9951847266721968 - 0.0980171403295606i, 0.989176509964781 - 0.14673047445536175i, 0.9807852804032304 - 0.19509032201612825i, 0.9700312531945441 - 0.24298017990326387i, 0.9569403357322088 - 0.29028467725446233i, 0.9415440651830208 - 0.33688985339222005i, 0.9238795325112867 - 0.3826834323650898i, 0.9039892931234433 - 0.4275550934302821i, 0.881921264348355 - 0.47139673682599764i, 0.8577286100002721 - 0.5141027441932217i, 0.8314696123025453 - 0.5555702330196022i, 0.8032075314806449 - 0.5956993044924334i, 0.773010453362737 - 0.6343932841636455i, 0.7409511253549591 - 0.6715589548470183i, 0.7071067811865476 - 0.7071067811865475i, 0.6715589548470184 - 0.7409511253549591i, 0.6343932841636456 - 0.7730104533627369i, 0.5956993044924335 - 0.8032075314806448i, 0.5555702330196023 - 0.8314696123025452i, 0.5141027441932218 - 0.8577286100002721i, 0.4713967368259978 - 0.8819212643483549i, 0.4275550934302822 - 0.9039892931234433i, 0.38268343236508984 - 0.9238795325112867i, 0.33688985339222005 - 0.9415440651830208i, 0.29028467725446233 - 0.9569403357322089i, 0.24298017990326398 - 0.970031253194544i, 0.1950903220161283 - 0.9807852804032304i, 0.14673047445536175 - 0.989176509964781i, 0.09801714032956077 - 0.9951847266721968i, 0.04906767432741813 - 0.9987954562051724i, 0 - 1i, -0.04906767432741801 - 0.9987954562051724i, -0.09801714032956066 - 0.9951847266721968i, -0.14673047445536164 - 0.989176509964781i, -0.1950903220161282 - 0.9807852804032304i, -0.24298017990326387 - 0.9700312531945441i, -0.2902846772544622 - 0.9569403357322089i, -0.33688985339221994 - 0.9415440651830209i, -0.3826834323650897 - 0.9238795325112867i, -0.42755509343028186 - 0.9039892931234434i, -0.4713967368259977 - 0.8819212643483549i, -0.5141027441932216 - 0.8577286100002722i, -0.555570233019602 - 0.8314696123025453i, -0.5956993044924332 - 0.8032075314806449i, -0.6343932841636453 - 0.7730104533627371i, -0.6715589548470184 - 0.7409511253549591i, -0.7071067811865475 - 0.7071067811865476i, -0.7409511253549589 - 0.6715589548470186i, -0.773010453362737 - 0.6343932841636455i, -0.8032075314806448 - 0.5956993044924335i, -0.8314696123025453 - 0.5555702330196021i, -0.8577286100002721 - 0.5141027441932218i, -0.8819212643483549 - 0.4713967368259978i, -0.9039892931234434 - 0.42755509343028203i, -0.9238795325112867 - 0.38268343236508984i, -0.9415440651830207 - 0.3368898533922203i, -0.9569403357322088 - 0.29028467725446233i, -0.970031253194544 - 0.24298017990326404i, -0.9807852804032303 - 0.19509032201612858i, -0.989176509964781 - 0.1467304744553618i, -0.9951847266721968 - 0.09801714032956084i, -0.9987954562051724 - 0.04906767432741797i, -1 + 0i, -0.9987954562051724 + 0.049067674327417724i, -0.9951847266721968 + 0.09801714032956059i, -0.989176509964781 + 0.14673047445536158i, -0.9807852804032304 + 0.19509032201612836i, -0.9700312531945441 + 0.24298017990326382i, -0.9569403357322089 + 0.29028467725446216i, -0.9415440651830208 + 0.3368898533922201i, -0.9238795325112868 + 0.38268343236508967i, -0.9039892931234436 + 0.4275550934302818i, -0.881921264348355 + 0.47139673682599764i, -0.8577286100002722 + 0.5141027441932216i, -0.8314696123025453 + 0.555570233019602i, -0.8032075314806449 + 0.5956993044924332i, -0.7730104533627371 + 0.6343932841636453i, -0.7409511253549591 + 0.6715589548470184i, -0.7071067811865477 + 0.7071067811865475i, -0.6715589548470187 + 0.7409511253549589i, -0.6343932841636459 + 0.7730104533627367i, -0.5956993044924332 + 0.803207531480645i, -0.5555702330196022 + 0.8314696123025453i, -0.5141027441932219 + 0.857728610000272i, -0.47139673682599786 + 0.8819212643483548i, -0.4275550934302825 + 0.9039892931234432i, -0.38268343236509034 + 0.9238795325112865i, -0.33688985339221994 + 0.9415440651830209i, -0.2902846772544624 + 0.9569403357322088i, -0.24298017990326412 + 0.970031253194544i, -0.19509032201612866 + 0.9807852804032303i, -0.14673047445536233 + 0.9891765099647809i, -0.09801714032956045 + 0.9951847266721968i, -0.04906767432741803 + 0.9987954562051724i, 0 + 1i, 0.04906767432741767 + 0.9987954562051724i, 0.09801714032956009 + 0.9951847266721969i, 0.14673047445536194 + 0.9891765099647809i, 0.19509032201612828 + 0.9807852804032304i, 0.24298017990326376 + 0.9700312531945441i, 0.2902846772544621 + 0.9569403357322089i, 0.3368898533922196 + 0.941544065183021i, 0.38268343236509 + 0.9238795325112866i, 0.4275550934302822 + 0.9039892931234433i, 0.4713967368259976 + 0.881921264348355i, 0.5141027441932214 + 0.8577286100002722i, 0.5555702330196018 + 0.8314696123025455i, 0.5956993044924328 + 0.8032075314806453i, 0.6343932841636456 + 0.7730104533627369i, 0.6715589548470183 + 0.7409511253549591i, 0.7071067811865475 + 0.7071067811865477i, 0.7409511253549589 + 0.6715589548470187i, 0.7730104533627367 + 0.6343932841636459i, 0.803207531480645 + 0.5956993044924332i, 0.8314696123025453 + 0.5555702330196022i, 0.857728610000272 + 0.5141027441932219i, 0.8819212643483548 + 0.4713967368259979i, 0.9039892931234431 + 0.427555093430282Line truncated
256: {1 + 0i, 0.9996988186962041 - 0.024541228522912288i, 0.9987954562051724 - 0.049067674327418015i, 0.9972904566786902 - 0.07356456359966743i, 0.9951847266721968 - 0.0980171403295606i, 0.9924795345987101 - 0.1224106751992162i, 0.989176509964781 - 0.14673047445536175i, 0.9852776423889412 - 0.17096188876030122i, 0.9807852804032304 - 0.19509032201612825i, 0.9757021300385286 - 0.2191012401568698i, 0.9700312531945441 - 0.24298017990326387i, 0.9637760657954398 - 0.26671275747489837i, 0.9569403357322088 - 0.29028467725446233i, 0.9495281805930367 - 0.3136817403988915i, 0.9415440651830208 - 0.33688985339222005i, 0.9329927988347388 - 0.3598950365349881i, 0.9238795325112867 - 0.3826834323650898i, 0.9142097557035307 - 0.40524131400498986i, 0.9039892931234433 - 0.4275550934302821i, 0.8932243011955153 - 0.44961132965460654i, 0.881921264348355 - 0.47139673682599764i, 0.8700869911087113 - 0.49289819222978404i, 0.8577286100002721 - 0.5141027441932217i, 0.8448535652497071 - 0.5349976198870972i, 0.8314696123025453 - 0.5555702330196022i, 0.8175848131515837 - 0.5758081914178453i, 0.8032075314806449 - 0.5956993044924334i, 0.7883464276266063 - 0.6152315905806268i, 0.773010453362737 - 0.6343932841636455i, 0.7572088465064846 - 0.6531728429537768i, 0.7409511253549591 - 0.6715589548470183i, 0.724247082951467 - 0.6895405447370669i, 0.7071067811865476 - 0.7071067811865475i, 0.6895405447370669 - 0.7242470829514668i, 0.6715589548470184 - 0.7409511253549591i, 0.6531728429537769 - 0.7572088465064845i, 0.6343932841636456 - 0.7730104533627369i, 0.6152315905806269 - 0.7883464276266062i, 0.5956993044924335 - 0.8032075314806448i, 0.5758081914178454 - 0.8175848131515836i, 0.5555702330196023 - 0.8314696123025452i, 0.5349976198870974 - 0.844853565249707i, 0.5141027441932218 - 0.8577286100002721i, 0.49289819222978415 - 0.8700869911087113i, 0.4713967368259978 - 0.8819212643483549i, 0.4496113296546066 - 0.8932243011955153i, 0.4275550934302822 - 0.9039892931234433i, 0.4052413140049898 - 0.9142097557035307i, 0.38268343236508984 - 0.9238795325112867i, 0.3598950365349883 - 0.9329927988347387i, 0.33688985339222005 - 0.9415440651830208i, 0.3136817403988915 - 0.9495281805930367i, 0.29028467725446233 - 0.9569403357322089i, 0.2667127574748984 - 0.9637760657954398i, 0.24298017990326398 - 0.970031253194544i, 0.21910124015686977 - 0.9757021300385286i, 0.1950903220161283 - 0.9807852804032304i, 0.17096188876030136 - 0.9852776423889412i, 0.14673047445536175 - 0.989176509964781i, 0.12241067519921628 - 0.9924795345987101i, 0.09801714032956077 - 0.9951847266721968i, 0.07356456359966745 - 0.9972904566786902i, 0.04906767432741813 - 0.9987954562051724i, 0.024541228522912267 - 0.9996988186962041i, 0 - 1i, -0.024541228522912142 - 0.9996988186962041i, -0.04906767432741801 - 0.9987954562051724i, -0.07356456359966734 - 0.9972904566786902i, -0.09801714032956066 - 0.9951847266721968i, -0.12241067519921617 - 0.9924795345987101i, -0.14673047445536164 - 0.989176509964781i, -0.17096188876030124 - 0.9852776423889412i, -0.1950903220161282 - 0.9807852804032304i, -0.21910124015686966 - 0.9757021300385286i, -0.24298017990326387 - 0.9700312531945441i, -0.2667127574748983 - 0.9637760657954398i, -0.2902846772544622 - 0.9569403357322089i, -0.31368174039889146 - 0.9495281805930367i, -0.33688985339221994 - 0.9415440651830209i, -0.35989503653498817 - 0.9329927988347388i, -0.3826834323650897 - 0.9238795325112867i, -0.40524131400498975 - 0.9142097557035308i, -0.42755509343028186 - 0.9039892931234434i, -0.4496113296546067 - 0.8932243011955153i, -0.4713967368259977 - 0.8819212643483549i, -0.4928981922297839 - 0.8700869911087115i, -0.5141027441932216 - 0.8577286100002722i, -0.5349976198870969 - 0.8448535652497072i, -0.555570233019602 - 0.8314696123025453i, -0.5758081914178453 - 0.8175848131515837i, -0.5956993044924332 - 0.8032075314806449i, -0.6152315905806267 - 0.7883464276266063i, -0.6343932841636453 - 0.7730104533627371i, -0.6531728429537765 - 0.7572088465064848i, -0.6715589548470184 - 0.7409511253549591i, -0.6895405447370669 - 0.724247082951467i, -0.7071067811865475 - 0.7071067811865476i, -0.7242470829514668 - 0.689540544737067i, -0.7409511253549589 - 0.6715589548470186i, -0.7572088465064847 - 0.6531728429537766i, -0.773010453362737 - 0.6343932841636455i, -0.7883464276266062 - 0.6152315905806269i, -0.8032075314806448 - 0.5956993044924335i, -0.8175848131515835 - 0.5758081914178454i, -0.8314696123025453 - 0.5555702330196021i, -0.8448535652497071 - 0.5349976198870972i, -0.8577286100002721 - 0.5141027441932218i, -0.8700869911087113 - 0.49289819222978415i, -0.8819212643483549 - 0.4713967368259978i, -0.8932243011955152 - 0.4496113296546069i, -0.9039892931234434 - 0.42755509343028203i, -0.9142097557035307 - 0.40524131400498986i, -0.9238795325112867 - 0.38268343236508984i, -0.9329927988347387 - 0.35989503653498833i, -0.9415440651830207 - 0.3368898533922203i, -0.9495281805930367 - 0.3136817403988914i, -0.9569403357322088 - 0.29028467725446233i, -0.9637760657954398 - 0.2667127574748985i, -0.97003125Line truncated
512: {1 + 0i, 0.9999247018391446 - 0.012271538285719925i, 0.9996988186962041 - 0.024541228522912288i, 0.9993223845883494 - 0.03680722294135883i, 0.9987954562051724 - 0.049067674327418015i, 0.9981181129001492 - 0.06132073630220858i, 0.9972904566786902 - 0.07356456359966743i, 0.996312612182778 - 0.0857973123444399i, 0.9951847266721968 - 0.0980171403295606i, 0.9939069700023561 - 0.11022220729388306i, 0.9924795345987101 - 0.1224106751992162i, 0.99090263542778 - 0.13458070850712617i, 0.989176509964781 - 0.14673047445536175i, 0.9873014181578584 - 0.15885814333386145i, 0.9852776423889412 - 0.17096188876030122i, 0.9831054874312164 - 0.18303988795514095i, 0.9807852804032304 - 0.19509032201612825i, 0.9783173707196277 - 0.20711137619221856i, 0.9757021300385286 - 0.2191012401568698i, 0.9729399522055602 - 0.2310581082806711i, 0.9700312531945441 - 0.24298017990326387i, 0.9669764710448521 - 0.25486565960451457i, 0.9637760657954398 - 0.26671275747489837i, 0.9604305194155658 - 0.27851968938505306i, 0.9569403357322088 - 0.29028467725446233i, 0.9533060403541938 - 0.3020059493192281i, 0.9495281805930367 - 0.3136817403988915i, 0.9456073253805213 - 0.3253102921622629i, 0.9415440651830208 - 0.33688985339222005i, 0.937339011912575 - 0.34841868024943456i, 0.9329927988347388 - 0.3598950365349881i, 0.9285060804732156 - 0.37131719395183754i, 0.9238795325112867 - 0.3826834323650898i, 0.9191138516900577 - 0.3939920400610481i, 0.9142097557035307 - 0.40524131400498986i, 0.9091679830905225 - 0.41642956009763715i, 0.9039892931234433 - 0.4275550934302821i, 0.8986744656939538 - 0.43861623853852766i, 0.8932243011955153 - 0.44961132965460654i, 0.8876396204028539 - 0.46053871095824i, 0.881921264348355 - 0.47139673682599764i, 0.8760700941954066 - 0.4821837720791227i, 0.8700869911087113 - 0.49289819222978404i, 0.8639728561215867 - 0.5035383837257176i, 0.8577286100002721 - 0.5141027441932217i, 0.8513551931052652 - 0.524589682678469i, 0.8448535652497071 - 0.5349976198870972i, 0.8382247055548381 - 0.5453249884220465i, 0.8314696123025453 - 0.5555702330196022i, 0.8245893027850253 - 0.5657318107836131i, 0.8175848131515837 - 0.5758081914178453i, 0.8104571982525948 - 0.5857978574564389i, 0.8032075314806449 - 0.5956993044924334i, 0.7958369046088836 - 0.6055110414043255i, 0.7883464276266063 - 0.6152315905806268i, 0.7807372285720945 - 0.6248594881423863i, 0.773010453362737 - 0.6343932841636455i, 0.765167265622459 - 0.6438315428897914i, 0.7572088465064846 - 0.6531728429537768i, 0.7491363945234594 - 0.6624157775901718i, 0.7409511253549591 - 0.6715589548470183i, 0.7326542716724129 - 0.680600997795453i, 0.724247082951467 - 0.6895405447370669i, 0.7157308252838186 - 0.6983762494089729i, 0.7071067811865476 - 0.7071067811865475i, 0.6983762494089729 - 0.7157308252838186i, 0.6895405447370669 - 0.7242470829514668i, 0.6806009977954531 - 0.7326542716724128i, 0.6715589548470184 - 0.7409511253549591i, 0.6624157775901718 - 0.7491363945234593i, 0.6531728429537769 - 0.7572088465064845i, 0.6438315428897915 - 0.765167265622459i, 0.6343932841636456 - 0.7730104533627369i, 0.6248594881423865 - 0.7807372285720944i, 0.6152315905806269 - 0.7883464276266062i, 0.6055110414043255 - 0.7958369046088835i, 0.5956993044924335 - 0.8032075314806448i, 0.585797857456439 - 0.8104571982525947i, 0.5758081914178454 - 0.8175848131515836i, 0.5657318107836132 - 0.8245893027850253i, 0.5555702330196023 - 0.8314696123025452i, 0.5453249884220466 - 0.838224705554838i, 0.5349976198870974 - 0.844853565249707i, 0.524589682678469 - 0.8513551931052652i, 0.5141027441932218 - 0.8577286100002721i, 0.5035383837257176 - 0.8639728561215866i, 0.49289819222978415 - 0.8700869911087113i, 0.4821837720791229 - 0.8760700941954065i, 0.4713967368259978 - 0.8819212643483549i, 0.46053871095824 - 0.8876396204028539i, 0.4496113296546066 - 0.8932243011955153i, 0.43861623853852766 - 0.8986744656939538i, 0.4275550934302822 - 0.9039892931234433i, 0.4164295600976373 - 0.9091679830905224i, 0.4052413140049898 - 0.9142097557035307i, 0.3939920400610481 - 0.9191138516900577i, 0.38268343236508984 - 0.9238795325112867i, 0.3713171939518376 - 0.9285060804732156i, 0.3598950365349883 - 0.9329927988347387i, 0.3484186802494345 - 0.937339011912575i, 0.33688985339222005 - 0.9415440651830208i, 0.325310292162263 - 0.9456073253805213i, 0.3136817403988915 - 0.9495281805930367i, 0.3020059493192282 - 0.9533060403541938i, 0.29028467725446233 - 0.9569403357322089i, 0.27851968938505306 - 0.9604305194155658i, 0.2667127574748984 - 0.9637760657954398i, 0.2548656596045146 - 0.9669764710448521i, 0.24298017990326398 - 0.970031253194544i, 0.23105810828067125 - 0.9729399522055602i, 0.21910124015686977 - 0.9757021300385286i, 0.20711137619221856 - 0.9783173707196277i, 0.1950903220161283 - 0.9807852804032304i, 0.18303988795514103 - 0.9831054874312164i, 0.17096188876030136 - 0.9852776423889412i, 0.1588581433338614 - 0.9873014181578584i, 0.14673047445536175 - 0.989176509964781i, 0.13458070850712622 - 0.99090263542778i, 0.12241067519921628 - 0.9924795345987101i, 0.11022Line truncated
1024: {1 + 0i, 0.9999811752826011 - 0.006135884649154475i, 0.9999247018391446 - 0.012271538285719925i, 0.9998305817958234 - 0.01840672990580482i, 0.9996988186962041 - 0.024541228522912288i, 0.9995294175010931 - 0.030674803176636626i, 0.9993223845883494 - 0.03680722294135883i, 0.9990777277526454 - 0.04293825693494082i, 0.9987954562051724 - 0.049067674327418015i, 0.9984755805732948 - 0.05519524434968994i, 0.9981181129001492 - 0.06132073630220858i, 0.9977230666441916 - 0.06744391956366405i, 0.9972904566786902 - 0.07356456359966743i, 0.9968202992911658 - 0.07968243797143013i, 0.996312612182778 - 0.0857973123444399i, 0.9957674144676598 - 0.09190895649713272i, 0.9951847266721968 - 0.0980171403295606i, 0.9945645707342554 - 0.10412163387205459i, 0.9939069700023561 - 0.11022220729388306i, 0.9932119492347945 - 0.11631863091190475i, 0.9924795345987101 - 0.1224106751992162i, 0.9917097536690995 - 0.12849811079379317i, 0.99090263542778 - 0.13458070850712617i, 0.9900582102622971 - 0.1406582393328492i, 0.989176509964781 - 0.14673047445536175i, 0.9882575677307495 - 0.15279718525844344i, 0.9873014181578584 - 0.15885814333386145i, 0.9863080972445987 - 0.16491312048996992i, 0.9852776423889412 - 0.17096188876030122i, 0.984210092386929 - 0.17700422041214875i, 0.9831054874312164 - 0.18303988795514095i, 0.9819638691095552 - 0.1890686641498062i, 0.9807852804032304 - 0.19509032201612825i, 0.9795697656854406 - 0.2011046348420919i, 0.9783173707196277 - 0.20711137619221856i, 0.9770281426577543 - 0.21311031991609136i, 0.9757021300385286 - 0.2191012401568698i, 0.9743393827855759 - 0.22508391135979283i, 0.9729399522055602 - 0.2310581082806711i, 0.9715038909862518 - 0.2370236059943672i, 0.9700312531945441 - 0.24298017990326387i, 0.9685220942744173 - 0.24892760574572015i, 0.9669764710448521 - 0.25486565960451457i, 0.9653944416976894 - 0.2607941179152755i, 0.9637760657954398 - 0.26671275747489837i, 0.9621214042690416 - 0.272621355449949i, 0.9604305194155658 - 0.27851968938505306i, 0.9587034748958715 - 0.2844075372112719i, 0.9569403357322088 - 0.29028467725446233i, 0.9551411683057708 - 0.2961508882436238i, 0.9533060403541938 - 0.3020059493192281i, 0.9514350209690083 - 0.30784964004153487i, 0.9495281805930367 - 0.3136817403988915i, 0.9475855910177412 - 0.3195020308160157i, 0.9456073253805213 - 0.3253102921622629i, 0.9435934581619604 - 0.33110630575987643i, 0.9415440651830208 - 0.33688985339222005i, 0.9394592236021899 - 0.3426607173119944i, 0.937339011912575 - 0.34841868024943456i, 0.9351835099389476 - 0.35416352542049034i, 0.9329927988347388 - 0.3598950365349881i, 0.9307669610789837 - 0.36561299780477385i, 0.9285060804732156 - 0.37131719395183754i, 0.9262102421383114 - 0.37700741021641826i, 0.9238795325112867 - 0.3826834323650898i, 0.921514039342042 - 0.38834504669882625i, 0.9191138516900577 - 0.3939920400610481i, 0.9166790599210427 - 0.3996241998456468i, 0.9142097557035307 - 0.40524131400498986i, 0.9117060320054299 - 0.4108431710579039i, 0.9091679830905225 - 0.41642956009763715i, 0.9065957045149153 - 0.4220002707997997i, 0.9039892931234433 - 0.4275550934302821i, 0.901348847046022 - 0.43309381885315196i, 0.8986744656939538 - 0.43861623853852766i, 0.8959662497561852 - 0.4441221445704292i, 0.8932243011955153 - 0.44961132965460654i, 0.8904487232447579 - 0.45508358712634384i, 0.8876396204028539 - 0.46053871095824i, 0.8847970984309378 - 0.4659764957679662i, 0.881921264348355 - 0.47139673682599764i, 0.8790122264286335 - 0.4767992300633221i, 0.8760700941954066 - 0.4821837720791227i, 0.8730949784182901 - 0.487550160148436i, 0.8700869911087113 - 0.49289819222978404i, 0.8670462455156926 - 0.49822766697278187i, 0.8639728561215867 - 0.5035383837257176i, 0.8608669386377673 - 0.508830142543107i, 0.8577286100002721 - 0.5141027441932217i, 0.8545579883654005 - 0.5193559901655896i, 0.8513551931052652 - 0.524589682678469i, 0.8481203448032972 - 0.5298036246862946i, 0.8448535652497071 - 0.5349976198870972i, 0.8415549774368984 - 0.5401714727298929i, 0.8382247055548381 - 0.5453249884220465i, 0.8348628749863801 - 0.5504579729366048i, 0.8314696123025453 - 0.5555702330196022i, 0.8280450452577557 - 0.560661576197336i, 0.8245893027850253 - 0.5657318107836131i, 0.8211025149911046 - 0.5707807458869673i, 0.8175848131515837 - 0.5758081914178453i, 0.8140363297059484 - 0.5808139580957645i, 0.8104571982525948 - 0.5857978574564389i, 0.8068475535437993 - 0.5907597018588742i, 0.8032075314806449 - 0.5956993044924334i, 0.799537269107905 - 0.600616479383869i, 0.7958369046088836 - 0.6055110414043255i, 0.7921065773002124 - 0.6103828062763095i, 0.7883464276266063 - 0.6152315905806268i, 0.7845565971555752 - 0.6200572117632891i, 0.7807372285720945 - 0.6248594881423863i, 0.7768884656732324 - 0.629638238914927i, 0.773010453362737 - 0.6343932841636455i, 0.7691033376455796 - 0.6391244448637757i, 0.765167265622459 - 0.6438315428897914i, 0.7612023854842618 - 0.6485144010221124i, 0.7572088465064846 - 0.6531728429537768i, 0.7531867990436125 - 0.6578066932970786i, 0.7491363945234594 - 0.66241577Line truncated
}
+46
View File
@@ -0,0 +1,46 @@
package fourier
// RevBitsTypes is a type constraint interface to scope the allowed types to
// call the ReverseBits function.
type RevBitsTypes interface {
uint | uint16 | uint32 | uint64 | int | int16 | int32 | int64
}
// ReverseFirstBits returns the first `size` bits of `value` in reverse order
// from: http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
func ReverseFirstBits[T RevBitsTypes](value, size T) (reverse T) {
for ; value > 0; value, size = value>>1, size-1 {
reverse <<= 1 // left shift
reverse |= value & 1 // add next bit
}
return reverse << size
}
// ReverseBits returns the bits of `value` in reverse order
// from: http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
func ReverseBits[T RevBitsTypes](value T) (reverse T) {
for ; value > 0; value >>= 1 {
reverse <<= 1 // left shift
reverse |= value & 1 // add next bit
}
return reverse
}
// ReorderData shuffles the input complex128 values to re-order it,
// setting the first half of the slice in even indexes and the last half
// of the slice in odd indexes.
func ReorderData(value []complex128) []complex128 {
var (
ln = len(value)
reorder = make([]complex128, ln)
sizeLog = Log2(ln)
)
for i := range value {
reorder[ReverseFirstBits(i, sizeLog)] = value[i]
}
return reorder
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+54
View File
@@ -0,0 +1,54 @@
package window
import (
"math"
)
const (
minBlockSize = 4
tau = math.Pi * 2
twoTau = math.Pi * 4
)
// GeneratorFunc is a type of function that generates a Window based on an input size.
type GeneratorFunc func(int) Window
// Generate calls the GeneratorFunc itself, with the input int `size`.
func (w GeneratorFunc) Generate(size int) Window {
return w(size)
}
// Window is a custom type for a slice of float64, that repesents a Window that shapes
// input signal.
type Window []float64
// Apply will go through the input slice of float64 values, and apply the window to it by
// multiplying the value by the ratio in the respective element in the Window.
func (w Window) Apply(value []float64) {
for idx := range value {
value[idx] *= w[idx]
}
}
//nolint:gochecknoglobals // immutable slice that contains supported block sizes
var blockSizes = []int{8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192}
// New creates a new Window from the input GeneratorFunc and size
//
// The size should be a power of two supported in the fft package's BlockSize.
//
// In case the input size `int` is not a power of two, it will fallback to the next
// available block size, with a series of bit-shifting operations on the input size
// to derive the closest element in the (private) blockSizes slice of ints.
func New(w GeneratorFunc, size int) Window {
var (
count int
blockSize = size >> minBlockSize
)
for i := blockSize; i > 0; i >>= 1 {
count++
}
return w(blockSizes[count])
}
+38
View File
@@ -0,0 +1,38 @@
package safe
import (
"image"
"sync/atomic"
)
type Point struct {
X, Y atomic.Int64
}
func (p *Point) Load() image.Point {
return image.Pt(
int(p.X.Load()),
int(p.Y.Load()),
)
}
func (p *Point) Store(point image.Point) {
p.X.Store(int64(point.X))
p.Y.Store(int64(point.Y))
}
type Rectangle struct {
Min, Max Point
}
func (r *Rectangle) Load() image.Rectangle {
return image.Rectangle{
Min: r.Min.Load(),
Max: r.Max.Load(),
}
}
func (r *Rectangle) Store(rect image.Rectangle) {
r.Min.Store(rect.Min)
r.Max.Store(rect.Max)
}
+1 -1
View File
@@ -3,7 +3,7 @@ package util_test
import ( import (
"testing" "testing"
"go.maze.io/harmon/internal/util" "github.com/BeatGlow/beatglow/internal/util"
) )
func TestMakeAddr(t *testing.T) { func TestMakeAddr(t *testing.T) {
+4 -4
View File
@@ -2,8 +2,8 @@
package all package all
import ( import (
_ "go.maze.io/harmon/player/moode" _ "github.com/BeatGlow/beatglow/player/moode"
_ "go.maze.io/harmon/player/mpd" _ "github.com/BeatGlow/beatglow/player/mpd"
_ "go.maze.io/harmon/player/runeaudio" _ "github.com/BeatGlow/beatglow/player/runeaudio"
_ "go.maze.io/harmon/player/volumio" _ "github.com/BeatGlow/beatglow/player/volumio"
) )
+14
View File
@@ -94,6 +94,10 @@ type (
MuteEvent struct { MuteEvent struct {
baseEvent baseEvent
} }
PlaylistEvent struct {
baseEvent
}
) )
func NewError(p Player, err error) Event { func NewError(p Player, err error) Event {
@@ -193,3 +197,13 @@ func NewMuteEvent(p Player) Event {
func (e MuteEvent) String() string { func (e MuteEvent) String() string {
return fmt.Sprintf("mute player=%s time=%s", e.player.Name(), e.time) return fmt.Sprintf("mute player=%s time=%s", e.player.Name(), e.time)
} }
func NewPlaylistEvent(p Player) Event {
return PlaylistEvent{
baseEvent: makeBaseEvent(p),
}
}
func (e PlaylistEvent) String() string {
return "playlst"
}
+19 -13
View File
@@ -9,10 +9,10 @@ import (
"strings" "strings"
"time" "time"
"go.maze.io/harmon/config" "github.com/BeatGlow/beatglow/config"
"go.maze.io/harmon/internal/util" "github.com/BeatGlow/beatglow/internal/util"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/player"
"go.maze.io/harmon/player/mpd" "github.com/BeatGlow/beatglow/player/mpd"
) )
const ( const (
@@ -36,24 +36,30 @@ func New(config config.Player) (player.Player, error) {
}, nil }, nil
} }
func (p *Player) Halt() error { return p.mpd.Halt() } func (p *Player) Halt() error { return p.mpd.Halt() }
func (Player) Type() string { return "moode" } func (Player) Type() string { return "moode" }
func (p *Player) Name() string { return "moOde" } func (p *Player) Name() string { return "moOde" }
func (p *Player) Next() error { return p.mpd.Next() }
func (p *Player) Previous() error { return p.mpd.Previous() }
func (p *Player) Play() error { return p.mpd.Play() }
func (p *Player) Pause() error { return p.mpd.Pause() }
func (p *Player) Seek(d time.Duration) error { return p.mpd.Seek(d) }
func (p *Player) ChangeVolume(delta int) error { return p.mpd.ChangeVolume(delta) }
func (p *Player) SetVolume(level int) error { return p.mpd.SetVolume(level) }
func (p *Player) ToggleMute() error { return p.mpd.ToggleMute() }
func (p *Player) Events() (<-chan player.Event, error) { func (p *Player) Events() (<-chan player.Event, error) {
return nil, nil return nil, nil
} }
func (Player) Next() error { return nil }
func (Player) Previous() error { return nil }
func (Player) Pause() error { return nil }
func (Player) Play() error { return nil }
func (Player) Seek(time.Duration) error { return nil }
func (p *Player) AlbumArt(t *player.Track) (image.Image, bool) { func (p *Player) AlbumArt(t *player.Track) (image.Image, bool) {
return p.mpd.AlbumArt(t) return p.mpd.AlbumArt(t)
} }
func (p *Player) Playlist() ([]*player.Track, error) {
return p.mpd.Playlist()
}
func (Player) Status() *player.Status { func (Player) Status() *player.Status {
s, _ := parseStatus(currentSongFile) s, _ := parseStatus(currentSongFile)
return s return s
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"periph.io/x/conn/v3/physic" "periph.io/x/conn/v3/physic"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/player"
) )
func TestParseAudioFormat(t *testing.T) { func TestParseAudioFormat(t *testing.T) {
+43 -3
View File
@@ -1,11 +1,16 @@
package mpd package mpd
import ( import (
"bytes"
"image" "image"
"strings"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/player"
_ "image/jpeg"
_ "image/png"
) )
type artRequest struct { type artRequest struct {
@@ -34,11 +39,46 @@ func (d *Player) AlbumArt(track *player.Track) (image.Image, bool) {
} }
func (d *Player) artLoop(conn *clientConn) { func (d *Player) artLoop(conn *clientConn) {
loop:
for { for {
select { select {
case request := <-d.artRequest: case request := <-d.artRequest:
logrus.WithField("path", request.Path).Debug("requesting album art") log := conn.log().WithFields(logrus.Fields{
request.Art <- nil "path": request.Path,
})
log.Debug("requesting album art")
var (
offset, size int
b, chunk []byte
i image.Image
err error
)
for {
if chunk, size, err = d.sendBinaryCommand(conn, "albumart %q %d", request.Path, offset); err != nil {
request.Art <- nil
if !strings.Contains(err.Error(), "No file exists") {
log.WithError(err).Error("error reading album art")
break loop
}
log.WithError(err).Debug("no album art found")
continue loop
}
b = append(b, chunk...)
offset = len(b)
if offset >= size {
break
}
}
if i, _, err = image.Decode(bytes.NewBuffer(b)); err != nil {
request.Art <- nil
log.WithError(err).Warn("image corrupt?")
log.WithField("data", string(b)).Debug("image data")
continue loop
}
request.Art <- i
case <-d.quit: case <-d.quit:
return return
+46
View File
@@ -0,0 +1,46 @@
package mpd
func (p *Player) Command(format string, args ...interface{}) error {
command := newSimpleCommand(format, args...)
p.simpleCommands <- command
err := <-command.Err
close(command.Err)
return err
}
type simpleCommand struct {
Format string
Args []interface{}
Err chan error
}
func newSimpleCommand(format string, args ...interface{}) *simpleCommand {
return &simpleCommand{
Format: format,
Args: args,
Err: make(chan error, 1),
}
}
func (p *Player) CommandData(format string, args ...interface{}) ([]string, error) {
command := newDataCommand(format, args...)
p.dataCommands <- command
err := <-command.Err
close(command.Err)
return command.Lines, err
}
func newDataCommand(format string, args ...interface{}) *dataCommand {
return &dataCommand{
Format: format,
Args: args,
Err: make(chan error, 1),
}
}
type dataCommand struct {
Format string
Args []interface{}
Lines []string
Err chan error
}
+104
View File
@@ -0,0 +1,104 @@
package mpd
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/BeatGlow/beatglow/player"
"github.com/sirupsen/logrus"
)
// Version number.
type Version struct {
Major int
Minor int
Patch int
}
func (v Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
func versionError(s string) error {
return fmt.Errorf("mpd: unexpected version %q", s)
}
func parseVersion(s string) (Version, error) {
part := strings.Split(s, ".")
if len(part) != 3 {
return Version{}, versionError(s)
}
var (
v Version
err error
)
if v.Major, err = strconv.Atoi(part[0]); err != nil {
return Version{}, err
}
if v.Minor, err = strconv.Atoi(part[1]); err != nil {
return Version{}, err
}
if v.Patch, err = strconv.Atoi(part[2]); err != nil {
return Version{}, err
}
return v, nil
}
func parseStatus(p player.Player, status, track map[string]string) *player.Status {
logrus.Tracef("mpd status: %#+v", status)
s := &player.Status{
Player: p,
Duration: parseSeconds(status["duration"]),
Elapsed: parseSeconds(status["elapsed"]),
Volume: parseInt(status["volume"]),
}
s.Format, _ = player.ParseMPDAudioFormat(status["audio"])
s.Format.BitRate, _ = strconv.Atoi(status["bitrate"])
switch status["state"] {
case "play":
s.Playing = true
s.Paused = false
case "pause":
s.Playing = true
s.Paused = false
}
s.Repeat = status["repeat"] == "1"
s.Shuffle = status["shuffle"] == "1"
// Parse track information.
s.Track = parseTrack(track)
return s
}
func parseTrack(data map[string]string) *player.Track {
track := &player.Track{
ID: data["Id"],
Track: parseInt(data["Track"]),
Disc: parseInt(data["Disc"]),
Artist: data["Artist"],
Title: data["Title"],
Album: data["Album"],
Label: data["Label"],
Genre: strings.Split(data["Genra"], ";"),
Path: data["file"],
Duration: parseSeconds(data["duration"]),
Format: player.GuessFormat(data["file"]),
}
track.Date, _ = time.Parse("2006-02-01", data["Date"])
return track
}
func parseInt(s string) int {
i, _ := strconv.Atoi(s)
return i
}
func parseSeconds(s string) time.Duration {
d, _ := time.ParseDuration(s + "s")
return d
}
+181 -99
View File
@@ -2,6 +2,7 @@ package mpd
import ( import (
"fmt" "fmt"
"io"
"net" "net"
"net/textproto" "net/textproto"
"strconv" "strconv"
@@ -11,9 +12,9 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.maze.io/harmon/config" "github.com/BeatGlow/beatglow/config"
"go.maze.io/harmon/internal/util" "github.com/BeatGlow/beatglow/internal/util"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/player"
) )
func init() { func init() {
@@ -37,7 +38,8 @@ type Player struct {
idleSubsystems []string idleSubsystems []string
artCache sync.Map // map of path to image artCache sync.Map // map of path to image
artRequest chan *artRequest artRequest chan *artRequest
commands chan *Command simpleCommands chan *simpleCommand
dataCommands chan *dataCommand
errors chan error errors chan error
quit chan struct{} quit chan struct{}
} }
@@ -54,41 +56,24 @@ func (c *clientConn) log() *logrus.Entry {
}) })
} }
// Version number. func (c *clientConn) readBytes(size int) (b []byte, err error) {
type Version struct { c.log().WithField("size", size).Debug("read bytes")
Major int
Minor int
Patch int
}
func (v Version) String() string { b = make([]byte, size)
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch) if _, err := io.ReadFull(c.Conn.R, b); err != nil {
} return nil, err
func versionError(s string) error {
return fmt.Errorf("mpd: unexpected version %q", s)
}
func ParseVersion(s string) (Version, error) {
part := strings.Split(s, ".")
if len(part) != 3 {
return Version{}, versionError(s)
} }
var ( // Verify there's a linebreak afterwards and skip it
v Version termByte, err := c.Conn.R.ReadByte()
err error if err != nil {
) return nil, textproto.ProtocolError("failed to read binary data terminator: " + err.Error())
if v.Major, err = strconv.Atoi(part[0]); err != nil {
return Version{}, err
} }
if v.Minor, err = strconv.Atoi(part[1]); err != nil { if termByte != '\n' {
return Version{}, err return nil, textproto.ProtocolError(fmt.Sprintf("wrong binary data terminator: want 0x0a, got %x", termByte))
} }
if v.Patch, err = strconv.Atoi(part[2]); err != nil {
return Version{}, err return
}
return v, nil
} }
func New(addr, password string) (*Player, error) { func New(addr, password string) (*Player, error) {
@@ -97,11 +82,12 @@ func New(addr, password string) (*Player, error) {
return nil, err return nil, err
} }
p := &Player{ p := &Player{
addr: addr, addr: addr,
commands: make(chan *Command, 16), simpleCommands: make(chan *simpleCommand, 8),
artRequest: make(chan *artRequest, 16), dataCommands: make(chan *dataCommand, 8),
errors: make(chan error, 1), artRequest: make(chan *artRequest, 8),
quit: make(chan struct{}, 2), errors: make(chan error, 1),
quit: make(chan struct{}, 2),
} }
return p, nil return p, nil
} }
@@ -135,7 +121,7 @@ func newConn(addr, password, kind, name string) (*clientConn, *Version, error) {
return nil, nil, fmt.Errorf("mpd: unexpected server greeting %q", line) return nil, nil, fmt.Errorf("mpd: unexpected server greeting %q", line)
} }
version, err := ParseVersion(line[7:]) version, err := parseVersion(line[7:])
if err != nil { if err != nil {
_ = conn.Close() _ = conn.Close()
return nil, nil, fmt.Errorf("mpd: unexpected server version %q: %w", line[6:], err) return nil, nil, fmt.Errorf("mpd: unexpected server version %q: %w", line[6:], err)
@@ -164,7 +150,7 @@ func newConn(addr, password, kind, name string) (*clientConn, *Version, error) {
return &clientConn{conn, kind}, &version, nil return &clientConn{conn, kind}, &version, nil
} }
func (Player) Type() string { return "mpd" } func (*Player) Type() string { return "mpd" }
func (p *Player) Halt() error { func (p *Player) Halt() error {
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
@@ -213,7 +199,41 @@ func (p *Player) sendCommand(conn *clientConn, format string, args ...interface{
return return
} }
func (p *Player) sendCommandList(conn *clientConn, commands []Command) (err error) { func (p *Player) sendDataCommand(conn *clientConn, format string, args ...interface{}) (lines []string, err error) {
log := conn.log().WithField("command", fmt.Sprintf(format, args...))
log.Trace("sending data command")
var id uint
if id, err = conn.Cmd(format, args...); err != nil {
log.WithError(err).Warn("data command failed")
return
}
log = log.WithField("id", id)
log.Trace("start data response")
conn.StartResponse(id)
for {
var line string
if line, err = conn.ReadLine(); err != nil {
log.WithError(err).Warn("data command response read failed")
break
}
log.WithField("data", line).Trace("data command response")
if line == "OK" {
break
}
lines = append(lines, line)
}
log.Trace("end response")
conn.EndResponse(id)
return
}
func (p *Player) sendCommandList(conn *clientConn, commands []simpleCommand) (err error) {
log := conn.log() log := conn.log()
log.Trace("sending command list") log.Trace("sending command list")
@@ -280,6 +300,80 @@ func (p *Player) sendMapCommand(conn *clientConn, format string, args ...interfa
return return
} }
func (p *Player) sendBinaryCommand(conn *clientConn, format string, args ...interface{}) (chunk []byte, size int, err error) {
log := conn.log().WithField("command", fmt.Sprintf(format, args...))
log.Trace("sending binary command")
var id uint
if id, err = conn.Cmd(format, args...); err != nil {
log.WithError(err).Warn("binary command failed")
return
}
log = log.WithField("id", id)
log.Trace("start binary response")
conn.StartResponse(id)
if chunk, size, err = p.readBinary(conn); err != nil {
conn.EndResponse(id)
return
}
log.Trace("end binary response")
conn.EndResponse(id)
return
}
func (p *Player) readBinary(conn *clientConn) (b []byte, size int, err error) {
size = -1
for {
line, err := conn.ReadLine()
switch {
case err != nil:
return nil, 0, err
// Check for the size key
case strings.HasPrefix(line, "size: "):
if size, err = strconv.Atoi(line[6:]); err != nil {
return nil, 0, textproto.ProtocolError("failed to parse size: " + err.Error())
}
// Check for the binary key
case strings.HasPrefix(line, "binary: "):
length := -1
if length, err = strconv.Atoi(line[8:]); err != nil {
return nil, 0, textproto.ProtocolError("failed to parse binary: " + err.Error())
}
// If no size is given, assume it's equal to the provided data's length
if size < 0 {
size = length
}
// The binary data must follow the 'binary:' key
data, err := conn.readBytes(length)
if err != nil {
return nil, 0, err
}
// The binary data must be followed by the "OK" line
if s, err := conn.ReadLine(); err != nil {
return nil, 0, err
} else if s != "OK" {
return nil, 0, textproto.ProtocolError("expected 'OK', got " + s)
}
return data, size, nil
// No more data. Obviously, no binary data encountered
case line == "", line == "OK":
return nil, 0, textproto.ProtocolError("no binary data found in response")
default:
return nil, 0, textproto.ProtocolError("unexpected binary response: " + line)
}
}
}
func (p *Player) run(events chan player.Event) { func (p *Player) run(events chan player.Event) {
log := logrus.WithFields(logrus.Fields{ log := logrus.WithFields(logrus.Fields{
"protocol": "mpd", "protocol": "mpd",
@@ -314,7 +408,7 @@ func (p *Player) run(events chan player.Event) {
continue continue
} }
p.commands = make(chan *Command) p.simpleCommands = make(chan *simpleCommand)
p.errors = make(chan error) p.errors = make(chan error)
p.quit = make(chan struct{}, 2) p.quit = make(chan struct{}, 2)
@@ -328,7 +422,7 @@ func (p *Player) run(events chan player.Event) {
_ = idle.Close() _ = idle.Close()
_ = main.Close() _ = main.Close()
close(p.commands) close(p.simpleCommands)
close(p.errors) close(p.errors)
} }
@@ -350,7 +444,7 @@ func (p *Player) mainLoop(conn *clientConn, events chan player.Event) {
loop: loop:
for { for {
select { select {
case command := <-p.commands: case command := <-p.simpleCommands:
if command == nil { if command == nil {
break loop break loop
} }
@@ -361,13 +455,24 @@ loop:
command.Err <- nil command.Err <- nil
} }
case command := <-p.dataCommands:
if command == nil {
break loop
}
if command.Lines, err = p.sendDataCommand(conn, command.Format, command.Args...); err != nil {
command.Err <- err
break loop
} else {
command.Err <- nil
}
case <-ticker.C: case <-ticker.C:
var status map[string]string var status map[string]string
if status, err = p.sendMapCommand(conn, "status"); err != nil { if status, err = p.sendMapCommand(conn, "status"); err != nil {
log.WithError(err).Error("error retrieving status") log.WithError(err).Error("error retrieving status")
break loop break loop
} }
log.WithField("status", status).Debug("status") log.WithField("status", status).Trace("status")
var track map[string]string var track map[string]string
if track, err = p.sendMapCommand(conn, "currentsong"); err != nil { if track, err = p.sendMapCommand(conn, "currentsong"); err != nil {
@@ -410,72 +515,49 @@ func (p *Player) Name() string {
return p.name return p.name
} }
func (p *Player) Command(format string, args ...interface{}) error {
command := newCommand(format, args...)
p.commands <- command
return <-command.Err
}
func (p *Player) Play() error { return p.Command("play") } func (p *Player) Play() error { return p.Command("play") }
func (p *Player) Pause() error { return p.Command("pause") } func (p *Player) Pause() error { return p.Command("pause") }
func (p *Player) Next() error { return p.Command("next") } func (p *Player) Next() error { return p.Command("next") }
func (p *Player) Previous() error { return p.Command("previous") } func (p *Player) Previous() error { return p.Command("previous") }
func (p *Player) Seek(d time.Duration) error { return p.Command("seekcur %f", d.Seconds()) } func (p *Player) Seek(d time.Duration) error { return p.Command("seekcur %f", d.Seconds()) }
type Command struct { func (p *Player) ChangeVolume(delta int) error {
Format string return p.Command("volume %d", delta)
Args []interface{}
Err chan error
} }
func newCommand(format string, args ...interface{}) *Command { func (p *Player) SetVolume(level int) error {
return &Command{ if level < 0 {
Format: format, level = 0
Args: args,
Err: make(chan error),
} }
if level > 100 {
level = 100
}
return p.Command("setvol %d", level)
} }
func parseStatus(p player.Player, status, track map[string]string) *player.Status { func (p *Player) ToggleMute() error {
s := &player.Status{ // MPD doesn't mute, it can pause...
Player: p, return p.Command("pause")
}
s.Source, _ = player.ParseMPDAudioFormat(status["audio"])
s.Source.BitRate, _ = strconv.Atoi(status["bitrate"])
s.Elapsed, _ = time.ParseDuration(status["elapsed"] + "s")
s.Volume, _ = strconv.Atoi(status["volume"])
switch status["state"] {
case "play":
s.Playing = true
s.Paused = false
case "pause":
s.Playing = true
s.Paused = false
}
s.Repeat = status["repeat"] == "1"
s.Shuffle = status["shuffle"] == "1"
// Parse track information.
s.Track, s.Source = parseTrack(track)
return s
} }
func parseTrack(data map[string]string) (*player.Track, player.AudioFormat) { func (p *Player) Playlist() ([]*player.Track, error) {
track := &player.Track{ lines, err := p.CommandData("playlistinfo")
Artist: data["Artist"], if err != nil {
Title: data["Title"], return nil, err
Album: data["Album"],
Label: data["Label"],
Genre: strings.Split(data["Genra"], ";"),
Path: data["file"],
} }
track.Track, _ = strconv.Atoi(data["Track"])
track.Disc, _ = strconv.Atoi(data["Disc"])
track.Date, _ = time.Parse("2006-02-01", data["Date"])
track.Duration, _ = time.ParseDuration(data["duration"] + "s")
audio, _ := player.ParseMPDAudioFormat(data["Format"]) var (
tracks []*player.Track
return track, audio data = make(map[string]string)
)
for _, line := range lines {
if i := strings.IndexByte(line, ':'); i > -1 {
k, v := line[:i], line[i+1:]
data[k] = v
if k == "Id" {
tracks = append(tracks, parseTrack(data))
}
}
}
return tracks, nil
} }
+34 -49
View File
@@ -9,7 +9,7 @@ import (
"periph.io/x/conn/v3/physic" "periph.io/x/conn/v3/physic"
"go.maze.io/harmon/hardware" "github.com/BeatGlow/beatglow/hardware"
) )
// Player controls music playback. // Player controls music playback.
@@ -25,12 +25,24 @@ type Player interface {
// Status of the player // Status of the player
Status() *Status Status() *Status
// ChangeVolume changes the relative volume of the player.
ChangeVolume(delta int) error
// SetVolume changes the volume of the player.
SetVolume(level int) error
// ToggleMute toggles mute.
ToggleMute() error
// Player controls // Player controls
Play() error Play() error
Pause() error Pause() error
Next() error Next() error
Previous() error Previous() error
Seek(time.Duration) error Seek(time.Duration) error
// Playlist controls.
Playlist() ([]*Track, error)
} }
type AlbumArt interface { type AlbumArt interface {
@@ -82,11 +94,11 @@ type Status struct {
// Player instance. // Player instance.
Player Player Player Player
// Source format // Format of the stream.
Source AudioFormat Format AudioFormat
// Output format // Duration of the current track.
Output AudioFormat Duration time.Duration
// Elapsed time playing the current track. // Elapsed time playing the current track.
Elapsed time.Duration Elapsed time.Duration
@@ -117,51 +129,24 @@ type Status struct {
} }
func (s *Status) String() string { func (s *Status) String() string {
return fmt.Sprintf("source=%s output=%s elapsed=%s play=%t", s.Source, s.Output, s.Elapsed, s.Playing) return fmt.Sprintf("format=%s elapsed=%s/%d play=%t", s.Format, s.Elapsed, s.Duration, s.Playing)
} }
// Track represents an audio track. func (s *Status) Eq(o *Status) bool {
type Track struct { if s == nil || o == nil {
// Artist is the performing artist. return false
Artist string
// Title of the track.
Title string
// Album the track appears on.
Album string
// Label the album is released on.
Label string
// Date the track was published.
Date time.Time
// Track number.
Track int
// Disc number.
Disc int
// Duration is the track length.
Duration time.Duration
// Format is the audio format.
Format string
// Genre names.
Genre []string
// Path is the file path of the track.
Path string
// Image is the track or album art.
Image image.Image
}
func (t *Track) String() string {
if t == nil {
return "nil"
} }
return fmt.Sprintf("%s - %s (%d on %s, %s)", t.Artist, t.Title, t.Track, t.Album, t.Duration) return s.Playing == o.Playing && s.Paused == o.Paused
}
type EventObserver interface {
PlayerEvent(Event)
}
type StatusObserver interface {
StatusChanged(*Status)
}
type TrackObserver interface {
TrackChanged(Player, *Track)
} }
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"periph.io/x/conn/v3/physic" "periph.io/x/conn/v3/physic"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/player"
) )
func TestParseMPDAudioFormat(t *testing.T) { func TestParseMPDAudioFormat(t *testing.T) {
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.maze.io/harmon/config" "github.com/BeatGlow/beatglow/config"
) )
// ErrNotFound indicates no instance was saved. // ErrNotFound indicates no instance was saved.
+86
View File
@@ -0,0 +1,86 @@
package player
import (
"fmt"
"image"
"path/filepath"
"strings"
"time"
)
// Track represents an audio track.
type Track struct {
// ID is the internal identifier.
ID string
// Artist is the performing artist.
Artist string
// Title of the track.
Title string
// Album the track appears on.
Album string
// Label the album is released on.
Label string
// Date the track was published.
Date time.Time
// Track number.
Track int
// Disc number.
Disc int
// Duration is the track length.
Duration time.Duration
// Format is the audio format.
Format string
// Genre names.
Genre []string
// Path is the file path of the track.
Path string
// Image is the track or album art.
Image image.Image
}
func (t *Track) String() string {
if t == nil {
return "nil"
}
return fmt.Sprintf("%s - %s (%d on %s, %s)", t.Artist, t.Title, t.Track, t.Album, t.Duration)
}
func (t *Track) Eq(o *Track) bool {
if t == nil || o == nil {
return false
}
return strings.EqualFold(t.Artist, o.Artist) &&
strings.EqualFold(t.Title, o.Title) &&
strings.EqualFold(t.Album, o.Album) &&
strings.EqualFold(t.Label, o.Label)
}
// GuessFormat guesses the audio format base on file name.
//
// TODO(maze): read the container from the file on disk.
func GuessFormat(name string) string {
switch strings.ToLower(filepath.Ext(name)) {
case ".alac", ".m3a", ".m4a":
return "ALAC"
case ".flac":
return "FLAC"
case ".mp3":
return "MP3"
case ".wav":
return "WAVE"
default:
return "Dunno"
}
}
+19 -12
View File
@@ -4,9 +4,9 @@ import (
"image" "image"
"time" "time"
"go.maze.io/harmon/config" "github.com/BeatGlow/beatglow/config"
"go.maze.io/harmon/player" "github.com/BeatGlow/beatglow/player"
"go.maze.io/harmon/player/mpd" "github.com/BeatGlow/beatglow/player/mpd"
) )
const ( const (
@@ -35,15 +35,18 @@ func New(config config.Player) (player.Player, error) {
}, nil }, nil
} }
func (p *Player) Halt() error { return p.mpd.Halt() } func (p *Player) Halt() error { return p.mpd.Halt() }
func (Player) Type() string { return "volumio" } func (Player) Type() string { return "volumio" }
func (Player) Name() string { return "Volumio" } func (Player) Name() string { return "Volumio" }
func (p *Player) Status() *player.Status { return p.mpd.Status() } func (p *Player) Status() *player.Status { return p.mpd.Status() }
func (p *Player) Next() error { return p.mpd.Next() } func (p *Player) Next() error { return p.mpd.Next() }
func (p *Player) Previous() error { return p.mpd.Previous() } func (p *Player) Previous() error { return p.mpd.Previous() }
func (p *Player) Play() error { return p.mpd.Play() } func (p *Player) Play() error { return p.mpd.Play() }
func (p *Player) Pause() error { return p.mpd.Pause() } func (p *Player) Pause() error { return p.mpd.Pause() }
func (p *Player) Seek(d time.Duration) error { return p.mpd.Seek(d) } func (p *Player) Seek(d time.Duration) error { return p.mpd.Seek(d) }
func (p *Player) ChangeVolume(delta int) error { return p.mpd.ChangeVolume(delta) }
func (p *Player) SetVolume(level int) error { return p.mpd.SetVolume(level) }
func (p *Player) ToggleMute() error { return p.mpd.ToggleMute() }
func (p *Player) Events() (<-chan player.Event, error) { func (p *Player) Events() (<-chan player.Event, error) {
return p.mpd.Events() return p.mpd.Events()
@@ -52,3 +55,7 @@ func (p *Player) Events() (<-chan player.Event, error) {
func (p *Player) AlbumArt(t *player.Track) (image.Image, bool) { func (p *Player) AlbumArt(t *player.Track) (image.Image, bool) {
return p.mpd.AlbumArt(t) return p.mpd.AlbumArt(t)
} }
func (p *Player) Playlist() ([]*player.Track, error) {
return p.mpd.Playlist()
}
+7
View File
@@ -0,0 +1,7 @@
package sound
import "github.com/BeatGlow/audio"
type Processor interface {
ProcessBuffer(audio.Buffer[float64])
}
+26
View File
@@ -0,0 +1,26 @@
package sound
import (
"fmt"
"github.com/BeatGlow/beatglow/config"
)
type Opener = func(config.Audio) (Source, error)
var drivers = make(map[string]Opener)
func Register(name string, opener Opener) {
if _, dupe := drivers[name]; dupe {
panic(fmt.Sprintf("sound source %q already registered", name))
}
drivers[name] = opener
}
func New(config config.Audio) (Source, error) {
opener, ok := drivers[config.Type]
if ok {
return opener(config)
}
return nil, fmt.Errorf("sound: no %q driver was found", config.Type)
}
+198
View File
@@ -0,0 +1,198 @@
package sound
import (
"encoding/binary"
"fmt"
"io"
"os"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/beatglow/config"
)
func init() {
Register("fifo", newReader)
Register("file", newReader)
}
type Source interface {
String() string
// ReadBuffer reads samples.
ReadBuffer(audio.Buffer[float64]) (int, error)
// Channels is the number of channels.
Channels() int
// BitDepth is the number of bits per sample.
BitDepth() int
// SampleRate is the sample rate in samples per second.
SampleRate() int
}
type Reader struct {
io.ReadCloser
// Name of the reader (path).
Name string
// Ch is the number of channels.
Ch int
// Bits is the bit depth.
Bits int
// Rate is the sample rate.
Rate int
// Order is the byte order.
Order binary.ByteOrder
// Opener is a function that can be called if the reader is closed.
Opener func() (io.ReadCloser, error)
// buffers are allocated on the fly
buffer []byte
bufferFloat audio.Samples[float64]
bufferInt8 audio.Samples[int8]
bufferInt16 audio.Samples[int16]
}
func newReader(config config.Audio) (Source, error) {
var (
ch = config.Channels
bits = config.Bits
rate = config.Rate
order binary.ByteOrder = binary.LittleEndian
)
if ch == 0 {
ch = 2
}
if bits == 0 {
bits = 16
}
if rate == 0 {
rate = 44100
}
if config.BigEndian {
order = binary.BigEndian
}
return &Reader{
Name: config.Path,
Ch: ch,
Bits: bits,
Rate: rate,
Order: order,
Opener: func() (io.ReadCloser, error) { return os.Open(config.Path) },
buffer: make([]byte, 1024*ch*(bits>>4)),
bufferFloat: make(audio.Samples[float64], 1024*ch),
bufferInt8: make(audio.Samples[int8], 1024*ch*(bits>>4)),
bufferInt16: make(audio.Samples[int16], 1024*ch*(bits>>4)),
}, nil
}
func (s Reader) String() string {
return "reader " + s.Name
}
func (s Reader) Channels() int {
return s.Ch
}
func (s Reader) BitDepth() int {
return s.Bits
}
func (s Reader) SampleRate() int {
return s.Rate
}
func (s *Reader) ReadBuffer(buffer audio.Buffer[float64]) (int, error) {
// Ensure we have an open reader.
if s.ReadCloser == nil {
var err error
if s.ReadCloser, err = s.Opener(); err != nil {
s.ReadCloser = nil
return 0, err
}
}
switch s.Bits {
case 8:
return s.readBufferInt8(buffer)
case 16:
return s.readBufferInt16(buffer)
default:
return 0, fmt.Errorf("sound: unsupported bit depth %d for Reader", s.Bits)
}
}
func (s *Reader) readBufferInt8(buffer audio.Buffer[float64]) (int, error) {
var (
samples = buffer.Samples()
channels = buffer.Channels()
length = samples * channels
)
// Dynamically resize, if needed.
if l := len(s.bufferFloat); l != length {
s.buffer = make([]byte, length)
s.bufferFloat = make(audio.Samples[float64], length)
s.bufferInt8 = make(audio.Samples[int8], length)
}
// Read bytes
if n, err := io.ReadFull(s.ReadCloser, s.buffer); err != nil {
return n, err
}
// Convert
s.bufferInt8.Decode(s.buffer, s.Order) // bytes -> int8
s.bufferInt8.ToFloat(s.bufferFloat) // int8 -> float64
if channels == 1 {
// Straight conversion into the target buffer.
return copy(buffer[0], s.bufferFloat), nil
}
// Deinterleave.
audio.Deinterleave(buffer, s.bufferFloat, channels)
return samples, nil
}
func (s *Reader) readBufferInt16(buffer audio.Buffer[float64]) (int, error) {
var (
samples = buffer.Samples()
channels = buffer.Channels()
length = samples * channels
)
// Dynamically resize, if needed.
//if l := len(s.bufferFloat); l != length {
s.buffer = make([]byte, length*2)
s.bufferFloat = make(audio.Samples[float64], length)
s.bufferInt16 = make(audio.Samples[int16], length)
//}
// Read bytes
if n, err := io.ReadFull(s.ReadCloser, s.buffer); err != nil {
return n, err
}
//logrus.Printf("read %d bytes: %#02x", len(s.buffer), s.buffer)
// Convert
s.bufferInt16.Decode(s.buffer, s.Order) // bytes -> int16
s.bufferInt16.ToFloat(s.bufferFloat) // int16 -> float64
if channels == 1 {
// Straight conversion into the target buffer.
return copy(buffer[0], s.bufferFloat), nil
}
// Deinterleave.
audio.Deinterleave(buffer, s.bufferFloat, channels)
return samples, nil
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
View File
Whitespace-only changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more