From 55bba19a3f30994082ff778331dfffee542eb5b9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 12 Nov 2026 09:21:18 +0100 Subject: [PATCH] Add experimental feedback-verified Load next preset --- .../media-player-classic/README.md | 48 ++++- .../media-player-classic/companion/HELP.md | 9 +- .../media-player-classic/src/definitions.js | 19 +- .../media-player-classic/src/feedbacks.js | 16 +- .../media-player-classic/src/load-next.js | 88 +++++++++ .../media-player-classic/src/main.js | 53 +++++- .../media-player-classic/src/player.js | 46 ++++- .../test/lifecycle.test.js | 50 ++++- .../test/load-next.test.js | 172 ++++++++++++++++++ 9 files changed, 482 insertions(+), 19 deletions(-) create mode 100644 companion-modules/media-player-classic/src/load-next.js create mode 100644 companion-modules/media-player-classic/test/load-next.test.js diff --git a/companion-modules/media-player-classic/README.md b/companion-modules/media-player-classic/README.md index e677cfb..d4e3e97 100644 --- a/companion-modules/media-player-classic/README.md +++ b/companion-modules/media-player-classic/README.md @@ -97,18 +97,46 @@ with the player, follows seeks, and does not predict wall-clock completion at nonstandard playback speeds. Playback state is MPC's reported state, not proof that frames or audio are physically reaching an output device. -## Loading the next item without playback +## Experimental Load next -The current MPC-HC web API cannot reliably cue the next playlist item in the -player without starting it. Both Next File and the playlist-index command open -the selected item through MPC-HC's normal autoplay path; neither exposes an -open-paused option. Sending Next followed by Stop can briefly play audio/video, -so this module does not offer that sequence as a safe cue preset. +Drag **Load next (experimental)** from **Transport & timing** onto a spare button. +This is a workaround, not a true open-paused command: MPC-HC may briefly display +moving video before Stop takes effect. Test on non-live output first. -To load the next file in MPC-HC itself and keep it at the beginning until Play, -MPC-HC needs an open-paused playlist-selection API, or an additional helper on -the Windows player computer. Selecting a future item only inside Companion -would not preload it in MPC-HC and is not implemented here. +1. Read fresh state and remember the current file and mute setting. +2. Mute if needed and wait for player feedback confirming mute. Never retry a + mute toggle blindly; if mute cannot be confirmed, do not advance. +3. Send Next File (`920`) once, then Stop (`890`) immediately after its HTTP + response, without waiting for a status poll in between. +4. Check about every 50 ms (plus HTTP latency), retrying Stop while not stopped. + Require a different nonempty filename and stopped state continuously observed + for at least 500 ms. Each confirmation phase has a 5-second deadline; an + in-flight request can add its normal 2.5-second timeout. +5. Only then restore the original mute setting and confirm it. A player that + started muted stays muted. + +The button shows **LOADING**, **LOADED NEXT**, or **LOAD FAILED**, following the +main player. `load_next_status` and `load_next_detail` expose the result; +`backup_load_next_status` and `backup_load_next_detail` expose the backup result. +Each targeted player runs independently. The default target is Both; no backup +is required. Main success does not imply backup success—check backup/sync status. + +Repeated presses while running are coalesced. Other module commands are ignored +until the sequence finishes, to prevent Play or Mute from interfering. Direct +MPC-HC control or another connection can still interfere. Reconfiguration and +module shutdown cancel the sequence without attempting to unmute. + +If loading cannot be confirmed, the action attempts a final Stop and does not +restore audio. Check the player before manually unmuting or trying again. If a +network error occurs during the final unmute, its outcome is unknown; the action +reports failure and never blindly repeats the toggle. + +The web status reports a filename, not a playlist-entry identity. Consecutive +entries with the same reported filename, a single-item loop, or reaching the end +without advancing cannot be confirmed and remain muted. A different filename +following the single Next command is the available evidence of advancement; +external playlist changes cannot be distinguished. True preload without any +playback still requires an MPC-HC open-paused API or a helper on the player PC. ## Optional backup player diff --git a/companion-modules/media-player-classic/companion/HELP.md b/companion-modules/media-player-classic/companion/HELP.md index 545c46e..b4fd4c0 100644 --- a/companion-modules/media-player-classic/companion/HELP.md +++ b/companion-modules/media-player-classic/companion/HELP.md @@ -12,7 +12,14 @@ Choose **Transport & timing** in this connection's Presets: - **Stop**: subdued red while playing; full red while stopped. - **Previous / Next**: navigate playlist items (verified command IDs 919/920). These load and start playback; the web API has no reliable open-next-paused - command. A Next-then-Stop sequence can briefly play and is not offered as cueing. + command. +- **Load next (experimental)**: confirm mute, advance once, stop immediately and + retry Stop as needed. Restore the original mute setting only after a different + filename is confirmed stopped for 500 ms. Video may briefly play. Failed + loading leaves audio muted; duplicate filenames cannot be confirmed. Test on + non-live output first. Already-muted players stay muted. Other module commands + are ignored while loading. The button follows the main; backup results are in + `backup_load_next_status` / `backup_load_next_detail`. See the README for limits. - **Mute**: red **MUTED** when the player mute switch is on. - **Pause**: amber while paused. - **Remaining / Elapsed**: live time with a progress bar (passive displays). diff --git a/companion-modules/media-player-classic/src/definitions.js b/companion-modules/media-player-classic/src/definitions.js index ffa6445..5efb1c2 100644 --- a/companion-modules/media-player-classic/src/definitions.js +++ b/companion-modules/media-player-classic/src/definitions.js @@ -1,8 +1,8 @@ import { commands } from './commands.js' import { colors } from './feedbacks.js' -export function actions(send) { - return Object.fromEntries( +export function actions(send, loadNext) { + const definitions = Object.fromEntries( Object.entries(commands).map(([id, name]) => [ id, { @@ -25,6 +25,13 @@ export function actions(send) { }, ]), ) + if (loadNext) + definitions.load_next = { + name: 'Load next (experimental: mute, Next, Stop)', + options: definitions['887'].options, + callback: (action) => loadNext(action?.options?.target ?? 'both'), + } + return definitions } export function presets(label = 'MPC_DEV') { @@ -66,6 +73,14 @@ export function presets(label = 'MPC_DEV') { steps: [{ down: [], up: [] }], feedbacks: [{ feedbackId: 'redundancy', options: {} }], }, + transport_load_next: button( + 'Load next (experimental)', + 'LOAD\nNEXT', + 'load_next', + [{ feedbackId: 'load_next_status', options: {} }], + 12, + 0x243b50, + ), transport_play: button( 'Play — green while playing', '▶\nPLAY', diff --git a/companion-modules/media-player-classic/src/feedbacks.js b/companion-modules/media-player-classic/src/feedbacks.js index 9936bc8..5c0bd98 100644 --- a/companion-modules/media-player-classic/src/feedbacks.js +++ b/companion-modules/media-player-classic/src/feedbacks.js @@ -74,7 +74,7 @@ export function transportBorder(state, image, control) { } } -export function feedbacks(getState, getSync = () => null) { +export function feedbacks(getState, getSync = () => null, getLoadStatus = () => 'idle') { const boolean = (name, callback, color) => ({ type: 'boolean', name, @@ -83,6 +83,20 @@ export function feedbacks(getState, getSync = () => null) { callback, }) return { + load_next_status: { + type: 'advanced', + name: 'Experimental Load next status', + options: [], + affectedProperties: ['text', 'bgcolor', 'color'], + callback: () => { + const status = getLoadStatus() + return { + text: { loading: 'LOADING', ready: 'LOADED\nNEXT', failed: 'LOAD\nFAILED' }[status] ?? 'LOAD\nNEXT', + bgcolor: { loading: colors.amber, ready: colors.blue, failed: colors.red }[status] ?? 0x243b50, + color: status === 'loading' ? colors.dark : colors.white, + } + }, + }, in_sync: boolean('Backup in sync with main', () => getSync()?.status === 'in_sync', colors.green), out_of_sync: boolean('Backup out of sync with main', () => getSync()?.status === 'out_of_sync', colors.red), redundancy: { diff --git a/companion-modules/media-player-classic/src/load-next.js b/companion-modules/media-player-classic/src/load-next.js new file mode 100644 index 0000000..bbc0f1d --- /dev/null +++ b/companion-modules/media-player-classic/src/load-next.js @@ -0,0 +1,88 @@ +import { setTimeout as delay } from 'node:timers/promises' + +// Experimental web-API workaround: Next still autoplays. Never retry Next or +// mute toggles: an HTTP response is not an acknowledgement of player state. +export async function loadNext(player, timing = {}) { + const poll = timing.poll ?? 50 + const settle = timing.settle ?? 500 + const timeout = timing.timeout ?? 5000 + const signal = player.client.abort.signal + const wait = () => delay(poll, undefined, { signal }) + const fresh = async () => { + await player.pending + signal.throwIfAborted() + await player.refresh() + signal.throwIfAborted() + if (!player.state) throw new Error('Player status unavailable; check mute and playback state') + return player.state + } + const command = async (id) => { + signal.throwIfAborted() + await player.client.command(id) + } + const filename = (state) => state.file.replaceAll('\\', '/').toLowerCase() + let advanced = false + try { + const original = await fresh() + if (!original.file || original.state === 'idle') throw new Error('Load a playlist item before using Load next') + const wasMuted = original.muted + if (!wasMuted) await command('909') + let deadline = performance.now() + timeout + while (!(await fresh()).muted) { + if (performance.now() >= deadline) throw new Error('Mute was not confirmed; Next was not sent') + await wait() + } + + advanced = true + await command('920') + // No status request or artificial delay between Next and the first Stop. + await command('890') + deadline = performance.now() + timeout + let candidate = '' + let stableSince = 0 + while (performance.now() < deadline) { + await wait() + const state = await fresh() + if (!state.muted) throw new Error('Mute changed during loading; audio was not restored') + const file = filename(state) + if (file && file !== filename(original) && state.state === 'stopped') { + if (candidate !== file) { + candidate = file + stableSince = performance.now() + } + if (performance.now() - stableSince >= settle) { + if (!wasMuted) { + await command('909') + const restoreDeadline = performance.now() + timeout + while (true) { + const restored = await fresh() + if (filename(restored) !== candidate || restored.state !== 'stopped') { + throw new Error('Player changed while restoring audio; check the player') + } + if (!restored.muted) return restored.file + if (performance.now() >= restoreDeadline) throw new Error('Audio restoration was not confirmed') + await wait() + } + } + return state.file + } + } else { + candidate = '' + if (state.state !== 'stopped') await command('890') + } + } + throw new Error('A different file stopped for 500 ms was not confirmed; audio was not restored') + } catch (error) { + // A lost Next response may still mean it executed. Best-effort Stop is + // idempotent; blind mute toggles or another Next would not be. + if (advanced && !signal.aborted) { + try { + await command('890') + await fresh() + } catch { + /* Keep the original failure. */ + } + } + throw error + } +} diff --git a/companion-modules/media-player-classic/src/main.js b/companion-modules/media-player-classic/src/main.js index c8205b7..9bbcf40 100644 --- a/companion-modules/media-player-classic/src/main.js +++ b/companion-modules/media-player-classic/src/main.js @@ -10,14 +10,27 @@ export const UpgradeScripts = [] export default class MpcInstance extends InstanceBase { async init(config) { - this.setActionDefinitions(actions((id, target) => this.send(id, target))) + this.setActionDefinitions( + actions( + (id, target) => this.send(id, target), + (target) => this.loadNext(target), + ), + ) this.setFeedbackDefinitions( feedbacks( () => this.state, () => this.sync, + () => this.main?.loadStatus, ), ) - this.setVariableDefinitions({ ...variableDefinitions, ...redundancyDefinitions }) + this.setVariableDefinitions({ + ...variableDefinitions, + ...redundancyDefinitions, + load_next_status: { name: 'Main experimental Load next: idle, loading, ready, failed' }, + load_next_detail: { name: 'Main experimental Load next result' }, + backup_load_next_status: { name: 'Backup experimental Load next status (or not_configured)' }, + backup_load_next_detail: { name: 'Backup experimental Load next result' }, + }) await this.configUpdated(config) } @@ -26,6 +39,11 @@ export default class MpcInstance extends InstanceBase { this.sync = comparePlayers(this.main, this.backup, this.syncOptions) this.setVariableValues({ ...variables(this.state), + load_next_status: this.main?.loadStatus ?? 'idle', + load_next_detail: this.main?.loadDetail ?? '', + backup_load_next_status: + this.backup?.loadStatus ?? (this.syncOptions?.configured ? 'unavailable' : 'not_configured'), + backup_load_next_detail: this.backup?.loadDetail ?? '', ...redundancyVariables(this.backup, this.syncOptions, this.sync), }) this.checkAllFeedbacks() @@ -98,13 +116,42 @@ export default class MpcInstance extends InstanceBase { await Promise.allSettled([this.main?.refresh(), this.backup?.refresh()]) } + async loadNext(target = 'both') { + if (this.loadingNext) return this.loadingNext + if (!['both', 'main', 'backup'].includes(target)) return + const players = ( + target === 'main' ? [this.main] : target === 'backup' ? [this.backup] : [this.main, this.backup] + ).filter(Boolean) + this.loadingNext = Promise.allSettled( + players.map(async (player) => { + await player.loadNext() + if (player.active && player.loadStatus === 'failed') + this.log('warn', `Load next (${player === this.main ? 'main' : 'backup'}): ${player.loadDetail}`) + }), + ) + try { + await this.loadingNext + } finally { + this.loadingNext = undefined + } + } + async send(id, target = 'both') { + if (this.loadingNext) { + this.log('warn', 'Command ignored while experimental Load next is running') + return + } if (!['both', 'main', 'backup'].includes(target)) { this.log('warn', `Unknown player target: ${target}`) return } const players = target === 'main' ? [this.main] : target === 'backup' ? [this.backup] : [this.main, this.backup] - await Promise.allSettled(players.filter(Boolean).map((player) => player.send(id))) + await Promise.allSettled( + players.filter(Boolean).map(async (player) => { + if ((await player.send(id)) === false) + this.log('warn', 'Command ignored while experimental Load next is running') + }), + ) } async destroy() { diff --git a/companion-modules/media-player-classic/src/player.js b/companion-modules/media-player-classic/src/player.js index 8ad4386..9c1a99d 100644 --- a/companion-modules/media-player-classic/src/player.js +++ b/companion-modules/media-player-classic/src/player.js @@ -1,4 +1,5 @@ import { MpcClient } from './client.js' +import { loadNext } from './load-next.js' // Each player owns its polling loop so an unavailable backup never delays the main. export class Player { @@ -8,6 +9,9 @@ export class Player { this.changed = changed this.state = null this.active = true + this.commands = new Set() + this.loadStatus = 'idle' + this.loadDetail = '' } refresh() { @@ -20,6 +24,10 @@ export class Player { const state = await this.client.status() if (!this.active) return this.state = state + if (this.loadStatus === 'ready' && (state.file !== this.loadedFile || state.state !== 'stopped')) { + this.loadStatus = 'idle' + this.loadDetail = '' + } // Approximate when the remote snapshot was taken, not when it arrived. this.sampledAt = (started + performance.now()) / 2 this.error = null @@ -37,12 +45,48 @@ export class Player { } failed(error) { + if (this.loadStatus === 'ready') { + this.loadStatus = 'idle' + this.loadDetail = '' + } this.state = null this.error = String(error.cause?.code ?? error.message) this.changed(this) } - async send(id) { + loadNext() { + if (!this.active) return Promise.resolve() + if (this.loading) return this.loading + this.loading = (async () => { + this.loadStatus = 'loading' + this.loadDetail = 'Muting, advancing once, and confirming stopped' + this.changed(this) + try { + await Promise.allSettled([...this.commands]) + this.loadedFile = await loadNext(this) + if (!this.active) return + this.loadStatus = 'ready' + this.loadDetail = 'Different file loaded and stopped; original mute state restored' + } catch (error) { + if (!this.active) return + this.loadStatus = 'failed' + this.loadDetail = error.message + } finally { + this.loading = undefined + if (this.active) this.changed(this) + } + })() + return this.loading + } + + send(id) { + if (this.loading) return Promise.resolve(false) + const pending = this.sendCommand(id) + this.commands.add(pending) + return pending.finally(() => this.commands.delete(pending)) + } + + async sendCommand(id) { if (!this.active) return try { await this.client.command(id) diff --git a/companion-modules/media-player-classic/test/lifecycle.test.js b/companion-modules/media-player-classic/test/lifecycle.test.js index cf3fe13..44cdec4 100644 --- a/companion-modules/media-player-classic/test/lifecycle.test.js +++ b/companion-modules/media-player-classic/test/lifecycle.test.js @@ -47,7 +47,7 @@ test('initialization registers API 2 presets; successful actions recover failed await module.init({ host: '127.0.0.1', port: server.address().port }) await module.send('887') assert.equal(state.statuses.at(-1), InstanceStatus.Ok) - assert.equal(Object.keys(state.actions).length, 138) + assert.equal(Object.keys(state.actions).length, 139) assert.deepEqual(state.sections.flatMap((section) => section.definitions).sort(), Object.keys(state.presets).sort()) assert.equal(state.variables.remaining, '00:48') assert.equal(state.feedbacks.playing.callback(), true) @@ -135,3 +135,51 @@ test('polling discovers external changes, retries failures, and stops on destroy await new Promise((resolve) => setTimeout(resolve, 350)) assert.equal(requests, lastCount) }) + +test('experimental preset runs on main with unavailable backup and exposes independent results', async (t) => { + const data = { ...sample, state: 0 } + const commands = [] + const mainServer = createServer((req, res) => { + const id = new URL(req.url, 'http://localhost').searchParams.get('wm_command') + if (id) { + commands.push(id) + if (id === '909') data.muted = !data.muted + if (id === '920') { + data.file = 'Next.mp4' + data.state = 2 + } + if (id === '890') data.state = 0 + } + res.end(JSON.stringify(data)) + }) + const backupServer = createServer((_, res) => { + res.writeHead(503) + res.end() + }) + await Promise.all( + [mainServer, backupServer].map((server) => new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))), + ) + const { module, state } = instance() + t.after(async () => { + await module.destroy() + for (const server of [mainServer, backupServer]) { + server.closeAllConnections() + server.close() + } + }) + await module.init({ + host: '127.0.0.1', + port: mainServer.address().port, + backup_host: '127.0.0.1', + backup_port: backupServer.address().port, + }) + assert.equal(state.presets.transport_load_next.steps[0].down[0].actionId, 'load_next') + const pending = state.actions.load_next.callback({ options: { target: 'both' } }) + await module.send('887') + await Promise.all([pending, state.actions.load_next.callback({ options: { target: 'both' } })]) + assert.deepEqual(commands, ['909', '920', '890', '909']) + assert.equal(state.variables.load_next_status, 'ready') + assert.equal(state.variables.backup_load_next_status, 'failed') + assert.equal(state.statuses.at(-1), InstanceStatus.Ok) + assert.equal(state.feedbacks.load_next_status.callback().text, 'LOADED\nNEXT') +}) diff --git a/companion-modules/media-player-classic/test/load-next.test.js b/companion-modules/media-player-classic/test/load-next.test.js new file mode 100644 index 0000000..65307af --- /dev/null +++ b/companion-modules/media-player-classic/test/load-next.test.js @@ -0,0 +1,172 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { setTimeout as delay } from 'node:timers/promises' +import { test } from 'node:test' +import { Player } from '../src/player.js' +import { loadNext } from '../src/load-next.js' +import { status } from './fixture.js' + +async function mock(t, handle, initial = {}) { + const data = { ...status, state: 0, ...initial } + const commands = [] + const events = [] + const server = createServer((req, res) => { + const id = new URL(req.url, 'http://localhost').searchParams.get('wm_command') + if (id) { + commands.push(id) + events.push(id) + if (handle?.(id, data, res) === false) return + if (id === '909') data.muted = !data.muted + res.end() + } else { + events.push(data.muted ? 'muted-status' : 'unmuted-status') + res.end(JSON.stringify(data)) + } + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const player = new Player({ host: '127.0.0.1', port: server.address().port }, 5000, () => {}) + t.after(() => { + player.close() + server.closeAllConnections() + server.close() + }) + return { player, data, commands, events } +} +const fast = { poll: 10, settle: 40, timeout: 250 } + +test('Load next waits for confirmed mute, immediately stops, retries delayed autoplay, then restores audio', async (t) => { + let stops = 0 + const { player, commands, events } = await mock(t, (id, data) => { + if (id === '920') + setTimeout(() => { + data.file = 'Next.mp4' + data.state = 2 + }, 35) + if (id === '890' && ++stops >= 3) data.state = 0 + }) + assert.equal(await loadNext(player, fast), 'Next.mp4') + assert.equal(commands.filter((id) => id === '920').length, 1) + assert.equal(commands.filter((id) => id === '909').length, 2) + const next = events.indexOf('920') + assert.ok(events.slice(0, next).includes('muted-status')) + assert.equal(events[next + 1], '890', 'no status request delays the first Stop') + assert.ok(stops >= 3) + assert.equal(player.state.state, 'stopped') + assert.equal(player.state.muted, false) +}) + +test('Load next preserves existing mute and waits through a false stopped snapshot', async (t) => { + const { player, commands } = await mock( + t, + (id, data) => { + if (id === '920') { + data.file = 'Next.mp4' + setTimeout(() => { + data.state = 2 + }, 25) + } + if (id === '890') data.state = 0 + }, + { muted: true }, + ) + await loadNext(player, fast) + assert.ok(commands.filter((id) => id === '890').length >= 2) + assert.ok(!commands.includes('909')) + assert.equal(player.state.muted, true) +}) + +test('unconfirmed mute never advances and toggle is not retried', async (t) => { + const { player, commands } = await mock(t, (id, _, res) => { + if (id === '909') { + res.end() + return false + } + }) + await assert.rejects(loadNext(player, fast), /Mute was not confirmed/) + assert.deepEqual(commands, ['909']) +}) + +test('unchanged filename or failure to stop leaves mute enabled and never skips twice', async (t) => { + for (const changeFile of [false, true]) { + const { player, commands, data } = await mock(t, (id, data) => { + if (id === '920' && changeFile) { + data.file = 'Next.mp4' + data.state = 2 + } + }) + await assert.rejects(loadNext(player, fast), /not confirmed/) + assert.equal(data.muted, true) + assert.equal(commands.filter((id) => id === '920').length, 1) + assert.equal(commands.filter((id) => id === '909').length, 1) + } +}) + +test('lost Next response triggers best-effort Stop without retrying Next or unmuting', async (t) => { + const { player, commands, data } = await mock(t, (id, data, res) => { + if (id === '920') { + data.file = 'Next.mp4' + data.state = 2 + res.writeHead(500) + res.end() + return false + } + if (id === '890') data.state = 0 + }) + await assert.rejects(loadNext(player, fast), /HTTP 500/) + assert.deepEqual(commands, ['909', '920', '890']) + assert.equal(data.muted, true) + assert.equal(data.state, 0) +}) + +test('Player coalesces repeated Load next, excludes normal commands and publishes verified success', async (t) => { + const { player, commands } = await mock(t, (id, data) => { + if (id === '920') { + data.file = 'Next.mp4' + data.state = 2 + } + if (id === '890') data.state = 0 + }) + const pending = player.loadNext() + assert.equal(player.loadNext(), pending) + assert.equal(await player.send('887'), false) + await pending + assert.equal(player.loadStatus, 'ready') + assert.deepEqual(commands, ['909', '920', '890', '909']) +}) + +test('closing a player cancels a load sequence without sending Next or restoring audio', async (t) => { + const { player, commands } = await mock(t, (id, _, res) => { + if (id === '909') { + res.end() + return false + } + }) + const pending = player.loadNext() + while (!commands.length) await delay(5) + player.close() + await pending + await delay(80) + assert.deepEqual(commands, ['909']) +}) + +test('uncertain final unmute is not toggled again and cannot report ready', async (t) => { + let toggles = 0 + const { player, commands } = await mock(t, (id, data, res) => { + if (id === '920') { + data.file = 'Next.mp4' + data.state = 2 + } + if (id === '890') data.state = 0 + if (id === '909' && ++toggles === 2) { + data.muted = false + res.writeHead(500) + res.end() + return false + } + }) + await player.loadNext() + assert.equal(player.loadStatus, 'failed') + assert.equal(commands.filter((id) => id === '909').length, 2) + assert.equal(commands.filter((id) => id === '920').length, 1) + assert.equal(commands.at(-1), '890') +})