feat(client): implement server-initiated mode with WebSocket support
This commit is contained in:
50
third_party/sendspin-go/pkg/sendspin/player.go
vendored
50
third_party/sendspin-go/pkg/sendspin/player.go
vendored
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/Sendspin/sendspin-go/pkg/audio/output"
|
||||
"github.com/Sendspin/sendspin-go/pkg/protocol"
|
||||
"github.com/Sendspin/sendspin-go/pkg/sync"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// ReconnectConfig controls automatic reconnect behavior after the protocol
|
||||
@@ -216,6 +217,55 @@ func (p *Player) Connect() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Accept drives the player over a server-initiated WebSocket connection
|
||||
// (the server discovered this player via mDNS and dialed it). It builds a
|
||||
// receiver over the accepted conn, starts audio consumption, and BLOCKS
|
||||
// until the connection drops or the player is closed — so callers running a
|
||||
// listener can serialize one session at a time and re-accept on return.
|
||||
//
|
||||
// Unlike Connect, Accept does not start the dial-based reconnect loop: in
|
||||
// server-initiated mode the server redials, so reconnection is the listener's
|
||||
// responsibility, not the player's. The caller transfers ownership of conn.
|
||||
func (p *Player) Accept(conn *websocket.Conn) error {
|
||||
recv, err := p.buildReceiver("server-initiated")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := recv.AcceptConn(conn); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.receiver = recv
|
||||
p.state.Connected = true
|
||||
p.notifyStateChange()
|
||||
|
||||
go p.consumeAudio(recv)
|
||||
|
||||
// Block for the lifetime of this connection so the caller's accept loop
|
||||
// serializes sessions (one server connection at a time).
|
||||
select {
|
||||
case <-recv.Done():
|
||||
case <-p.ctx.Done():
|
||||
}
|
||||
|
||||
recv.Close()
|
||||
p.state.Connected = false
|
||||
p.state.State = "idle"
|
||||
p.notifyStateChange()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseConnection drops the currently active receiver, if any, without
|
||||
// tearing down the Player or its audio output. In server-initiated mode a
|
||||
// listener calls this to evict a stale/superseded session before accepting
|
||||
// a newer connection; the blocked Accept for the old session then returns.
|
||||
func (p *Player) CloseConnection() {
|
||||
if p.receiver != nil {
|
||||
p.receiver.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Player) buildReceiver(addr string) (*Receiver, error) {
|
||||
p.ensureCapsResolved()
|
||||
return NewReceiver(ReceiverConfig{
|
||||
|
||||
115
third_party/sendspin-go/pkg/sendspin/receiver.go
vendored
115
third_party/sendspin-go/pkg/sendspin/receiver.go
vendored
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/Sendspin/sendspin-go/pkg/audio/decode"
|
||||
"github.com/Sendspin/sendspin-go/pkg/protocol"
|
||||
"github.com/Sendspin/sendspin-go/pkg/sync"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// Time-sync burst parameters. Mirrors sendspin-cpp's TimeBurst defaults and
|
||||
@@ -109,6 +110,12 @@ type Receiver struct {
|
||||
// from r.clockSync.ServerMicrosNow so tests can drive the
|
||||
// timestamp-deferral path with a fake clock.
|
||||
clockNow func() int64
|
||||
|
||||
// closeOnce guards Close so it is idempotent: in server-initiated mode
|
||||
// a listener may evict a session via CloseConnection (which closes the
|
||||
// receiver) while Accept's own deferred Close also fires. Without this
|
||||
// the second close(r.output) panics.
|
||||
closeOnce stdsync.Once
|
||||
}
|
||||
|
||||
// NewReceiver creates a new Receiver with the given configuration.
|
||||
@@ -189,17 +196,59 @@ func (r *Receiver) Stats() ReceiverStats {
|
||||
return stats
|
||||
}
|
||||
|
||||
// Connect establishes a connection to the server, performs initial clock sync,
|
||||
// and starts background goroutines for connection watching and clock sync.
|
||||
// Connect establishes a client-initiated connection to the server (dials
|
||||
// ServerAddr), performs initial clock sync, and starts background goroutines
|
||||
// for connection watching and clock sync.
|
||||
func (r *Receiver) Connect() error {
|
||||
clientConfig, err := r.buildClientConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.client = protocol.NewClient(clientConfig)
|
||||
|
||||
if err := r.client.Connect(); err != nil {
|
||||
return fmt.Errorf("connection failed: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Connected to server: %s", r.serverAddr)
|
||||
return r.startSession()
|
||||
}
|
||||
|
||||
// AcceptConn drives the receiver protocol over an already-established
|
||||
// WebSocket connection (server-initiated mode: the server discovered this
|
||||
// player via mDNS and dialed it). The client still sends client/hello first
|
||||
// per spec, so the handshake and message loop are identical to Connect once
|
||||
// the socket exists. The caller transfers ownership of conn; Close() (or a
|
||||
// dropped connection) closes it.
|
||||
func (r *Receiver) AcceptConn(conn *websocket.Conn) error {
|
||||
clientConfig, err := r.buildClientConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.client = protocol.NewClientFromConn(clientConfig, conn)
|
||||
|
||||
if err := r.client.Start(); err != nil {
|
||||
return fmt.Errorf("handshake failed: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Accepted server-initiated connection from %s", conn.RemoteAddr())
|
||||
return r.startSession()
|
||||
}
|
||||
|
||||
// buildClientConfig validates required fields and assembles the protocol
|
||||
// client config (advertised formats, device info, role support) shared by
|
||||
// both the client-initiated (Connect) and server-initiated (AcceptConn) paths.
|
||||
func (r *Receiver) buildClientConfig() (protocol.Config, error) {
|
||||
if r.config.ClientID == "" {
|
||||
return fmt.Errorf("ReceiverConfig.ClientID is required (resolve via sendspin.ResolveClientID)")
|
||||
return protocol.Config{}, fmt.Errorf("ReceiverConfig.ClientID is required (resolve via sendspin.ResolveClientID)")
|
||||
}
|
||||
|
||||
supportedFormats := buildSupportedFormats(r.config.PreferredCodec, r.config.MaxSampleRate, r.config.MaxBitDepth)
|
||||
logAdvertisedFormats(supportedFormats, r.config.MaxSampleRate, r.config.MaxBitDepth)
|
||||
|
||||
clientConfig := protocol.Config{
|
||||
return protocol.Config{
|
||||
ServerAddr: r.serverAddr,
|
||||
ClientID: r.config.ClientID,
|
||||
Name: r.config.PlayerName,
|
||||
@@ -222,15 +271,13 @@ func (r *Receiver) Connect() error {
|
||||
VisualizerV1Support: &protocol.VisualizerV1Support{
|
||||
BufferCapacity: r.config.BufferCapacity,
|
||||
},
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
r.client = protocol.NewClient(clientConfig)
|
||||
|
||||
if err := r.client.Connect(); err != nil {
|
||||
return fmt.Errorf("connection failed: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Connected to server: %s", r.serverAddr)
|
||||
// startSession marks the receiver connected, runs the initial clock-sync
|
||||
// burst, and launches the background goroutines. Shared by Connect and
|
||||
// AcceptConn; r.client must already be started.
|
||||
func (r *Receiver) startSession() error {
|
||||
r.connected = true
|
||||
|
||||
if err := r.performInitialSync(); err != nil {
|
||||
@@ -795,29 +842,31 @@ func (r *Receiver) notifyError(err error) {
|
||||
}
|
||||
|
||||
func (r *Receiver) Close() error {
|
||||
// Send goodbye BEFORE cancelling the context so the message
|
||||
// reaches the server while the connection is still alive.
|
||||
if r.client != nil {
|
||||
r.client.SendGoodbye("shutdown")
|
||||
}
|
||||
|
||||
r.cancel()
|
||||
|
||||
if r.client != nil {
|
||||
r.client.Close()
|
||||
}
|
||||
|
||||
if r.scheduler != nil {
|
||||
r.scheduler.Stop()
|
||||
}
|
||||
|
||||
if r.decoder != nil {
|
||||
if err := r.decoder.Close(); err != nil {
|
||||
log.Printf("Receiver: decoder close error: %v", err)
|
||||
r.closeOnce.Do(func() {
|
||||
// Send goodbye BEFORE cancelling the context so the message
|
||||
// reaches the server while the connection is still alive.
|
||||
if r.client != nil {
|
||||
r.client.SendGoodbye("shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
close(r.output)
|
||||
r.cancel()
|
||||
|
||||
if r.client != nil {
|
||||
r.client.Close()
|
||||
}
|
||||
|
||||
if r.scheduler != nil {
|
||||
r.scheduler.Stop()
|
||||
}
|
||||
|
||||
if r.decoder != nil {
|
||||
if err := r.decoder.Close(); err != nil {
|
||||
log.Printf("Receiver: decoder close error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
close(r.output)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user