package mpd import ( "fmt" "io" "net" "net/textproto" "strconv" "strings" "sync" "time" "github.com/sirupsen/logrus" "github.com/BeatGlow/beatglow/config" "github.com/BeatGlow/beatglow/internal/util" "github.com/BeatGlow/beatglow/player" ) func init() { player.Register("mpd", func(config *config.Player) (player.Player, error) { return New(config.Host, config.Password) }, 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 artCache sync.Map // map of path to image artRequest chan *artRequest simpleCommands chan *simpleCommand dataCommands chan *dataCommand 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, }) } func (c *clientConn) readBytes(size int) (b []byte, err error) { c.log().WithField("size", size).Debug("read bytes") b = make([]byte, size) if _, err := io.ReadFull(c.Conn.R, b); err != nil { return nil, 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 termByte != '\n' { return nil, textproto.ProtocolError(fmt.Sprintf("wrong binary data terminator: want 0x0a, got %x", termByte)) } return } func New(addr, password string) (*Player, error) { addr = util.MakeAddr(addr, DefaultAddr) if _, err := net.ResolveTCPAddr("tcp", addr); err != nil { return nil, err } p := &Player{ 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 } 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) String() string { return "mpd@" + p.addr } func (p *Player) Halt() 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) 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") 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) 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", }) 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 } art, _, err := newConn(p.addr, p.password, "art", p.name) if err != nil { _ = idle.Close() _ = main.Close() log.WithError(err).Warn("connection failed; retrying") time.Sleep(time.Second) continue } p.simpleCommands = make(chan *simpleCommand) p.errors = make(chan error) p.quit = make(chan struct{}, 2) events <- player.NewConnectedEvent(p) go p.idleLoop(idle) go p.artLoop(art) p.mainLoop(main, events) events <- player.NewDisconnectedEvent(p) _ = idle.Close() _ = main.Close() close(p.simpleCommands) 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.simpleCommands: 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 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).Trace("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) 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()) } func (p *Player) ChangeVolume(delta int) error { return p.Command("volume %d", delta) } func (p *Player) SetVolume(level int) error { if level < 0 { level = 0 } if level > 100 { level = 100 } return p.Command("setvol %d", level) } func (p *Player) ToggleMute() error { // MPD doesn't mute, it can pause... return p.Command("pause") } func (p *Player) Playlist() ([]*player.Track, error) { lines, err := p.CommandData("playlistinfo") if err != nil { return nil, err } 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 }