sendspin

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 43 Imported by: 0

README

sendspin-player-go

A Go SDK for Sendspin players, targeting specification 1.0.0-rc1 at 671a34d. Requires Go 1.27.3+. The SDK core, including PCM, FLAC and Opus decoding, is pure Go. Native audio input/output is optional and uses purego, without CGO.

Status: The API may change before v1. This release adds native I/O, Source, optional PIN pairing and host-managed player control, and removes the old Oto/PortAudio adapters. Historical tags remain unchanged. This is not a declaration of complete RC1 conformance. Independent server interoperability is tested; physical synchronization has not been measured. See coverage and remaining work. The machine-readable requirement catalog and CI traceability report separate reviewed requirements, actual test results and unresolved conformance gaps.

Features

The SDK logs through the github.com/echocat/slf4g facade only. Applications choose the provider/output (the player example chooses slf4g/native); Config.Logger can inject a per-client logger. Default lifecycle logs omit raw errors, endpoints, credentials and media. Sinks must return promptly; no audio-packet logging occurs. Tests can use slf4g/sdk/testlog or slf4g/testing/recording without installing a process-global provider.

  • Client- and server-initiated WebSockets, with mutually exclusive discovery modes.
  • Dynamic mDNS publication preserves live listener restrictions.
  • Noise KKpsk2, both RC1 cipher suites, PSK pairing, re-handshakes and unpairing.
  • Persistent identity, pairing records and output delay; legacy software volume/mute persistence.
  • Player, controller, metadata, artwork, visualizer and color roles; individually enabled.
  • PCM 16/24-bit, FLAC and gopus Opus decoding.
  • Reference time-filter port, bounded playback queue, scheduling and drift correction.
  • Scheduled metadata/colors, multipart artwork and visualizer buffering.
  • Pluggable audio I/O and codecs; purego ALSA, PipeWire, WASAPI and CoreAudio, a compile-time platform selector, and an explicitly selected no-hardware noop output.
  • Opt-in source@v1 capture: backend-neutral audio.Input, server-authorized PCM16 upstream, never direct local monitoring.

Embed

go get github.com/echocat/sendspin-player-go@latest
client, err := sendspin.New(ctx, sendspin.Config{
    Name:   "Living room",
    Store:  sendspin.FileStore{Path: credentialPath},
    Output: myAudioOutput, // implements audio.Output; real device-clock feedback required
    Roles:  []sendspin.Role{sendspin.Player, sendspin.Controller, sendspin.MetadataRole},
    MinBuffer: 100 * time.Millisecond,
    RequiredLeadTime: 250 * time.Millisecond,
})
if err != nil {
    return err
}
return client.Run(ctx, "ws://192.0.2.1:8927/sendspin")

Import github.com/echocat/sendspin-player-go as sendspin. Run reconnects transient handshake, idle and playback failures; a dropped pairing-only session requires operator-driven resumption. Connect runs one session. DiscoverAndRun selects the first discovered server. For server-initiated connections, pass a TCP listener to Serve; it advertises _sendspin._tcp unless DisableDiscovery is explicitly enabled for controlled environments. ServeHTTP integrates with an existing HTTP server; the application then owns advertising and shutdown.

RecommendedListenAddress is :8928; DefaultWebSocketPath is /sendspin. These are explicit defaults for integrations, not an automatically opened port.

Unpaired playback is disabled by default. Transfer client.PairingToken() to the server's operator interface to pair. The token is confidential: never put it in logs or a URL. MemoryStore is for tests, not persistent devices. On Windows, applications must secure the credential directory's ACL.

Read Snapshot() for current state and consume Events() for notifications. Events are bounded and best-effort; slow consumers do not block protocol processing. Snapshot().ActiveStreams distinguishes an active role from an open stream. Use CurrentArtwork(channel) to recover the current image even after missed events, and CurrentPosition() for the synchronized playback position in milliseconds. See SDK usage and audio contracts.

Player example

The application under _examples/player has its own go.mod/go.sum and uses the checkout's SDK through a local replacement. Build with mise run build:example; inspect help with go -C _examples/player run . -h. Native libraries are loaded only at device Open; no native compiler or development headers are needed for the player:

player -pairing-token
player -output native -server ws://192.0.2.1:8927/sendspin
player -output alsa -device hw:CARD=S3,DEV=0 -server ws://192.0.2.1:8927/sendspin

Linux automatic selection prefers usable PipeWire, then direct ALSA. Windows uses WASAPI, macOS CoreAudio. Explicit backend/library choices do not silently fall back. -output noop deliberately discards audio; automatic selection never chooses it. No backend selection is a physical synchronization certificate.

Credentials default to the operating system's user-config directory, not the source tree. This is an example application, not a production-ready packaged player. See backends and their limitations. The direct Linux ALSA package, other platform backends and the native selector share the SDK module. The selector offers a platform-independent entry point. SDK also supports optional dynamic and static PIN pairing, with PSK-only behavior retained by default.

