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 ¶
- Constants
- 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 CrossfadeSettings
- type DebugEvent
- type DebugKind
- type EffectKindInfo
- type EffectMeters
- type EffectStage
- type Event
- type Experimental
- type Failed
- type PipelineChanged
- type RepeatChanged
- type RepeatMode
- 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) Crossfade() CrossfadeSettings
- func (s *Session) DebugDropped() int64
- func (s *Session) DebugEvents() <-chan DebugEvent
- 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) Repeat() RepeatMode
- func (s *Session) Resume() error
- func (s *Session) Seek(d time.Duration) error
- func (s *Session) SetCrossfade(c CrossfadeSettings) error
- func (s *Session) SetEffectBypass(id string, bypassed bool) error
- func (s *Session) SetEffectParam(id, key string, value any) error
- func (s *Session) SetRepeat(m RepeatMode) error
- func (s *Session) SetSettings(next Settings) error
- func (s *Session) SetShuffle(on bool) error
- func (s *Session) SetVolume(v float64)
- func (s *Session) Settings() Settings
- func (s *Session) Shuffled() bool
- 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 ¶
const ( // MinCrossfadeMs is the shortest accepted overlap. MinCrossfadeMs = 1000 // MaxCrossfadeMs is the longest accepted overlap, twelve seconds. MaxCrossfadeMs = 12000 // DefaultCrossfadeMs is the starting duration when none was chosen: long // enough to read as a blend, short enough not to swallow a song's end. DefaultCrossfadeMs = 5000 )
Crossfade bounds. The duration is the overlap window in milliseconds: the outgoing track fades out while the incoming one fades in. The 1 to 12 second range is the one most players expose, so a listener finds the same control.
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. With // no providers the session runs the legacy local path (behaviourally // LocalAudio), so an unclaimed ref with providers configured 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. 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, 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 (behaviourally LocalAudio). When 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. 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.
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 CrossfadeSettings ¶ added in v1.1.0
CrossfadeSettings is the overlap between tracks. It is a runtime setting, like Volume: it can change while a track plays and applies to the next handoff.
Enabled turns the overlap on. DurationMs is the overlap length in milliseconds, bounded by MinCrossfadeMs and MaxCrossfadeMs. SkipSameAlbum suppresses the overlap for two consecutive tracks from the same album, so a continuous album is not cut by a blend.
func DefaultCrossfade ¶ added in v1.1.0
func DefaultCrossfade() CrossfadeSettings
DefaultCrossfade returns the settings in force before a caller changes anything: off, with the default duration and same-album skip armed for the moment it is switched on. A fresh install therefore behaves exactly as it did before the feature existed.
func ValidateCrossfade ¶ added in v1.1.0
func ValidateCrossfade(c CrossfadeSettings) CrossfadeSettings
ValidateCrossfade returns the settings with the duration clamped into the accepted range. A duration outside it is corrected rather than rejected, matching how the gain clamps a bad volume: the nearest bound is always a usable value.
type DebugEvent ¶ added in v1.1.0
type DebugEvent struct {
// Time is stamped when the record is accepted by the sink.
Time time.Time
Kind DebugKind
// Path is the track the record belongs to, empty when not track-scoped.
Path string
// Message is a short human sentence. A UI may show it as-is or ignore it.
Message string
// Delta is the per-interval count: the underrun increase since the last
// sample. Zero for kinds that are not deltas.
Delta int64
// Count is the absolute figure: cumulative underruns, total frames, or the
// stage count, depending on Kind.
Count int64
// Buffered is the streamer ring occupancy at the sample, zero otherwise.
Buffered int64
// Elapsed is how long the reported operation took, zero when it has no
// duration.
Elapsed time.Duration
// Decoder, Parser and Backend name the resolved components when the record
// is about a track or a swap.
Decoder string
Parser string
Backend string
}
DebugEvent is one diagnostic record. It is separate from the sealed control Event set: debug traffic is frequent and disposable, and it must never displace a control event such as Failed or StateChanged.
Which numeric fields are meaningful depends on Kind and is documented per field.
type DebugKind ¶ added in v1.1.0
type DebugKind uint8
DebugKind classifies one debug record. It is a small closed set so a UI can filter without parsing the message.
const ( // DebugTrack is emitted when a track is activated, naming the resolved // decoder, parser and backend. DebugTrack DebugKind = iota // DebugUnderrun is emitted when the streamer's underrun counter advances. DebugUnderrun // DebugSeek is emitted after a reposition lands. DebugSeek // DebugSwap is emitted after a live decoder or backend change lands. DebugSwap // DebugPipeline is emitted when a new post-ring chain is installed. DebugPipeline // DebugProbe is emitted when the asynchronous duration probe answers. DebugProbe // DebugState is emitted for an accepted state transition. DebugState // DebugError is emitted for a decode, device or engine failure. DebugError )
type EffectKindInfo ¶
EffectKindInfo describes one registered implementation for a chooser: 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, and Readings and Visuals are empty, for an effect that does not implement the corresponding interface.
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 RepeatChanged ¶ added in v1.1.0
type RepeatChanged struct {
Mode RepeatMode
}
RepeatChanged confirms that the repeat mode in force changed. It is emitted by the control loop, so a UI sees the same value the end-of-track decision uses rather than whatever it last asked for, and a set that changed nothing emits no event.
type RepeatMode ¶ added in v1.1.0
type RepeatMode uint8
RepeatMode is what the engine does when a track reaches its natural end.
It lives in [runtimeSettings] rather than in the view because the control loop reads it at end-of-track to pick the next track, while the view is only what Snapshot reports. Keeping it with the other runtime settings means a setter and the control loop share one guarded copy.
const ( // RepeatOff stops at the end of the queue, which is the behaviour before // repeat existed. RepeatOff RepeatMode = iota // RepeatAll wraps from the last track back to the first. RepeatAll // RepeatOne restarts the current track instead of advancing. RepeatOne )
func ValidateRepeat ¶ added in v1.1.0
func ValidateRepeat(m RepeatMode) RepeatMode
ValidateRepeat maps any value outside the known set to RepeatOff, so a stale or hand-set mode can never wedge the queue.
type Seeked ¶
Seeked confirms a seek after it has been applied and audio resumed. Position is where the seek landed, From is where playback was, and Elapsed is 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 and the caller can set a parameter on it immediately.
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.
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) Crossfade ¶ added in v1.1.0
func (s *Session) Crossfade() CrossfadeSettings
Crossfade returns the crossfade settings in force. It is a value copy, so a caller that mutates what it gets cannot reach the engine.
func (*Session) DebugDropped ¶ added in v1.1.0
DebugDropped reports how many debug records a slow consumer cost. It is the debug stream's counterpart to Snapshot.DroppedEvents.
func (*Session) DebugEvents ¶ added in v1.1.0
func (s *Session) DebugEvents() <-chan DebugEvent
DebugEvents is the stream of diagnostic records. It is separate from Events and never blocks the engine: it is a no-op until this method is called, and after that it drops the oldest record when a consumer falls behind, counted in DebugDropped.
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. 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 one the control loop last installed. A chain caught mid-install reports the accepted description with no meters rather than a wrong pairing.
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. 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. A session built through the facade always has at least the built-in list; it is empty only for a session constructed directly with no providers.
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) Repeat ¶ added in v1.1.0
func (s *Session) Repeat() RepeatMode
Repeat returns the repeat mode the control loop will use at the next end-of-track, which is what Snapshot reports.
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) SetCrossfade ¶ added in v1.1.0
func (s *Session) SetCrossfade(c CrossfadeSettings) error
SetCrossfade replaces the crossfade settings. An out-of-range duration is clamped to the accepted range rather than rejected, matching the gain's behaviour, so a UI can send what it holds without pre-clamping. The change applies to the next handoff; a crossfade already in flight is left to finish.
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 never runs while holding a lock the audio thread could want.
func (*Session) SetRepeat ¶ added in v1.1.0
func (s *Session) SetRepeat(m RepeatMode) error
SetRepeat replaces the repeat mode. An unknown value is mapped to RepeatOff rather than rejected, matching how a bad crossfade duration is corrected, so a UI can send what it holds. The change applies to the next end-of-track, so it is safe to call while audio is running. It emits nothing itself: the control loop emits RepeatChanged once the mode actually changes.
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 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 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) SetShuffle ¶ added in v1.1.0
SetShuffle turns baked shuffle on or off. On, the queue in force is replaced with a shuffled permutation of itself and the current track keeps playing; the next advance follows the shuffled order rather than picking a random track each time. Off restores the order the last shuffle was taken from.
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.
The fields take effect at different moments:
- 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
// Repeat is the mode the control loop uses at end-of-track, so a UI shows
// the same value the engine acts on rather than one it last requested.
Repeat RepeatMode
// 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.