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

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.
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.
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.
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.
+292
View File
@@ -0,0 +1,292 @@
package font
import (
"bytes"
"image"
"image/color"
"math"
"os"
"strings"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
"github.com/BeatGlow/display/draw"
_ "embed" // Embed binary files
)
// Fonts contained
var (
MairyBlackItalic = Must(NewFromBytes(mairyBlackItalicTTF))
MicroGrotesk = Must(NewFromBytes(microgroteskTTF))
Monaco = Must(NewFromBytes(monacoRegularTTF))
Montserrat = Must(NewFromBytes(montserratTTF))
MontserratItalic = Must(NewFromBytes(montserratItalicTTF))
SmoochSans = Must(NewFromBytes(smoochSansTTF))
)
func Must(font *Font, err error) *Font {
if err != nil {
panic(err)
}
return font
}
// Font contains a TrueType or OpenType font face.
type Font struct {
ttf *truetype.Font
otf *opentype.Font
face font.Face
attr FontAttr
fg, bg image.Image
scaleX, scaleY float64
changed bool
}
type FontAttr struct {
PointSize float64 // Point size of the font
DPI float64 // Resolution of the font in dots per inch
LineSpacing float64 // Spacing between lines (in terms of font height)
Hinting font.Hinting // Font hinting
}
// Hinting is a type alias.
type Hinting = font.Hinting
const (
HintingNone = font.HintingNone
HintingVertical = font.HintingVertical
HintingFull = font.HintingFull
)
func (a *FontAttr) newTTOptions(scaleX, scaleY float64) *truetype.Options {
dpi := a.DPI
if scaleX*scaleY != 0 {
dpi *= math.Sqrt(scaleX * scaleY)
}
return &truetype.Options{
Size: a.PointSize,
DPI: dpi,
Hinting: a.Hinting,
}
}
func (a *FontAttr) newOTOptions(scaleX, scaleY float64) *opentype.FaceOptions {
dpi := a.DPI
if scaleX*scaleY != 0 {
dpi *= math.Sqrt(scaleX * scaleY)
}
return &opentype.FaceOptions{
Size: a.PointSize,
DPI: dpi,
Hinting: a.Hinting,
}
}
func New(name string) (*Font, error) {
b, err := os.ReadFile(name)
if err != nil {
return nil, err
}
return NewFromBytes(b)
}
func NewFromBytes(b []byte) (*Font, error) {
var (
attr = FontAttr{
PointSize: 12,
DPI: 72,
LineSpacing: 1,
Hinting: font.HintingFull,
}
ttf *truetype.Font
otf *opentype.Font
face font.Face
err error
)
switch {
case bytes.HasPrefix(b, []byte("OTTO")):
if otf, err = opentype.Parse(b); err != nil {
return nil, err
}
face, _ = opentype.NewFace(otf, attr.newOTOptions(0, 0))
default:
if ttf, err = truetype.Parse(b); err != nil {
return nil, err
}
face = truetype.NewFace(ttf, attr.newTTOptions(0, 0))
}
return &Font{
ttf: ttf,
otf: otf,
face: face,
attr: attr,
}, nil
}
func (f Font) Attr() FontAttr {
return f.attr
}
// SetPointSize sets the point size of the font.
func (f *Font) SetPointSize(size float64) {
if size == f.attr.PointSize {
return
}
f.attr.PointSize = size
f.changed = true
}
// WithPointSize returns a new font instance with new point size settings.
func (f *Font) WithPointSize(size float64) *Font {
v := new(Font)
*v = *f
v.SetPointSize(size)
return v
}
// SetDPI sets the resolution of the font in dots per inches (DPI).
func (f *Font) SetDPI(dpi float64) {
if dpi == f.attr.DPI {
return
}
f.attr.DPI = dpi
f.changed = true
}
// WithDPI returns a new font instance with new DPI settings.
func (f *Font) WithDPI(dpi float64) *Font {
v := new(Font)
*v = *f
v.SetDPI(dpi)
return v
}
// SetLineSpacing sets the amount of spacing between lines (in terms of font height).
func (f *Font) SetLineSpacing(spacing float64) {
if spacing == f.attr.LineSpacing {
return
}
f.attr.LineSpacing = spacing
f.changed = true
}
// SetHinting sets the hinting type.
func (f *Font) SetHinting(hinting Hinting) {
if hinting == f.attr.Hinting {
return
}
f.attr.Hinting = hinting
f.changed = true
}
// SetScale sets the ratio of actual pixel/GL point.
func (f *Font) SetScaleXY(x, y float64) {
if x == f.scaleX && y == f.scaleY {
return
}
f.scaleX = x
f.scaleY = y
f.changed = true
}
// updateFace updates the font face if parameters have changed.
func (f *Font) updateFace() {
if f.changed {
switch {
case f.ttf != nil:
f.face = truetype.NewFace(f.ttf, f.attr.newTTOptions(f.scaleX, f.scaleY))
case f.otf != nil:
f.face, _ = opentype.NewFace(f.otf, f.attr.newOTOptions(f.scaleX, f.scaleY))
}
f.changed = false
}
}
// MeasureText returns the minimum width and height in pixels necessary for an image to contain
// the specified text. The supplied text string can contain line break escape sequences (\n).
func (f *Font) MeasureText(text string) (width, height int) {
f.updateFace()
var (
metrics = f.face.Metrics()
lineHeight = (metrics.Ascent + metrics.Descent).Ceil()
lineGap = int((f.attr.LineSpacing - float64(1)) * float64(lineHeight))
lines = strings.Split(text, "\n")
drawer = &font.Drawer{
Dst: nil,
Src: image.NewUniform(color.Black),
Face: f.face,
}
)
for i, line := range lines {
drawer.Dot = fixed.P(0, height)
lineWidth := drawer.MeasureString(line).Ceil()
if lineWidth > width {
width = lineWidth
}
height += lineHeight
if i > 1 {
height += lineGap
}
}
return width, height
}
// Metrics returns the font metrics.
func (f *Font) Metrics() font.Metrics {
f.updateFace()
return f.face.Metrics()
}
// Draw text onto an image using this font.
func (f *Font) Draw(dst draw.Image, p image.Point, fg image.Image, text string) {
f.updateFace()
var (
metrics = f.face.Metrics()
py = p.Y + metrics.Ascent.Round()
lineHeight = (metrics.Ascent + metrics.Descent).Ceil()
lineGap = int((f.attr.LineSpacing - float64(1)) * float64(lineHeight))
lines = strings.Split(text, "\n")
drawer = &font.Drawer{
Dst: dst,
Src: fg,
Face: f.face,
}
)
for i, line := range lines {
drawer.Dot = fixed.P(p.X, py)
drawer.DrawString(line)
py += lineHeight
if i > 1 {
py += lineGap
}
}
}
var (
//go:embed asset/Mairy-BlackItalic.ttf
mairyBlackItalicTTF []byte
//go:embed asset/MicroGrotesk.ttf
microgroteskTTF []byte
//go:embed asset/Monaco.ttf
monacoRegularTTF []byte
//go:embed asset/Montserrat.ttf
montserratTTF []byte
//go:embed asset/Montserrat-Italic.ttf
montserratItalicTTF []byte
//go:embed asset/SmoochSans-Regular.ttf
smoochSansTTF []byte
)
+7992
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+44522
View File
File diff suppressed because it is too large. Load diff
+57
View File
@@ -0,0 +1,57 @@
package ui
import (
"bytes"
"image"
"image/color"
"image/png"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/BeatGlow/display/pixel"
)
func MustDecodePNG(b []byte) image.Image {
i, err := png.Decode(bytes.NewBuffer(b))
if err != nil {
panic(err)
}
return i
}
// BufferFor creates a new image buffer for the provided display matching its color model.
func BufferFor(model color.Model, width, height int) draw.Image {
switch model {
case pixel.MonoModel:
return pixel.NewMonoImage(width, height)
case pixel.Gray2Model:
return pixel.NewGray2Image(width, height)
case pixel.Gray4Model:
return pixel.NewGray4Image(width, height)
case pixel.CRGB15Model:
return pixel.NewCRGB15Image(width, height)
case pixel.CRGB16Model:
return pixel.NewCRGB16Image(width, height)
default:
return nil
}
}
type Clearer interface {
Clear()
}
// Clear an image.
func Clear(i draw.Image) {
if clear, ok := i.(Clearer); ok {
clear.Clear()
return
}
draw.Draw(i, i.Bounds(), image.Black, image.Point{}, draw.Src)
}
// Refresh display from image buffer.
func Refresh(display display.Display, src image.Image) error {
draw.Draw(display, display.Bounds(), src, image.Point{}, draw.Src)
return display.Refresh()
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+72
View File
@@ -0,0 +1,72 @@
package screen
import (
"image"
"github.com/BeatGlow/beatglow/hardware"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/widget"
"github.com/BeatGlow/display"
)
type boot struct {
display display.Display
widgets []ui.Widget
}
func Boot(displays ...display.Display) ui.Screen {
widgets := make([]ui.Widget, len(displays))
for i, display := range displays {
if i == 0 {
widgets[i] = newBoot(display)
} else {
widgets[i] = newEmpty(display)
}
}
return &boot{
display: displays[0],
widgets: widgets,
}
}
func (boot) String() string { return "boot" }
func (boot) HandleInput(_ hardware.InputEvent) {}
func (s *boot) SetVisible(_ bool) {
s.display.Clear()
}
func (s *boot) Widgets() []ui.Widget {
return s.widgets
}
func newBoot(display display.Display) ui.Widget {
var (
style = ui.StylesFor(display.ColorModel()).Boot
size = display.Bounds().Size()
)
switch {
case size.Y >= 64:
style.Font.SetPointSize(style.FontSize * 2)
default:
style.Font.SetPointSize(style.FontSize)
}
var (
width, height = style.Font.MeasureText("beatglow")
at = image.Pt(
(size.X-width)/2,
(size.Y-height)/2,
)
)
text := widget.NewText(display, at)
text.SetStyle(style)
text.Set("beatglow")
return text
}
func newEmpty(display display.Display) ui.Widget {
return widget.Empty{display}
}
+222
View File
@@ -0,0 +1,222 @@
package screen
import (
"fmt"
"image"
"time"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/widget"
"github.com/BeatGlow/display"
"github.com/nfnt/resize"
"github.com/sirupsen/logrus"
_ "embed" // Embed assets
)
type playing struct {
main display.Display
meta display.Display
status *player.Status
format *widget.Text
duration *widget.Text
progress *widget.Progress
track *widget.Scroller
art *widget.Image
artPlaceholder image.Image
spectrum *widget.Spectrum
visible bool
}
func Playing(main, meta display.Display, config *config.ScreenPlaying) ui.Screen {
var (
mainR = main.Bounds()
mainW = mainR.Dx()
mainW1_3 = mainW / 3 // 1/3rd of the width
mainW2_3 = mainW1_3 * 2 // 2/3rd of the width
mainH = mainR.Dy()
metaR = meta.Bounds()
metaW = uint(metaR.Dx())
metaH = uint(metaR.Dy())
styles = ui.StylesFor(main.ColorModel())
)
s := &playing{
main: main,
meta: meta,
format: widget.NewText(main, image.Pt(0, 0)).SetStyle(styles.Format).Set("Dunno"),
duration: widget.NewText(main, image.Pt(40, 0)).SetStyle(styles.Format).Set("--:-- / --:--"),
progress: widget.NewProgress(main, image.Pt(mainW2_3, 0), mainW1_3-1, 9).SetStyle(styles.Format),
track: widget.NewScroller(main, image.Pt(0, 10), 0, 32).SetStyle(styles.Track),
art: widget.NewImage(meta, image.Point{}, nil),
artPlaceholder: resize.Thumbnail(metaW, metaH, ui.MustDecodePNG(recordPNG), resize.Lanczos3),
spectrum: widget.NewSpectrum(main, image.Pt(0, mainH-24), mainW, 24),
}
s.configure(config, styles)
return s
}
func (s *playing) configure(config *config.ScreenPlaying, styles ui.Styles) {
if config == nil {
return
}
// Apply/load styles (if set).
if config.Track != nil {
config.Track.Apply(&styles.Track)
s.track.SetStyle(styles.Track)
}
if config.Format != nil {
config.Format.Apply(&styles.Format)
s.format.SetStyle(styles.Format)
s.duration.SetStyle(styles.Format)
s.progress.SetStyle(styles.Format)
}
// Configure spectrum analyzer
if config.Spectrum != nil {
s.spectrum.SetWaterwall(config.Spectrum.Waterfall)
if config.Spectrum.MinFrequency != 0 || config.Spectrum.MaxFrequency != 0 {
s.spectrum.SetRange(config.Spectrum.MinFrequency, config.Spectrum.MaxFrequency)
}
if config.Spectrum.Hold != 0 {
s.spectrum.SetHold(config.Spectrum.Hold)
}
}
}
func (s *playing) String() string {
return "playing"
}
func (s *playing) Widgets() []ui.Widget {
return []ui.Widget{
s.format,
s.duration,
s.progress,
s.track,
s.art,
s.spectrum,
}
}
func (s *playing) ProcessBuffer(buffer audio.Buffer[float64]) {
if !s.visible {
logrus.WithField("screen", "player").Debug("discarding buffer, not visible")
return
}
s.spectrum.ProcessBuffer(buffer)
}
func (s *playing) TrackChanged(source player.Player, track *player.Track) {
if track == nil || (track.Artist == "" && track.Title == "") {
s.format.Set("Idle")
s.track.Set("Not playing")
s.progress.Set(0)
s.art.Set(s.artPlaceholder)
return
}
// Update title.
if track.Artist != "" && track.Title != "" {
s.track.Set(track.Artist + " - " + track.Title)
} else if track.Title != "" {
s.track.Set("Unknown artist - " + track.Title)
} else if track.Artist != "" {
s.track.Set(track.Artist + " - Unknown")
}
// Update format.
s.format.Set(fmt.Sprintf("%-5s", track.Format))
// Update progress.
s.progress.Set(0)
// Update artwork.
log := logrus.WithField("screen", "playing")
if track.Image == nil {
log.Debug("track has no image, retrieving album art")
s.art.Set(s.artPlaceholder)
go s.artUpdate(source, track)
} else {
log.WithField("image", track.Image.Bounds().Size()).Debug("track has image, updating")
s.art.Set(track.Image)
}
}
func (s *playing) artUpdate(source player.Player, track *player.Track) {
log := logrus.WithField("screen", "playing")
if source != nil && track != nil {
a, ok := source.(player.AlbumArt)
if ok {
log.Debug("requesting album art from player")
i, ok := a.AlbumArt(track)
if ok {
log.WithField("image", i.Bounds().Size()).Debug("track has image, updating")
var (
r = s.meta.Bounds()
width = uint(r.Dx())
height = uint(r.Dy())
)
s.art.Set(resize.Thumbnail(width, height, i, resize.Lanczos3))
return
}
log.Debug("request didn't return an image, using fallback")
} else {
log.Debug("player doesn't support album art, using fallback")
}
}
// Fallback:
s.art.Set(s.artPlaceholder)
}
func (s *playing) StatusChanged(status *player.Status) {
/*
logrus.WithFields(logrus.Fields{
"screen": "playing",
"status": fmt.Sprintf("%#+v", status),
}).Debug("status changed")
*/
if status == nil {
s.TrackChanged(nil, nil)
s.duration.Set("--:-- / --:--")
s.progress.Set(0)
return
}
if status.Track.Duration > 0 {
s.duration.Set(fmt.Sprintf("%s / %s", formatDuration(status.Elapsed), formatDuration(status.Duration)))
s.progress.Set(float64(status.Elapsed) / float64(status.Duration))
} else {
s.duration.Set("--:-- / --:--")
s.progress.Set(0)
}
}
func (s *playing) SetVisible(visible bool) {
s.main.Clear()
s.meta.Clear()
if visible {
for _, widget := range s.Widgets() {
_ = widget.Render(true)
}
}
s.visible = visible
}
func formatDuration(d time.Duration) string {
m := int(d / time.Minute)
s := int((d - time.Duration(m)*time.Minute) / time.Second)
if m > 99 {
m = 99
}
return fmt.Sprintf("%02d:%02d", m, s)
}
//go:embed asset/record.png
var recordPNG []byte
+89
View File
@@ -0,0 +1,89 @@
package screen
import (
"image"
"sort"
"strings"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/widget"
"github.com/BeatGlow/display"
"github.com/sirupsen/logrus"
)
type playlist struct {
display display.Display
list *widget.List
player player.Player
status *player.Status
track *player.Track
}
func Playlist(main display.Display, config *config.ScreenPlaying) ui.Screen {
bounds := main.Bounds()
screen := &playlist{
list: widget.NewList(main, image.Point{}, bounds.Dx(), bounds.Dy()),
}
screen.configure(ui.StylesFor(main.ColorModel()).Format)
return screen
}
func (s *playlist) configure(style ui.Style) {
s.list.SetStyle(style)
}
func (playlist) String() string {
return "playlist"
}
func (s *playlist) Widgets() []ui.Widget {
return []ui.Widget{
s.list,
}
}
func (s *playlist) TrackChanged(source player.Player, track *player.Track) {
s.player = source
s.track = track
}
func (s *playlist) StatusChanged(status *player.Status) {
s.status = status
}
func (s *playlist) SetVisible(visible bool) {
s.display.Clear()
if visible {
if s.player != nil {
tracks, err := s.player.Playlist()
if err != nil {
logrus.WithError(err).Warn("error fetching playlist")
s.list.Index = 0
s.list.Items = nil
} else {
sort.Slice(tracks, func(i, j int) bool {
return strings.Compare(tracks[i].ID, tracks[j].ID) < 0
})
s.list.Index = 0
s.list.Items = make([]string, len(tracks))
for i, track := range tracks {
s.list.Items[i] = track.String()
if track.Eq(s.track) {
s.list.Index = i
}
}
}
} else {
s.list.Index = 0
s.list.Items = []string{"Player unavailable..."}
}
for _, widget := range s.Widgets() {
_ = widget.Render(true)
}
}
}
+99
View File
@@ -0,0 +1,99 @@
package screen
import (
"image"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/dsp"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/widget"
"github.com/BeatGlow/display"
)
type stereoSpectrum struct {
display display.Display
l, r *dsp.FrequencyPowerCalculator[float64]
waveform *widget.WaveForm
spectrum *widget.StereoSpectrum
visible bool
}
func StereoSpectrum(display display.Display, config *config.ScreenSpectrum) ui.Screen {
size := display.Bounds().Size()
const split = 24
s := &stereoSpectrum{
display: display,
waveform: widget.NewWaveform(display, image.Point{}, size.X, split),
spectrum: widget.NewStereoSpectrum(display, image.Pt(0, split), size.X, size.Y-split),
}
s.configure(config)
return s
}
func (s *stereoSpectrum) configure(config *config.ScreenSpectrum) {
if config == nil {
return
}
if config.MinFrequency != 0 || config.MaxFrequency != 0 {
s.spectrum.SetRange(config.MinFrequency, config.MaxFrequency)
}
if config.Hold != 0 {
s.spectrum.SetHold(config.Hold)
}
s.spectrum.SetWaterwall(config.Waterfall)
}
func (s *stereoSpectrum) String() string {
return "stereo spectrum"
}
func (s *stereoSpectrum) SetVisible(visible bool) {
s.visible = visible
}
func (s *stereoSpectrum) Widgets() []ui.Widget {
return []ui.Widget{
s.waveform,
s.spectrum,
}
}
func (s *stereoSpectrum) ProcessBuffer(buffer audio.Buffer[float64]) {
s.waveform.ProcessBuffer(buffer)
s.spectrum.ProcessBuffer(buffer)
}
type waveForm struct {
display display.Display
waveform *widget.WaveForm
visible bool
}
func WaveForm(display display.Display) ui.Screen {
size := display.Bounds().Size()
return &waveForm{
display: display,
waveform: widget.NewWaveform(display, image.Pt(0, 16), size.X, size.Y-16),
}
}
func (s *waveForm) String() string {
return "waveform"
}
func (s *waveForm) SetVisible(visible bool) {
s.visible = visible
}
func (s *waveForm) Widgets() []ui.Widget {
return []ui.Widget{
s.waveform,
}
}
func (s *waveForm) ProcessBuffer(buffer audio.Buffer[float64]) {
s.waveform.ProcessBuffer(buffer)
}
+73
View File
@@ -0,0 +1,73 @@
package screen
import (
"fmt"
"image"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/beatglow/ui/widget"
"github.com/BeatGlow/display"
)
type volume struct {
display display.Display
player player.Player
text *widget.Text
level *widget.Text
progress *widget.Progress
}
func Volume(player player.Player, display display.Display) ui.Screen {
var (
styles = ui.StylesFor(display.ColorModel())
size = display.Bounds().Size()
width = (size.X / 4) * 3
at = image.Pt((size.X-width)/2, size.Y-16)
)
return &volume{
display: display,
player: player,
text: widget.NewText(display, image.Pt(widget.CenterX, 0)).SetStyle(styles.Volume),
level: widget.NewText(display, image.Pt(widget.CenterX, int(styles.Volume.FontSize))).SetStyle(styles.Format),
progress: widget.NewProgress(display, at, width, 12),
}
}
func (volume) String() string {
return "volume"
}
func (s *volume) Widgets() []ui.Widget {
return []ui.Widget{
s.text,
s.progress,
}
}
func (s *volume) SetVisible(visible bool) {
if visible {
s.display.Clear()
s.text.Set("Player volume")
s.text.Render(true)
s.level.Render(true)
s.progress.Render(true)
}
}
func (s *volume) StatusChanged(status *player.Status) {
if status != nil {
if status.Volume == 0 {
s.level.Set("mute")
s.progress.Set(0)
} else {
s.level.Set(fmt.Sprintf("%3d%%", status.Volume))
s.progress.Set(float64(status.Volume) / 100)
}
}
}
var (
_ ui.Screen = (*volume)(nil)
_ player.StatusObserver = (*volume)(nil)
)
+132
View File
@@ -0,0 +1,132 @@
package ui
import (
"image"
"image/color"
"github.com/BeatGlow/beatglow/ui/font"
"github.com/BeatGlow/display/pixel"
"github.com/mazznoer/colorgrad"
)
type Style struct {
Background image.Image
Foreground color.Color
Gradient colorgrad.Gradient
Font *font.Font
FontSize float64
FontDPI float64
}
type Styles struct {
Default Style
Boot Style
Track Style
Format Style
Volume Style
}
var (
Gray1Style = Styles{
Default: Style{
Background: image.NewUniform(pixel.Off),
Foreground: pixel.On,
Font: font.SmoochSans,
},
Track: Style{
Background: image.NewUniform(pixel.Off),
Foreground: pixel.On,
Font: font.SmoochSans,
},
Format: Style{
Background: image.NewUniform(pixel.Off),
Foreground: pixel.On,
Font: font.Monaco,
},
}
Gray4Style = Styles{
Default: Style{
Background: image.NewUniform(pixel.Gray4{}),
Foreground: pixel.Gray4{Y: 0xff},
Font: font.SmoochSans.WithPointSize(24),
FontSize: 24,
},
Boot: Style{
Background: image.NewUniform(pixel.Gray4{}),
Foreground: pixel.Gray4{Y: 0xff},
Font: font.MairyBlackItalic.WithPointSize(24),
FontSize: 24,
},
Track: Style{
Background: image.NewUniform(pixel.Gray4{}),
Foreground: pixel.Gray4{Y: 0xff},
Font: font.SmoochSans.WithPointSize(24),
FontSize: 24,
},
Format: Style{
Background: image.NewUniform(pixel.Gray4{}),
Gradient: Gradient("#808080", "#cfcfcf"),
Foreground: pixel.Gray4{Y: 0xff},
Font: font.Monaco.WithPointSize(9),
FontSize: 9,
},
Volume: Style{
Background: image.NewUniform(pixel.Gray4{}),
Foreground: pixel.Gray4{Y: 0xff},
Font: font.SmoochSans.WithPointSize(24),
FontSize: 24,
},
}
DefaultStyle = Styles{
Default: Style{
Background: image.NewUniform(color.RGBA{R: 0x11, G: 0xff, B: 0xe3, A: 0xff}),
Foreground: color.RGBA{R: 0x8a, G: 0x00, B: 0xc4, A: 0xff},
Font: font.SmoochSans,
},
Boot: Style{
Background: image.NewUniform(color.RGBA{R: 0x11, G: 0xff, B: 0xe3, A: 0xff}),
Foreground: color.RGBA{R: 0x8a, G: 0x00, B: 0xc4, A: 0xff},
Font: font.MairyBlackItalic,
FontSize: 24,
},
Track: Style{
Background: image.NewUniform(color.RGBA{R: 0x11, G: 0xff, B: 0xe3, A: 0xff}),
Foreground: color.RGBA{R: 0x8a, G: 0x00, B: 0xc4, A: 0xff},
Font: font.SmoochSans,
},
Format: Style{
Background: image.NewUniform(color.RGBA{R: 0x11, G: 0xff, B: 0xe3, A: 0xff}),
Foreground: color.RGBA{R: 0x8a, G: 0x00, B: 0xc4, A: 0xff},
Font: font.Monaco,
},
Volume: Style{
Background: image.Black,
Foreground: color.White,
Font: font.SmoochSans.WithPointSize(24),
FontSize: 24,
},
}
)
func Gradient(htmlColors ...string) colorgrad.Gradient {
g, err := colorgrad.NewGradient().HtmlColors("#888888", "#cccccc").Build()
if err != nil {
panic(err)
}
return g
}
func Rainbow() colorgrad.Gradient {
return colorgrad.Rainbow().Sharp(10, 1.0)
}
func StylesFor(model color.Model) Styles {
switch model {
case pixel.MonoModel:
return Gray1Style
case pixel.Gray4Model:
return Gray4Style
default:
return DefaultStyle
}
}
+16
View File
@@ -0,0 +1,16 @@
package ui
// Screen is a named collection of widgets.
type Screen interface {
String() string
Widgets() []Widget
SetVisible(visible bool)
}
type Widget interface {
// Render the widget to the display buffer; after rendering the display probably still
// requires refreshing.
Render(redraw bool) bool
}
+32
View File
@@ -0,0 +1,32 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
)
type base struct {
display display.Display
style ui.Style
position image.Point
buffer draw.Image
changed bool
}
func makeBase(display display.Display, at image.Point, width, height int) base {
m := display.ColorModel()
return base{
display: display,
style: ui.StylesFor(m).Default,
position: at,
buffer: ui.BufferFor(m, width, height),
}
}
func (w *base) SetStyle(style ui.Style) {
w.style = style
w.changed = true
}
+78
View File
@@ -0,0 +1,78 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/display"
)
// Empty display.
type Empty struct {
// Display this widget renders on.
Display display.Display
}
func (w Empty) Render(_ bool) bool {
w.Display.Clear()
return true
}
// Image displays an image.
type Image struct {
// Display this widget renders on.
Display display.Display
// Position on the display.
Position image.Point
// SourcePoint is the point from which this image is copied onto the display.
SourcePoint image.Point
// DrawOp is the drawing operation.
DrawOp draw.Op
buffer image.Image
changed bool
}
func NewImage(display display.Display, at image.Point, im image.Image) *Image {
return &Image{
Display: display,
Position: at,
DrawOp: draw.Src,
buffer: im,
}
}
func (w *Image) Set(i image.Image) {
w.buffer = i
w.changed = true
}
func (w *Image) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
if w.buffer != nil {
r := w.buffer.Bounds()
if w.Position.Eq(Center) {
b := w.buffer.Bounds().Size()
r.Min = image.Point{}
if x := r.Dx(); b.X < x {
r.Min.X = (x - b.X) / 2
}
if y := r.Dy(); b.Y < y {
r.Min.Y = (y - b.Y) / 2
}
} else {
r.Min = r.Min.Add(w.Position)
}
draw.Draw(w.Display, r, w.buffer, w.SourcePoint, w.DrawOp)
}
w.changed = false
return true
}
+89
View File
@@ -0,0 +1,89 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/beatglow/hardware"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
)
type List struct {
base
Items []string
Index int
OnSelect func(index int)
fontHeight int
top int
changed bool
}
func NewList(display display.Display, at image.Point, width, height int) *List {
w := &List{
base: makeBase(display, at, width, height),
}
w.SetStyle(w.style)
return w
}
func (w *List) Rotary(event hardware.RotaryEvent) {
w.Index = (w.Index + event.Delta) % len(w.Items)
w.changed = true
}
func (w *List) RotaryPress(event hardware.RotaryPressEvent) {
if w.OnSelect != nil {
w.OnSelect(w.Index)
}
}
func (w *List) SetStyle(style ui.Style) {
w.style = style
_, w.fontHeight = w.style.Font.MeasureText("^<>%MX#gjy")
w.changed = true
}
func (w *List) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
ui.Clear(w.buffer)
var (
bounds = w.buffer.Bounds()
point = bounds.Min
max = bounds.Dy() / w.fontHeight
fg = image.NewUniform(w.style.Foreground)
bg = w.style.Background
)
if w.top >= max {
w.top = w.Index - max + 1
} else if w.Index < w.top {
w.top = w.Index
}
for row := w.top; row < len(w.Items) && point.Y < bounds.Max.Y; row++ {
box := image.Rectangle{Min: point, Max: point.Add(image.Pt(bounds.Dx(), w.fontHeight))}
if row == w.Index {
draw.Draw(w.buffer, box, fg, image.Point{}, draw.Src)
w.style.Font.Draw(w.buffer, box.Min, bg, w.Items[row])
} else {
draw.Draw(w.buffer, box, bg, image.Point{}, draw.Src)
w.style.Font.Draw(w.buffer, box.Min, fg, w.Items[row])
}
point = point.Add(image.Pt(0, w.fontHeight))
}
_ = ui.Refresh(w.display, w.buffer)
return true
}
var (
_ ui.Widget = (*List)(nil)
_ hardware.RotaryHandler = (*List)(nil)
_ hardware.RotaryPressHandler = (*List)(nil)
)
+88
View File
@@ -0,0 +1,88 @@
package widget
import (
"image"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/BeatGlow/display/pixel"
"github.com/sirupsen/logrus"
)
type Progress struct {
Display display.Display
Style ui.Style
Position image.Point
width int
height int
progress float64
buffer draw.Image
changed bool
}
func NewProgress(display display.Display, at image.Point, width, height int) *Progress {
logrus.WithFields(logrus.Fields{
"width": width,
"height": height,
"at": at,
}).Debug("new progress bar")
model := display.ColorModel()
w := &Progress{
Display: display,
Style: ui.StylesFor(model).Format,
Position: at,
width: width,
height: height,
buffer: ui.BufferFor(model, width, height),
}
w.Set(0)
return w
}
func (w *Progress) Set(progress float64) {
if progress < 0 {
progress = 0
}
if progress > 1 {
progress = 1
}
w.progress = progress
w.changed = true
}
func (w *Progress) SetStyle(style ui.Style) *Progress {
w.Style = style
return w
}
func (w *Progress) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
var stop = 1
if w.progress > 0 {
stop = 1 + int(float64(w.width-2)*w.progress+.5)
}
for y := 0; y < w.height; y++ {
for x := 0; x < w.width; x++ {
if ((x == 0 || x == w.width-1) && y != 0 && y != w.height-1) ||
((y == 0 || y == w.height-1) && x != 0 && x != w.width-1) {
//if (x != 0 && y == 0) || y == w.height-1 || x == 0 || x == w.width-1 || x < stop {
w.buffer.Set(x, y, w.Style.Foreground)
} else if x > 0 && x < stop {
w.buffer.Set(x, y, pixel.Gray4{Y: 0x77})
} else {
w.buffer.Set(x, y, w.Style.Background.At(x, y))
}
}
}
draw.Draw(w.Display, w.buffer.Bounds().Add(w.Position), w.buffer, image.Point{}, draw.Src)
w.changed = false
return true
}
var _ ui.Widget = (*Progress)(nil)
+147
View File
@@ -0,0 +1,147 @@
package widget
import (
"fmt"
"image"
"image/color"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/sirupsen/logrus"
)
type Scroller struct {
Display display.Display
Position image.Point
Style ui.Style
width int
height int
buffer draw.Image
mask image.Image
text string
dir int
scroll int
scrollWidth int
required bool
changed bool
}
func NewScroller(display display.Display, at image.Point, width, height int) *Scroller {
r := display.Bounds()
if width <= 0 {
width = r.Dx()
}
if height <= 0 {
height = r.Dy()
}
w := &Scroller{
Display: display,
Position: at,
width: width,
height: height,
dir: +1,
}
w.SetStyle(ui.StylesFor(display.ColorModel()).Track)
w.Set("")
return w
}
func (w *Scroller) Set(text string) *Scroller {
width, _ := w.Style.Font.MeasureText(text)
if w.required = width > w.width; w.required {
// add spaces to the text and re-measure
width, _ = w.Style.Font.MeasureText(text + " ")
}
if width < w.width {
width = w.width
}
logrus.WithFields(logrus.Fields{
"size": fmt.Sprintf("%dx%d", width, w.height),
"text": text,
"widget": "scroller",
}).Debug("create new buffer")
w.buffer = ui.BufferFor(w.Display.ColorModel(), width, w.height)
draw.Draw(w.buffer, w.buffer.Bounds(), w.Style.Background, image.Point{}, draw.Src)
w.Style.Font.Draw(w.buffer, image.Point{}, w.mask, text)
if w.required {
w.buffer = horizontalRepeatingImage{
Image: w.buffer,
Size: image.Pt(width, w.height),
}
}
w.changed = true
w.text = text
w.scroll = 0
w.scrollWidth = width
return w
}
func (w *Scroller) SetDir(dir int) *Scroller {
w.dir = dir
if w.text != "" {
w.Set(w.text)
}
return w
}
func (w *Scroller) SetStyle(style ui.Style) *Scroller {
w.Style = style
w.mask = image.NewUniform(w.Style.Foreground)
if w.text != "" {
w.Set(w.text)
}
return w
}
func (w *Scroller) nextFrame() {
if !w.required || w.dir == 0 {
return
}
w.scroll += w.dir
if w.scroll > w.scrollWidth || w.scroll < -w.scrollWidth {
w.scroll = 0
}
w.changed = true
}
func (w *Scroller) Render(redraw bool) bool {
w.nextFrame()
if !(redraw || w.changed) {
return false
}
sp := image.Pt(w.scroll, 0)
draw.Draw(w.Display, image.Rectangle{
Min: w.Position,
Max: w.Position.Add(image.Point{X: w.width, Y: w.height}),
}, w.buffer, sp, draw.Src)
w.changed = false
return true
}
type horizontalRepeatingImage struct {
draw.Image
Size image.Point
}
func (i horizontalRepeatingImage) 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 horizontalRepeatingImage) Bounds() image.Rectangle {
b := i.Image.Bounds()
b.Min.X -= i.Size.X
b.Max.X += i.Size.X
return b
}
+262
View File
@@ -0,0 +1,262 @@
package widget
import (
"image"
"math"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/dsp"
"github.com/BeatGlow/audio/dsp/window"
"github.com/BeatGlow/audio/filter"
"github.com/BeatGlow/beatglow/internal/calc"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/BeatGlow/display/pixel"
)
const (
spectrumBandPixels = 7
spectrumPeakHold = 20
)
type Spectrum struct {
Display display.Display
Position image.Point
buffer draw.Image
width int
height int
mono []float64
bands []float64
peaks [][]float64
scale float64
thresholdDBFS float64
analyzer *dsp.FrequencyPowerCalculator[float64]
minFrequency int
maxFrequency int
hold int
waterfall bool
changed bool
}
func NewSpectrum(display display.Display, at image.Point, width, height int) *Spectrum {
bins := width / spectrumBandPixels
return &Spectrum{
Display: display,
Position: at,
buffer: ui.BufferFor(display.ColorModel(), width, height),
width: width,
height: height,
bands: make([]float64, bins),
peaks: make([][]float64, bins),
thresholdDBFS: -dsp.SQNR(16),
analyzer: dsp.NewFrequencyPowerCalculator[float64](44100, window.Blackman(1024)),
minFrequency: 500,
maxFrequency: 15000,
hold: spectrumPeakHold,
scale: 1.0,
}
}
func (w *Spectrum) SetWaterwall(on bool) {
w.waterfall = on
var bins int
if on {
bins = w.width
} else {
bins = w.width / spectrumBandPixels
}
w.bands = make([]float64, bins)
w.peaks = make([][]float64, bins)
}
func (w *Spectrum) SetRange(min, max int) {
if min > max {
min, max = max, min
}
w.minFrequency = min
w.maxFrequency = max
}
func (w *Spectrum) SetHold(hold int) {
if hold < 1 {
hold = 1
}
w.hold = hold
}
func (w *Spectrum) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
if w.waterfall {
switch buffer := w.buffer.(type) {
case *pixel.Gray2Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.Gray4Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.CRGB15Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.CRGB16Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *image.RGBA:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
default:
for y := w.height - 1; y > 0; y-- {
draw.Draw(w.buffer, image.Rect(0, y, w.width, y+1), w.buffer, image.Pt(0, y-1), draw.Src)
}
}
for x, level := range w.bands {
intesity := uint8(16*level + .5)
w.buffer.Set(x, w.height-1, pixel.Gray4{Y: intesity})
}
} else {
draw.Draw(w.buffer, w.buffer.Bounds(), image.Black, image.Point{}, draw.Src)
for i, level := range w.bands {
height := int(float64(w.height)*level + .5)
offset := i * spectrumBandPixels
//logrus.Infof("band %d at height %d (%f)", i, height, level)
for y := w.height - height; y < w.height; y++ {
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, y, pixel.Gray4{Y: 0x8})
}
}
if w.hold <= 0 {
continue
}
height = w.height - int(float64(w.height)*calc.Max(w.peaks[i])+.5)
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, height, pixel.On)
}
}
}
draw.Draw(w.Display, w.buffer.Bounds().Add(w.Position), w.buffer, image.Point{}, draw.Src)
return true
}
func (w *Spectrum) ProcessBuffer(buffer audio.Buffer[float64]) {
// Dynamically resize if needed.
if samples := buffer.Samples(); len(w.mono) != samples {
w.mono = make([]float64, samples)
}
// Convert buffer to mono.
buffer.ToMono(w.mono)
// High pass filter on 50Hz to remove DC bias.
w.mono = filter.HighPass(nil, w.mono, 50, 44100)
// Calculate spectral powers.
powers := w.analyzer.Apply(nil, w.mono)
// Adjust scale
for _, v := range powers {
w.scale = math.Min(math.Max(w.scale, v.Magnitude), 8)
}
// Compress powers to our visible bins.
var (
frequencyBinSize = 44100 / float64(len(w.mono))
frequencyMin = float64(powers[0].Frequency)
frequencyMax = float64(powers[len(powers)-1].Frequency)
frequencyScale = (frequencyMax - frequencyMin) / float64(len(w.bands))
)
for i := range w.bands {
var (
frequencyStart = frequencyMin + float64(i)*frequencyScale
frequencyEnd = frequencyMin + float64(i+1)*frequencyScale
binStart = int((frequencyStart / frequencyBinSize) + .5)
binEnd = int((frequencyEnd / frequencyBinSize) + .5)
)
var total float64
var count int
for bin := binStart; bin < binEnd; bin++ {
total += math.Min(powers[bin].Magnitude/w.scale, 1)
count += 1
}
if count == 0 {
w.bands[i] = 0
} else {
w.bands[i] = total / float64(count)
}
}
// Peak level per band.
for i, v := range w.bands {
w.peaks[i] = append(w.peaks[i], v)
if len(w.peaks[i]) > w.hold {
w.peaks[i] = w.peaks[i][1:]
}
}
/*
logrus.Infof("%d peaks from %d samples in %dHz-%dHz: %f..%f %f..%f [%d/%d] scale %f",
len(w.bands), len(powers),
powers[0].Frequency, powers[len(powers)-1].Frequency,
calc.Min(w.bands), calc.Max(w.bands),
calc.Min(w.mono), calc.Max(w.mono),
buffer.Channels(), buffer.Samples(),
w.scale)
*/
w.changed = true
}
func summarizePowerBands(bands []float64, powers []dsp.FrequencyPower, samples int) {
var (
frequencyBinSize = 44100 / float64(samples)
frequencyMin = float64(powers[0].Frequency)
frequencyMax = float64(powers[len(powers)-1].Frequency)
frequencyScale = (frequencyMax - frequencyMin) / float64(len(bands))
)
for i := range bands {
var (
frequencyStart = frequencyMin + float64(i)*frequencyScale
frequencyEnd = frequencyMin + float64(i+1)*frequencyScale
binStart = int((frequencyStart / frequencyBinSize) + .5)
binEnd = int((frequencyEnd / frequencyBinSize) + .5)
)
var total float64
var count int
for bin := binStart; bin < binEnd; bin++ {
total += math.Min(powers[bin].Magnitude, 1)
count += 1
}
if count == 0 {
bands[i] = 0
} else {
bands[i] = total / float64(count)
}
}
}
func frequencyAbove(powers []dsp.FrequencyPower, frequency int) (i int) {
var power dsp.FrequencyPower
for i, power = range powers {
if power.Frequency >= frequency {
return
}
}
return
}
func frequencyBelow(powers []dsp.FrequencyPower, frequency int) (i int) {
var power dsp.FrequencyPower
for i = len(powers) - 1; i >= 0; i-- {
if power.Frequency <= frequency {
return
}
}
return
}
+217
View File
@@ -0,0 +1,217 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/dsp"
"github.com/BeatGlow/audio/dsp/window"
"github.com/BeatGlow/audio/filter"
"github.com/BeatGlow/beatglow/internal/calc"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/pixel"
)
type StereoSpectrum struct {
Display display.Display
Position image.Point
buffer draw.Image
height int
width int
bands [2][]float64
peaks [2][][]float64
samples [2]audio.Samples[float64]
power [2][]dsp.FrequencyPower
analyzer *dsp.FrequencyPowerCalculator[float64]
minFrequency int
maxFrequency int
hold int
waterfall bool
changed bool
}
func NewStereoSpectrum(display display.Display, at image.Point, width, height int) *StereoSpectrum {
bins := width / spectrumBandPixels / 2
return &StereoSpectrum{
Display: display,
Position: at,
buffer: ui.BufferFor(display.ColorModel(), width, height),
height: height,
width: width,
bands: makeStereoBands(bins),
peaks: makeStereoPeaks(bins),
analyzer: dsp.NewFrequencyPowerCalculator[float64](44100, window.Blackman1024),
minFrequency: 500,
maxFrequency: 15000,
hold: spectrumPeakHold,
}
}
func (w *StereoSpectrum) SetWaterwall(on bool) {
w.waterfall = on
var bins int
if on {
bins = w.width / 2
} else {
bins = w.width / spectrumBandPixels / 2
}
w.bands = makeStereoBands(bins)
w.peaks = makeStereoPeaks(bins)
}
func (w *StereoSpectrum) SetRange(min, max int) {
if min > max {
min, max = max, min
}
w.minFrequency = min
w.maxFrequency = max
}
func (w *StereoSpectrum) SetHold(hold int) {
w.hold = hold
}
func (w *StereoSpectrum) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
bounds := w.buffer.Bounds()
//draw.Draw(w.buffer, bounds, image.Black, image.Point{}, draw.Src)
if w.waterfall {
switch buffer := w.buffer.(type) {
case *pixel.Gray2Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.Gray4Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.CRGB15Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.CRGB16Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *image.RGBA:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
default:
for y := w.height - 1; y > 0; y-- {
draw.Draw(w.buffer, image.Rect(0, y, w.width, y+1), w.buffer, image.Pt(0, y-1), draw.Src)
}
}
for i := range w.bands[0] {
w.drawPoints(0, i)
w.drawPoints(1, i)
}
} else {
draw.Draw(w.buffer, w.buffer.Bounds(), image.Black, image.Point{}, draw.Src)
for i := range w.bands[0] {
w.drawBar(0, i)
w.drawBar(1, i)
}
}
draw.Draw(w.Display, bounds.Add(w.Position), w.buffer, image.Point{}, draw.Src)
return true
}
func (w *StereoSpectrum) drawBar(channel, i int) {
var offset int
if channel == 0 {
offset = (w.width / 2) - (i+1)*spectrumBandPixels
} else {
offset = (w.width / 2) + i*spectrumBandPixels
}
height := int(float64(w.height)*w.bands[channel][i] + .5)
for y := w.height - height; y < w.height; y++ {
colorY := pixel.Gray4{Y: 0xf - uint8(float64(y)/float64(w.height)*12+.5)}
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, y, colorY)
}
}
if w.hold <= 0 {
return
}
height = w.height - int(float64(w.height)*calc.Max(w.peaks[channel][i])+5)
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, height, pixel.On)
}
}
func (w *StereoSpectrum) drawPoints(channel, i int) {
var offset int
if channel == 0 {
offset = (w.width / 2) - (i + 1)
} else {
offset = (w.width / 2) + i
}
intesity := uint8(16*w.bands[channel][i] + .5)
w.buffer.Set(offset, w.height-1, pixel.Gray4{Y: intesity})
}
func (w *StereoSpectrum) ProcessBuffer(buffer audio.Buffer[float64]) {
var (
channels = buffer.Channels()
)
// Convert buffers to mono and high pass on 50Hz.
if channels == 1 { // unlikely
w.samples[0] = filter.HighPass(w.samples[0], buffer[0], 50, 44100)
w.samples[1] = w.samples[0]
} else {
w.samples[0] = filter.HighPass(w.samples[0], buffer[0], 50, 44100)
w.samples[1] = filter.HighPass(w.samples[1], buffer[1], 50, 44100)
}
// Calculate spectral powers.
w.power[0] = w.analyzer.Apply(w.power[0], w.samples[0])
w.power[1] = w.analyzer.Apply(w.power[1], w.samples[1])
// Adjust scale.
for i := range w.power[0] {
w.power[0][i].Magnitude /= 8
w.power[1][i].Magnitude /= 8
}
// Compress powers to our visible bars.
var (
highPassIndex = frequencyAbove(w.power[0], w.minFrequency)
lowPassIndex = frequencyBelow(w.power[0], w.maxFrequency)
)
summarizePowerBands(w.bands[0], w.power[0][highPassIndex:lowPassIndex], lowPassIndex-highPassIndex)
summarizePowerBands(w.bands[1], w.power[1][highPassIndex:lowPassIndex], lowPassIndex-highPassIndex)
// Calculate peaks per band.
if w.hold > 0 {
for c := range w.bands {
for i, v := range w.bands[c] {
w.peaks[c][i] = append(w.peaks[c][i], v)
for len(w.peaks[c][i]) > w.hold {
w.peaks[c][i] = w.peaks[c][i][1:]
}
}
}
}
w.changed = true
}
func makeStereoBands(n int) [2][]float64 {
return [2][]float64{
make([]float64, n),
make([]float64, n),
}
}
func makeStereoPeaks(n int) [2][][]float64 {
return [2][][]float64{
make([][]float64, n),
make([][]float64, n),
}
}
+108
View File
@@ -0,0 +1,108 @@
package widget
import (
"fmt"
"image"
"math"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/sirupsen/logrus"
)
const (
// CenterX is a position coordinate to indicate the widget should be centered horizontally.
CenterX = math.MinInt
// CenterY is a position coordinate to indicate the widget should be centered vertically.
CenterY = math.MinInt
)
// Center magic position shortcut.
var Center = image.Point{
X: CenterX,
Y: CenterY,
}
// Text widget can render text.
type Text struct {
Display display.Display
Position image.Point
Style ui.Style
buffer draw.Image
mask image.Image
text string
changed bool
}
func NewText(display display.Display, at image.Point) *Text {
return &Text{
Display: display,
Position: at,
}
}
func (w *Text) Set(text string) *Text {
width, height := w.Style.Font.MeasureText(text)
if w.buffer == nil || !w.buffer.Bounds().Eq(image.Rect(0, 0, width, height)) {
logrus.WithFields(logrus.Fields{
"size": fmt.Sprintf("%dx%d", width, height),
"text": text,
"widget": "text",
}).Debug("create new buffer")
w.buffer = ui.BufferFor(w.Display.ColorModel(), width, height)
}
draw.Draw(w.buffer, w.buffer.Bounds(), w.Style.Background, image.Point{}, draw.Src)
w.Style.Font.Draw(w.buffer, image.Point{}, w.mask, text)
w.text = text
w.changed = true
return w
}
func (w *Text) SetStyle(style ui.Style) *Text {
w.Style = style
if style.FontSize > 0 {
w.Style.Font.SetPointSize(style.FontSize)
}
w.mask = image.NewUniform(w.Style.Foreground)
if w.text != "" {
w.Set(w.text)
}
return w
}
func (w *Text) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
var (
r = w.Display.Bounds()
displaySize = r.Size()
bufferSize = w.buffer.Bounds().Size()
)
if w.Position.X == CenterX {
if bufferSize.X < displaySize.X {
r.Min.X = (displaySize.X - bufferSize.X) / 2
}
} else {
r.Min.X += w.Position.X
}
if w.Position.Y == CenterY {
if bufferSize.Y < displaySize.Y {
r.Min.Y = (displaySize.Y - bufferSize.Y) / 2
}
} else {
r.Min.Y += w.Position.Y
}
draw.Draw(w.Display, r, w.buffer, image.Point{}, draw.Src)
w.changed = false
return true
}
+76
View File
@@ -0,0 +1,76 @@
package widget
import (
"image"
"math"
)
const (
halfPi = math.Pi / 2
)
type Transitioner interface {
Transition(float64) float64
}
type TransitionFunc func(float64) float64
func (f TransitionFunc) Transition(x float64) float64 { return f(x) }
var (
Linear = TransitionFunc(func(x float64) float64 { return x })
Exponential = TransitionFunc(func(x float64) float64 { return math.Pow(2, 8*(x-1)) })
Circular = TransitionFunc(func(x float64) float64 { return 1 - math.Sin(math.Acos(x)) })
Sine = TransitionFunc(func(x float64) float64 { return 1 - math.Sin(x*halfPi) })
Elastic = TransitionFunc(func(x float64) float64 { return math.Pow(2, 10*(x-1)) * math.Cos(20*x*math.Pi/3) })
Bounce = TransitionFunc(bounce)
)
func bounce(x float64) (v float64) {
for a, b := 0.0, 1.0; true; a, b = a+b, b/2 {
if x >= (7-4*a)/11 {
v = b*b - math.Pow((11-6*a-11*x)/4, 2)
break
}
}
return
}
type PointTransition struct {
start, final image.Point
t Transitioner
dx, dy float64
step, steps int
}
func NewPointTransition(final image.Point, t Transitioner) *PointTransition {
return &PointTransition{
final: final,
t: t,
}
}
// Start a new transition for point at start to final.
func (p *PointTransition) Start(start image.Point, steps int) {
p.start = start
p.dx = float64(p.final.X-start.X) / float64(steps)
p.dy = float64(p.final.Y-start.Y) / float64(steps)
}
// Next step.
func (p *PointTransition) Next() (at image.Point, done bool) {
if p.step >= p.steps {
return p.final, true
}
p.step++
tx := 1.0
if p.t != nil {
tx = p.t.Transition(float64(p.step) / float64(p.steps))
}
at = p.start
at.X += int(p.dx * float64(p.step) * tx)
at.Y += int(p.dy * float64(p.step) * tx)
return
}
+111
View File
@@ -0,0 +1,111 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/pixel"
)
type WaveForm struct {
Display display.Display
Position image.Point
buffer draw.Image
height int
width int
bins int
level [2][]float64
changed bool
}
func NewWaveform(display display.Display, at image.Point, width, height int) *WaveForm {
bins := width / 2
return &WaveForm{
Display: display,
Position: at,
buffer: ui.BufferFor(display.ColorModel(), width, height),
width: width,
height: height,
bins: bins,
}
}
func (w *WaveForm) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
draw.Draw(w.buffer, w.buffer.Bounds(), image.Black, image.Point{}, draw.Src)
for i := range w.level[0] {
w.drawLevel(0, i)
w.drawLevel(1, i)
}
draw.Draw(w.Display, w.buffer.Bounds().Add(w.Position), w.buffer, image.Point{}, draw.Src)
return true
}
func (w *WaveForm) drawLevel(channel, i int) {
var offset = (w.width / 2)
if channel == 0 {
offset -= i
} else {
offset += i
}
y := w.height/2 + int(float64(w.height/2)*w.level[channel][i]+.5)
w.buffer.Set(offset, y, pixel.On)
}
func (w *WaveForm) ProcessBuffer(buffer audio.Buffer[float64]) {
var (
channels = buffer.Channels()
)
if channels == 1 {
w.level[0] = condenseSamples(w.level[0], buffer[0], w.bins)
w.level[1] = w.level[0]
} else {
w.level[0] = condenseSamples(w.level[0], buffer[0], w.bins)
w.level[1] = condenseSamples(w.level[1], buffer[1], w.bins)
}
w.changed = true
}
// condenseSamples reduces the input samples to a fixed number of points.
// It aggregates values within each segment using averaging.
func condenseSamples(dst, src []float64, targetWidth int) []float64 {
if len(dst) != targetWidth {
dst = make([]float64, targetWidth)
}
if len(src) <= targetWidth {
// If the buffer is smaller than or equal to the target width, return as is.
copy(dst, src)
return dst
}
binSize := float64(len(src)) / float64(targetWidth)
for i := 0; i < targetWidth; i++ {
start := int(float64(i) * binSize)
end := int(float64(i+1) * binSize)
if end > len(src) {
end = len(src)
}
// Compute the average for the segment.
sum := 0.0
for j := start; j < end; j++ {
sum += src[j]
}
dst[i] = sum / float64(end-start)
}
return dst
}