Develop and test

With mise:

mise trust
mise install
mise run check:full

mise run format and mise run lint use the pinned golangci-lint v2 configuration, including tagged SDK sources and separate checks for both example modules. Project build outputs, test reports and fixture environments live under var; shared tool caches and system temporary directories keep their defaults.

mise run test:e2e starts the pinned aiosendspin 10.2.1 reference server. No Music Assistant installation, container runtime, sound card or manual pairing is required. Python and locked dependencies are provisioned through uv. After provisioning, the tests use loopback sockets only, not LAN discovery.

mise run test:conformance additionally runs 15 selected cases from the pinned official harness using this SDK's own local adapter. See scope and evidence; this is not full certification.

Plain go test ./... requires no sound card or Python. Live device tests require explicit device environment variables and E2E tests additionally use -tags=e2e. See development and releasing. Normal Go tests also replay frozen C++ time-filter vectors without C++ tooling. The full contributor gate compiles the pinned oracle live and therefore additionally requires a native GCC/Clang-compatible C++17 compiler (CXX can select its path). It also runs mise run test:mdns in a private internal Linux container network; Podman or Docker is required for that isolated multicast suite, not for ordinary Go tests or test:e2e. See discovery testing.

mise run test:soak performs the longer virtual-output resource campaign (three minutes per cipher suite by default); receipts and limits stay separate from the shorter ordinary E2E run. The API/release review records ownership, cancellation, public errors and archive boundaries.

Additional hardware-free work is documented in the transport/load campaign, cryptographic source review, supplemental template inventory, and extension contracts. None is physical conformance evidence. The internal offline loopback tool prepares reference WAVs and analyzes supplied recordings without playback, capture or audio-library dependencies. Synthetic known-answer results are not physical timing evidence. Real examples under _examples/player and _examples/external-control each have their own module; SDK backends, selector and internal Go tools stay in the root module. See module layout.

Host-managed volume/mute

Software volume/mute remains the default. Hosts can explicitly select immutable unity gain and bind independent external controls, observations and capabilities. See the host-control API and migration guide and the fake-only _examples/external-control.

License

MIT, except the Apache-2.0-derived time-filter implementation; see NOTICES and Apache License 2.0. Sendspin is a trademark of the Open Home Foundation. Protocol implementation does not grant trademark rights. Opus has its own applicable patent terms.

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

Examples

Constants

View Source
const DefaultWebSocketPath = "/sendspin"

DefaultWebSocketPath is the endpoint mounted and advertised by Serve.

View Source
const RecommendedListenAddress = ":8928"

RecommendedListenAddress is RC1's suggested server-initiated client port. Serve accepts a caller-owned listener and never binds this address implicitly.

View Source
const Specification = protocol.Specification

Variables

View Source
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")
)
View Source
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")
)
View Source
var ErrNoCredentials = errors.New("sendspin: no credentials stored")
View Source
var ErrPairingActive = errors.New("sendspin: a pairing attempt is active")
View Source
var ErrPairingDisabled = errors.New("sendspin: PIN pairing is disabled")

Functions

This section is empty.

Types

type Artwork

type Artwork struct {
	Channel   int
	Timestamp int64
	Data      []byte
}

type ArtworkChannel

type ArtworkChannel struct {
	Source string `json:"source"`
	Format string `json:"format,omitempty"`
	Width  int    `json:"width,omitempty"`
	Height int    `json:"height,omitempty"`
}

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

func New(ctx context.Context, config Config) (*Client, error)

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

func (c *Client) CancelPairing(ctx context.Context) error

CancelPairing closes the local window and aborts an active/pending attempt. With no admitted session it still closes the window and succeeds.

func (*Client) ClientID

func (c *Client) ClientID() string

ClientID returns the persistent public Curve25519 identity (not a secret).

func (*Client) Command

func (c *Client) Command(ctx context.Context, command Command) error

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

func (c *Client) Connect(ctx context.Context, endpoint string) error

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

func (c *Client) CurrentArtwork(channel int) (Artwork, bool)

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

func (c *Client) CurrentPosition() (int64, bool)

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

func (c *Client) DiscoverAndRun(ctx context.Context) error

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) Events

func (c *Client) Events() <-chan Event

Events remains open for the reusable lifetime of the Client.

func (*Client) LeaveGroup

func (c *Client) LeaveGroup(ctx context.Context) error

LeaveGroup asks the admitted server to leave the current group.

func (*Client) OpenPairingWindow added in v0.2.0

func (c *Client) OpenPairingWindow(ctx context.Context) error

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.

func (*Client) PairingToken

func (c *Client) PairingToken() string

PairingToken returns the confidential operator token. Expose it only through an intentional local provisioning interface, never ordinary logs or telemetry.

func (*Client) PreferFormat

func (c *Client) PreferFormat(ctx context.Context, format codec.Format) error

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) Run

func (c *Client) Run(ctx context.Context, endpoint string) error

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

