Files
2026-10-29 17:29:54 +01:00

127 lines
2.7 KiB
Go

package player
import (
"errors"
"fmt"
"sort"
"sync"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/config"
)
// ErrNotFound indicates no instance was saved.
var ErrNotFound = errors.New("player not registered")
// NotFound signals the player type can not be found.
type NotFound struct {
Type string
}
func (err NotFound) Error() string {
return fmt.Sprintf("player %q can not be found", err.Type)
}
// 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
// instance holds the current player instance
instance Player
)
// Register a new protocol factory.
func Register(name string, f Factory, d Detector, priority int) {
logrus.WithField("type", name).Debug("register player type")
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) {
log := logrus.WithField("type", config.Type)
log.Trace("create new player")
f, ok := protocols.Load(config.Type)
if !ok {
log.Warn("player type not found")
return nil, NotFound{Type: config.Type}
}
log.Trace("create new player instance")
p, err := f.(Factory)(config)
if err != nil {
log.WithError(err).Warn("player instance failed")
return nil, err
}
if config.Type == "" || config.Type == "auto" {
log = log.WithField("type", p.Name())
}
log.Trace("store player instance")
instance = p
return p, nil
}
// Get a previously registered instance.
func Get() (Player, error) {
if instance != nil {
return instance, nil
}
return nil, ErrNotFound
}
// Detect what player is available.
func Detect() (name string, factory Factory) {
logrus.Trace("auto detecting player type")
for _, d := range detectors {
if d.Detect() {
logrus.WithField("type", d.Name).Debug("auto detected player type")
return d.Name, d.New
}
}
logrus.Warn("auto detecting player type failed")
return "", nil
}
func autoDetect(config *config.Player) (Player, error) {
if _, f := Detect(); f != nil {
return f(config)
}
return nil, ErrNotFound
}
func init() {
Register("auto", autoDetect, nil, 0)
Register("", autoDetect, nil, 0)
}