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.
CodePairingConfig documents opt-in automatic PIN admission, its protocol limits and durable rate protection. Client.CurrentPairingPIN is the explicit secret display interface; Client.RestartPairing documents administrator authorization, revocation and before/after-commit cancellation semantics.
Index ¶
- Constants
- Variables
- type Artwork
- type ArtworkChannel
- type Client
- func (c *Client) BindPlayerControl(target PlayerControlTarget) (PlayerControlBinding, error)
- func (c *Client) CancelPairing(ctx context.Context) error
- 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) CurrentPairingPIN() (PairingPINDisplay, 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) OpenPairingWindow(ctx context.Context) error
- func (c *Client) PairingState() PairingState
- func (c *Client) PairingToken() string
- func (c *Client) PreferFormat(ctx context.Context, format codec.Format) error
- func (c *Client) ReportPlayerControl(binding PlayerControlBinding, report PlayerControlReport) (PlayerControlBinding, error)
- func (c *Client) RestartPairing(ctx context.Context) (PairingRestartResult, 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
- func (c *Client) StaticPairingPIN() (PairingPIN, bool)
- type CodePairingConfig
- 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 PairingDisplay
- type PairingPIN
- type PairingPINDisplay
- type PairingRecord
- type PairingRestartResult
- type PairingState
- type PlayerControlBinding
- type PlayerControlCapabilities
- type PlayerControlConfig
- type PlayerControlReport
- type PlayerControlRequest
- type PlayerControlSnapshot
- type PlayerControlTarget
- 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 ( ErrPlayerControlMode = errors.New("sendspin: host-managed player control is not configured") ErrPlayerControlStale = errors.New("sendspin: stale player control binding or generation") ErrPlayerControlOverload = errors.New("sendspin: player control queue is full") )
var ErrNoCredentials = errors.New("sendspin: no credentials stored")
var ErrPairingActive = errors.New("sendspin: a pairing attempt is active")
var ErrPairingDisabled = errors.New("sendspin: PIN pairing is disabled")
var ErrPairingRestarting = errors.New("sendspin: pairing restart or session revocation in progress")
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) BindPlayerControl ¶ added in v0.2.0
func (c *Client) BindPlayerControl(target PlayerControlTarget) (PlayerControlBinding, error)
BindPlayerControl replaces the host target without writing hardware. It invalidates/cancels all old queued/in-flight writes, observations and tokens. An empty target is a fixed/no-controls backend with unknown state.
func (*Client) CancelPairing ¶ added in v0.2.0
CancelPairing closes the local window and aborts an active/pending attempt. With no admitted session it still closes the window and succeeds. Automatic mode is also paused for this process; OpenPairingWindow resumes it.
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) CurrentPairingPIN ¶ added in v0.3.0
func (c *Client) CurrentPairingPIN() (PairingPINDisplay, bool)
CurrentPairingPIN explicitly retrieves the automatic mode's active six-digit PIN for local display or an authenticated administration UI. The application must authenticate/authorize remote callers. No PIN exists before server init, or after confirmation, expiry, cancellation, disconnect, reset or durable pairing.
Only PIN.Value and PIN.Grouped deliberately reveal plaintext; formatting and JSON redact it. Never forward extracted strings to logs, telemetry or generic snapshots. Hide the UI when unavailable and refresh after pairing_changed events and periodically while visible: events can be dropped and ValidUntil is only an upper bound. The SDK cannot erase copies retained by the host. The host must also secure remote administration transport and, where relevant, protect against CSRF. Credentials serialization and Client.PairingToken are separate secret persistence/provisioning interfaces, not UI snapshots.
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) OpenPairingWindow ¶ added in v0.2.0
OpenPairingWindow represents a deliberate LOCAL operator gesture. Applications must not expose it to unauthenticated network commands. It opens a five-minute static-PIN window and resets the persistent, device-wide dynamic round limit. The first static attempt binds the window to its connection. Active attempts must first be canceled; merely reconnecting/restarting never unlocks the limit. In Automatic mode this resumes an operator/storage pause or the 20-round lockout, without clearing failure counts or cooldowns; otherwise it is a no-op.
func (*Client) PairingState ¶ added in v0.3.0
func (c *Client) PairingState() PairingState
PairingState returns non-secret readiness and protection state. Events sends best-effort pairing_changed notifications; re-read this state after an event and when refreshing a UI, since the bounded event channel may drop events. Ready is false while paired, active, cooling down, locked out, paused, blocked by storage or cleaning up a restart. Offline server records remain Paired. See CodePairingConfig for counting, persistence and clock semantics.
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) ReportPlayerControl ¶ added in v0.2.0
func (c *Client) ReportPlayerControl(binding PlayerControlBinding, report PlayerControlReport) (PlayerControlBinding, error)
ReportPlayerControl is thread-safe and never invokes a setter. The report is copied. A capability or known/unknown change cancels old writes and returns a fresh binding; value-only updates retain the token. Retain the returned token. Do not report values inferred merely from successful request completion.
func (*Client) RestartPairing ¶ added in v0.3.0
func (c *Client) RestartPairing(ctx context.Context) (PairingRestartResult, error)
RestartPairing is an explicit ADMINISTRATOR operation for Automatic mode. The host MUST authenticate, authorize and obtain confirmation from the operator. It preserves identity, audio and unrelated settings, replaces the bootstrap PSK/token, removes every server record and revokes all old session generations. Without CodePairingConfig.Automatic it returns ErrPairingDisabled. It works while paired and does not require an active connection.
The reset also removes the old static PIN and last-playback server hint. The private key/client ID, volume, mute, output delay and host audio target bindings remain intact. The explicit administrator action releases the 20-round lockout but retains short failure counts/cooldown. An unresolved authentication becomes a full cooldown. A fresh PIN exists only after a new server-started attempt, not immediately upon reset; see CodePairingConfig for protocol constraints.
Commit point: successful atomic Store.Save under the credential lock. Before it, failure has no effects. Afterwards revocation is unconditional, even when ctx is canceled; Committed is true. Cancellation can stop waiting for cleanup, but cannot roll back credentials. New sessions/PINs remain blocked until old actors have exited. Retrying would perform ANOTHER reset, not finish the first. Store must obey the atomic Save contract (nil means committed, error means no replacement). As with other SDK calls a context-ignoring Store cannot be preempted.
After commit, transport closure and revocation include provisional handshakes. Credential writes and finalization check the session generation inside the same transaction lock: finalize either commits first and is erased by reset, or reset commits first and the old finalize is rejected. Expiry and ordinary finalization execute serially in the session actor. Aborted in-flight messages are discarded until the next activation barrier. Old tokens/PSKs cannot authenticate: initial unknown credentials follow unauthenticated Sentinel fallback; old re-handshake credentials are rejected.
A post-commit context error stops waiting, not revocation/transport closure. Old actors finish cleanup themselves; state reads or the next connection reconcile completion without another worker. An uncooperative callback/backend keeps new readiness closed. The SDK cannot undo external hardware effects or revoke application-held secret copies. A new process loads only the committed snapshot. Success means Committed=true and err=nil, with all old actors exited; retained cooldown protection may still postpone Ready.
Example ¶
package main
import (
"context"
"fmt"
sendspin "github.com/echocat/sendspin-player-go"
"github.com/echocat/slf4g/testing/recording"
)
func main() {
ctx := context.Background()
client, err := sendspin.New(ctx, sendspin.Config{
Name: "Automatic controller", Store: &sendspin.MemoryStore{},
Roles: []sendspin.Role{sendspin.Controller},
CodePairing: &sendspin.CodePairingConfig{Automatic: true},
Logger: recording.NewLogger(),
})
if err != nil {
panic(err)
}
// A product uses a durable Store. Authenticate/authorize the administrator
// and obtain explicit confirmation BEFORE invoking this operation.
result, err := client.RestartPairing(ctx)
if err != nil {
// result.Committed distinguishes an irreversible reset from no commit.
panic(err)
}
fmt.Println(result.Committed, client.PairingState().Ready)
_, visible := client.CurrentPairingPIN() // No PIN before server nonce exchange.
fmt.Println(visible)
}
Output: true true false
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 unless Automatic PIN mode is enabled. Protocol and authorization failures are returned as well. A committed pairing restart is reported by Connect as GoodbyeError("restart"); Run reconnects after backoff.
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) SetMuted ¶
SetMuted updates/persists legacy mute, or accepts an asynchronous host write.
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.
func (*Client) SetVolume ¶
SetVolume updates/persists legacy software volume without clearing mute. In host-managed mode it accepts an asynchronous write, not an observation; inspect Snapshot().PlayerControl for completion and report readback separately.
func (*Client) StaticPairingPIN ¶ added in v0.2.0
func (c *Client) StaticPairingPIN() (PairingPIN, bool)
StaticPairingPIN returns the per-device provisioned eight-digit PIN, only when explicitly enabled. Never print Value in routine logs or telemetry.
type CodePairingConfig ¶ added in v0.2.0
type CodePairingConfig struct {
Static bool
Display func(context.Context, PairingDisplay) error
// Automatic offers dynamic six-digit pairing only while no server records
// exist. Display is optional: CurrentPairingPIN provides explicit UI access.
// The protocol's persistent 20-round operator lockout still applies.
Automatic bool
}
CodePairingConfig opts into static PIN pairing or dynamic displayed PINs. Automatic is an opt-in policy for the dynamic method, not a new wire method. RC1 allows at most one code method in hello; Static cannot be combined with Display or Automatic. Without Automatic, existing window/round behavior stays unchanged.
Display is called synchronously by the session actor, must return promptly and honor its context, and must not call Client methods. Copy/post the event to a UI thread; Active=false hides it. It is not a logging/telemetry callback. If shared with artwork or another role's output, the host owns display takeover and restoration. Without Display, automatic-mode presentation uses Client.CurrentPairingPIN and Client.PairingState.
Automatic admission and protocol limits ¶
Automatic accepts dynamic PIN attempts only while no durable server records exist. A disconnected/offline paired server does not reopen admission; an authenticated server/unpair removing the last record does. No application loop opening or renewing a pairing window is needed. Held attempts receive standard client/pair-pending. At most one pairing attempt, including PSK pairing, is active.
Sendspin 1.0.0-rc1 requires dynamic digit codes to have six digits, derived from the Noise binding and two CSPRNG nonces. No PIN exists before the server starts pairing and supplies its nonce. The same PIN is used across an attempt's retry rounds; the entire attempt has a two-minute deadline, including callbacks, writes and persistence. Expiry or the fifth failed confirmation aborts it; another server pairing activation is needed for a new attempt. New attempts use fresh nonces/transcripts, but their digits may coincidentally be identical. Old transcript proofs/finalizes cannot complete a new attempt. Independent eight-digit PINs, guaranteed different digits and ten-minute device-PIN rotation are not supported by this standard method. Static codes remain fixed, eight-digit and gesture-window-gated; automatically reopening their window is not a standard alternative.
Pairing PSK/token remains supported independently of PIN admission. Successful PIN pairing neither consumes nor disables it. Only Client.RestartPairing replaces the bootstrap PSK; anyone holding the current token can still pair.
Automatic-mode rate protection ¶
Protection is device-wide, not partitioned by connection, address or server ID:
- Save a round before emitting its PIN. An emitted round remains consumed after malformed input, cancellation, timeout or disconnect. A verified server_kc resets the counter. Otherwise, after 20 rounds a deliberate operator release is required, using Client.OpenPairingWindow or the confirmed administrator reset. Cooldown, new PIN, reconnect and process restart never release that lockout.
- Count a wrong authentication only when a correctly sequenced, well-formed server_kc fails CPace verification. Wrong codes and forged confirmations are indistinguishable. Malformed input, server-declared errors, timeouts, cancellation and network loss are not proven wrong PINs.
- The fifth such failure durably starts a 30-second cooldown, resets the short counter and aborts/hides the PIN. Earlier failures may retry the same code. Durably completed pairing clears the short counter.
- Before emitting a valid PAKE response, persist an unresolved-authentication reservation. If no verification outcome can be saved, including after a disconnect or crash, conservatively wait 30 seconds before another attempt. This does not count as a proven failure; its round remains consumed.
- A protection-write error suppresses the associated PIN/PAKE output, hides the PIN and latches automatic admission closed for this process. Fix storage before explicitly releasing the pause. Final trust requires a successful atomic record save. Administrator reset retains short failures/cooldown and turns an outstanding reservation into a cooldown.
Persistence and clocks ¶
Use a durable Store, not MemoryStore, for a device. Existing credential fields/records are retained when opting in; missing protection fields mean zero/false. Custom Stores must preserve all Credentials fields. Do not use older writers that discard them. No dynamic PIN or PAKE transcript is persisted. Deleting/rolling back storage or running competing Clients defeats protection.
Live deadlines use the process-local monotonic clock; wall-clock jumps cannot shorten them. A persisted cooldown or unresolved reservation starts a fresh full 30-second wait on every process startup, regardless of downtime. Its marker is cleared atomically by the next admitted round, not by elapsed downtime. Repeated restarts may extend but cannot shorten the wait. Existing session ticks and public state/PIN reads reconcile deadlines; New starts no policy goroutine, timer or callback queue. Events are bounded, best-effort hints; refresh state/PIN while displaying and honor PairingPINDisplay.ValidUntil.
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
// PlayerControl selects host-managed volume/mute and immutable unity gain.
// Nil retains legacy software gain and persistence. Non-nil, even empty,
// never falls back to software control; bind a host target after New.
PlayerControl *PlayerControlConfig
// Input is used only with explicitly configured SourceRole, and only after
// an active, available, authorized server requests source start. It is never
// routed to Output. AllowUnpaired defaults to false, also for sources.
Input audio.Input
// SourceFormat selects the capture format. Zero defaults to 48 kHz stereo.
// Upstream encoding is PCM16; supported capture rates are 8–192 kHz, 1–8 channels.
SourceFormat audio.Format
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
// CodePairing enables optional PIN methods and automatic unpaired policy.
// Nil keeps PSK-only behavior.
CodePairing *CodePairingConfig
// 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"`
StaticPairingPIN *Secret `json:"static_pairing_pin,omitempty"`
DynamicPairingRounds uint32 `json:"dynamic_pairing_rounds,omitempty"`
// Automatic-pairing protection, additive for old credential files. No PIN
// is persisted. Cooldowns are restarted in full on process startup.
PairingFailures uint8 `json:"pairing_failures,omitempty"`
PairingCooldown bool `json:"pairing_cooldown,omitempty"`
PairingAuthPending bool `json:"pairing_auth_pending,omitempty"`
}
Credentials are persisted as one transaction. Records are ordered oldest first. JSON/Secret serialization is a confidential persistence format, not a redacted snapshot. Never expose it through UI responses, logs or telemetry. Custom Stores must preserve every field; missing optional pairing-protection fields in older files mean zero/false. See CodePairingConfig for counting and reboot behavior.
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. File data is synced before replacement; the parent directory is not fsynced. This is not a guarantee against every storage/power-loss scenario. A successful rename is the commit point; cancellation afterwards is not rollback.
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 PairingDisplay ¶ added in v0.2.0
type PairingDisplay struct {
Active bool
PIN PairingPIN
ServerID string
Round uint32
}
PairingDisplay transfers presentation to the application's display. While Active it replaces artwork/other output using that same display, without changing stream timelines or availability. No speaker output is generated.
type PairingPIN ¶ added in v0.2.0
type PairingPIN struct {
// contains filtered or unexported fields
}
PairingPIN is a secret. Formatting and JSON redact it; Value explicitly returns contiguous digits for an intentional local operator interface.
func (PairingPIN) GoString ¶ added in v0.2.0
func (PairingPIN) GoString() string
func (PairingPIN) Grouped ¶ added in v0.2.0
func (p PairingPIN) Grouped() string
Grouped formats the operator presentation (3-3 or 4-4), never the PAKE input.
func (PairingPIN) MarshalJSON ¶ added in v0.2.0
func (PairingPIN) MarshalJSON() ([]byte, error)
func (PairingPIN) String ¶ added in v0.2.0
func (PairingPIN) String() string
func (PairingPIN) Value ¶ added in v0.2.0
func (p PairingPIN) Value() string
type PairingPINDisplay ¶ added in v0.3.0
type PairingPINDisplay struct {
PIN PairingPIN
ValidUntil time.Time
Revision uint64
}
PairingPINDisplay is explicitly requested secret UI data, never a Snapshot. PIN formatting/JSON is redacted; Value/Grouped deliberately reveal it. ValidUntil is an upper bound, not a lease: cancellation, confirmation, disconnect or reset can invalidate it earlier. Do not retain UI copies.
type PairingRecord ¶
PairingRecord binds a long-term PSK to an authenticated server identity.
type PairingRestartResult ¶ added in v0.3.0
type PairingRestartResult struct{ Committed bool }
PairingRestartResult distinguishes cancellation before and after the durable commit. Committed=true is irreversible even when the returned error is non-nil.
type PairingState ¶ added in v0.3.0
type PairingState struct {
Automatic bool
Paired bool
Ready bool
Active bool
// RequiresOperator reports the persistent 20-round lockout. Release it with
// an intentional OpenPairingWindow action or confirmed RestartPairing.
RequiresOperator bool
// Paused reports cancellation for this process; OpenPairingWindow resumes it.
Paused bool
// Restarting blocks new sessions and PINs until revoked actors have exited.
Restarting bool
// StorageBlocked requires fixing storage and explicitly releasing the pause.
StorageBlocked bool
FailedConfirmations uint8
Rounds uint32
// CooldownRemaining is monotonic, not computed from a persisted wall clock.
CooldownRemaining time.Duration
// Revision is a process-local change counter, not a durable identifier or
// authorization capability. It changes on rounds, attempts and invalidation.
Revision uint64
}
PairingState contains no secrets. Paired means at least one durable record, not an online server. Ready means a new automatic PIN attempt can start; Active means an attempt already owns the device. State is sampled, not a lease.
type PlayerControlBinding ¶ added in v0.2.0
type PlayerControlBinding struct {
// contains filtered or unexported fields
}
PlayerControlBinding is an opaque generation token. Keep the token returned by ReportPlayerControl: capability and known/unknown changes replace it. Old tokens cannot update a replacement target or a later control generation. Automatic setter-failure withdrawal keeps this token valid for recovery reports.
type PlayerControlCapabilities ¶ added in v0.2.0
PlayerControlCapabilities advertises independent absolute setters. Relative volume controls must NOT be adapted into SetVolume. Read-only state needs no setter.
type PlayerControlConfig ¶ added in v0.2.0
type PlayerControlConfig struct {
// QueueCapacity bounds queued plus in-flight writes (default 16, max 256).
// FIFO rejects overload and never coalesces accepted writes. A failed
// executed setter withdraws all controls and cancels remaining queued writes.
QueueCapacity int
// RequestTimeout includes queue time (default 2s, maximum 1 minute).
RequestTimeout time.Duration
}
PlayerControlConfig explicitly disables software volume/mute gain. Empty configuration is a fixed/no-controls player until a host target is bound.
type PlayerControlReport ¶ added in v0.2.0
type PlayerControlReport struct {
Capabilities PlayerControlCapabilities
Volume *int
Muted *bool
Err error
}
PlayerControlReport is a complete, coherent observation, not a patch. Nil means unknown (including after loss of readback). Err is a nonterminal local diagnostic; withdraw capabilities explicitly if the backend cannot write. After automatic setter-failure withdrawal, a fresh report may restore them using the same valid target token (retain the returned token as usual). Reports never cause writes, never clear mute implicitly and are not persisted.
type PlayerControlRequest ¶ added in v0.2.0
PlayerControlRequest describes the latest accepted request for one control, independently of the observed state. Status: pending, succeeded, failed or canceled. Succeeded means only that the setter returned nil, NOT readback.
type PlayerControlSnapshot ¶ added in v0.2.0
type PlayerControlSnapshot struct {
Capabilities PlayerControlCapabilities
VolumeRequest *PlayerControlRequest
MuteRequest *PlayerControlRequest
// Error retains the latest host-report diagnostic or executed setter error,
// independently of best-effort Events and the latest per-control request.
// Only a fresh host report or target binding clears/replaces it.
Error string
}
type PlayerControlTarget ¶ added in v0.2.0
type PlayerControlTarget struct {
SetVolume func(context.Context, int) error
SetMuted func(context.Context, bool) error
Initial PlayerControlReport
}
PlayerControlTarget binds host-owned callbacks to one physical/logical target. The SDK invokes them serially, outside all protocol/audio loops and locks. Callbacks MUST honor context cancellation promptly; Go cannot forcibly stop arbitrary host code. A callback ignoring cancellation occupies the single worker, but never spawns replacement workers or blocks protocol/audio loops. Capture an immutable target, not a mutable global "current device". SetVolume is absolute 0..100 perceived loudness and MUST NOT unmute the target. Any error/panic after invocation, including an in-flight caller cancel or timeout, conservatively withdraws both controls until a fresh host report. Requests canceled/expired before invocation do not withdraw controls. Stale target/session/capability completions cannot withdraw a newer generation.
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
// Known flags distinguish unknown external state from zero/false. Legacy
// software state is always known. PlayerControl is nil in legacy mode.
VolumeKnown bool
MutedKnown bool
PlayerControl *PlayerControlSnapshot
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
- pairing_automatic.go
- pairing_codes.go
- player_control.go
- session.go
- session_activation.go
- session_controls.go
- session_hello.go
- session_media.go
- session_pairing.go
- session_pairing_codes.go
- session_presentation.go
- session_roles.go
- session_source.go
- session_time.go
- session_visualizer.go
- source_capture.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. |
|
alsa
Package alsa provides direct Linux ALSA playback without Oto or PortAudio.
|
Package alsa provides direct Linux ALSA playback without Oto or PortAudio. |
|
coreaudio
Package coreaudio provides direct macOS AUHAL playback and capture.
|
Package coreaudio provides direct macOS AUHAL playback and capture. |
|
internal/audiotest
Package audiotest contains test fixtures only, never production audio paths.
|
Package audiotest contains test fixtures only, never production audio paths. |
|
internal/bridge
Package bridge owns callback tokens and native-clock arithmetic.
|
Package bridge owns callback tokens and native-clock arithmetic. |
|
internal/capture
Package capture owns bounded native-input queues.
|
Package capture owns bounded native-input queues. |
|
internal/dynlib
Package dynlib owns lazy, explicit native library binding.
|
Package dynlib owns lazy, explicit native library binding. |
|
internal/render
Package render contains the bounded queue and lifecycle shared by the native desktop outputs.
|
Package render contains the bounded queue and lifecycle shared by the native desktop outputs. |
|
native
Package native selects native audio through compile-time platform files.
|
Package native selects native audio through compile-time platform files. |
|
noop
Package noop provides an explicit, paced discard output.
|
Package noop provides an explicit, paced discard output. |
|
pipewire
Package pipewire provides direct Linux PipeWire playback through libpipewire.
|
Package pipewire provides direct Linux PipeWire playback through libpipewire. |
|
wasapi
Package wasapi provides direct Windows event-driven shared-mode WASAPI audio.
|
Package wasapi provides direct Windows event-driven shared-mode WASAPI audio. |
|
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. |
|
cpace
Package cpace implements Sendspin's exact draft-21 CPACE-X25519-SHA512 initiator/responder transcript, with explicit mutual confirmation.
|
Package cpace implements Sendspin's exact draft-21 CPACE-X25519-SHA512 initiator/responder transcript, with explicit mutual confirmation. |
|
devpath
Package devpath owns repository-local generated development paths.
|
Package devpath owns repository-local generated development paths. |
|
e2etest
Package e2etest owns test-only reference processes and their pinned runtimes.
|
Package e2etest owns test-only reference processes and their pinned runtimes. |
|
examplecmd
command
Command examplecmd provides the Go-only implementation of mise's example tasks.
|
Command examplecmd provides the Go-only implementation of mise's example tasks. |
|
examples
Package examples locates and operates on the independent example modules.
|
Package examples locates and operates on the independent example modules. |
|
loopback
Package loopback generates reference WAV files and analyzes recordings offline.
|
Package loopback generates reference WAV files and analyzes recordings offline. |
|
loopbackcmd
command
Command loopbackcmd generates reference WAV files and analyzes recordings offline.
|
Command loopbackcmd generates reference WAV files and analyzes recordings offline. |
|
mdns
Package mdns is the SDK-private, source-pinned mDNS transport adaptation.
|
Package mdns is the SDK-private, source-pinned mDNS transport adaptation. |
|
mdnsimportcmd
command
Command mdnsimportcmd reproducibly imports/checks the pinned scoped mDNS fork.
|
Command mdnsimportcmd reproducibly imports/checks the pinned scoped mDNS fork. |
|
mdnstest
Package mdnstest contains the isolated real-multicast E2E fixture.
|
Package mdnstest contains the isolated real-multicast E2E fixture. |
|
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. |