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

+181 -99
View File
@@ -2,6 +2,7 @@ package mpd
import (
"fmt"
"io"
"net"
"net/textproto"
"strconv"
@@ -11,9 +12,9 @@ import (
"github.com/sirupsen/logrus"
"go.maze.io/harmon/config"
"go.maze.io/harmon/internal/util"
"go.maze.io/harmon/player"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/beatglow/internal/util"
"github.com/BeatGlow/beatglow/player"
)
func init() {
@@ -37,7 +38,8 @@ type Player struct {
idleSubsystems []string
artCache sync.Map // map of path to image
artRequest chan *artRequest
commands chan *Command
simpleCommands chan *simpleCommand
dataCommands chan *dataCommand
errors chan error
quit chan struct{}
}
@@ -54,41 +56,24 @@ func (c *clientConn) log() *logrus.Entry {
})
}
// Version number.
type Version struct {
Major int
Minor int
Patch int
}
func (c *clientConn) readBytes(size int) (b []byte, err error) {
c.log().WithField("size", size).Debug("read bytes")
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)
b = make([]byte, size)
if _, err := io.ReadFull(c.Conn.R, b); err != nil {
return nil, err
}
var (
v Version
err error
)
if v.Major, err = strconv.Atoi(part[0]); err != nil {
return Version{}, err
// Verify there's a linebreak afterwards and skip it
termByte, err := c.Conn.R.ReadByte()
if err != nil {
return nil, textproto.ProtocolError("failed to read binary data terminator: " + err.Error())
}
if v.Minor, err = strconv.Atoi(part[1]); err != nil {
return Version{}, err
if termByte != '\n' {
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 v, nil
return
}
func New(addr, password string) (*Player, error) {
@@ -97,11 +82,12 @@ func New(addr, password string) (*Player, error) {
return nil, err
}
p := &Player{
addr: addr,
commands: make(chan *Command, 16),
artRequest: make(chan *artRequest, 16),
errors: make(chan error, 1),
quit: make(chan struct{}, 2),
addr: addr,
simpleCommands: make(chan *simpleCommand, 8),
dataCommands: make(chan *dataCommand, 8),
artRequest: make(chan *artRequest, 8),
errors: make(chan error, 1),
quit: make(chan struct{}, 2),
}
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)
}
version, err := ParseVersion(line[7:])
version, err := parseVersion(line[7:])
if err != nil {
_ = conn.Close()
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
}
func (Player) Type() string { return "mpd" }
func (*Player) Type() string { return "mpd" }
func (p *Player) Halt() error {
for i := 0; i < 2; i++ {
@@ -213,7 +199,41 @@ func (p *Player) sendCommand(conn *clientConn, format string, args ...interface{
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.Trace("sending command list")
@@ -280,6 +300,80 @@ func (p *Player) sendMapCommand(conn *clientConn, format string, args ...interfa
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) {
log := logrus.WithFields(logrus.Fields{
"protocol": "mpd",
@@ -314,7 +408,7 @@ func (p *Player) run(events chan player.Event) {
continue
}
p.commands = make(chan *Command)
p.simpleCommands = make(chan *simpleCommand)
p.errors = make(chan error)
p.quit = make(chan struct{}, 2)
@@ -328,7 +422,7 @@ func (p *Player) run(events chan player.Event) {
_ = idle.Close()
_ = main.Close()
close(p.commands)
close(p.simpleCommands)
close(p.errors)
}
@@ -350,7 +444,7 @@ func (p *Player) mainLoop(conn *clientConn, events chan player.Event) {
loop:
for {
select {
case command := <-p.commands:
case command := <-p.simpleCommands:
if command == nil {
break loop
}
@@ -361,13 +455,24 @@ loop:
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:
var status map[string]string
if status, err = p.sendMapCommand(conn, "status"); err != nil {
log.WithError(err).Error("error retrieving status")
break loop
}
log.WithField("status", status).Debug("status")
log.WithField("status", status).Trace("status")
var track map[string]string
if track, err = p.sendMapCommand(conn, "currentsong"); err != nil {
@@ -410,72 +515,49 @@ func (p *Player) Name() string {
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) Pause() error { return p.Command("pause") }
func (p *Player) Next() error { return p.Command("next") }
func (p *Player) Previous() error { return p.Command("previous") }
func (p *Player) Seek(d time.Duration) error { return p.Command("seekcur %f", d.Seconds()) }
type Command struct {
Format string
Args []interface{}
Err chan error
func (p *Player) ChangeVolume(delta int) error {
return p.Command("volume %d", delta)
}
func newCommand(format string, args ...interface{}) *Command {
return &Command{
Format: format,
Args: args,
Err: make(chan error),
func (p *Player) SetVolume(level int) error {
if level < 0 {
level = 0
}
if level > 100 {
level = 100
}
return p.Command("setvol %d", level)
}
func parseStatus(p player.Player, status, track map[string]string) *player.Status {
s := &player.Status{
Player: p,
}
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 (p *Player) ToggleMute() error {
// MPD doesn't mute, it can pause...
return p.Command("pause")
}
func parseTrack(data map[string]string) (*player.Track, player.AudioFormat) {
track := &player.Track{
Artist: data["Artist"],
Title: data["Title"],
Album: data["Album"],
Label: data["Label"],
Genre: strings.Split(data["Genra"], ";"),
Path: data["file"],
func (p *Player) Playlist() ([]*player.Track, error) {
lines, err := p.CommandData("playlistinfo")
if err != nil {
return nil, err
}
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"])
return track, audio
var (
tracks []*player.Track
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
}