From 290511c23ca5e781034c2e7a64aaa62fa73ca941 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 12 Nov 2026 09:37:54 +0100 Subject: [PATCH] Add configurable playlist item loading and ten numbered presets --- .../media-player-classic/README.md | 40 ++++- .../media-player-classic/companion/HELP.md | 16 ++ .../media-player-classic/src/client.js | 27 ++++ .../media-player-classic/src/definitions.js | 43 ++++- .../media-player-classic/src/feedbacks.js | 21 ++- .../media-player-classic/src/load-item.js | 38 ++++- .../media-player-classic/src/main.js | 1 + .../test/lifecycle.test.js | 2 +- .../test/playlist.test.js | 152 ++++++++++++++++++ 9 files changed, 328 insertions(+), 12 deletions(-) create mode 100644 companion-modules/media-player-classic/test/playlist.test.js diff --git a/companion-modules/media-player-classic/README.md b/companion-modules/media-player-classic/README.md index b8f5ea3..6bbba2e 100644 --- a/companion-modules/media-player-classic/README.md +++ b/companion-modules/media-player-classic/README.md @@ -97,7 +97,7 @@ 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. -## EXPERIMENTAL — Load next / Load previous: not a guaranteed cue/preload +## EXPERIMENTAL — Load next / previous / playlist item: not a guaranteed cue/preload > **EXPERIMENTAL: these buttons deliberately start the next or previous video, > then try to stop it. They do not load an item paused, and cannot guarantee that @@ -190,6 +190,44 @@ following the single navigation command is the available evidence of movement; 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. +### Load a specific playlist item + +**Load playlist item 1–10** presets are in **Experimental**. They use the same +experimental mute → select → Stop → verify → restore-mute sequence and the same +two-second result display. **Last load result** retains the outcome as **#1**, **#2**, +and so on; `load_result_direction` contains `item_1`, `item_2`, etc. + +The action is reusable, not limited to ten items. Duplicate a numbered preset +and edit **Playlist item number (1 = first)** in its action and **Load playlist +item status** feedback to the same number. Update its base label too if desired. +Numbers from 1 to 10000 are supported, subject to the actual playlist length. +The feedback renders the chosen number; preserve it when customizing the button. + +These are **playlist positions, not saved file identities**. Reordering a playlist +changes what a numbered button loads. Presets remain available even if the +playlist has fewer than ten entries. Each press fetches `/playlist.json` and +rejects absent items before muting or navigating. An unsupported or malformed +playlist response also aborts without starting the sequence; relative Load +next/previous do not require this endpoint. Names are not embedded in presets, +so a copied button cannot silently retain an old filename label after reordering. + +Each player validates its own playlist and selects the same item number. Keep +main and backup playlists in matching order. The action does not map filenames +between players, and main success does not imply backup success. + +Indexed loading uses MPC-HC's `wm_command=-3&index=N` with zero-based numbering +internally. It checks the selected index as well as stopped state and a changed +filename, and aborts if the playlist entries/labels/durations change during the +sequence. A selected index can update before the media has loaded, so it is not +sufficient evidence by itself. Different entries with the same reported filename +still cannot be confirmed safely and leave audio muted after timeout. + +If the requested item is already selected with media loaded, it is stopped in +place without reopening it; the original mute setting is preserved. If the +player is idle, it opens the selected item instead. **Indexed loading can briefly +play video too. It remains experimental and needs real-player testing.** Failed +validation before muting leaves the original audio setting untouched. + ### Before considering this usable for your show Test stopped and playing starting states; initially muted and unmuted audio; diff --git a/companion-modules/media-player-classic/companion/HELP.md b/companion-modules/media-player-classic/companion/HELP.md index 30e7fa9..a557447 100644 --- a/companion-modules/media-player-classic/companion/HELP.md +++ b/companion-modules/media-player-classic/companion/HELP.md @@ -54,6 +54,22 @@ is based on reported state, not proof of silent or seamless preload. Test on non-live output and read the README's experimental section before use. Re-add existing copied presets to remove the EXP label; linked presets update. +### Load playlist items 1–10 + +The **Experimental** folder also contains ten numbered **Load playlist item** +presets. To make another, duplicate one and set its action's item number and +**Load playlist item status** feedback's item number to match (1 = first). +The action accepts 1–10000, but checks the actual playlist before muting. +Missing items or unavailable `/playlist.json` abort without navigation. + +Numbers follow playlist order, not file identity; keep main/backup orders aligned. +The same experimental brief-playback limitation applies. Selection is verified +by index, changed filename, and stable stopped state; playlist changes abort. +An already selected, loaded item is stopped without reopening. Duplicate reported +filenames across different entries cannot be confirmed. Last load result shows +**#N**, and `load_result_direction` uses `item_N`. Results reset after two seconds +on the numbered buttons and remain on the last-result display. + ### Load status display Load previous/next show their result for two seconds, then return to their normal diff --git a/companion-modules/media-player-classic/src/client.js b/companion-modules/media-player-classic/src/client.js index dd6bc75..e23a8f9 100644 --- a/companion-modules/media-player-classic/src/client.js +++ b/companion-modules/media-player-classic/src/client.js @@ -37,6 +37,33 @@ export class MpcClient { await this.request(`/command.html?wm_command=${id}`) } + async playlist() { + const data = JSON.parse(await this.request('/playlist.json', true)) + if ( + !data || + !Array.isArray(data.items) || + !Number.isInteger(data.active) || + data.active < -1 || + data.active >= data.items.length || + data.items.some( + (item, index) => + !item || + item.index !== index || + typeof item.label !== 'string' || + !Number.isFinite(item.duration) || + item.duration < 0, + ) + ) { + throw new Error('Invalid MPC-HC playlist response') + } + return data + } + + async selectPlaylistItem(index) { + if (!Number.isSafeInteger(index) || index < 0) throw new Error('Invalid playlist index') + await this.request(`/command.html?wm_command=-3&index=${index}`) + } + async status() { if (this.statusSource !== 'html') { try { diff --git a/companion-modules/media-player-classic/src/definitions.js b/companion-modules/media-player-classic/src/definitions.js index bd37cdf..014202c 100644 --- a/companion-modules/media-player-classic/src/definitions.js +++ b/companion-modules/media-player-classic/src/definitions.js @@ -1,7 +1,7 @@ import { commands } from './commands.js' import { colors } from './feedbacks.js' -export function actions(send, loadNext, loadPrevious) { +export function actions(send, loadNext, loadPrevious, loadPlaylistItem) { const definitions = Object.fromEntries( Object.entries(commands).map(([id, name]) => [ id, @@ -36,6 +36,23 @@ export function actions(send, loadNext, loadPrevious) { callback: (action) => callback(action?.options?.target ?? 'both'), } } + if (loadPlaylistItem) + definitions.load_playlist_item = { + name: 'Load playlist item', + options: [ + { + type: 'number', + id: 'item', + label: 'Playlist item number (1 = first)', + default: 1, + min: 1, + max: 10000, + step: 1, + }, + ...definitions['887'].options, + ], + callback: (action) => loadPlaylistItem(action?.options?.item ?? 1, action?.options?.target ?? 'both'), + } return definitions } @@ -150,7 +167,22 @@ export function presets(label = 'MPC_DEV') { '14', ), } - return { ...transport, ...catalog } + const playlist = Object.fromEntries( + Array.from({ length: 10 }, (_, index) => { + const item = index + 1 + return [ + `transport_load_item_${item}`, + { + type: 'simple', + name: `Load playlist item ${item}`, + style: { text: `↓\nLOAD\n${item}`, size: 12, color: colors.white, bgcolor: 0x243b50, show_topbar: true }, + steps: [{ down: [{ actionId: 'load_playlist_item', options: { item, target: 'both' } }], up: [] }], + feedbacks: [{ feedbackId: 'load_playlist_item_status', options: { item } }, offline], + }, + ] + }), + ) + return { ...transport, ...playlist, ...catalog } } export function presetSections(buttons) { @@ -165,7 +197,12 @@ export function presetSections(buttons) { { id: 'experimental', name: 'Experimental', - definitions: ['transport_load_previous', 'transport_load_next', 'transport_load_result'], + definitions: [ + 'transport_load_previous', + 'transport_load_next', + 'transport_load_result', + ...Object.keys(buttons).filter((id) => id.startsWith('transport_load_item_')), + ], }, { id: 'commands', name: 'All commands', definitions: Object.keys(commands) }, ] diff --git a/companion-modules/media-player-classic/src/feedbacks.js b/companion-modules/media-player-classic/src/feedbacks.js index c569309..2830a83 100644 --- a/companion-modules/media-player-classic/src/feedbacks.js +++ b/companion-modules/media-player-classic/src/feedbacks.js @@ -107,6 +107,21 @@ export function feedbacks(getState, getSync = () => null, getLoadStatus = () => }, ]), ), + load_playlist_item_status: { + type: 'advanced', + name: 'Load playlist item status', + options: [{ type: 'number', id: 'item', label: 'Playlist item number', default: 1, min: 1, max: 10000, step: 1 }], + affectedProperties: ['text', 'bgcolor', 'color'], + callback: (feedback) => { + const item = feedback.options.item + const status = getLoadStatus(`item_${item}`) + return { + text: `↓\n${{ loading: 'LOADING', ready: 'LOADED', failed: 'FAILED' }[status] ?? 'LOAD'}\n${item}`, + bgcolor: { loading: colors.amber, ready: colors.blue, failed: colors.red }[status] ?? 0x243b50, + color: status === 'loading' ? colors.dark : colors.white, + } + }, + }, load_result: { type: 'advanced', name: 'Last load result (retained)', @@ -114,7 +129,11 @@ export function feedbacks(getState, getSync = () => null, getLoadStatus = () => affectedProperties: ['text', 'bgcolor', 'color'], callback: () => { const result = getLoadResult() - const direction = result?.direction === 'previous' ? 'PREV' : 'NEXT' + const direction = result?.direction?.startsWith('item_') + ? `#${result.direction.slice(5)}` + : result?.direction === 'previous' + ? 'PREV' + : 'NEXT' return { text: { diff --git a/companion-modules/media-player-classic/src/load-item.js b/companion-modules/media-player-classic/src/load-item.js index a985511..1b8bedd 100644 --- a/companion-modules/media-player-classic/src/load-item.js +++ b/companion-modules/media-player-classic/src/load-item.js @@ -3,7 +3,11 @@ import { setTimeout as delay } from 'node:timers/promises' // Experimental web-API workaround: Navigation still autoplays. Never retry navigation or // mute toggles: an HTTP response is not an acknowledgement of player state. export async function loadItem(player, direction, timing = {}) { - if (!['next', 'previous'].includes(direction)) throw new Error('Invalid load direction') + const itemMatch = /^item_([1-9]\d*)$/.exec(direction) + const itemNumber = itemMatch ? Number(itemMatch[1]) : null + if (itemNumber !== null && (!Number.isSafeInteger(itemNumber) || itemNumber > 10000)) + throw new Error('Invalid playlist item number') + if (!['next', 'previous'].includes(direction) && itemNumber === null) throw new Error('Invalid load direction') const navigationId = direction === 'next' ? '920' : '919' const poll = timing.poll ?? 50 const settle = timing.settle ?? 500 @@ -26,8 +30,23 @@ export async function loadItem(player, direction, timing = {}) { let advanced = false try { const original = await fresh() - if (!original.file || original.state === 'idle') + if (itemNumber === null && (!original.file || original.state === 'idle')) throw new Error(`Load a playlist item before using Load ${direction}`) + let playlistSignature + let alreadySelected = false + const verifyPlaylist = async () => { + const list = await player.client.playlist() + if (JSON.stringify(list.items) !== playlistSignature) + throw new Error('Playlist changed during loading; audio was not restored') + return list.active === itemNumber - 1 + } + if (itemNumber !== null) { + const list = await player.client.playlist() + if (itemNumber > list.items.length) + throw new Error(`Playlist item ${itemNumber} does not exist (${list.items.length} items)`) + playlistSignature = JSON.stringify(list.items) + alreadySelected = list.active === itemNumber - 1 && original.state !== 'idle' && !!original.file + } const wasMuted = original.muted if (!wasMuted) await command('909') let deadline = performance.now() + timeout @@ -36,8 +55,10 @@ export async function loadItem(player, direction, timing = {}) { await wait() } + if (itemNumber !== null) await verifyPlaylist() advanced = true - await command(navigationId) + if (itemNumber === null) await command(navigationId) + else if (!alreadySelected) await player.client.selectPlaylistItem(itemNumber - 1) // No status request or artificial delay between navigation and the first Stop. await command('890') deadline = performance.now() + timeout @@ -48,7 +69,8 @@ export async function loadItem(player, direction, timing = {}) { 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') { + const selected = itemNumber === null || (await verifyPlaylist()) + if (selected && file && (alreadySelected || file !== filename(original)) && state.state === 'stopped') { if (candidate !== file) { candidate = file stableSince = performance.now() @@ -59,7 +81,11 @@ export async function loadItem(player, direction, timing = {}) { const restoreDeadline = performance.now() + timeout while (true) { const restored = await fresh() - if (filename(restored) !== candidate || restored.state !== 'stopped') { + if ( + filename(restored) !== candidate || + restored.state !== 'stopped' || + (itemNumber !== null && !(await verifyPlaylist())) + ) { throw new Error('Player changed while restoring audio; check the player') } if (!restored.muted) return restored.file @@ -74,7 +100,7 @@ export async function loadItem(player, direction, timing = {}) { if (state.state !== 'stopped') await command('890') } } - throw new Error('A different file stopped for 500 ms was not confirmed; audio was not restored') + throw new Error('The requested file stopped for 500 ms was not confirmed; audio was not restored') } catch (error) { // A lost navigation response may still mean it executed. Best-effort Stop is // idempotent; blind mute toggles or another navigation command would not be. diff --git a/companion-modules/media-player-classic/src/main.js b/companion-modules/media-player-classic/src/main.js index 0a79592..98272a0 100644 --- a/companion-modules/media-player-classic/src/main.js +++ b/companion-modules/media-player-classic/src/main.js @@ -15,6 +15,7 @@ export default class MpcInstance extends InstanceBase { (id, target) => this.send(id, target), (target) => this.loadItem('next', target), (target) => this.loadItem('previous', target), + (item, target) => this.loadItem(`item_${item}`, target), ), ) this.setFeedbackDefinitions( diff --git a/companion-modules/media-player-classic/test/lifecycle.test.js b/companion-modules/media-player-classic/test/lifecycle.test.js index 0496dcb..49f772a 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, 140) + assert.equal(Object.keys(state.actions).length, 141) 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) diff --git a/companion-modules/media-player-classic/test/playlist.test.js b/companion-modules/media-player-classic/test/playlist.test.js new file mode 100644 index 0000000..5cf7288 --- /dev/null +++ b/companion-modules/media-player-classic/test/playlist.test.js @@ -0,0 +1,152 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { test } from 'node:test' +import { Player } from '../src/player.js' +import { loadItem } from '../src/load-item.js' +import { actions, presets } from '../src/definitions.js' +import { feedbacks } from '../src/feedbacks.js' +import { status } from './fixture.js' + +const fast = { poll: 10, settle: 40, timeout: 220 } +async function mock(t, onSelect) { + const data = { ...status, file: 'Clip 1.mp4', state: 0 } + const playlist = { + active: 0, + items: Array.from({ length: 12 }, (_, index) => ({ index, label: `Clip ${index + 1}.mp4`, duration: 60000 })), + } + const commands = [] + const server = createServer((req, res) => { + const url = new URL(req.url, 'http://localhost') + if (url.pathname === '/playlist.json') return res.end(JSON.stringify(playlist)) + const command = url.searchParams.get('wm_command') + if (command) { + commands.push(req.url) + if (command === '909') data.muted = !data.muted + if (command === '890') data.state = 0 + if (command === '-3') { + const index = Number(url.searchParams.get('index')) + if (onSelect) onSelect({ index, data, playlist, res }) + else { + playlist.active = index + data.file = playlist.items[index].label + data.state = 2 + } + } + if (!res.writableEnded) res.end() + } else 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, playlist, commands } +} + +test('numbered loading converts 1-based numbers, supports items beyond the presets, and restores mute', async (t) => { + const { player, commands, data, playlist } = await mock(t) + assert.equal(await loadItem(player, 'item_12', fast), 'Clip 12.mp4') + assert.deepEqual(commands, [ + '/command.html?wm_command=909', + '/command.html?wm_command=-3&index=11', + '/command.html?wm_command=890', + '/command.html?wm_command=909', + ]) + assert.equal(playlist.active, 11) + assert.equal(data.state, 0) + assert.equal(data.muted, false) +}) + +test('invalid or missing playlist items fail before muting or navigation', async (t) => { + const { player, commands, playlist } = await mock(t) + for (const direction of ['item_0', 'item_-1', 'item_1.5', 'item_13', 'item_10001', 'item_1&index=2']) { + await assert.rejects(loadItem(player, direction, fast)) + } + playlist.items = [] + playlist.active = -1 + await assert.rejects(loadItem(player, 'item_1', fast), /does not exist/) + assert.deepEqual(commands, []) +}) + +test('loading the already selected item stops without reopening and preserves existing mute', async (t) => { + const { player, commands, data } = await mock(t) + data.state = 2 + data.muted = true + assert.equal(await loadItem(player, 'item_1', fast), 'Clip 1.mp4') + assert.deepEqual(commands, ['/command.html?wm_command=890']) + assert.equal(data.muted, true) +}) + +test('indexed selection does not mistake an early active-index update for completed loading', async (t) => { + const { player, data, commands } = await mock(t, ({ index, data, playlist }) => { + playlist.active = index + setTimeout(() => { + data.file = playlist.items[index].label + data.state = 2 + }, 70) + }) + assert.equal(await loadItem(player, 'item_3', { ...fast, timeout: 500 }), 'Clip 3.mp4') + assert.equal(data.state, 0) + assert.equal(data.muted, false) + assert.ok(commands.filter((path) => path.includes('wm_command=890')).length >= 2) + assert.equal(commands.filter((path) => path.includes('wm_command=-3')).length, 1) +}) + +test('wrong active index, unchanged filename, or playlist changes cannot restore audio', async (t) => { + for (const problem of ['index', 'filename', 'reorder']) { + const { player, commands, data } = await mock(t, ({ index, data, playlist }) => { + if (problem !== 'index') playlist.active = index + if (problem !== 'filename') data.file = 'Clip 2.mp4' + if (problem === 'reorder') playlist.items[1].label = 'Replacement.mp4' + }) + await assert.rejects(loadItem(player, 'item_2', fast)) + assert.equal(data.muted, true) + assert.equal(commands.filter((path) => path.includes('wm_command=909')).length, 1) + assert.equal(commands.filter((path) => path.includes('wm_command=-3')).length, 1) + } +}) + +test('uncertain indexed-selection response stops without selecting again or restoring audio', async (t) => { + const { player, commands, data } = await mock(t, ({ index, data, playlist, res }) => { + playlist.active = index + data.file = 'Clip 2.mp4' + data.state = 2 + res.writeHead(500) + res.end() + }) + await assert.rejects(loadItem(player, 'item_2', fast), /HTTP 500/) + assert.equal(commands.filter((path) => path.includes('wm_command=-3')).length, 1) + assert.equal(commands.filter((path) => path.includes('wm_command=909')).length, 1) + assert.equal(data.state, 0) + assert.equal(data.muted, true) +}) + +test('modular action, first ten presets and load-result feedback agree on item numbers', async () => { + let sent + const definitions = actions( + () => {}, + null, + null, + (item, target) => { + sent = { item, target } + }, + ) + await definitions.load_playlist_item.callback({ options: { item: 12, target: 'backup' } }) + assert.deepEqual(sent, { item: 12, target: 'backup' }) + for (let item = 1; item <= 10; item++) { + const preset = presets()[`transport_load_item_${item}`] + assert.equal(preset.steps[0].down[0].options.item, item) + assert.equal(preset.feedbacks[0].options.item, item) + } + const fb = feedbacks( + () => null, + () => null, + (key) => (key === 'item_12' ? 'ready' : 'idle'), + () => ({ status: 'ready', direction: 'item_12' }), + ) + assert.equal(fb.load_playlist_item_status.callback({ options: { item: 12 } }).text, '↓\nLOADED\n12') + assert.equal(fb.load_playlist_item_status.callback({ options: { item: 1 } }).text, '↓\nLOAD\n1') + assert.equal(fb.load_result.callback().text, 'LAST\nLOADED\n#12') +})