/** * Navidrome MCP Server - Playback Engine * Copyright (C) 2025 * SPDX-License-Identifier: AGPL-3.0-or-later */ import type { Config } from '../../config.js'; import { type AudioDevice } from './audio-devices.js'; export declare const REPLACE_PENDING_PROPERTY = "user-data/navidrome-mcp/replace-pending"; export declare const REPLACE_GENERATION_PROPERTY = "user-data/navidrome-mcp/replace-generation"; interface SelectedAudioDevice { id: string; name: string | null; connected: boolean; } export interface MissingAudioOutput { id: string; name: string | null; } export interface AudioDeviceReport { selected: SelectedAudioDevice; output: string | null; devices: AudioDevice[]; source: 'player' | 'probe'; } export interface PlaybackStatus { engineRunning: boolean; mpvPath: string | null; mpvVersion: string | null; volume: number | null; idle: boolean | null; audioDevice: SelectedAudioDevice | null; audioOutputLost: boolean | null; } export interface QueueEntry { index: number; /** Null for any filename the engine did not build, such as a radio stream. */ songId: string | null; /** mpv's per-entry id survives a move, so it tells a shifted entry from a new one. */ entryId?: number; title?: string; artist?: string; album?: string; duration?: number; isCurrent: boolean; isPlaying: boolean; } /** mpv loads metadata only for tracks it touches, so without this, future entries are bare IDs. */ export interface QueueTrackMetadata { songId: string; title?: string; artist?: string; album?: string; /** Seconds, matching mpv's `duration`. */ duration?: number; } /** A caller that must never replace the queue, such as a guest add, gets this instead of a demotion. */ export declare class RadioQueueRefusedError extends Error { constructor(); } /** A guarded removal found its entry playing, and only the host may skip a playing song. */ export declare class QueueEntryStartedError extends Error { constructor(entryId: number); } /** An mpv without user-data, or a replace from a release that never marks one, reads as no replace. */ export interface ReplaceMarks { generation: number; pending: boolean; } /** Any entry without a song id counts as radio. */ export declare function holdsRadioStream(entries: readonly QueueEntry[]): boolean; export type StateChangeEvent = { kind: 'property'; name: string; data: unknown; } | { kind: 'queue'; } | { kind: 'attach'; } | { kind: 'message'; args: string[]; } | { kind: 'visualizer'; }; type StateChangeHandler = (event: StateChangeEvent) => void; declare class PlaybackEngine { private static instance; private config; private mpvBinary; private ipcPath; private ipc; private startPromise; private attachPromise; private mpvVersion; private shuttingDown; private readonly propertyCache; private queueGeneration; private mutationLock; private controlledMpv; private pendingSpawn; private readonly filenameCache; private readonly metadataCache; private liveSongIds; private readonly stateChangeHandlers; private visualizerWanted; private visualizerKeepsInSync; private visualizerPending; private visualizerRefusal; private playbackRestarts; private visualizerSyncChain; private audioDeviceSource; private saveAudioDevice; private audioOutputWasLost; private selectedDeviceWasConnected; private lastListedSelection; private replacingDeviceId; private lostOutputPause; private constructor(); static getInstance(): PlaybackEngine; /** A null clears the config, so a runtime with playback off never streams with an earlier runtime's settings. */ configure(config: Config | null): void; /** * Every engine adds the filter to an mpv it spawns, so the first track plays through it. Only an * engine with `keepInSync` changes it later, so two processes that read the setting differently * never undo each other. */ setVisualizerSource(source: () => boolean, options?: { keepInSync?: boolean; }): void; syncVisualizerFilter(): Promise; isVisualizerUnsupported(): boolean; /** * Read at each spawn, so a device saved after this process started applies. `save` stores the new * id when Windows re-registers the saved device. */ setAudioDeviceSource(source: () => Config['playbackAudioDevice'], options?: { save?: (device: AudioDevice) => boolean; }): void; isRunning(): boolean; /** A spawn still connecting counts, since its detached child outlives an exit without quitMpv. */ hasControlledMpv(): boolean; /** * Never spawns, so a read after an MCP restart re-attaches to a running mpv without starting an * empty one. It never rejects, and the caller checks isRunning() after. */ ensureAttached(): Promise; ensureRunning(): Promise; pause(): Promise; resume(): Promise<{ outputMissing: MissingAudioOutput | null; }>; setVolume(level: number): Promise; /** `entryIds` lists the mpv ids of the loaded entries in load order, leaving out any id mpv never reported. */ enqueue(songIds: readonly string[], mode: 'replace' | 'append', metadata?: ReadonlyArray, options?: { refuseRadioQueue?: boolean; }): Promise<{ demoted: boolean; outputMissing: MissingAudioOutput | null; entryIds: number[]; }>; private loadEntry; /** * An older mpv answers a loadfile without the entry id. Each stream URL carries a fresh * auth salt, so its filename names one entry in the playlist. The songs already loaded, so a * failed read leaves those ids out instead of failing the enqueue. */ private resolveEntryIds; /** A foreign filename yields a null songId, not an error, since any client can load anything. */ getQueue(): Promise; /** Back-fills metadata for entries the engine never saw, such as after an attach. */ ingestQueueMetadata(metadata: ReadonlyArray): void; private ingestMetadata; /** Uses mpv `stop`, since `playlist-clear` keeps the playing entry and its audio. */ clearQueue(): Promise; /** * Always replaces the entire queue, as Navidrome's web UI does, since an infinite stream among * finite tracks breaks skip, queue position and scrobbling. */ enqueueRadio(streamUrl: string, stationId: string): Promise<{ outputMissing: MissingAudioOutput | null; }>; getRadioStationTag(): string | null; private writeUserData; private readUserData; private raiseReplaceGeneration; private readGeneration; /** * Live reads, since the observed values can lag a mark another process just wrote. The pending * mark is read first, since a replace raises the generation before it clears the pending mark. */ readReplaceMarks(): Promise; /** A live read of the generation alone. Zero when unset or when mpv is not attached. */ readReplaceGeneration(): Promise; /** Reads the live playlist, since the observed `playlist-count` can lag a load that just finished. */ hasRadioStream(): Promise; /** A live read, since the observed `pause` can lag a set_property sent just before. Null when unknown. */ readPaused(): Promise; getQueueGeneration(): number; /** * The playing track keeps playing and moves to index 0, so the queue top shows what is audible. * The position is read fresh, since the observed `playlist-pos` can lag the shuffle. */ shuffleQueue(): Promise; /** * The web remote's shuffle restarts from the top, while shuffleQueue keeps the playing track for * shuffle_play_queue. */ shuffleQueueFromTop(): Promise; /** mpv tracks the play head by entry, not by index, so a move never changes what is playing. */ moveQueueEntry(from: number, to: number): Promise; /** mpv starts the next entry when the current one is removed. */ removeQueueEntry(index: number): Promise; /** * The entry is checked and resolved inside the lock, since a track change or a move before it would * start or shift the entry. Returns false when the entry is gone or now names another song. * `refuseStarted` throws QueueEntryStartedError while the entry is current and not paused. * It never spawns, since a new mpv instance cannot hold the entry. */ removeQueueEntryById(entryId: number, options?: { songId?: string; refuseStarted?: boolean; }): Promise; /** `force` stops playback on the last entry, where the default `weak` does nothing. */ next(): Promise; /** * Restarts the track on the first entry, where `playlist-prev` does nothing and * `playlist-prev force` stops playback. */ previous(): Promise; seek(seconds: number, mode: 'absolute' | 'relative'): Promise; /** * mpv stops playback on an index past the end, so the tool layer checks the bound first. No queue * event is emitted, since mpv's `playlist-pos` event reaches subscribers. */ jumpToQueueEntry(index: number): Promise<{ outputMissing: MissingAudioOutput | null; }>; /** * Live reads, since a cached property event can lag a loadfile sent just before. mpv reports -1 * with no current entry. */ readQueueState(): Promise<{ position: number; count: number; }>; getCachedProperty(name: string): unknown; /** * Events are not buffered, so a subscriber reads the getters for a baseline. A long-lived * subscriber, such as an SSE client, must call the returned unsubscribe to avoid a leak. */ onStateChange(handler: StateChangeHandler): () => void; getStatus(): PlaybackStatus; /** Never spawns mpv. Without a running mpv the devices come from a headless probe of the binary. */ describeAudioDevices(): Promise; /** Never spawns mpv, and returns false when none runs. The pause state stays as it is. */ selectAudioDevice(id: string): Promise; songIdForPath(path: string): string | null; /** Matches the path, not the configured origin, so songs loaded before a URL change parse. */ private parseSongIdCached; /** Without `mpv-version`, it falls back to the client API version, or null if neither answers. */ private readMpvVersion; broadcastMessage(args: string[]): Promise; private requireIpc; /** A throwing handler is skipped, so one dead SSE client cannot deny notifications to others. */ private emitStateChange; /** mpv cannot compute auth, so salted-MD5 params ride in the URL, which omits the password. */ private buildStreamUrl; /** The stored lock swallows rejections, so one failed task does not poison the chain. */ private withMutationLock; private startOrAttach; /** Concurrent callers share one attach, so no two connections each relay every event. */ private attachExistingShared; private tryAttachExisting; /** A failed spawn kills its child, since a detached orphan mpv would hold the audio device. */ private spawnAndConnect; /** * Primes the cache, since observe's initial emits can arrive after its replies. The change * handler registers before observe_property, so mpv's initial emit is the latest write. */ private installObservers; private queueVisualizerSync; private applyVisualizerFilter; private installVisualizerFilter; /** Undefined when the check outlasts `waitMs`. */ private awaitVisualizerCheck; private checkLiveBuild; private setVisualizerRefusal; private isSafeForFilterChange; private readVisualizerWanted; private isIdleOrPaused; /** * Written even for a device mpv does not list, so mpv opens the null output and never a different * speaker. A device re-registered under a new id is matched by name. An attach skips this, since * the spawning process applied it. */ private applySavedAudioDevice; private onAudioOutputChange; private pauseOnLostOutput; /** A twin that left the list before the selected device did is still a different output. */ private rememberListedSelection; private findReplacement; /** * The pause moves to the new id before the write, so the write's own event can resume it. A failed * write leaves the lost device selected, so it gets the pause a plain loss gets. */ private adoptReplacementDevice; /** Only a saved choice is updated, so a device picked while no store exists stays unsaved. */ private storeReplacementDevice; /** * mpv keeps a returned device on its null output until the output is re-opened. Playback resumes * only when this engine paused for that device moments ago, since a longer outage may be on purpose. */ private recoverReturnedOutput; /** * A loss while paused raised no pause, and mpv sends no new output event when playback starts. * The live read keeps a stale cached `null` output from pausing an output a re-open restored. */ private pauseOnStartOverLostOutput; private readCachedAudioOutput; private readCachedAudioOutputValues; /** A rejected `current-ao` read means no output is open, which is not a loss. */ private readLiveAudioOutput; /** Reads live values, since the cache can lag a device change. */ private checkAudioOutput; /** * mpv ignores a write of the value it holds, so a named device is re-opened through `auto`. No * documented write re-opens `auto` itself, so it takes `ao-reload`. */ private reopenAudioOutput; private describeSelectedDevice; private savedDeviceName; private readAudioDeviceSource; /** * A spawn still connecting is killed directly, since waiting for it can outlast the caller's exit * and leave its detached child running. */ quitMpv(): Promise; /** * Leaves mpv running, so playback persists across restarts. Subscribers are dropped and must * subscribe again. */ shutdown(): void; } export declare const playbackEngine: PlaybackEngine; export {}; //# sourceMappingURL=playback-engine.d.ts.map