Skip to main content

@afkcodes/timbre-player

Classes

ClassDescription
ContentUriResolverRewrites Android content:// URIs into fd:// URLs mpv can open, once per URI, for the life of the player.
PlayerThe typed audio player.
PlayerErrorExceptionAn Error subclass carrying a PlayerError, so that typed information survives throw/await.
SourceResolverControllerOwns one player's source resolver: the function itself, the in-flight de-duplication, the ahead-of-time resolution, and the answers to mpv.
VisualizerControllerThe lazy, reference-counted owner of one player's audio visualizer.

Interfaces

InterfaceDescription
AudioFilterOne entry of an mpv audio filter chain.
AudioFilterParamChangeOne af-command: which labelled entry, which sub-option, its new value.
ChapterChangedEventPayload of the chapterChanged event.
ChapterEntryOne chapter of the current entry, as read from the chapter-list node property.
CommonMetadataThe tags a now-playing screen needs, normalised across tag formats.
CompressorOptionsAudioFilters.compressor options (ffmpeg acompressor).
ContentUriOpenerWhat ContentUriResolver needs from the platform. One method to open, one to close.
CrossfeedOptionsAudioFilters.crossfeed options.
DisposedErrorThe player (or its underlying mpv core) has already been destroyed.
DynamicNormalizerOptionsAudioFilters.dynamicNormalizer options (ffmpeg dynaudnorm).
EndFileEventA playlist entry stopped playing (MPV_EVENT_END_FILE).
EqualizerThe equaliser: its live state, and every operation an EQ screen performs on it.
EqualizerBandOne slider of the equaliser: the ISO octave centre it sits on, and where the user has it.
EqualizerGainRangeInclusive slider bounds, in dB.
EqualizerOptionsAudioFilters.equalizer options.
EqualizerPresetA named equaliser curve: one gain in dB per band of EQUALIZER_BANDS.
EqualizerPresetChainOptionsOptions for equalizerPresetChain.
EqualizerSettingsEverything about an equaliser worth surviving a process death: whether it is on, the curve it is set to, and the curves the user saved.
EqualizerStorageWhere an equaliser is written. Injected, structurally typed, and never depended on — the same two-method shape as @afkcodes/timbre-media-session's MediaSessionStorage, deliberately, so an app can hand both libraries the same object.
GraphicEqualizerOptionsAudioFilters.graphicEqualizer options.
InvalidStateErrorA call was made in a state that does not allow it (e.g. double initialize).
LimiterOptionsAudioFilters.limiter options (ffmpeg alimiter).
LoadFailedErrorThe source could not be opened at all (missing file, refused connection).
LoadOptionsOptions for Player.load.
LoadPlaylistOptionsOptions for Player.loadPlaylist.
LogEventAn mpv log line (MPV_EVENT_LOG_MESSAGE).
LoopRawThe raw loop-file / loop-playlist strings behind PlayerState.loop.
LoudnessNormalizationOptionsOptions for Player.setLoudnessNormalization.
LoudnormOptionsAudioFilters.loudnorm options (ffmpeg loudnorm, EBU R128).
MilestoneA milestone that has been reached, exactly once per playthrough.
MpvClientA thin, complete binding over one mpv_handle (one mpv_create() core).
MpvEventOne event from the mpv event loop, already translated out of mpv_event.
NetworkErrorPlayback of a network source failed part-way: a premature EOF, a dropped connection, or a stream that never delivered decodable data.
NetworkReconnectOptionsFFmpeg's own HTTP reconnection, wired through mpv's stream-lavf-o.
ObservedPropertyOne entry of the observation table: an mpv property name plus the MpvFormat it is observed in.
PassOptionsAudioFilters.lowpass / AudioFilters.highpass options.
PlaybackRestartEventPlayback restarted after a seek or after loading finished (MPV_EVENT_PLAYBACK_RESTART). This is the point at which time-pos is meaningful again, so it is the primary position-anchor discontinuity.
PlayerErrorInfoExtra facts about an error event, beyond the typed error itself.
PlayerEventMapDiscrete events, as opposed to the whole-state subscription.
PlayerOptionsOptions for Player.create.
PlayerStateOne immutable snapshot of everything the player knows.
PlaylistAddOptionsOptions for PlaylistApi.add.
PlaylistApiQueue manipulation, backed by mpv's own playlist (which is what makes gapless transitions gapless — the next entry is demuxed before the current one ends).
PlaylistEntryOne entry of mpv's playlist, as read from the playlist node property.
PlaylistPositionWhere we are in mpv's playlist.
PositionAnchorThe fixed point from which projectPosition extrapolates.
PositionAnchorMsThe same anchor in the units every remote surface speaks: milliseconds.
PrefetchActivempv is holding an opened-early next entry — the current track's end is going to be gapless. Carries what prefetchStarted carried, plus when it fired.
PrefetchIdleNo prefetch is in flight. The state usePrefetchStatus starts in, returns to at every boundary, and stays in forever on binaries without the prefetch hook (see the event's own docs for that honesty).
PrefetchStartedEventmpv has just started opening the next playlist entry ahead of time.
ProgressWhat useProgress returns.
PropertyEventA property observation changed (or became unavailable).
QueueChangedEventPayload of the queueChanged event.
RawMpvErrorAnything mpv reported that this layer does not classify further.
ReducerContextEverything the reducer needs that is not carried by the event itself.
ReplayGainOptionsLoudness normalisation from the ReplayGain tags embedded in a file.
RetryingEventPayload of the retrying event.
RetryOptionsGive a failed entry another go before the queue moves past it.
RnMediaContentSourceTurns an Android content:// URI into a file descriptor mpv can read.
RnMediaScreenStateWhether the device's display is currently on ("interactive"), and a notification when that changes.
ScreenStateSourceA source of truth for "can anything this app draws actually be seen".
SeekCompletedEventPayload of the seekCompleted event.
SeekEventA seek was initiated (MPV_EVENT_SEEK). Position is not yet valid.
SeekStartedEventPayload of the seekStarted event.
ShelfOptionsAudioFilters.bass / AudioFilters.treble options.
ShutdownEventThe core is shutting down (MPV_EVENT_SHUTDOWN). No further events follow.
SourceOptionsPer-source options shared by Player.load, Player.loadPlaylist and PlaylistApi.add — everything that becomes a loadfile per-file option.
SourceResolutionRequestmpv is about to open a source and does not know its concrete URL yet.
SourceResolverOptionsWhat SourceResolverController needs from its owner.
StartFileEventmpv began loading a playlist entry (MPV_EVENT_START_FILE).
TrackChangedEventPayload of the trackChanged event.
TrackChangeReadsThe file-scoped values the Player reads once when the playlist cursor moves.
TrackEndedEventPayload of the trackEnded event.
UnsupportedErrorThe operation is not implemented by the audio core — currently only attachVideoOutput/detachVideoOutput, which the future video plugin owns.
UnsupportedFormatErrormpv could not demux/decode the source: no matching demuxer or codec.
UseEqualizerOptionsOptions for useEqualizer.
UsePlayerOptionsOptions for usePlayer.
UsePlayerResultWhat usePlayer returns.
UseVisualizerResultWhat useVisualizer returns.
VisualizerCapabilitiesWhat the visualizer can deliver, probed from the linked libmpv rather than assumed.
VisualizerCaptureOne analysed window of the audio mpv last handed to the audio device.
VisualizerDecodeStatePer-subscription state the smoothing and the auto-gain need between frames.
VisualizerFrameOne decoded frame, ready to paint.
VisualizerOptionsTuning for VisualizerController.subscribe.
VolumeOptionsAudioFilters.volume options.

Type Aliases

Type AliasDescription
AudioChannelModeWhich channel layout the output is forced to — the typed subset of mpv's --audio-channels this library exposes.
AudioFilterOptionOne key=value pair of a filter's sub-options, in the order it will be written. A tuple rather than an object because the compiled string is part of this module's contract and must be deterministic.
BiquadWidthTypeHow a biquad filter's width is interpreted (ffmpeg's width_type/t).
BuiltInSourceRewriteA rewrite this library performs itself, before and after the app's resolver.
EndFileOutcomeHow a playlist entry stopped, as classified from mpv's end-file event.
EqualizerPresetIdIdentifier of a built-in preset.
EqualizerRestoreResultWhat parseEqualizerSettings found. A typed result, never a throw: a corrupt record is an ordinary runtime condition (a half-written file, an app downgrade, a user clearing storage), and an app whose EQ screen has to try/catch its cold start will eventually not.
GaplessAudioModeHow hard mpv should try to keep the audio device open across a playlist entry change — mpv's `--gapless-audio=<no
HttpHeadersHTTP request headers to send for one source, as a plain object.
LoopModeRepeat behaviour, mapped onto mpv's loop-file / loop-playlist.
MetadataA read-only view of the current entry's tag map — mpv's metadata property.
MpvClientFactoryA factory that produces a fresh, uninitialised MpvClient.
MpvEndFileReasonmpv_end_file_reason. unknown covers reason values added by future mpv releases.
MpvEventKindDiscriminator of MpvEvent.
MpvFormatThe mpv format a property is observed/read in.
MpvLogLevelmpv_log_level minus no/none (which are never delivered as messages).
MpvPropertyValueThe value of an observed/read property, in its observed MpvFormat.
PlayerErrorThe typed error taxonomy of @afkcodes/timbre-player.
PlayerErrorCodeMachine-readable classification of a PlayerError.
PlayerEventA proper TypeScript discriminated union over the flat MpvEvent struct that crosses the Nitro boundary.
PlayerEventNameName of a discrete event.
PlayerLogLevelmpv log levels the core can be asked for, plus 'no' to silence logging.
PlayerStateSelectorA pure projection of PlayerState down to what a component needs.
PlayerStatusCoarse lifecycle of a player.
PositionDiscontinuityReasonWhy the playback position jumped — the two causes this library can tell apart from mpv's own events, and no more.
PrefetchStatusWhat usePrefetchStatus returns: a discriminated union on active, so status.uri only exists where it means something.
QueueChangeReasonWhat this library knows about a QueueChangedEvent.
ReplayGainModeWhich ReplayGain tag set to honour, mapped 1:1 onto mpv's replaygain option (`--replaygain=<no
RetryableWhether repeating the identical operation could plausibly succeed with nothing else changed.
SourceResolverTurns the logical URI in a playlist into the concrete URL mpv should open.
UnsubscribeUnsubscribes a listener. Safe to call more than once.
VisualizerListenerCalled once per decoded frame.
VisualizerUnsubscribeRemoves a visualizer subscription. Safe to call more than once.

