Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:28:51 +01:00
1 parent 7b6db17870
commit 0295eb1ad2
125 files changed
+59376

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
// Package all loads all supported player types.
package all
import (
_ "git.maze.io/go/bragi/player/moode"
_ "git.maze.io/go/bragi/player/mpd"
_ "git.maze.io/go/bragi/player/runeaudio"
_ "git.maze.io/go/bragi/player/volumio"
)
+195
View File
@@ -0,0 +1,195 @@
package player
import (
"fmt"
"time"
)
// Event emitted by the player.
type Event interface {
// String is a human readable version of the event.
String() string
// Player that this event originated from.
Player() Player
// Time that the event occurred.
Time() time.Time
}
// baseEvent is the base for most events
type baseEvent struct {
player Player
time time.Time
}
func makeBaseEvent(p Player) baseEvent {
return baseEvent{
player: p,
time: time.Now(),
}
}
func (e baseEvent) Player() Player { return e.player }
func (e baseEvent) Time() time.Time { return e.time }
func (e *baseEvent) SetTime(t time.Time) { e.time = t }
// Common event types.
type (
// ErrorEvent event.
ErrorEvent struct {
baseEvent
// Err is the error.
Err error
}
// StatusEvent sends the player status.
StatusEvent struct {
baseEvent
Status *Status
}
// ConnectedEvent event.
ConnectedEvent struct {
baseEvent
}
// DisconnectedEvent event.
DisconnectedEvent struct {
baseEvent
}
// PlayEvent event.
PlayEvent struct {
baseEvent
// Track that is being played.
Track *Track
}
// StopEvent event.
StopEvent struct {
baseEvent
}
// PauseEvent event.
PauseEvent struct {
baseEvent
// Track that is being paused.
Track *Track
}
// VolumeEvent event.
VolumeEvent struct {
baseEvent
// Level is the volume level [0..100].
Level uint8
}
// MuteEvent event.
MuteEvent struct {
baseEvent
}
)
func NewError(p Player, err error) Event {
return ErrorEvent{
baseEvent: makeBaseEvent(p),
Err: err,
}
}
func (e ErrorEvent) String() string {
return fmt.Sprintf("error player=%s time=%s", e.player.Name(), e.time)
}
func NewStatusEvent(p Player, s *Status) Event {
return StatusEvent{
baseEvent: makeBaseEvent(p),
Status: s,
}
}
func (e StatusEvent) String() string {
return fmt.Sprintf("status player=%s time=%s status=%s", e.player.Name(), e.time, e.Status)
}
func NewConnectedEvent(p Player) Event {
return ConnectedEvent{
baseEvent: makeBaseEvent(p),
}
}
func (e ConnectedEvent) String() string {
return fmt.Sprintf("connected player=%s time=%s", e.player.Name(), e.time)
}
func NewDisconnectedEvent(p Player) Event {
return DisconnectedEvent{
baseEvent: makeBaseEvent(p),
}
}
func (e DisconnectedEvent) String() string {
return fmt.Sprintf("disconnected player=%s time=%s", e.player.Name(), e.time)
}
func NewPlayEvent(p Player, t *Track) Event {
return PlayEvent{
baseEvent: makeBaseEvent(p),
Track: t,
}
}
func (e PlayEvent) String() string {
return fmt.Sprintf("play player=%s time=%s", e.player.Name(), e.time)
}
func NewStopEvent(p Player) Event {
return StopEvent{
baseEvent: makeBaseEvent(p),
}
}
func (e StopEvent) String() string {
return fmt.Sprintf("stop player=%s time=%s", e.player.Name(), e.time)
}
func NewPauseEvent(p Player, t *Track) Event {
return PauseEvent{
baseEvent: makeBaseEvent(p),
Track: t,
}
}
func (e PauseEvent) String() string {
return fmt.Sprintf("pause player=%s time=%s", e.player.Name(), e.time)
}
func NewVolumeEvent(p Player, level uint8) Event {
if level > 100 {
level = 100
}
return VolumeEvent{
baseEvent: makeBaseEvent(p),
Level: level,
}
}
func (e VolumeEvent) String() string {
return fmt.Sprintf("volume player=%s time=%s level=%d", e.player.Name(), e.time, e.Level)
}
func NewMuteEvent(p Player) Event {
return MuteEvent{
baseEvent: makeBaseEvent(p),
}
}
func (e MuteEvent) String() string {
return fmt.Sprintf("mute player=%s time=%s", e.player.Name(), e.time)
}
+9
View File
@@ -0,0 +1,9 @@
package moode
import "os"
// Detect if moOde is installed.
func Detect() bool {
_, err := os.Stat("/var/www/command/moode.php")
return err == nil
}
+142
View File
@@ -0,0 +1,142 @@
package moode
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
"git.maze.io/go/bragi/config"
"git.maze.io/go/bragi/player"
"git.maze.io/go/bragi/player/mpd"
"git.maze.io/go/bragi/util"
)
const (
DefaultHost = "localhost"
DefaultPort = "80"
DefaultAddr = DefaultHost + ":" + DefaultPort
currentSongFile = "/var/local/www/currentsong.txt"
)
type Player struct {
addr string
mpd *mpd.Player
isLocal bool
}
func New(config *config.Player) (player.Player, error) {
addr := util.MakeAddr(config.Host, DefaultAddr)
return &Player{
addr: addr,
}, nil
}
func (p *Player) Name() string {
return "moOde"
}
func (p *Player) Events() (<-chan player.Event, error) {
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 (Player) Status() *player.Status {
s, _ := parseStatus(currentSongFile)
return s
}
func parseStatus(name string) (*player.Status, error) {
if name == "" {
name = currentSongFile
}
f, err := os.Open(name)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
status := &player.Status{Track: new(player.Track)}
for scanner.Scan() {
if err = scanner.Err(); err != nil {
break
}
line := scanner.Text()
if line == "" {
continue
} else if i := strings.Index(line, "="); i > 0 {
k, v := line[:i], line[i+1:]
switch k {
case "file":
status.Track.Path = v
case "artist":
status.Track.Artist = v
case "album":
status.Track.Album = v
case "title":
status.Track.Title = v
case "state":
switch v {
case "play":
status.Playing = true
status.Paused = false
case "pause":
status.Playing = true
status.Paused = true
case "stop":
status.Playing = false
status.Paused = false
}
}
}
}
return status, err
}
// parseAudioFormat takes a moOde notated audio format
//
// PCM 16/44.1 kHz, 2ch
// FLAC 16/48.0 kHz, 2ch
func parseAudioFormat(s string) (f player.AudioFormat, err error) {
var i int
if i = strings.IndexByte(s, ' '); i == -1 {
return f, fmt.Errorf("moode: unknown audio format %q", s)
}
f.Encoding, s = s[:i], s[i+1:]
if i = strings.IndexByte(s, '/'); i == -1 {
return f, fmt.Errorf("moode: unknown audio format %q", s)
}
if f.Bits, err = strconv.Atoi(s[:i]); err != nil {
return
}
s = s[i+1:] // "xx.y kHz, nch"
if i = strings.IndexByte(s, ','); i == -1 {
return f, fmt.Errorf("moode: unknown audio format %q", s)
}
if f.SampleRate, err = util.ParseFrequency(strings.Replace(s[:i], " ", "", 1)); err != nil {
return
}
s = strings.TrimSpace(s[i+1:]) // "nch"
if f.Channels, err = strconv.Atoi(s[:1]); err != nil {
return
}
return
}
+42
View File
@@ -0,0 +1,42 @@
package moode
import (
"testing"
"git.maze.io/go/bragi/player"
"periph.io/x/conn/v3/physic"
)
func TestParseAudioFormat(t *testing.T) {
testCases := []struct {
Test string
Want player.AudioFormat
}{
{"PCM 16/44.1 kHz, 2ch", player.AudioFormat{Encoding: "PCM", Bits: 16, SampleRate: 44100 * physic.Hertz, Channels: 2}},
{"FLAC 24/48.0 kHz, 2ch", player.AudioFormat{Encoding: "FLAC", Bits: 24, SampleRate: 48 * physic.KiloHertz, Channels: 2}},
{"MP3 16/44.1 kHz, 2ch", player.AudioFormat{Encoding: "MP3", Bits: 16, SampleRate: 44100 * physic.Hertz, Channels: 2}},
{"AAC 24/96.0 kHz, 2ch", player.AudioFormat{Encoding: "AAC", Bits: 24, SampleRate: 96 * physic.KiloHertz, Channels: 2}},
{"WAV 16/44.1 kHz, 1ch", player.AudioFormat{Encoding: "WAV", Bits: 16, SampleRate: 44100 * physic.Hertz, Channels: 1}},
}
for _, test := range testCases {
t.Run(test.Test, func(it *testing.T) {
f, err := parseAudioFormat(test.Test)
if err != nil {
it.Fatal(err)
}
if f.Encoding != test.Want.Encoding {
it.Errorf("expected encoding %q, got %q", test.Want.Encoding, f.Encoding)
}
if f.Bits != test.Want.Bits {
it.Errorf("expected bits %d, got %d", test.Want.Bits, f.Bits)
}
if f.SampleRate != test.Want.SampleRate {
it.Errorf("expected sample rate %d, got %d", test.Want.SampleRate, f.SampleRate)
}
if f.Channels != test.Want.Channels {
it.Errorf("expected channels %d, got %d", test.Want.Channels, f.Channels)
}
it.Log(f)
})
}
}
+9
View File
@@ -0,0 +1,9 @@
package mpd
import "os/exec"
// Detect if music player daemon is installed.
func Detect() bool {
_, err := exec.LookPath("mpd")
return err == nil
}
+79
View File
@@ -0,0 +1,79 @@
package mpd
import (
"strings"
"github.com/sirupsen/logrus"
)
func (c *Player) idleLoop(conn *clientConn) {
defer func() {
_ = conn.Close()
}()
log := conn.log()
log.Debug("starting loop")
var (
subsystems []interface{}
err error
)
subsystems = make([]interface{}, len(c.idleSubsystems))
for i, subsystem := range c.idleSubsystems {
subsystems[i] = subsystem
}
loop:
for {
/*
var kv map[string]string
log.WithField("subsystems", c.idleSubsystems).Debug("sending idle command")
if kv, err = c.commandMap(conn, "idle", subsystems...); err != nil {
log.WithError(err).Error("error sending idle command")
break loop
} else if subsystem, ok := kv["changed"]; ok {
if err = c.idleChanged(subsystem); err != nil {
break loop
}
}
*/
var id uint
log.Debug("enter idle mode")
if id, err = conn.Cmd("idle"); err != nil {
break loop
}
log.WithField("id", id).Debug("idle mode ready")
conn.StartResponse(id)
for {
var line string
if line, err = conn.ReadLine(); err != nil {
break loop
} else if line == "OK" {
break
} else if i := strings.Index(line, ": "); i > 0 && line[:i] == "changed" {
if err = c.idleChanged(line[i+2:]); err != nil {
break loop
}
} else {
log.WithField("data", line).Warn("unexpected idle response")
break
}
}
conn.EndResponse(id)
}
if err != nil {
log.WithError(err).Error("idle loop terminating")
} else {
log.Info("idle loop terminating")
}
}
func (c *Player) idleChanged(subsystem string) (err error) {
logrus.WithFields(logrus.Fields{
"protocol": "mpd",
"addr": c.addr,
"subsystem": subsystem,
}).Debug("subsystem changed")
return
}
+465
View File
@@ -0,0 +1,465 @@
package mpd
import (
"fmt"
"net"
"net/textproto"
"strconv"
"strings"
"time"
"git.maze.io/go/bragi/config"
"git.maze.io/go/bragi/player"
"git.maze.io/go/bragi/util"
"github.com/sirupsen/logrus"
)
func init() {
player.Register("mpd", func(config *config.Player) (player.Player, error) {
return New(config.Host, config.Password, config.Name)
}, Detect, 10)
}
const (
DefaultPort = "6600"
DefaultAddr = "localhost:" + DefaultPort
)
type Player struct {
// Version is the server protocol version.
Version Version
name string
addr string
password string
idleSubsystems []string
commands chan *Command
errors chan error
quit chan struct{}
}
type clientConn struct {
*textproto.Conn
name string
}
func (c *clientConn) log() *logrus.Entry {
return logrus.WithFields(logrus.Fields{
"protocol": "mpd",
"loop": c.name,
})
}
// 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 New(addr, password, name string) (*Player, error) {
addr = util.MakeAddr(addr, DefaultAddr)
if _, err := net.ResolveTCPAddr("tcp", addr); err != nil {
return nil, err
}
p := &Player{
name: name,
addr: addr,
commands: make(chan *Command, 16),
errors: make(chan error, 1),
quit: make(chan struct{}, 2),
}
return p, nil
}
func newConn(addr, password, kind, name string) (*clientConn, *Version, error) {
log := logrus.WithFields(logrus.Fields{
"protocol": "mpd",
"player": name,
"addr": addr,
"conn": kind,
})
if addr == "" {
addr = DefaultAddr
}
log.Info("connecting to Music Player Daemon")
conn, err := textproto.Dial("tcp", addr)
if err != nil {
return nil, nil, err
}
line, err := conn.ReadLine()
if err != nil {
return nil, nil, err
}
log.WithField("response", line).Trace("reading server hello")
if !strings.HasPrefix(line, "OK MPD ") {
_ = conn.Close()
return nil, nil, fmt.Errorf("mpd: unexpected server greeting %q", line)
}
version, err := ParseVersion(line[7:])
if err != nil {
_ = conn.Close()
return nil, nil, fmt.Errorf("mpd: unexpected server version %q: %w", line[6:], err)
}
if password != "" {
log.Debug("sending password")
id, err := conn.Cmd("password %s", password)
if err != nil {
_ = conn.Close()
return nil, nil, err
}
conn.StartResponse(id)
defer conn.EndResponse(id)
if line, err = conn.ReadLine(); err != nil {
_ = conn.Close()
return nil, nil, err
}
log.WithField("response", line).Trace("reading server password response")
if line != "OK" {
_ = conn.Close()
return nil, nil, fmt.Errorf("mpd: unexpected response to password: %q", line)
}
}
return &clientConn{conn, kind}, &version, nil
}
func (p *Player) Close() error {
for i := 0; i < 2; i++ {
select {
case p.quit <- struct{}{}:
default:
}
}
select {
case err := <-p.errors:
return err
default:
return nil
}
}
func (p *Player) sendCommand(conn *clientConn, format string, args ...interface{}) (err error) {
log := conn.log().WithField("command", fmt.Sprintf(format, args...))
log.Trace("sending command")
var id uint
if id, err = conn.Cmd(format, args...); err != nil {
log.WithError(err).Warn("command failed")
return
}
log = log.WithField("id", id)
log.Trace("start response")
conn.StartResponse(id)
for {
var line string
if line, err = conn.ReadLine(); err != nil {
log.WithError(err).Warn("command response read failed")
break
}
log.WithField("data", line).Trace("command response")
if line == "OK" {
break
}
}
log.Trace("end response")
conn.EndResponse(id)
return
}
func (p *Player) sendCommandList(conn *clientConn, commands []Command) (err error) {
log := conn.log()
log.Trace("sending command list")
if len(commands) == 0 {
return
}
id := conn.Next()
conn.StartRequest(id)
if err = conn.PrintfLine("command_list_begin"); err != nil {
return
}
for _, command := range commands {
if err = conn.PrintfLine(command.Format, command.Args...); err != nil {
conn.EndRequest(id)
return
}
}
if err = conn.PrintfLine("command_list_end"); err != nil {
return
}
conn.EndRequest(id)
log = log.WithField("id", id)
log.Trace("start response")
conn.StartResponse(id)
conn.EndResponse(id)
return
}
func (p *Player) sendMapCommand(conn *clientConn, format string, args ...interface{}) (kv map[string]string, err error) {
log := conn.log().WithField("command", fmt.Sprintf(format, args...))
log.Trace("sending map command")
var id uint
if id, err = conn.Cmd(format, args...); err != nil {
log.WithError(err).Warn("map command failed")
return
}
log = log.WithField("id", id)
log.Trace("start map response")
conn.StartResponse(id)
kv = make(map[string]string)
for {
var line string
if line, err = conn.ReadLine(); err != nil {
log.WithError(err).Warn("command response read failed")
break
}
log.WithField("data", line).Trace("command response")
if line == "OK" {
break
} else if i := strings.Index(line, ": "); i > 0 {
kv[line[:i]] = line[i+2:]
}
}
log.Trace("end map response")
conn.EndResponse(id)
return
}
func (p *Player) run(events chan player.Event) {
log := logrus.WithFields(logrus.Fields{
"protocol": "mpd",
})
log.Info("starting client")
events <- player.NewDisconnectedEvent(p)
for {
main, version, err := newConn(p.addr, p.password, "main", p.name)
if err != nil {
log.WithError(err).Warn("connection failed; retrying")
time.Sleep(time.Second)
continue
}
main.log().WithField("version", version).Info("connected to Music Player Daemon")
idle, _, err := newConn(p.addr, p.password, "idle", p.name)
if err != nil {
_ = main.Close()
log.WithError(err).Warn("connection failed; retrying")
time.Sleep(time.Second)
continue
}
p.commands = make(chan *Command)
p.errors = make(chan error)
p.quit = make(chan struct{}, 2)
events <- player.NewConnectedEvent(p)
go p.idleLoop(idle)
p.mainLoop(main, events)
events <- player.NewDisconnectedEvent(p)
_ = idle.Close()
_ = main.Close()
close(p.commands)
close(p.errors)
}
log.Warn("client terminating")
}
func (p *Player) mainLoop(conn *clientConn, events chan player.Event) {
defer func() {
_ = conn.Close()
}()
log := conn.log()
log.Debug("starting loop")
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var err error
loop:
for {
select {
case command := <-p.commands:
if command == nil {
break loop
}
if err = p.sendCommand(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")
var track map[string]string
if track, err = p.sendMapCommand(conn, "currentsong"); err != nil {
log.WithError(err).Error("error retrieving current song")
break loop
}
events <- player.NewStatusEvent(p, parseStatus(p, status, track))
case <-p.quit:
break loop
}
}
if err != nil {
log.WithError(err).Error("main loop terminating")
select {
case p.errors <- err:
default:
}
} else {
log.Info("main loop terminating")
}
select {
case p.quit <- struct{}{}:
default:
}
}
func (p *Player) Events() (<-chan player.Event, error) {
events := make(chan player.Event)
go p.run(events)
return events, nil
}
func (Player) Status() *player.Status {
return nil
}
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 newCommand(format string, args ...interface{}) *Command {
return &Command{
Format: format,
Args: args,
Err: make(chan error),
}
}
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 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"],
}
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
}
+159
View File
@@ -0,0 +1,159 @@
package player
import (
"fmt"
"image"
"strconv"
"strings"
"time"
"git.maze.io/go/bragi/util"
"periph.io/x/conn/v3/physic"
)
// Player controls music playback.
type Player interface {
// Name returns the name of the source.
Name() string
// Events returns a channel that will be used to send events to the source.
Events() (<-chan Event, error)
// Status of the player
Status() *Status
Play() error
Pause() error
Next() error
Previous() error
Seek(time.Duration) error
}
// AudioFormat is the audio format.
type AudioFormat struct {
Encoding string
SampleRate physic.Frequency
Bits int
Channels int
BitRate int
}
func (f AudioFormat) String() string {
e := f.Encoding
if e == "" {
e = "PCM"
}
return fmt.Sprintf("%s %s %d-bits %dch %d bits/s", e, f.SampleRate, f.Bits, f.Channels, f.BitRate)
}
func ParseMPDAudioFormat(s string) (f AudioFormat, err error) {
var i int
if i = strings.IndexByte(s, ':'); i == -1 {
return f, fmt.Errorf("player: malformed MPD audio format %q", s)
} else if f.SampleRate, err = util.ParseFrequency(s[:i]); err != nil {
return
}
s = s[i+1:]
if i = strings.IndexByte(s, ':'); i == -1 {
return f, fmt.Errorf("player: malformed MPD audio format %q", s)
} else if f.Bits, err = strconv.Atoi(s[:i]); err != nil {
return
}
s = s[i+1:]
if f.Channels, err = strconv.Atoi(s); err != nil {
return
}
return f, err
}
// Status represents the current status of the player.
type Status struct {
// Player instance.
Player Player
// Source format
Source AudioFormat
// Output format
Output AudioFormat
// Elapsed time playing the current track.
Elapsed time.Duration
// ElapsedPercentage of the current track.
ElapsedPercentage float64
// Playing indicates if a track is playing.
Playing bool
// Paused indicates if the track is paused.
Paused bool
// Repeat enabled.
Repeat bool
// Shuffle enabled.
Shuffle bool
// Volume in range [0..100]
Volume int
// Muted indicates if the player is muted.
Muted bool
// Track is the current track loaded in the player.
Track *Track
}
func (s *Status) String() string {
return fmt.Sprintf("source=%s output=%s elapsed=%s play=%t", s.Source, s.Output, s.Elapsed, s.Playing)
}
// Track represents an audio track.
type Track struct {
// 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)
}
+36
View File
@@ -0,0 +1,36 @@
package player_test
import (
"testing"
"git.maze.io/go/bragi/player"
"periph.io/x/conn/v3/physic"
)
func TestParseMPDAudioFormat(t *testing.T) {
testCases := []struct {
Input string
Format player.AudioFormat
}{
{"44100:16:2", player.AudioFormat{SampleRate: 44100 * physic.Hertz, Channels: 2, Bits: 16}},
{"22050:8:1", player.AudioFormat{SampleRate: 22050 * physic.Hertz, Channels: 1, Bits: 8}},
}
for _, test := range testCases {
t.Run(test.Input, func(it *testing.T) {
f, err := player.ParseMPDAudioFormat(test.Input)
if err != nil {
it.Fatal(err)
}
if f.SampleRate != test.Format.SampleRate {
it.Errorf("expected sample rate %s, got %s", test.Format.SampleRate, f.SampleRate)
}
if f.Channels != test.Format.Channels {
it.Errorf("expected %d channels, got %d", test.Format.Channels, f.Channels)
}
if f.Bits != test.Format.Bits {
it.Errorf("expected %d bits, got %d", test.Format.Bits, f.Bits)
}
it.Log(f)
})
}
}
+99
View File
@@ -0,0 +1,99 @@
package player
import (
"fmt"
"sort"
"sync"
"git.maze.io/go/bragi/config"
)
// NotFound signals the player can not be found.
type NotFound struct {
Name string
}
func (err NotFound) Error() string {
return fmt.Sprintf("player: %q can not be found", err.Name)
}
// Factory is a function that can instantiate a new Player.
type Factory func(*config.Player) (Player, error)
// Detector checks if this player is available.
type Detector func() bool
type detector struct {
Name string
New Factory
Detect Detector
Priority int
}
var (
// protocols holds the per protocol factories
protocols = new(sync.Map)
detectors []detector
// instances holds the named players
instances = new(sync.Map)
)
// Register a new protocol factory.
func Register(name string, f Factory, d Detector, priority int) {
if _, loaded := protocols.LoadOrStore(name, f); loaded {
panic(fmt.Sprintf("player type %q already registered", name))
}
if d != nil {
detectors = append(detectors, detector{
Name: name,
New: f,
Detect: d,
Priority: priority,
})
sort.Slice(detectors, func(i, j int) bool {
return detectors[i].Priority < detectors[j].Priority
})
}
}
// New returns a player factory for the requested type.
func New(config *config.Player) (Player, error) {
f, ok := protocols.Load(config.Protocol)
if !ok {
return nil, NotFound{Name: config.Protocol}
}
p, err := f.(Factory)(config)
if err != nil {
return nil, err
}
instances.Store(config.Name, p)
return p, nil
}
// RegisterInstance registers a new player instance by name.
func RegisterInstance(name string, p Player) {
if _, loaded := instances.LoadOrStore(name, p); loaded {
panic(fmt.Sprintf("player instance %q already registered", name))
}
}
// Lookup a previously registered instance.
func Lookup(name string) (Player, error) {
f, ok := instances.Load(name)
if ok {
return f.(Player), nil
}
return nil, NotFound{Name: name}
}
// Detect what player is available.
func Detect() (name string, factory Factory) {
for _, d := range detectors {
if d.Detect() {
return d.Name, d.New
}
}
return "", nil
}
+9
View File
@@ -0,0 +1,9 @@
package runeaudio
import "os"
// Detect if runeaudio is installed.
func Detect() bool {
_, err := os.Stat("/srv/http/command/rune_shutdown")
return err == nil
}
+9
View File
@@ -0,0 +1,9 @@
package volumio
import "os"
// Detect if Volumio is installed.
func Detect() bool {
i, err := os.Stat("/volumio")
return err == nil && i.IsDir()
}
+47
View File
@@ -0,0 +1,47 @@
package volumio
import (
"time"
"git.maze.io/go/bragi/config"
"git.maze.io/go/bragi/player"
"git.maze.io/go/bragi/player/mpd"
)
const (
DefaultPort = "3000"
)
func init() {
player.Register("volumio", func(config *config.Player) (player.Player, error) {
return New(config)
}, Detect, 1)
}
type Player struct {
mpd *mpd.Player
}
func New(config *config.Player) (player.Player, error) {
//return new(Player), nil
m, err := mpd.New(config.Host, config.Password, config.Name)
if err != nil {
return nil, err
}
return &Player{
mpd: m,
}, nil
}
func (Player) Name() string { return "volumio" }
func (p *Player) Status() *player.Status { return p.mpd.Status() }
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) Events() (<-chan player.Event, error) {
return p.mpd.Events()
}