sendspin

package module
v0.2.1 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

Go Reference Continuous Integration

sendspin-player-go

A Go SDK for Sendspin players: encrypted connections, audio decoding, synchronized playback, discovery, and optional audio capture.

Install

Go 1.27.3+ is required.

go get github.com/echocat/sendspin-player-go

The SDK and native audio backends build without CGO. Opening an audio device still requires the operating system's runtime libraries and permissions.

Quick start

package main

import (
    "context"
    "os"
    "os/signal"
    "path/filepath"

    sendspin "github.com/echocat/sendspin-player-go"
    "github.com/echocat/sendspin-player-go/audio/native"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()

    configDir, err := os.UserConfigDir()
    if err != nil {
        panic(err)
    }
    player, err := sendspin.New(ctx, sendspin.Config{
        Name:   "Living room",
        Store:  sendspin.FileStore{Path: filepath.Join(configDir, "sendspin-player-go", "device.json")},
        Output: native.Output{},
    })
    if err != nil {
        panic(err)
    }
    if err := player.Run(ctx, "ws://192.0.2.1:8927/sendspin"); err != nil && ctx.Err() == nil {
        panic(err)
    }
}

Pair the client with your server using player.PairingToken(). Treat the token and credential file as secrets. See SDK usage for pairing, discovery, server-initiated connections, and cancellation.

Features

  • Encrypted client- and server-initiated connections with mDNS discovery.
  • PCM, FLAC, and Opus decoding, buffering, clock synchronization, and drift correction.
  • Native ALSA, PipeWire, WASAPI, and CoreAudio playback and capture.
  • Controller commands, metadata, artwork, visualizer, and color updates.
  • Optional Source streaming, PIN pairing, and host-managed volume/mute.
  • Replaceable audio interfaces, codecs, storage, and application-selected logging.

Targets Sendspin 1.0.0-rc1. See protocol support and limitations.

Documentation

License

MIT, with third-party notices in NOTICES. The derived time-filter code uses Apache License 2.0. Sendspin is a trademark of the Open Home Foundation.

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/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.

Jump to

Keyboard shortcuts

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