Documentation
¶
Overview ¶
Package sendspin implements a Sendspin player SDK.
The initial protocol profile is specification 1.0.0-rc1. A Client owns its connection and shared playback pipeline, while applications provide persistent storage and an audio.Output. Roles are explicitly enabled in Config.
New may persist credentials but starts no network or audio worker. Cancel and join Connect, Run, DiscoverAndRun or Serve to stop those operations; a Client is reusable and has no process-global Close operation. Serve owns its listener; ServeHTTP only owns the upgraded connection, not the enclosing HTTP server.
Events is a bounded, best-effort single channel, not a broadcast or durable audit stream, and remains open across sessions. Consumers must also select on their own cancellation context. Snapshot and CurrentArtwork provide copies of the latest published state when events are missed.
The identity private key and pairing token are secrets; ClientID is the public identity. Never log a Credentials value or expose its serialized form to peers. Logging uses only the slf4g facade; applications choose the output provider.
Index ¶
- Constants
- Variables
- type Artwork
- type ArtworkChannel
- type Client
- func (c *Client) ClientID() string
- func (c *Client) Command(ctx context.Context, command Command) error
- func (c *Client) Connect(ctx context.Context, endpoint string) error
- func (c *Client) CurrentArtwork(channel int) (Artwork, bool)
- func (c *Client) CurrentPosition() (int64, bool)
- func (c *Client) DiscoverAndRun(ctx context.Context) error
- func (c *Client) Events() <-chan Event
- func (c *Client) LeaveGroup(ctx context.Context) error
- func (c *Client) PairingToken() string
- func (c *Client) PreferFormat(ctx context.Context, format codec.Format) error
- func (c *Client) Run(ctx context.Context, endpoint string) error
- func (c *Client) Serve(ctx context.Context, listener net.Listener) error
- func (c *Client) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (c *Client) SetAvailable(ctx context.Context, available bool) error
- func (c *Client) SetMuted(ctx context.Context, muted bool) error
- func (c *Client) SetOutputDelay(ctx context.Context, delay time.Duration) error
- func (c *Client) SetVolume(ctx context.Context, volume int) error
- func (c *Client) Snapshot() Snapshot
- type Colors
- type Command
- type Config
- type ControllerState
- type Credentials
- type DeviceInfo
- type Event
- type FileStore
- type GoodbyeError
- type Group
- type MemoryStore
- type Metadata
- type PairingRecord
- type Progress
- type Role
- type Secret
- type Snapshot
- type Spectrum
- type Store
- type Visualization
- type VisualizerConfig
Examples ¶
Constants ¶
const DefaultWebSocketPath = "/sendspin"
DefaultWebSocketPath is the endpoint mounted and advertised by Serve.
const RecommendedListenAddress = ":8928"
RecommendedListenAddress is RC1's suggested server-initiated client port. Serve accepts a caller-owned listener and never binds this address implicitly.
const Specification = protocol.Specification
Variables ¶
var ( // ErrProtocol identifies recognized message-shape, direction or sequencing // violations. It is the same sentinel used by the internal protocol layer; // transport/authentication and application Store/backend errors may differ. ErrProtocol = protocol.ErrProtocol ErrNotConnected = errors.New("sendspin: no admitted connection") ErrInactiveRole = errors.New("sendspin: role or command is not active") ErrConnectionMode = errors.New("sendspin: inbound and outbound modes cannot run simultaneously") ErrConnectionLimit = errors.New("sendspin: provisional connection limit") )
var ErrNoCredentials = errors.New("sendspin: no credentials stored")
Functions ¶
This section is empty.
Types ¶
type ArtworkChannel ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents one persistent device. Construct a separate Client and Store for each independent player. It is safe to call methods concurrently.
func New ¶
New validates and copies configuration and loads (or creates and saves) the persistent identity. It does not start network/audio workers or discovery.
Example ¶
package main
import (
"context"
"errors"
"fmt"
sendspin "github.com/echocat/sendspin-player-go"
"github.com/echocat/slf4g/testing/recording"
)
func main() {
// MemoryStore is deliberately ephemeral; use a private FileStore or another
// durable Store for a product identity. A controller needs no audio backend.
client, err := sendspin.New(context.Background(), sendspin.Config{Name: "Controller", Store: &sendspin.MemoryStore{}, Roles: []sendspin.Role{sendspin.Controller}, Logger: recording.NewLogger()})
if err != nil {
panic(err)
}
fmt.Println(client.Snapshot().Available)
fmt.Println(errors.Is(client.LeaveGroup(context.Background()), sendspin.ErrNotConnected))
}
Output: false true
func (*Client) ClientID ¶
ClientID returns the persistent public Curve25519 identity (not a secret).
func (*Client) Command ¶
Command sends a controller command only when that role/capability is active. Pointer arguments are copied; the caller may reuse the command after return.
func (*Client) Connect ¶
Connect runs one client-initiated session until cancellation or disconnect. Use Run for reconnect with backoff. The endpoint must use ws://: Sendspin's authenticated encryption is inside the WebSocket, not TLS.
func (*Client) CurrentArtwork ¶
CurrentArtwork returns an application-owned copy of a channel's current image. It returns false for invalid channels, cleared images, and disconnected clients. Pending images are never returned before their scheduled timestamp. Unlike best-effort events, this read model remains usable when the event buffer fills.
func (*Client) CurrentPosition ¶
CurrentPosition returns the current track position in milliseconds, using the active connection's clock mapping and applied (never pending) metadata. False means there is no synchronized, active metadata role with a known position.
func (*Client) DiscoverAndRun ¶
DiscoverAndRun chooses the first usable server and reconnects to it. To offer an application-specific selection UI, call discovery.Browse and Run instead.
func (*Client) LeaveGroup ¶
LeaveGroup asks the admitted server to leave the current group.
func (*Client) PairingToken ¶
PairingToken returns the confidential operator token. Expose it only through an intentional local provisioning interface, never ordinary logs or telemetry.
func (*Client) PreferFormat ¶
PreferFormat requests one of the immutable advertised formats. The server selects/changes the actual stream format; acceptance does not open hardware.
func (*Client) Run ¶
Run reconnects transient handshake, idle and playback failures with capped exponential backoff. A pairing-only drop terminates the attempt; resumption is operator-driven. Protocol and authorization failures are returned as well.
func (*Client) Serve ¶
Serve owns listener until ctx is canceled. It mounts /sendspin and announces it over mDNS unless DisableDiscovery is set. A context canceled at shutdown also interrupts upgraded WebSocket handlers, which http.Server.Shutdown alone cannot do.
func (*Client) ServeHTTP ¶
func (c *Client) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP accepts server-initiated WebSockets. It can be mounted in an existing HTTP server; advertising is managed by Serve or explicitly by the application. Browser origins are denied unless same-origin. Native Sendspin peers omit Origin.
func (*Client) SetAvailable ¶
SetAvailable declares the host's willingness to yield to Sendspin. Actual availability still depends on the SDK's clock/readiness gates.
func (*Client) SetOutputDelay ¶
SetOutputDelay clamps to [0,5s], truncates to whole milliseconds, and persists the external post-port delay. It does not calibrate internal DAC latency.
type Colors ¶
type Colors struct {
Timestamp int64 `json:"timestamp"`
BackgroundDark []int `json:"background_dark,omitempty"`
BackgroundLight []int `json:"background_light,omitempty"`
Primary []int `json:"primary,omitempty"`
Accent []int `json:"accent,omitempty"`
OnDark []int `json:"on_dark,omitempty"`
OnLight []int `json:"on_light,omitempty"`
}
type Config ¶
type Config struct {
// Specification explicitly pins a protocol profile, not the SDK's version.
// Empty selects RC1. Unsupported profiles fail before any storage changes.
Specification string
Name string
DeviceInfo *DeviceInfo
Store Store
Output audio.Output
Roles []Role
Formats []codec.Format
// Decoders adds or replaces codec factories. Defaults contain PCM, FLAC and
// Opus. Advertise only formats supported by the configured factories.
Decoders map[string]codec.Factory
BufferCapacity int
VisualizerCapacity int
MaxMessageBytes int
RecordCapacity int
RequiredLeadTime time.Duration
MinBuffer time.Duration
Artwork []ArtworkChannel
Visualizer VisualizerConfig
AllowUnpaired bool
CipherSuite string
HandshakeTimeout time.Duration
DisableDiscovery bool
// Logger overrides the package's slf4g facade for this Client. Nil uses the
// application's provider. The SDK never installs an output implementation.
// Logging runs synchronously outside Client locks; sinks must return promptly.
Logger log.Logger
// Decoded observes samples before gain/drift correction. It runs on the
// network loop, must return promptly, and must not call Client methods.
// Copy samples to retain them. Nil disables this diagnostic hook.
Decoded func(codec.Format, []float32)
// Observe is an opt-in, credential-redacted transport observer. Receive/send
// may invoke it concurrently. It must return promptly and not call Client.
Observe diagnostic.Observer
// Encoded observes actual audio payloads before decoding. Payload is borrowed
// read-only; copy to retain. It contains private media. Same actor contract as Decoded.
Encoded func(diagnostic.AudioChunk)
}
Config is copied by New. Output is required only when Player is enabled. Buffer limits are local memory bounds, not optional protocol extensions.
type ControllerState ¶
type Credentials ¶
type Credentials struct {
PrivateKey Secret `json:"private_key"`
PairingPSK Secret `json:"pairing_psk"`
Records []PairingRecord `json:"records"`
LastPlaybackServer string `json:"last_playback_server,omitempty"`
OutputDelayMS int `json:"output_delay_ms"`
Volume int `json:"volume"`
Muted bool `json:"muted"`
}
Credentials are persisted as one transaction. Records are ordered oldest first.
func NewCredentials ¶
func NewCredentials() (Credentials, error)
func (Credentials) ClientID ¶
func (c Credentials) ClientID() string
func (Credentials) GoString ¶
func (Credentials) GoString() string
func (Credentials) PairingToken ¶
func (c Credentials) PairingToken() string
PairingToken is confidential; expose it to the operator, never in routine logs.
func (Credentials) String ¶
func (Credentials) String() string
type DeviceInfo ¶
type Event ¶
type Event struct {
Kind string
ServerID string
Err error
Artwork *Artwork
Visualization *Visualization
}
Event contains immutable, application-owned data. Delivery is best-effort on the bounded Events channel; a slow consumer never stalls the protocol loop. StateChanged is a notification to obtain a fresh Snapshot.
type FileStore ¶
type FileStore struct{ Path string }
FileStore saves credentials with an atomic same-directory rename and 0600 permissions on Unix. On Windows the application must secure the directory ACL. Do not share a path between devices or concurrent Client instances.
type GoodbyeError ¶
type GoodbyeError struct{ Reason string }
GoodbyeError preserves the validated reason for a graceful session refusal or disconnect. Use errors.As; errors from custom Stores/backends remain wrapped.
func (*GoodbyeError) Error ¶
func (e *GoodbyeError) Error() string
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is intended for tests and ephemeral applications. It does not satisfy a device's persistence obligations across process restarts.
func (*MemoryStore) Load ¶
func (s *MemoryStore) Load(ctx context.Context) (Credentials, error)
func (*MemoryStore) Save ¶
func (s *MemoryStore) Save(ctx context.Context, c Credentials) error
type Metadata ¶
type Metadata struct {
Timestamp int64 `json:"timestamp"`
Title string `json:"title,omitempty"`
Artist string `json:"artist,omitempty"`
AlbumArtist string `json:"album_artist,omitempty"`
Album string `json:"album,omitempty"`
ArtworkURL string `json:"artwork_url,omitempty"`
Year int `json:"year,omitempty"`
Track int `json:"track,omitempty"`
Progress *Progress `json:"progress,omitempty"`
}
func (Metadata) Position ¶
Position returns whole milliseconds from this applied metadata state. It evaluates the RC1 formula without float rounding or integer overflow, rounds down after clamping at zero, and saturates an unlimited duration at MaxInt64. Clock-map uncertainty is unchanged: serverTime is supplied by the caller.
type PairingRecord ¶
PairingRecord binds a long-term PSK to an authenticated server identity.
type Secret ¶
type Secret [32]byte
Secret is a 256-bit secret. Formatting redacts it, serialization does not.
func ParsePairingToken ¶
ParsePairingToken accepts operator input and ignores reserved trailing bytes.
func (Secret) MarshalText ¶
func (*Secret) UnmarshalText ¶
type Snapshot ¶
type Snapshot struct {
ServerID, ServerName string
// ServerLanguages preserves the admitted server's language preference order
// and spelling. Nil means the optional hint was absent. The caller owns it.
ServerLanguages []string
ActiveRoles []Role
// ActiveStreams lists sorted, unversioned role families such as "artwork".
// A role can remain active after its stream ends.
ActiveStreams []string
Available bool
Group Group
Metadata *Metadata
Colors *Colors
Controller *ControllerState
Volume int
Muted bool
OutputDelayMS int
}
type Store ¶
type Store interface {
Load(context.Context) (Credentials, error)
Save(context.Context, Credentials) error
}
Store implementations must atomically save the complete snapshot. A failed Save must not partially replace an existing snapshot. One Client owns a Store. Methods should honor context cancellation promptly; pairing persistence carries the attempt deadline. Client cannot preempt a Store that ignores its context. Load must return a stable snapshot. The SDK detaches Records at Load/Save boundaries; implementations must never mutate another caller's input slices. Save runs inside a serialized credential transaction and must not call Client methods (including Snapshot). A canceled operation is not distributed rollback.
type Visualization ¶
type VisualizerConfig ¶
Source Files
¶
- client.go
- client_discovery.go
- client_media.go
- client_serve.go
- credentials.go
- doc.go
- listener_ipv6_unix.go
- logging.go
- metadata_position.go
- session.go
- session_activation.go
- session_controls.go
- session_hello.go
- session_media.go
- session_pairing.go
- session_presentation.go
- session_roles.go
- session_time.go
- session_visualizer.go
- store.go
- store_open_other.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audio defines the contract between the shared player and audio hardware.
|
Package audio defines the contract between the shared player and audio hardware. |
|
oto
Package oto provides an optional CGO-free output using Oto v3.
|
Package oto provides an optional CGO-free output using Oto v3. |
|
native
module
|
|
|
portaudio
module
|
|
|
Package codec provides bounded, pure-Go PCM, FLAC and Opus decoding.
|
Package codec provides bounded, pure-Go PCM, FLAC and Opus decoding. |
|
Package diagnostic defines opt-in SDK observations.
|
Package diagnostic defines opt-in SDK observations. |
|
Package discovery implements the two mutually exclusive Sendspin mDNS modes.
|
Package discovery implements the two mutually exclusive Sendspin mDNS modes. |
|
internal
|
|
|
conformanceclient
command
Command conformanceclient adapts the public SDK to Sendspin/conformance.
|
Command conformanceclient adapts the public SDK to Sendspin/conformance. |
|
conformancetestcmd
command
Command conformancetestcmd builds the client adapter and runs the pinned harness.
|
Command conformancetestcmd builds the client adapter and runs the pinned harness. |
|
devpath
Package devpath owns repository-local generated development paths.
|
Package devpath owns repository-local generated development paths. |
|
mdnstestcmd
command
Command mdnstestcmd runs real multicast tests in an isolated Linux network.
|
Command mdnstestcmd runs real multicast tests in an isolated Linux network. |
|
monotime
Package monotime supplies one process-local time.Time domain for protocol measurements and output scheduling.
|
Package monotime supplies one process-local time.Time domain for protocol measurements and output scheduling. |
|
netfault
Package netfault provides a loopback-only, ordered TCP impairment fixture.
|
Package netfault provides a loopback-only, ordered TCP impairment fixture. |
|
noisevectorcmd
command
Command noisevectorcmd verifies the frozen independent Noise oracle's source.
|
Command noisevectorcmd verifies the frozen independent Noise oracle's source. |
|
playback
Package playback implements the shared, hardware-independent render worker.
|
Package playback implements the shared, hardware-independent render worker. |
|
protocol
Package protocol contains wire details, not the public SDK version policy.
|
Package protocol contains wire details, not the public SDK version policy. |
|
specaudit
Package specaudit validates RC1 traceability and records test evidence.
|
Package specaudit validates RC1 traceability and records test evidence. |
|
specauditcmd
command
Command specauditcmd checks RC1 traceability and records/report test evidence.
|
Command specauditcmd checks RC1 traceability and records/report test evidence. |
|
timesync
Package timesync ports Sendspin/time-filter at revision 531e2707a6e82f30efe335b0f87eaa4b29390021 with its default parameters.
|
Package timesync ports Sendspin/time-filter at revision 531e2707a6e82f30efe335b0f87eaa4b29390021 with its default parameters. |
|
wire
Package wire implements the encrypted RC1 WebSocket channel.
|
Package wire implements the encrypted RC1 WebSocket channel. |