Documentation
¶
Overview ¶
Package molo is the facade every UI imports. It exposes the controller as a small interface of cheap queries and non-blocking commands, and re-exports the state and event types so a UI never has to reach into internal/session.
The package is deliberately UI-agnostic: no terminal code, no process exit. A TUI, a desktop window and a headless CLI all program against the same Player.
Index ¶
- Constants
- Variables
- func Backends() []string
- func SupportedExtensions() []string
- func UserBackends() []string
- func ValidateBackend(name string) error
- func ValidateDecoder(name string) error
- type Codec
- type Config
- type CrossfadeSettings
- type DebugEvent
- type DebugKind
- type EffectChain
- type EffectKind
- type EffectMeters
- type EffectStage
- type Effects
- type Event
- type Experimental
- type Failed
- type Option
- func WithBackend(name string) Option
- func WithDecoder(name string) Option
- func WithEventBuffer(n int) Option
- func WithExperimental(e Experimental) Option
- func WithPipeline(p dsp.Pipeline) Option
- func WithProbeMode(mode core.DurationMode) Option
- func WithProviders(ps ...provider.AudioProvider) Option
- func WithResolver(r meta.Resolver) Option
- func WithRingFrames(n int) Option
- func WithVolume(v float64) Option
- type PipelineChanged
- type Player
- type RepeatChanged
- type RepeatMode
- type Seeked
- type Settings
- type Snapshot
- type State
- type StateChanged
- type Swapped
- type Tap
- type TrackChanged
- type TrackEnded
Constants ¶
const ( // Idle is the state before any track has been started. Idle = session.StateIdle // Playing means a track is loaded and the device is consuming it. Playing = session.StatePlaying // Paused means a track is loaded but the device is paused. Paused = session.StatePaused // Stopped means playback ended, was stopped, or failed. Stopped = session.StateStopped )
const ( // RepeatOff stops at the end of the queue. It is the zero value and the // behaviour of a fresh install. RepeatOff = session.RepeatOff // RepeatAll wraps from the last track back to the first. RepeatAll = session.RepeatAll // RepeatOne restarts the current track instead of advancing. RepeatOne = session.RepeatOne )
const ( // DebugTrack is emitted when a track is activated, naming its resolved // decoder, parser and backend. DebugTrack = session.DebugTrack // DebugUnderrun is emitted when the streamer's underrun counter advances. DebugUnderrun = session.DebugUnderrun // DebugSeek is emitted after a reposition lands. DebugSeek = session.DebugSeek // DebugSwap is emitted after a live decoder or backend change lands. DebugSwap = session.DebugSwap // DebugPipeline is emitted when a new post-ring chain is installed. DebugPipeline = session.DebugPipeline // DebugProbe is emitted when the asynchronous duration probe answers. DebugProbe = session.DebugProbe // DebugState is emitted for an accepted state transition. DebugState = session.DebugState // DebugError is emitted for a decode, device or engine failure. DebugError = session.DebugError )
The debug record kinds. They mirror the control events but carry diagnostics rather than state transitions.
const ( // MinCrossfadeMs is the shortest accepted crossfade duration, in // milliseconds. MinCrossfadeMs = session.MinCrossfadeMs // MaxCrossfadeMs is the longest accepted crossfade duration, in // milliseconds. MaxCrossfadeMs = session.MaxCrossfadeMs // DefaultCrossfadeMs is the crossfade duration a fresh install starts with, // in milliseconds. DefaultCrossfadeMs = session.DefaultCrossfadeMs )
Variables ¶
var ( // ErrUnknownEffect means an editor command named a stage that is not in the // chain in force, either because it was removed or because a rebuild is // still installing. ErrUnknownEffect = session.ErrUnknownEffect // ErrEffectIndexOutOfRange means MoveEffect named a position outside the // chain. ErrEffectIndexOutOfRange = session.ErrEffectIndexOutOfRange )
The editor errors are re-exported so a UI outside the module can tell a stale stage ID apart from an out-of-range move without importing internal/session. Match them with errors.Is.
var ErrBadProbeMode = session.ErrBadProbeMode
ErrBadProbeMode reports a duration mode outside the known set. ApplySettings wraps it. Match it with errors.Is.
var ErrBadVolume = session.ErrBadVolume
ErrBadVolume reports a gain outside dsp's accepted range. ApplySettings wraps it. Match it with errors.Is.
var ErrEmptyQueue = session.ErrEmptyQueue
ErrEmptyQueue reports PlayQueue or InsertQueue handed nothing to play. Match it with errors.Is.
var ErrIndexOutOfRange = session.ErrIndexOutOfRange
ErrIndexOutOfRange reports a PlayIndex jump to a queue position that does not exist. Like the other command errors it is returned synchronously, before the request reaches the engine.
var ErrInvalidSetting = session.ErrInvalidSetting
ErrInvalidSetting reports a rejected Settings update. It wraps a field-specific error, so a UI can tell "bad value" apart from other failures.
var ErrNoLiveTrack = session.ErrNoLiveTrack
ErrNoLiveTrack reports InsertQueueAndPlay while a track is already loaded, which would cut that track off. The caller appends instead, which is behaviourally what the user meant. It is returned synchronously.
var ErrNoProvider = session.ErrNoProvider
ErrNoProvider reports a configured provider list where none claimed the reference, which WithProviders documents as a failed track rather than a silent fallback to a file path. Match it with errors.Is.
var ErrUnknownBackend = session.ErrUnknownBackend
ErrUnknownBackend reports a backend preference that named no registered backend. ApplySettings wraps it. Match it with errors.Is.
var ErrUnknownDecoder = session.ErrUnknownDecoder
ErrUnknownDecoder reports a decoder preference that named no registered codec. ApplySettings wraps it, so a UI can tell a bad decoder from any other rejected update. Match it with errors.Is.
Functions ¶
func Backends ¶
func Backends() []string
Backends lists the registered playback backend names, for a UI that offers a choice. Empty is always valid and means the default.
func SupportedExtensions ¶
func SupportedExtensions() []string
SupportedExtensions lists the file extensions this build can decode, each lowercased and including the leading dot (" .flac"). A caller that wants to turn a directory into a queue uses it to tell a playable file from a stray one without opening anything.
func UserBackends ¶
func UserBackends() []string
UserBackends lists the playback backends a UI should offer. It is Backends without the dev-only entries, so a fake or null sink never reaches a listener's output dropdown. Validation still accepts the full list, so a test or a CLI flag can select a dev backend by name.
func ValidateBackend ¶
ValidateBackend reports whether name is a usable playback backend, with empty meaning the default. Same rule as ApplySettings enforces.
func ValidateDecoder ¶
ValidateDecoder reports whether name is a usable decoder preference: empty means automatic selection. It is the same rule ApplySettings enforces, exposed so a caller can check a value before offering it (a CLI flag, a settings screen) without importing the registry or reimplementing the check.
Types ¶
type Codec ¶
Codec is one selectable decoder, re-exported so a UI can build a chooser without importing the decode registry itself.
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. See
// WithProviders for the ordering rule.
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.
Decoder string
// Pipeline is the post-ring effect chain. Zero is an empty chain, which
// means 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.
Experimental Experimental
}
Config holds the public construction knobs an Option writes. Zero fields take the documented default, and New maps a Config into the controller's own config, so the empty Config is the intended setup.
type CrossfadeSettings ¶ added in v1.1.0
type CrossfadeSettings = session.CrossfadeSettings
CrossfadeSettings is the overlap between tracks: whether it is on, how long it runs, and whether two tracks from the same album are left unblended. It is a runtime setting, like the volume, so it can change while a track plays.
func DefaultCrossfade ¶ added in v1.1.0
func DefaultCrossfade() CrossfadeSettings
DefaultCrossfade returns the crossfade settings a fresh install starts with: off, at the default duration, with the same-album skip armed. A UI can show it as the reset value without hard-coding the numbers.
type DebugEvent ¶ added in v1.1.0
type DebugEvent = session.DebugEvent
DebugEvent is one diagnostic record from the debug stream. It is separate from the control events: debug traffic is frequent and disposable, and it never displaces a control event. Which numeric fields are meaningful depends on Kind.
type EffectChain ¶
type EffectChain struct {
Stages []EffectStage
}
EffectChain is the chain in force in processing order. It is a value, not a live handle: mutating it cannot reach the engine, and the editor commands are the only way to change anything.
type EffectKind ¶
type EffectKind = session.EffectKindInfo
EffectKind is one registered effect implementation: the (kind, impl) pair a chooser offers and AddEffect accepts, plus the label and script flag a UI groups by.
type EffectMeters ¶
type EffectMeters = session.EffectMeters
EffectMeters is one stage's live meters with no schema or values attached, for a UI that wants to drive a meter faster than the full snapshot.
type EffectStage ¶
type EffectStage = session.EffectStage
EffectStage is one stage of the chain in force, with its schema, current values, live meters and described readings and visual.
type Effects ¶
type Effects interface {
// EffectKindList lists every registered implementation, so a chooser can
// offer each (kind, impl) pair.
EffectKindList() []EffectKind
// EffectChain returns the chain in force, in processing order.
EffectChain() EffectChain
// EffectMeters returns only the live meters of every stage that meters, for
// a UI that drives a needle faster than the full snapshot. It reads no
// schema and no values, so it is cheap enough for a high tick rate.
EffectMeters() []EffectMeters
// AddEffect appends a stage and returns its generated ID. The stage is
// built on the caller's goroutine; the control loop installs the rebuild.
AddEffect(kind, impl string) (string, error)
// RemoveEffect drops the stage with id.
RemoveEffect(id string) error
// MoveEffect moves the stage with id to index to in processing order.
MoveEffect(id string, to int) error
// SetEffectParam applies one parameter to the live effect, without
// rebuilding the chain, so effect state such as a filter's memory is not
// discarded.
SetEffectParam(id, key string, value any) error
// SetEffectBypass toggles the standard bypass parameter of the live effect,
// on the same no-rebuild path as any other parameter.
SetEffectBypass(id string, bypassed bool) error
}
Effects is the effect-chain editor surface. Player embeds it, so every Player offers these methods directly, and Effects returns the same view for callers that want to name the surface.
EffectKindList keeps the detailed (kind, impl) list, while Player.EffectKinds stays the plain []string a chooser already uses: the two share a name and one type cannot carry both methods.
type Event ¶
Event is the sealed set of things the player reports. A UI type-switches on the concrete aliases below.
type Experimental ¶
type Experimental = session.Experimental
Experimental toggles features that are not yet stable, re-exported so a UI can opt in without importing internal/session. The zero value is the current behaviour.
type Option ¶
type Option func(*Config)
Option customises a Player. It is a function over Config, so a new knob is one option and no new type, and a consumer outside the module can author one as a plain closure.
func WithBackend ¶
WithBackend selects the playback backend by registry name. The default is "oto".
func WithDecoder ¶
WithDecoder picks the decoder by registry name, for example "opus" or "opus-libopusfile". Empty means automatic selection, where the codec with the highest weight wins. It is the starting value; ApplySettings can change it while the player runs.
func WithEventBuffer ¶
WithEventBuffer sets the event channel depth. A deeper buffer tolerates a slower consumer before events are dropped.
func WithExperimental ¶
func WithExperimental(e Experimental) Option
WithExperimental enables or disables experimental features for this Player. It is read once, at construction, like WithProviders: these knobs change how a source is opened and swapped, so they cannot be a runtime setting. The zero value leaves every path exactly as it behaves today.
func WithPipeline ¶
WithPipeline sets the initial post-ring effect chain. Only the Post half is used; the Pre half belongs to the streamer. Each stage is validated when the player is built, so a bad stage fails New rather than becoming a Failed event on the first Play. ApplyPipeline can change the chain while the player runs.
func WithProbeMode ¶
func WithProbeMode(mode core.DurationMode) Option
WithProbeMode selects how much work the asynchronous duration probe may do when a track starts. It does not affect playback, only how quickly and how accurately the reported duration becomes known.
func WithProviders ¶
func WithProviders(ps ...provider.AudioProvider) Option
WithProviders sets the audio source providers, highest priority first. Each track reference is given to the first provider whose Match returns true, so a catch-all provider such as provider.LocalAudio must stay last.
Nil (the default) selects provider.Defaults(): direct http/https streaming, then the local filesystem. An explicit list replaces the default entirely, so a caller that wants only local files passes provider.LocalAudio{}.
A non-empty list that claims nothing fails the track with ErrNoProvider rather than silently treating the reference as a file path.
func WithResolver ¶
WithResolver supplies the metadata resolver. Nil selects meta.Default().
func WithRingFrames ¶
WithRingFrames sets the streamer ring size in output frames. Zero selects the streamer default of about 300 ms.
func WithVolume ¶
WithVolume sets the initial gain in [0, 1]. Zero means unity.
type PipelineChanged ¶
type PipelineChanged = session.PipelineChanged
PipelineChanged confirms that a new post-ring effect chain is in force. Stages is how many effects the chain runs after the change.
type Player ¶
type Player interface {
// Effects is the chain editor surface, embedded so every Player is
// directly usable as one. Effects returns the same view.
Effects
// Snapshot returns a cheap, read-only view of the player at one instant.
Snapshot() Snapshot
// Events returns the stream of player events. It never blocks the engine: a
// consumer that falls behind costs the oldest event, counted in
// Snapshot.DroppedEvents.
Events() <-chan Event
// DebugEvents returns the diagnostic stream: per-track codec selection,
// underrun deltas, seek and swap timings, pipeline installs and failures.
// It is separate from Events and costs the engine nothing until it is
// called. A consumer that falls behind costs the oldest record, counted in
// DebugDropped.
DebugEvents() <-chan DebugEvent
// DebugDropped reports how many debug records a slow consumer cost. It is
// the debug stream's counterpart to Snapshot.DroppedEvents.
DebugDropped() int64
// Play replaces the queue with one track and starts it. ref is a track
// reference, not necessarily a filesystem path: it may be any string a
// configured provider claims (see WithProviders). With no providers it is a
// path resolved by the decode registry.
Play(ref string) error
// PlayQueue replaces the queue with refs and starts at the first. Each entry
// is a track reference, as for Play.
PlayQueue(refs []string) error
// PlayIndex starts the queue entry at index, keeping the queue. It is what
// a click on a row in a track list means. An index outside the queue is
// rejected synchronously and changes nothing.
PlayIndex(index int) error
// Next advances to the next queued track; past the last track it stops.
Next() error
// Prev goes back one track, restarting the current one when it is the
// first.
Prev() error
// SetShuffle turns baked shuffle on or off. On, the queue in force is
// replaced with a shuffled permutation and the current track keeps playing;
// advances then follow that order. Off restores the order the last shuffle
// was taken from. It is the queue's order that changes, not a per-advance
// random pick.
SetShuffle(on bool) error
// Shuffled reports whether baked shuffle is in force.
Shuffled() bool
// InsertQueue inserts refs into the queue at index without touching the
// track that is playing, which is what "play next" means. An index at or
// past the end appends. The live track keeps sounding; the inserted refs
// are what the engine reaches when it advances.
InsertQueue(index int, refs []string) error
// InsertQueueAndPlay inserts refs and starts the first of them. With a
// track already sounding it would cut that track off, so it is refused with
// ErrNoLiveTrack and nothing changes; the caller then appends instead.
InsertQueueAndPlay(index int, refs []string) error
// MoveQueue moves one entry to another position without touching the track
// that is playing. Both indices must be in range; the playing index follows
// its ref, so a move around it does not change which track is sounding.
MoveQueue(from, to int) error
// RemoveQueue drops one entry from the queue. Removing a non-active entry
// leaves playback untouched and shifts the active index if needed; removing
// the active track advances or clears to idle if nothing remains.
RemoveQueue(index int) error
// ClearQueue stops playback and empties the queue.
ClearQueue() error
// Queue returns a copy of the current queue, which holds track references
// (for example "ytm:abc123") rather than paths once a provider is in use.
Queue() []string
// Providers lists the names of the providers in effect, in priority order,
// for a UI that shows where audio can come from. The default is the
// built-in list ("Network", then "local").
Providers() []string
// Pause stops the device; it is ignored unless the player is playing.
Pause() error
// Resume restarts a paused device; it is ignored unless the player is
// paused.
Resume() error
// Stop ends playback and keeps the queue, so a later Play resumes from the
// same queue.
Stop() error
// Seek repositions the current track once the device has been paused, so
// the device never reads a half-flushed ring.
Seek(d time.Duration) error
// SetVolume changes the post-ring gain in [0, 1]. It takes effect on the
// next buffer and is safe to call while audio is running.
SetVolume(v float64)
// 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. With no live
// track it just sets the preference the next track uses.
SwapDecoder(name string) error
// SwapBackend forces the named playback backend for the current device,
// reopening the device against the same provider without touching the
// stream. Empty means the default. An unknown name is rejected
// synchronously. With no open device it just sets the preference the next
// device uses.
SwapBackend(name string) error
// Settings reads the mutable configuration in effect.
Settings() Settings
// ApplySettings validates every field before applying any of them: a
// rejected update changes nothing, so a UI can report the error without
// worrying about partial state. It never blocks on disk or the device.
ApplySettings(s Settings) error
// Crossfade returns the track-overlap settings in force.
Crossfade() CrossfadeSettings
// SetCrossfade replaces the track-overlap settings. An out-of-range
// duration is clamped rather than rejected. The change applies to the next
// handoff, so it is safe to call while audio is running.
SetCrossfade(c CrossfadeSettings) error
// Repeat returns the repeat mode in force: stop at the end, wrap the queue,
// or restart the current track. The engine confirms a real change with a
// RepeatChanged event.
Repeat() RepeatMode
// SetRepeat replaces the repeat mode. An unknown mode falls back to
// RepeatOff rather than being rejected, so a caller can send what it holds.
// The change applies at the next end of track and is safe to call while
// audio is running.
SetRepeat(m RepeatMode) error
// Pipeline returns the effect chain in effect.
Pipeline() dsp.Pipeline
// ApplyPipeline validates every stage before applying any of them,
// matching ApplySettings: a rejected update changes nothing. The accepted
// chain is handed to the engine, which confirms it with PipelineChanged.
ApplyPipeline(p dsp.Pipeline) error
// EffectSchema returns the parameter schema for an effect kind, so a UI
// can render controls without building the effect. It returns an error for
// an unknown kind.
EffectSchema(kind string) ([]dsp.Param, error)
// EffectKinds lists the registered effect kinds, sorted.
EffectKinds() []string
// Effects returns the chain editor over this player, the same value the
// embedded Effects methods act on.
Effects() Effects
// Tap returns the visualizer feed. The feed starts publishing on the first
// Read, so holding a Tap without reading it costs the audio path nothing.
Tap() Tap
// Close stops every goroutine and releases the device. It is idempotent
// and safe to call from any goroutine.
Close() error
}
Player is what a UI holds. Every command is non-blocking; the only errors a command returns are immediate validation problems such as an empty queue.
Concurrency: every method is safe to call from any goroutine. A command appends to the engine's inbox under a short-lived mutex and wakes the control loop without blocking, and every slow step runs on its own goroutine, so a UI can drive the Player from whatever goroutine owns its event loop. Close is idempotent and safe to call from any goroutine; it blocks until the engine has stopped.
type RepeatChanged ¶ added in v1.1.0
type RepeatChanged = session.RepeatChanged
RepeatChanged confirms that the repeat mode in force changed. It is emitted by the control loop once the mode actually changes; a same-value set emits nothing.
type RepeatMode ¶ added in v1.1.0
type RepeatMode = session.RepeatMode
RepeatMode is what the player does at the end of a track: stop, wrap the queue, or restart the current track. It is an alias of the engine's type, so a value crossing the boundary needs no conversion.
type Settings ¶
Settings is the subset of configuration that can change while a Player is alive. Everything else is read once by New.
The fields take effect at different moments, which a UI should know:
- Volume applies immediately.
- Decoder and ProbeMode are read when the next track is built, so the track already playing keeps the decoder it started with.
- Backend is read when a device is built. An open device cannot be re-bound, so a backend change lands on the next Play that has to build one.
- Pipeline is applied to the running audio as soon as the engine accepts it, confirmed by a PipelineChanged event. Only its Post half is used; Pre belongs to the streamer.
Changing Decoder or Backend here is for the next build; to change what is playing now, call SwapDecoder or SwapBackend.
type Snapshot ¶
Snapshot is a read-only view of the player at one instant. It is cheap enough to poll every frame.
type State ¶
State is the playback lifecycle. It is an alias of the controller's type, so a value crossing the boundary needs no conversion.
type StateChanged ¶
type StateChanged = session.StateChanged
StateChanged is emitted for every accepted state transition.
type Swapped ¶
Swapped confirms a live decoder or backend change on the current track. Kind is "decoder" or "backend".
type Tap ¶
Tap is the real-time audio feed a visualizer reads. Read copies up to len(dst) mono downmixed frames in time order, never blocks, and reports zero when nothing is buffered.
type TrackChanged ¶
type TrackChanged = session.TrackChanged
TrackChanged is emitted when a new track becomes current.
type TrackEnded ¶
type TrackEnded = session.TrackEnded
TrackEnded is emitted once per track when it reaches its natural end.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package analysis computes information about a file that playback does not need, starting with the waveform a seek bar draws.
|
Package analysis computes information about a file that playback does not need, starting with the waveform a seek bar draws. |
|
cmd
|
|
|
molo
command
Command molo is the headless CLI for the molo engine.
|
Command molo is the headless CLI for the molo engine. |
|
Package core defines the data currency shared by every layer of the player: interleaved float32 PCM at a known frame format, frame-domain positions, and the Module contract that pre- and post-ring processing both satisfy.
|
Package core defines the data currency shared by every layer of the player: interleaved float32 PCM at a known frame format, frame-domain positions, and the Module contract that pre- and post-ring processing both satisfy. |
|
Package decode turns a file path into interleaved float32 PCM frames.
|
Package decode turns a file path into interleaved float32 PCM frames. |
|
Package dsp holds the real-time stages that run after the ring: gain, effects, metering.
|
Package dsp holds the real-time stages that run after the ring: gain, effects, metering. |
|
internal
|
|
|
session
Package session is the player's controller: the only component that owns mutable engine state.
|
Package session is the player's controller: the only component that owns mutable engine state. |
|
Package meta turns a media path into the descriptive metadata a UI shows: tags, cover art and the stream shape.
|
Package meta turns a media path into the descriptive metadata a UI shows: tags, cover art and the stream shape. |
|
Package playback turns a Provider of interleaved float32 frames into sound through a named backend.
|
Package playback turns a Provider of interleaved float32 frames into sound through a named backend. |
|
Package priority raises the process's scheduling priority for audio.
|
Package priority raises the process's scheduling priority for audio. |
|
Package provider maps a track reference to the audio bytes and metadata the engine needs.
|
Package provider maps a track reference to the audio bytes and metadata the engine needs. |
|
Package script builds dsp.Effect implementations from Lua descriptions.
|
Package script builds dsp.Effect implementations from Lua descriptions. |
|
Package stream bridges a decode.Decoder to a real-time consumer through a single-producer, single-consumer ring buffer.
|
Package stream bridges a decode.Decoder to a real-time consumer through a single-producer, single-consumer ring buffer. |