Variables

VariableDescription
AGC_SILENCE_DBBand power below which VisualizerOptions.autoGain stops adapting.
AUDIO_FILTER_RUNTIME_PARAMSThe sub-options that can be changed on a running filter, per filter name.
AudioFiltersFactories for the audio filters this library ships bindings for.
BUFFERED_POSITION_STEPHow far PlayerState.bufferedPosition must move before the reducer publishes it, in seconds.
BUFFERING_PERCENT_STEPHow far PlayerState.bufferingPercent must move before the reducer publishes it, in percentage points.
CONTENT_URI_FD_LIMITHow many descriptors one player keeps open at once.
CONTENT_URI_SCHEMEThe scheme Android's storage picker, MediaStore and every SAF provider use.
DEFAULT_CACHE_SECSDefault --cache-secs, i.e. how far ahead the demuxer is allowed to read on a network stream.
DEFAULT_EQUALIZER_GAIN_RANGE_DBDefault bounds for a band slider: ±12 dB.
DEFAULT_EQUALIZER_STORAGE_KEYDefault storage key. Namespaced so it cannot collide with the app's own, and distinct from the media-session key so one engine can hold both.
DEFAULT_LOUDNESS_TARGET_LUFSDefault integrated-loudness target of Player.setLoudnessNormalization, in LUFS. See LoudnessNormalizationOptions.targetLufs for why −16 and not ffmpeg's −24.
DEFAULT_MILESTONESDefault marks: the scrobbling/mark as played set.
DEFAULT_PROGRESS_INTERVAL_MSDefault re-render period of useProgress, in milliseconds.
DEFAULT_RECONNECT_DELAY_MAX_SECONDSDefault NetworkReconnectOptions.maxDelaySeconds.
DEFAULT_RESOLVER_TIMEOUT_MSDefault resolverTimeoutMs: how long a play-time miss may hold mpv's core.
DEFAULT_RESOLVER_TTL_MSDefault resolverTtlMs: how long one resolution stays usable.
DEFAULT_RESTART_THRESHOLD_SECONDSThe default number of seconds into an entry after which PlaylistApi.previous restarts it instead of going back.
DEFAULT_RETRY_MAX_ATTEMPTSDefault RetryOptions.maxAttempts.
DEFAULT_USER_AGENTDefault HTTP User-Agent.
DEFAULT_VISUALIZER_FPSDefault frame rate requested by VisualizerController.subscribe.
EQUALIZER_BAND_COUNTNumber of bands in an EqualizerPreset.
EQUALIZER_BANDSThe ten ISO octave band centres, in Hz, low to high.
EQUALIZER_LIMITER_LABELmpv filter label of the tail limiter of an editable chain (EqualizerPresetChainOptions.editable).
EQUALIZER_PREAMP_LABELmpv filter label of the pre-amp entry of an editable chain (EqualizerPresetChainOptions.editable).
EQUALIZER_PRESET_LISTThe built-in presets in display order: Flat first, then alphabetical by name — which is the order a picker should show them in.
EQUALIZER_PRESETSEvery built-in preset, keyed by EqualizerPresetId.
EQUALIZER_SCHEMA_VERSIONVersion stamped into every record and required on the way back in.
GRAPHIC_EQUALIZER_BANDSCentre frequencies of superequalizer's 18 bands, in Hz.
HTTP_HEADER_FIELDS_OPTIONThe mpv option a HttpHeaders map compiles to.
LIVE_EOF_BUDGET_RESET_SECONDSHow long a live entry must play, after a RetryOptions.retryLiveEof re-attempt, before its attempt budget starts over.
LOUDNESS_NORMALIZATION_LABELThe mpv filter label of the managed loudness-normalization entry.
MANAGED_FILTER_LABEL_PREFIXThe label prefix this library reserves for the af entries it manages.
MPV_VOLUME_SCALEmpv's volume property is a percentage: 100 is unattenuated output.
MpvPropertympv property names this library observes, as string constants so that the reducer's switch and the observation table can never drift apart.
OBSERVED_PROPERTIESEvery property the Player observes, with the format it observes it in. This is the complete set — time-pos is deliberately absent (see the position-projection contract in docs/specs/player-core.md §3).
VISUALIZER_DEFAULTSDefaults for every VisualizerOptions field.