func (c *Client) Serve(ctx context.Context, listener net.Listener) error

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

func (c *Client) SetAvailable(ctx context.Context, available bool) error

SetAvailable declares the host's willingness to yield to Sendspin. Actual availability still depends on the SDK's clock/readiness gates.

func (*Client) SetMuted

func (c *Client) SetMuted(ctx context.Context, muted bool) error

SetMuted updates/persists legacy mute, or accepts an asynchronous host write.

func (*Client) SetOutputDelay

func (c *Client) SetOutputDelay(ctx context.Context, delay time.Duration) error

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

func (c *Client) SetVolume(ctx context.Context, volume int) error

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) Snapshot

func (c *Client) Snapshot() Snapshot

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
}

CodePairingConfig opts into either static PIN pairing or dynamic displayed PINs. RC1 allows at most one code method in a Client's hello; both are supported by the SDK, but Static and Display cannot be configured together. 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.

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 Command

type Command struct {
	Command    string `json:"command"`
	Volume     *int   `json:"volume,omitempty"`
	Mute       *bool  `json:"mute,omitempty"`
	PositionMS *int64 `json:"position_ms,omitempty"`
	OffsetMS   *int64 `json:"offset_ms,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. 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 ControllerState struct {
	SupportedCommands []string `json:"supported_commands"`
	Volume            int      `json:"volume"`
	Muted             bool     `json:"muted"`
	Repeat            string   `json:"repeat"`
	Shuffle           bool     `json:"shuffle"`
	SeekMaxMS         *int64   `json:"seek_max_ms,omitempty"`
}

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"`
}

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) Format

func (Credentials) Format(state fmt.State, _ rune)

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 DeviceInfo struct {
	ProductName     string `json:"product_name,omitempty"`
	Manufacturer    string `json:"manufacturer,omitempty"`
	SoftwareVersion string `json:"software_version,omitempty"`
}

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.

func (FileStore) Load

func (s FileStore) Load(ctx context.Context) (Credentials, error)

func (FileStore) Save

func (s FileStore) Save(ctx context.Context, c Credentials) error

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 Group

type Group struct {
	PlaybackState string `json:"playback_state"`
	ID            string `json:"group_id"`
	Name          string `json:"group_name"`
}

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

func (m Metadata) Position(serverTime int64) (int64, bool)

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) Format added in v0.2.0

func (PairingPIN) Format(s fmt.State, _ rune)

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 PairingRecord

type PairingRecord struct {
	ServerID string `json:"server_id"`
	PSK      Secret `json:"psk"`
}

PairingRecord binds a long-term PSK to an authenticated server identity.

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

type PlayerControlCapabilities struct {
	Volume bool
	Mute   bool
}

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

type PlayerControlRequest struct {
	ID     uint64
	Volume *int
	Muted  *bool
	Status string
	Error  string
}

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 Progress

type Progress struct {
	PositionMS int64 `json:"track_progress"`
	DurationMS int64 `json:"track_duration"`
	Speed      int64 `json:"playback_speed"`
}

type Role

type Role string
const (
	Player         Role = "player@v1"
	Controller     Role = "controller@v1"
	MetadataRole   Role = "metadata@v1"
	ArtworkRole    Role = "artwork@v1"
	VisualizerRole Role = "visualizer@v1"
	ColorRole      Role = "color@v1"
	SourceRole     Role = "source@v1"
)

type Secret

type Secret [32]byte

Secret is a 256-bit secret. Formatting redacts it, serialization does not.

func ParsePairingToken

func ParsePairingToken(token string) (clientID string, psk Secret, err error)

ParsePairingToken accepts operator input and ignores reserved trailing bytes.

func (Secret) Format

func (Secret) Format(state fmt.State, _ rune)

func (Secret) GoString

func (Secret) GoString() string

func (Secret) MarshalText

func (s Secret) MarshalText() ([]byte, error)

func (Secret) String

func (Secret) String() string

func (*Secret) UnmarshalText

func (s *Secret) UnmarshalText(b []byte) error

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 Spectrum

type Spectrum struct {
	Bins         int    `json:"n_disp_bins"`
	Scale        string `json:"scale"`
	MinFrequency int    `json:"f_min"`
	MaxFrequency int    `json:"f_max"`
}

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 Visualization struct {
	Type      string
	Timestamp int64
	// Values preserves the received bins/scalars. For f_peak it is [dominant
	// frequency in Hz, amplitude], not an inferred musical fundamental or note.
	Values   []uint16
	Downbeat bool
	Strength uint8
}

type VisualizerConfig

type VisualizerConfig struct {
	Types    []string  `json:"types"`
	RateMax  int       `json:"rate_max"`
	Spectrum *Spectrum `json:"spectrum,omitempty"`
}

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/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.
conformancetestcmd command
Command conformancetestcmd builds the client adapter and runs the pinned harness.
Command conformancetestcmd builds the client adapter and runs the pinned harness.
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.
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.
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL