Documentation
¶
Overview ¶
Package session is the player's controller: the only component that owns mutable engine state. It drives the decoder, streamer, gain and device, keeps the queue, and reports changes as events so a UI can be built on top without ever touching the audio path.
Everything public on Session is safe to call from any goroutine and returns without waiting for audio work. A UI polls Snapshot for the cheap things (position, state, queue) and listens on Events for the rare ones.
Index ¶
- Variables
- func ValidateBackend(name string) error
- func ValidateDecoder(name string) error
- func ValidatePipeline(p dsp.Pipeline) error
- func ValidateProbeMode(mode core.DurationMode) error
- func ValidateVolume(v float64) error
- type Config
- type EffectKindInfo
- type EffectMeters
- type EffectStage
- type Event
- type Experimental
- type Failed
- type PipelineChanged
- type Seeked
- type Session
- func (s *Session) AddEffect(kind, impl string) (string, error)
- func (s *Session) ApplyPipeline(p dsp.Pipeline) error
- func (s *Session) Close() error
- func (s *Session) EffectKindNames() []string
- func (s *Session) EffectKinds() []EffectKindInfo
- func (s *Session) EffectMeters() []EffectMeters
- func (s *Session) EffectSchema(kind string) ([]dsp.Param, error)
- func (s *Session) EffectStages() []EffectStage
- func (s *Session) Events() <-chan Event
- func (s *Session) InsertQueue(index int, refs []string) error
- func (s *Session) InsertQueueAndPlay(index int, refs []string) error
- func (s *Session) MoveEffect(id string, to int) error
- func (s *Session) Next() error
- func (s *Session) Pause() error
- func (s *Session) Pipeline() dsp.Pipeline
- func (s *Session) Play(path string) error
- func (s *Session) PlayIndex(index int) error
- func (s *Session) PlayQueue(paths []string) error
- func (s *Session) Prev() error
- func (s *Session) Providers() []string
- func (s *Session) Queue() []string
- func (s *Session) RemoveEffect(id string) error
- func (s *Session) Resume() error
- func (s *Session) Seek(d time.Duration) error
- func (s *Session) SetEffectBypass(id string, bypassed bool) error
- func (s *Session) SetEffectParam(id, key string, value any) error
- func (s *Session) SetSettings(next Settings) error
- func (s *Session) SetVolume(v float64)
- func (s *Session) Settings() Settings
- func (s *Session) Snapshot() Snapshot
- func (s *Session) Stop() error
- func (s *Session) SwapBackend(name string) error
- func (s *Session) SwapDecoder(name string) error
- func (s *Session) Tap() Tap
- type Settings
- type Snapshot
- type State
- type StateChanged
- type Swapped
- type Tap
- type TrackChanged
- type TrackEnded
Constants ¶
This section is empty.
Variables ¶
var ( // ErrEmptyQueue means PlayQueue was handed nothing to play. ErrEmptyQueue = errors.New("session: queue is empty") // ErrEmptyPath means Play was handed an empty path. ErrEmptyPath = errors.New("session: path is empty") // ErrIndexOutOfRange means PlayIndex named a queue position that does not // exist. ErrIndexOutOfRange = errors.New("session: queue index out of range") // ErrNoLiveTrack means InsertQueueAndPlay was asked to start a track while // one is already loaded, which would cut that track off. It is not an error // state, just a refusal: the caller appends instead. ErrNoLiveTrack = errors.New("session: a track is already loaded") // ErrNegativeSeek means a seek target was negative. ErrNegativeSeek = errors.New("session: seek target is negative") // ErrNoProber means the registry has no duration probe for the path. The // duration simply stays unknown. ErrNoProber = errors.New("session: no duration prober for the path") // ErrClosed means the session is shutting down. ErrClosed = errors.New("session: closed") // ErrUnknownDecoder means a decoder preference named no registered codec. ErrUnknownDecoder = errors.New("session: unknown decoder") // ErrUnknownBackend means a backend preference named no registered backend. ErrUnknownBackend = errors.New("session: unknown playback backend") // ErrBadProbeMode means a duration mode outside the known set. ErrBadProbeMode = errors.New("session: unknown duration mode") // ErrBadVolume means a gain outside dsp's accepted range. ErrBadVolume = errors.New("session: volume out of range") // ErrNoProvider means the session was configured with providers, none of // them claimed the reference, and the reference is not a local path. It is // the error an empty provider list never produces: with no providers the // session runs the legacy local path, which is behaviourally LocalAudio. // Non-empty providers are a deliberate configuration, so an unclaimed ref is // a caller mistake rather than something to silently open as a file. ErrNoProvider = provider.ErrNoProvider // ErrProviderNoOpener means a matching provider returned a Source with no // Opener. The provider matched, so this is not ErrNoProvider: it is a broken // provider, and passing the Source on would panic the producer goroutine. ErrProviderNoOpener = errors.New("session: provider returned no Opener") // ErrProviderNoDecoder means a provider's Opener returned a nil decoder with // a nil error. The Source contract requires a non-nil decoder or an error, // so this is a provider bug, not a decode failure. ErrProviderNoDecoder = errors.New("session: provider Opener returned a nil decoder") // ErrProviderNoDecoderSwap means SwapDecoder was asked to change the decoder // of a track owned by a provider. A provider supplies an opaque Opener, so // the session cannot rebuild it with a different decoder name; a decoder // swap is only meaningful on the local path, where the registry can open the // named codec. Local references are unaffected. ErrProviderNoDecoderSwap = errors.New("session: cannot swap the decoder of a provider reference") // ErrInvalidSetting marks a rejected Settings update. The field-specific // errors above are wrapped inside it, so a caller can match on this one to // tell "bad value" apart from every other failure. ErrInvalidSetting = errors.New("session: invalid setting") )
var ErrEffectIndexOutOfRange = errors.New("session: effect index out of range")
ErrEffectIndexOutOfRange means MoveEffect named a position outside the chain.
var ErrUnknownEffect = errors.New("session: unknown effect stage")
ErrUnknownEffect means an effect stage ID does not name a stage in the chain in force. It is returned by every editor command that addresses a stage, so a UI can tell a stale ID apart from a bad parameter or an out-of-range move.
Functions ¶
func ValidateBackend ¶
ValidateBackend reports whether name is a usable playback backend. The empty string selects the default backend and is always valid.
func ValidateDecoder ¶
ValidateDecoder reports whether name is a usable decoder preference. The empty string means automatic selection and is always valid. This is the one copy of the rule: the facade and the config defaults both call it, so a chooser UI and a direct setter cannot disagree about what is legal.
func ValidatePipeline ¶
ValidatePipeline reports whether every post-ring stage can be built. It is the same check ApplyPipeline runs, exposed so a caller can reject a preset without applying it. The Pre half is never built here: it belongs to the streamer, which does not exist yet at validation time.
func ValidateProbeMode ¶
func ValidateProbeMode(mode core.DurationMode) error
ValidateProbeMode reports whether mode is one of the defined duration modes. Bounds are spelled out rather than compared to DurationScan, because a future mode inserted in the middle of the enum would otherwise pass unnoticed.
func ValidateVolume ¶
ValidateVolume reports whether v is inside the gain's accepted range.
Types ¶
type Config ¶
type Config struct {
// Backend is the playback backend name, default "oto".
Backend string
// EventBuffer is the event channel depth, default 64.
EventBuffer int
// RingFrames is the streamer ring size in output frames. Zero selects the
// streamer's own default of about 300 ms.
RingFrames int
// Volume is the initial gain in [0, 1]. Zero selects unity, because a
// muted-by-default player is never what a caller means.
Volume float64
// Resolver describes each track. Nil selects meta.Default().
Resolver meta.Resolver
// Providers resolves track references, highest priority first. Nil or empty
// selects the legacy local path, which is behaviourally LocalAudio and keeps
// the historic Config.openDecoder seam intact. When the list is non-empty
// the first provider whose Match returns true wins, so order is significant
// and a catch-all provider such as LocalAudio must stay last. A non-empty
// list that claims nothing is an error (ErrNoProvider) rather than a silent
// fallback to a file.
Providers []provider.AudioProvider
// ProbeMode selects how much work the asynchronous duration probe may do.
// Nil selects the cheap tail probe. A pointer, not a value, because
// core.DurationUnknown is the zero value and must stay distinguishable
// from "the caller did not choose".
ProbeMode *core.DurationMode
// Decoder is the initial decoder preference: a name from
// decode.Default.Codecs(), or empty for automatic selection. It is only the
// starting value; Settings can change it while the session runs.
Decoder string
// Pipeline is the post-ring effect chain. Zero is an empty chain, which is
// today's behaviour: only the master gain runs. The Pre half is the
// streamer's business and is ignored here.
Pipeline dsp.Pipeline
// Experimental toggles not-yet-stable features. Zero is today's behaviour,
// so leaving it unset keeps every existing path byte-for-byte.
Experimental Experimental
// contains filtered or unexported fields
}
Config tunes a Session. Zero fields take the documented default, so the empty Config is the intended setup.
type EffectKindInfo ¶
EffectKindInfo describes one registered implementation for a chooser. It is the (kind, impl) pair a caller passes to AddEffect, plus the label and the script flag a UI needs to group the list.
type EffectMeters ¶
EffectMeters is one stage's live meters with no schema or values attached. It is the lean shape a fast meter tick reads: the full EffectStage re-reads every parameter through Get, which is fine at the snapshot's 4 Hz and wasteful at the meter tick's ~30 Hz. Pairing is by ID, the same rule EffectStages uses.
type EffectStage ¶
type EffectStage struct {
ID string
Kind string
Impl string
Label string
Bypassed bool
Schema []dsp.Param
Values dsp.Values
Meters map[string]float32
Readings []dsp.Reading
Visuals []dsp.Visual
}
EffectStage is one stage of the chain in force: its identity, its schema, its current parameter values, its live meters and its described readings and visuals. Schema and Values are snapshots taken when the stage is read, so a UI can render it without holding an effect. Meters is nil for an effect that does not implement dsp.Metered. Readings is empty and Visuals is empty for an effect that does not implement dsp.Described or dsp.Visualized.
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is the sealed interface of everything the controller reports. The unexported method means only this package can add a kind, so a UI's type switch is exhaustive against a known set.
type Experimental ¶
type Experimental struct {
// SourceUpgrade enables the source-upgrade path: a provider Source that
// offers Upgrade is started forward-only, and later swapped to the upgraded
// decoder without flushing the streamer ring, so playback begins before the
// whole track is available and the switch is inaudible.
SourceUpgrade bool
}
Experimental toggles features that are not yet stable. The zero value is the current behaviour, so an empty Config changes nothing and no existing path is affected unless a caller opts in.
type Failed ¶
type Failed struct {
Err error
}
Failed reports a decode or device error that stopped playback. The session is still usable afterwards: the next Play creates a fresh pipeline.
type PipelineChanged ¶
type PipelineChanged struct {
Stages int
}
PipelineChanged confirms that a new post-ring effect chain is in force. Stages is how many effects the chain runs after the change, so a UI can tell an effect being added from the chain being cleared.
type Seeked ¶
type Seeked struct {
Position time.Duration // where the seek landed
From time.Duration // where playback was before the seek
Elapsed time.Duration // how long the reposition took
}
Seeked confirms a seek after it has been applied and audio resumed. From and Elapsed describe the move itself: where playback was, and how long the reposition took.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is the controller. It owns the queue, the current streamer, the device and the gain, and it is the only place those change.
Concurrency: public commands append to an inbox under a short-lived mutex and signal the control loop without blocking. The control loop moves the batch and reacts; every slow operation (opening a decoder, probing a file, resolving tags) runs on its own goroutine and reports back through a channel. That is what makes a command non-blocking by construction rather than by the caller being careful.
func New ¶
New builds a session and starts its control goroutine. It does not touch the audio device or the file system, so it succeeds on a machine with no audio server; a backend failure surfaces as a Failed event on the first Play.
func (*Session) AddEffect ¶
AddEffect appends one stage to the chain and returns its new ID. The stage is built on the caller's goroutine, exactly as ApplyPipeline builds, and the install is waited for, so the returned stage is already live: the caller can set a parameter on it immediately. Waiting is bounded by the control loop, which only does bounded work, and by Close.
The whole read-modify-write is serialized, so two concurrent calls each see the other's stage instead of starting from the same list and dropping one.
func (*Session) ApplyPipeline ¶
ApplyPipeline validates every post-ring stage before applying any of them, matching SetSettings: a pipeline with an unknown kind or an unknown parameter is rejected whole and leaves the chain in force untouched. Validation happens on the caller's goroutine: building an effect is bounded and never touches the device, just as validation of a decoder name never opens a file.
The accepted effects are handed to the control loop, which publishes them with an atomic swap. A successful call therefore means the pipeline is accepted, not that the audio path has already switched to it; the PipelineChanged event confirms the install.
func (*Session) Close ¶
Close stops every goroutine and releases the device and streamer. It is idempotent and safe to call from any goroutine.
func (*Session) EffectKindNames ¶
EffectKindNames lists the registered effect kinds, sorted, so a UI can offer the stages this build supports without hard-coding them. It is the plain name list; EffectKinds returns the detailed per-implementation list an editor needs.
func (*Session) EffectKinds ¶
func (s *Session) EffectKinds() []EffectKindInfo
EffectKinds lists every registered implementation, one entry per (kind, impl) pair, so a chooser can offer crossfeed-bs2b and a scripted effect side by side. It reads the process-wide registry, which never changes after init.
func (*Session) EffectMeters ¶
func (s *Session) EffectMeters() []EffectMeters
EffectMeters returns the live meters of every stage that meters, in processing order. It resolves the live chain by ID exactly as EffectStages does, but reads only the meters, so a UI can drive a moving needle at a higher rate than the full snapshot without re-walking schemas and values. A stage with no live effect yet, or an effect that does not implement dsp.Metered, is omitted rather than reported with empty meters.
func (*Session) EffectSchema ¶
EffectSchema returns the parameter schema of the implementation automatic selection would build for a kind, so a UI can render controls without instantiating an effect. An unknown kind is an error, never an empty schema.
func (*Session) EffectStages ¶
func (s *Session) EffectStages() []EffectStage
EffectStages returns the chain in force in processing order, each stage with its schema, values and live meters.
The runtime pipeline and the live chain are two views of one thing, published by different steps: the pipeline is written when a change is accepted and the chain is swapped by the control loop a moment later. A rebuild in flight can therefore leave the two briefly out of step. Pairing them by index in that window would report one stage's identity with another stage's meters, so this pairs them only while the pipeline generation matches the generation the control loop last installed. A chain caught mid-install reports the accepted description with no meters rather than a wrong pairing, and the next read settles.
func (*Session) Events ¶
Events is the stream of controller events. It never blocks the engine: a producer that outruns this channel costs the oldest event, counted in Snapshot.DroppedEvents.
func (*Session) InsertQueue ¶
InsertQueue inserts refs into the queue at index without touching the track that is playing. An index at or past the end appends. Insertion is what "play next" means: the current track keeps sounding, and the inserted refs are what the engine plays when it advances.
The live track is not preserved by re-seating the queue; it is preserved because the queue and the current track's index are the only things that change. Nothing re-opens the current streamer, so playback is continuous.
func (*Session) InsertQueueAndPlay ¶
InsertQueueAndPlay inserts refs like InsertQueue and then starts the first inserted ref. With nothing playing that is simply "play this now"; with a track sounding it would cut it off, so the live case is refused with ErrNoLiveTrack and the caller keeps the refs to append instead. It is one command rather than an insert plus a PlayIndex because PlayIndex validates its index synchronously, before the control loop has grown the queue.
func (*Session) MoveEffect ¶
MoveEffect moves the stage with id so it lands at index to in processing order. Reordering is a new chain, so it rebuilds through ApplyPipeline and its atomic install rather than mutating the live list the audio thread reads.
func (*Session) Pipeline ¶
Pipeline returns the post-ring effect chain in force. The returned Pipeline is a copy: mutating it cannot reach the engine, and ApplyPipeline must be used to change anything.
func (*Session) Play ¶
Play replaces the queue with one track and starts it. ref is a provider reference when a provider claims it, and a filesystem path otherwise.
func (*Session) PlayIndex ¶
PlayIndex starts the queue entry at index without replacing the queue, which is what a click on a row in a track list means: jump there, keep the rest. The bound is checked here so an out-of-range jump is an immediate error rather than a silent no-op, and the control loop re-checks it because the queue can change between the two.
func (*Session) PlayQueue ¶
PlayQueue replaces the queue and starts at the first track. Each entry is a provider reference when a provider claims it, and a filesystem path otherwise.
func (*Session) Providers ¶
Providers lists the names of the configured providers in the order they are tried. It is empty for the default local-only setup, which has no explicit provider list.
func (*Session) RemoveEffect ¶
RemoveEffect drops the stage with id and rebuilds the chain without it. Only the first match is removed, so a duplicate ID cannot silently delete more than the caller asked for.
func (*Session) Resume ¶
Resume restarts a paused device. It is ignored unless the session is paused.
func (*Session) Seek ¶
Seek repositions the current track once the device has been paused, so the device never reads a half-flushed ring.
func (*Session) SetEffectBypass ¶
SetEffectBypass toggles the standard bypass parameter of the live effect. Bypass is just another key on the effect, so it takes the same no-rebuild path as any other parameter and a bypassed stage keeps its state.
func (*Session) SetEffectParam ¶
SetEffectParam applies one parameter to the live effect named by id. It does not rebuild the chain: a rebuild constructs a new effect, which discards state such as a filter's memory or a fade's ramp position. dsp.Effect.Set is documented safe while Process runs, so the change lands on the running effect and its state survives.
Any lock the lookup takes is released before Set runs, so Set is never called while holding a lock the audio thread could want.
func (*Session) SetSettings ¶
SetSettings validates every field before applying any of them, so a partial update is impossible: either the whole set is accepted or nothing changes. Validation runs here, on the caller's goroutine, so a bad value is reported as an error instead of surfacing as a Failed event on the next track.
Pipeline is validated as part of the same all-or-nothing rule. It differs from the other fields in that it is applied by the control loop rather than here, because installing a chain must not race a build; the whole set is still rejected before anything is written.
func (*Session) SetVolume ¶
SetVolume changes the post-ring gain. It is atomic and takes effect on the next buffer, so it is safe to call while audio is running.
func (*Session) Snapshot ¶
Snapshot reports the controller state. It is safe to call from any goroutine and is cheap enough to poll every frame.
func (*Session) Stop ¶
Stop ends playback and keeps the queue. The device stays open, so the next Play reuses it.
func (*Session) SwapBackend ¶
SwapBackend forces the named playback backend for the current device, reopening it against the same stable provider. Empty means the default. An unknown name is rejected synchronously; an engine failure surfaces as a Failed event while the old device keeps playing.
func (*Session) SwapDecoder ¶
SwapDecoder forces the named decoder for the current track, reopening it at the position playback has reached. Empty means automatic selection. A bad name is rejected synchronously and changes nothing; an engine failure surfaces as a Failed event while the old decoder keeps playing.
A track owned by a provider cannot switch decoder: the provider supplied an opaque Opener, so the session has no way to rebuild it with the named codec. That is refused synchronously with ErrProviderNoDecoderSwap. A local track is unaffected.
type Settings ¶
type Settings struct {
Volume float64
Decoder string
Backend string
ProbeMode core.DurationMode
// Pipeline is the post-ring effect chain. Zero is an empty chain, which is
// today's behaviour: only the master gain runs.
Pipeline dsp.Pipeline
}
Settings is the mutable half of a Session's configuration: the values a caller may change while playback is running. Everything else in Config is read once by New and cannot change afterwards.
Three of these take effect at different moments, which callers must know:
- Volume applies immediately.
- Decoder and ProbeMode are read when the next track is built, so the current track keeps what it started with.
- Backend is read when a device is built. An already-open device keeps playing on the old backend, so the change lands on the next Play that has to build one.
- Pipeline applies to the running audio as soon as the control loop accepts it, which PipelineChanged confirms. Only the Post half is used; Pre belongs to the streamer.
type Snapshot ¶
type Snapshot struct {
State State
Path string
Meta meta.Meta
// Position is where the device is reading, in the streamer's output clock.
Position time.Duration
// Duration is zero until the async probe has answered, which a UI should
// read as "unknown" rather than "empty".
Duration time.Duration
Volume float64
Format core.FrameFormat
QueueIndex int
QueueLen int
Stats stream.Stats
// Decoder and Parser name the components handling the current track, for a
// debug view. Empty when the decoder does not describe itself.
Decoder string
Parser string
// Backend names the playback backend the device was opened against. It is
// the runtime preference, which a SwapBackend can change while a track
// plays, so it matches Settings().Backend once the swap lands.
Backend string
// DroppedEvents counts events discarded because the consumer fell behind.
DroppedEvents int64
}
Snapshot is a read-only view of the controller at one instant. It is cheap: the values a UI polls every frame come from atomics and a short-lived lock, never from the audio path.
type State ¶
type State uint8
State is the lifecycle of the controller. The legal transitions are few and deliberate; an illegal one is ignored rather than allowed to corrupt the device or streamer.
const ( // StateIdle is the state before any track has been started. StateIdle State = iota // StatePlaying means a track is loaded and the device is consuming it. StatePlaying // StatePaused means the current track is loaded but the device is paused. StatePaused // StateStopped means playback ended, was stopped, or failed. The queue may // still hold tracks, so Play or Next can start again. StateStopped )
type StateChanged ¶
StateChanged is emitted for every accepted state transition.
type Swapped ¶
Swapped confirms a live component change: the decoder or playback backend of the current track was rebuilt. Kind is "decoder" or "backend", Name is the forced component name (empty for automatic selection), and Elapsed is how long the rebuild took.
type Tap ¶
type Tap interface {
// Read copies up to len(dst) mono frames in time order. It never blocks
// and reports zero when nothing is buffered.
Read(dst []float32) int
}
Tap is the real-time audio feed a visualizer reads. The engine writes mono downmixed frames after the gain and before the device, so a consumer sees exactly what is heard.
type TrackChanged ¶
TrackChanged is emitted when a new track becomes current, whether from a command or from the queue advancing.
type TrackEnded ¶
type TrackEnded struct{}
TrackEnded is emitted once per track when it reaches its natural end.