Functions

FunctionDescription
assertValidAudioFiltersValidate a whole chain before it is written.
classifyEndFileClassify an end-file event into a natural end, a deliberate stop, a playlist redirect, or a typed failure.
clearPlayerErrorDrop a settled error on request, leaving every other field alone.
compileAudioFiltersCompile a filter chain into the string mpv's af property takes.
compileHttpHeaderFieldsCompile a header map into one http-header-fields option value.
createDecodeStateA fresh VisualizerDecodeState for bands bands.
createInitialStateThe state of a freshly created, not-yet-loaded player.
createMpvClient@afkcodes/timbre-player — a React Native audio player built on libmpv.
decodeVisualizerFrameTurn one native capture into a paintable VisualizerFrame.
defineEqualizerPresetBuild a custom preset from your own band gains.
diffAudioFilterParamsWork out whether one chain can be turned into another in place.
disposedErrorThe disposed error this library raises for use-after-destroy().
equalizerBandLabelmpv filter label of one band of an editable chain (EqualizerPresetChainOptions.editable) — rnmedia_eq_1000 for the 1 kHz band.
equalizerPresetChainTurn a preset into a safe, ready-to-apply filter chain.
escapeAfParamEscape one filter sub-option key or value the way mpv itself does.
escapeSubparamEscape one sub-option key or value the way mpv itself does.
getContentUriOpenerThe platform's content:// opener, created on first use.
getScreenStateSourceThe installed ScreenStateSource, creating the native one on first use.
isContentUriWhether uri is an Android content:// URI.
isMetadataPropertyWhether a property change means "the current entry's metadata changed".
isNetworkUriWhether a source URI is fetched over the network.
isPositionDiscontinuityWhether an event invalidates the position anchor badly enough that the Player should spend one synchronous time-pos read on it.
isRetryableErrnoWhether a bare MPV_ERROR_* number describes a condition that could clear on its own — the code: 'mpv' half of Retryable.
metadataByKeyPropertyThe property that yields one metadata value by tag name.
metadataKeyPropertyThe property that yields the key of the index-th metadata entry.
metadataValuePropertyThe property that yields the value of the index-th metadata entry.
parseEqualizerSettingsRead back what serializeEqualizerSettings wrote.
peakResponseDbThe true peak of a curve's combined magnitude response, in dB.
playlistFilenamePropertyThe property that yields the logical URI of the index-th playlist entry.
projectPositionProject the current playback position from state's anchor.
reducePlayerStateThe pure state reducer: (state, event, context) → state.
resolveVisualizerOptionsResolve user options against VISUALIZER_DEFAULTS, clamping every field into a range the maths below is total over.
serializeEqualizerSettingsTurn settings into the exact string parseEqualizerSettings reads back.
setContentUriOpenerReplace the platform opener.
setScreenStateSourceReplace the display-state signal.
toCommonMetadataNormalise a raw mpv tag map into CommonMetadata.
toPlayerErrorMap anything thrown by the native MpvClient (or by this library) onto the typed PlayerError taxonomy.
toPlayerEventTranslate one flat native MpvEvent into the PlayerEvent discriminated union.
toPlayerEventsTranslate a whole native batch, dropping malformed entries.
toVisualizerErrorMap a throw from the native visualizer engine onto the typed taxonomy.
useEqualizerA ten-band equaliser as one hook: the curve, the presets, the persistence, and the one af write that puts it on the signal.
useMilestonesFire a callback once when playback passes 25 % / 50 % / 75 % / 90 % of an entry — the scrobbling primitive, forward-only and once per playthrough.
usePlayerCreate a Player on mount and destroy it on unmount.
usePlayerStateSubscribe to the whole player state.
usePrefetchStatusThe player's prefetchStarted signal as renderable state: active from the moment mpv opens the next entry early, cleared at the boundary that consumes it.
useProgressA ticking view of the playback position.
useVisualizerSubscribe a component to the player's visualizer for as long as it is mounted.
utf8LengthUTF-8 byte length. mpv's %N% prefix counts bytes, not UTF-16 code units.
withResyncedAnchorRe-anchor the projection on an authoritative position, without touching any other field.