diff --git a/companion-modules/media-player-classic/README.md b/companion-modules/media-player-classic/README.md index 436a717..d464870 100644 --- a/companion-modules/media-player-classic/README.md +++ b/companion-modules/media-player-classic/README.md @@ -101,6 +101,66 @@ 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. +## Optional backup player + +In this connection's configuration, keep your existing **Main player** host/port +and optionally fill in **Backup IP address or hostname** and its web-interface +port. Leave the backup host blank when using one player. The module does not +infer a backup address from other connections. + +All actions now have a **Player target** option: **Both players** (default), +**Main only**, or **Backup only**. Existing buttons without the option also +use Both. With no backup configured, Both sends only to the main. Each player +receives its command independently; failure or delay on one does not prevent +delivery to the other. Commands are not retried. + +The main player remains authoritative for normal transport feedback, countdown, +progress, existing variables, and connection health. Backup failures do not +turn this connection red or generate recurring error logs. The module does not +promote the backup to main or switch video outputs automatically. + +Add **Backup sync status** from **Transport & timing**. This is a passive display: +pressing it does not start playback or force synchronization. + +| Display | Color | Meaning | +| ------------------------- | ----- | ---------------------------------------------------- | +| No backup | Grey | Backup address is blank | +| Backup offline | Blue | Configured backup has no available status | +| Backup empty | Blue | Backup responds but has no active media | +| Backup config | Blue | Invalid backup address/port or same endpoint as main | +| In sync | Green | Both players agree within the configured tolerance | +| Out of sync | Red | Media, state, speed, or timing differs | +| Main offline / Main empty | Amber | Main cannot provide a usable reference | +| Checking sync | Blue | Waiting for fresh samples | + +Comparison uses case-insensitive filenames (allowing different media folders), +duration, playback state, playback rate, and estimated position. The default +**Playback sync tolerance** is **1000 ms**, configurable from 100–10000 ms. +Sample timestamps and playback rates compensate for different poll arrival +times; this is a monitoring estimate, not frame-accurate synchronization or a +media-content checksum. A brief mismatch can appear while files load or commands +reach the two players. Use the same ordered playlists on both machines. + +**Include mute and volume in sync comparison** is off by default, allowing an +intentionally silent backup. Enable it if audio settings should match too. +Toggle commands (such as Mute) are sent to each player as-is; they do not copy +the main's state to the backup or repair an existing mismatch. Use Main only or +Backup only actions to correct the relevant player independently. + +Use distinct player addresses. An identical configured endpoint is rejected as +a backup to prevent double commands; different hostnames resolving to the same +machine are not detected. Unavailable backup states remain informational. + +For custom buttons, `sync_label` provides display text, `sync_status` a stable +code (`no_backup`, `backup_offline`, `backup_empty`, `backup_config`, `in_sync`, +`out_of_sync`, `main_offline`, `main_empty`, `checking`), and `sync_detail` explains +the comparison. `backup_offset_ms` is estimated backup minus main position; +positive means ahead. Every main variable also has a `backup_` counterpart, +plus `backup_configured` and `backup_status`. Unknown values are cleared; +Companion can display null values as empty strings. **Backup in sync with main**, +**Backup out of sync with main**, and **Backup sync status** feedbacks are available +for custom buttons. + ## Variables and custom feedback The elapsed preset uses **ELAPSED** with size 14 text to avoid wrapping. The @@ -138,7 +198,7 @@ cd companion-modules/media-player-classic npm test npm run check npm run format # apply formatting after edits -npm run package # produce media-player-classic-1.2.0-dev.0.tgz +npm run package # produce media-player-classic-1.3.0-dev.0.tgz ``` Companion watches the developer folder and reloads the module after source @@ -159,6 +219,8 @@ No fork, publishing, or additional update server is required for local use. - `src/main.js`: Companion lifecycle, configuration, and connection status. - `src/client.js`: HTTP transport, timeout, and cancellation. +- `src/player.js`: independent player polling and command lifecycle. +- `src/redundancy.js`: backup comparison and variables. - `src/commands.js`: original command catalog and stable action IDs. - `src/definitions.js`: action and preset definitions. - `src/state.js`: JSON/HTML normalization, timing, and module variables. @@ -170,7 +232,8 @@ No fork, publishing, or additional update server is required for local use. Automated tests exercise all 138 command URLs against a mock server, HTTP errors, redirect refusal, timeout, cancellation, JSON/HTML parsing, feedback states, -countdown/progress edge cases, polling recovery, and configuration validation. They do +countdown/progress edge cases, polling recovery, independent dual-player delivery, +main authority, optional backup failures, comparison tolerance, and configuration validation. They do not establish that every legacy command still works in current MPC-HC. On a spare page with a disposable media file: diff --git a/companion-modules/media-player-classic/companion/HELP.md b/companion-modules/media-player-classic/companion/HELP.md index 63f0b01..2e32111 100644 --- a/companion-modules/media-player-classic/companion/HELP.md +++ b/companion-modules/media-player-classic/companion/HELP.md @@ -22,6 +22,35 @@ The bar fills left to right, turning amber with 10 media seconds left and red with 5 seconds left. All 138 original command presets remain in **All commands**. Open File opens a dialog on the player computer; it does not upload a file. +## Optional backup + +Configure a backup host and port to send commands to both players. Leave the host +blank when unused. Every action offers **Both players** (default), **Main only**, +or **Backup only**. Existing actions without a target default to Both. + +The main is the authority for normal feedback, timing, variables, and connection +health. Backup failures do not turn the connection into an error. Both players +receive commands independently; neither can block delivery to the other. + +Add the **Backup sync status** preset: + +- Grey **No backup**: no backup host configured. +- Blue **Backup offline / Backup empty / Backup config**: optional backup unavailable. +- Green **In sync**: playback agrees within tolerance. +- Red **Out of sync**: media, state, rate, or timing differs. +- Amber **Main offline / Main empty**: no usable main reference. + +The preset is informational; pressing it does not synchronize players. Default +position tolerance is 1000 ms (configurable). Filenames and durations identify +media; different folders are allowed. Use matching ordered playlists. Timing +comparison estimates position from poll timestamps, not frame-accurate sync. +Mute/volume comparison is optional and off by default for silent backups. + +Use `sync_label`, `sync_status`, `sync_detail`, and `backup_offset_ms` variables +for more detail; main variables also have `backup_` equivalents. Toggle commands +are sent as-is and do not repair mismatches. No automatic failover or video-output +switching is performed. + ## Live state Feedback follows MPC-HC, including changes made outside Companion. The module diff --git a/companion-modules/media-player-classic/companion/manifest.json b/companion-modules/media-player-classic/companion/manifest.json index 392d1ba..c73fee4 100644 --- a/companion-modules/media-player-classic/companion/manifest.json +++ b/companion-modules/media-player-classic/companion/manifest.json @@ -5,7 +5,7 @@ "name": "Media Player Classic (local development)", "shortname": "MPC", "description": "Local MPC-HC development module", - "version": "1.2.0-dev.0", + "version": "1.3.0-dev.0", "license": "MIT", "maintainers": [ { diff --git a/companion-modules/media-player-classic/package-lock.json b/companion-modules/media-player-classic/package-lock.json index 0fc313d..1dd30da 100644 --- a/companion-modules/media-player-classic/package-lock.json +++ b/companion-modules/media-player-classic/package-lock.json @@ -1,12 +1,12 @@ { "name": "media-player-classic", - "version": "1.2.0-dev.0", + "version": "1.3.0-dev.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "media-player-classic", - "version": "1.2.0-dev.0", + "version": "1.3.0-dev.0", "license": "MIT", "dependencies": { "@companion-module/base": "2.1.3" diff --git a/companion-modules/media-player-classic/package.json b/companion-modules/media-player-classic/package.json index cbdde16..aa018da 100644 --- a/companion-modules/media-player-classic/package.json +++ b/companion-modules/media-player-classic/package.json @@ -1,6 +1,6 @@ { "name": "media-player-classic", - "version": "1.2.0-dev.0", + "version": "1.3.0-dev.0", "private": true, "type": "module", "main": "src/main.js", diff --git a/companion-modules/media-player-classic/src/definitions.js b/companion-modules/media-player-classic/src/definitions.js index 974928c..4ec1622 100644 --- a/companion-modules/media-player-classic/src/definitions.js +++ b/companion-modules/media-player-classic/src/definitions.js @@ -7,8 +7,21 @@ export function actions(send) { id, { name, - options: [], - callback: async () => send(id), + options: [ + { + type: 'dropdown', + id: 'target', + label: 'Player target', + default: 'both', + choices: [ + { id: 'both', label: 'Both players' }, + { id: 'main', label: 'Main only' }, + { id: 'backup', label: 'Backup only' }, + ], + disableAutoExpression: true, + }, + ], + callback: async (action) => send(id, action?.options?.target ?? 'both'), }, ]), ) @@ -22,7 +35,7 @@ export function presets(label = 'MPC_DEV') { type: 'simple', name, style: { text: name, size: 'auto', color: 0xffffff, bgcolor: 0 }, - steps: [{ down: [{ actionId: id, options: {} }], up: [] }], + steps: [{ down: [{ actionId: id, options: { target: 'both' } }], up: [] }], feedbacks: [], }, ]), @@ -42,10 +55,17 @@ export function presets(label = 'MPC_DEV') { type: 'simple', name, style: { text, size, color: colors.white, bgcolor: colors.dark, show_topbar: false }, - steps: [{ down: id ? [{ actionId: id, options: {} }] : [], up: [] }], + steps: [{ down: id ? [{ actionId: id, options: { target: 'both' } }] : [], up: [] }], feedbacks: [...feedback, offline], }) const transport = { + transport_redundancy: { + type: 'simple', + name: 'Backup sync status', + style: { text: 'No\nbackup', size: '14', color: 0x99a4af, bgcolor: colors.dark, show_topbar: false }, + steps: [{ down: [], up: [] }], + feedbacks: [{ feedbackId: 'redundancy', options: {} }], + }, transport_play: button('Play — green while playing', '▶\nPLAY', '887', [ active('playing', colors.green), active('paused', colors.amber, 'Ⅱ\nPAUSED'), diff --git a/companion-modules/media-player-classic/src/feedbacks.js b/companion-modules/media-player-classic/src/feedbacks.js index ea0b056..f1c2548 100644 --- a/companion-modules/media-player-classic/src/feedbacks.js +++ b/companion-modules/media-player-classic/src/feedbacks.js @@ -35,7 +35,7 @@ export function progressBar(state, image) { } } -export function feedbacks(getState) { +export function feedbacks(getState, getSync = () => null) { const boolean = (name, callback, color) => ({ type: 'boolean', name, @@ -44,6 +44,15 @@ export function feedbacks(getState) { callback, }) return { + 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: { + type: 'advanced', + name: 'Backup sync status', + options: [], + affectedProperties: ['text', 'color', 'bgcolor'], + callback: () => redundancyStyle(getSync()), + }, playing: boolean('Playing', () => getState()?.state === 'playing', colors.green), stopped: boolean('Stopped', () => getState()?.state === 'stopped', colors.red), paused: boolean('Paused', () => getState()?.state === 'paused', colors.amber), @@ -59,3 +68,30 @@ export function feedbacks(getState) { }, } } + +export function redundancyStyle(sync) { + const status = sync?.status ?? 'no_backup' + const text = + { + no_backup: 'No\nbackup', + backup_config: 'Backup\nconfig', + backup_offline: 'Backup\noffline', + backup_empty: 'Backup\nempty', + main_offline: 'Main\noffline', + main_empty: 'Main\nempty', + checking: 'Checking\nsync', + in_sync: 'In sync', + out_of_sync: 'Out of\nsync', + }[status] ?? 'Checking\nsync' + const bgcolor = + status === 'in_sync' + ? colors.green + : status === 'out_of_sync' + ? colors.red + : status === 'no_backup' + ? colors.dark + : status.startsWith('main_') + ? colors.amber + : colors.blue + return { text, bgcolor, color: status === 'no_backup' ? 0x99a4af : colors.white } +} diff --git a/companion-modules/media-player-classic/src/main.js b/companion-modules/media-player-classic/src/main.js index f5f5417..c8205b7 100644 --- a/companion-modules/media-player-classic/src/main.js +++ b/companion-modules/media-player-classic/src/main.js @@ -1,5 +1,7 @@ import { InstanceBase, InstanceStatus } from '@companion-module/base' -import { MpcClient } from './client.js' +import { endpoint } from './client.js' +import { Player } from './player.js' +import { comparePlayers, redundancyDefinitions, redundancyVariables } from './redundancy.js' import { actions, presets, presetSections } from './definitions.js' import { feedbacks } from './feedbacks.js' import { variableDefinitions, variables } from './state.js' @@ -8,97 +10,108 @@ export const UpgradeScripts = [] export default class MpcInstance extends InstanceBase { async init(config) { - this.setActionDefinitions(actions((id) => this.send(id))) - this.setFeedbackDefinitions(feedbacks(() => this.state)) - this.setVariableDefinitions(variableDefinitions) - const buttons = presets(this.label) - this.setPresetDefinitions(presetSections(buttons), buttons) + this.setActionDefinitions(actions((id, target) => this.send(id, target))) + this.setFeedbackDefinitions( + feedbacks( + () => this.state, + () => this.sync, + ), + ) + this.setVariableDefinitions({ ...variableDefinitions, ...redundancyDefinitions }) await this.configUpdated(config) } - publish(state) { - this.state = state - this.setVariableValues(variables(state)) + publish() { + this.state = this.main?.state ?? null + this.sync = comparePlayers(this.main, this.backup, this.syncOptions) + this.setVariableValues({ + ...variables(this.state), + ...redundancyVariables(this.backup, this.syncOptions, this.sync), + }) this.checkAllFeedbacks() } async configUpdated(config) { - clearTimeout(this.pollTimer) - this.client?.close() - this.client = undefined - this.pendingPoll = undefined - this.publish(null) + this.main?.close() + this.backup?.close() + this.main = undefined + this.backup = undefined + this.lastError = undefined + this.syncOptions = { + configured: !!String(config.backup_host ?? '').trim(), + interval: Number(config.poll_interval ?? 500), + tolerance: Number(config.sync_tolerance ?? 1000), + compareAudio: config.compare_audio === true, + } + this.publish() try { - this.pollInterval = Number(config.poll_interval ?? 500) - if (!Number.isInteger(this.pollInterval) || this.pollInterval < 250 || this.pollInterval > 5000) { + if ( + !Number.isInteger(this.syncOptions.interval) || + this.syncOptions.interval < 250 || + this.syncOptions.interval > 5000 + ) { throw new Error('Status polling must be between 250 and 5000 milliseconds.') } - this.client = new MpcClient(config, 2500) + if ( + !Number.isInteger(this.syncOptions.tolerance) || + this.syncOptions.tolerance < 100 || + this.syncOptions.tolerance > 10000 + ) { + throw new Error('Sync tolerance must be between 100 and 10000 milliseconds.') + } + this.main = new Player(config, this.syncOptions.interval, (player) => { + if (player !== this.main) return + this.publish() + if (player.error) { + this.updateStatus(InstanceStatus.ConnectionFailure, player.error) + if (player.error !== this.lastError) + this.log('error', `Main MPC-HC: ${player.error}. Check the Web Interface setting, host, and port.`) + } else this.updateStatus(InstanceStatus.Ok) + this.lastError = player.error + }) } catch (error) { this.updateStatus(InstanceStatus.BadConfig, error.message) return } - this.lastError = undefined - // Rebuild variable references if the connection label changed. + if (this.syncOptions.configured) { + try { + const backupConfig = { host: config.backup_host, port: config.backup_port ?? 13579 } + if (endpoint(config).origin === endpoint(backupConfig).origin) + throw new Error('Backup must be a different player address; duplicate commands are disabled.') + this.backup = new Player(backupConfig, this.syncOptions.interval, (player) => { + if (player === this.backup) this.publish() + }) + } catch (error) { + // The optional backup never changes the main connection's health. + this.syncOptions.configError = error.message + } + } + this.publish() const buttons = presets(this.label) this.setPresetDefinitions(presetSections(buttons), buttons) this.updateStatus(InstanceStatus.Connecting) - void this.refresh() + void this.main.refresh() + void this.backup?.refresh() } - failed(error) { - this.publish(null) - const detail = String(error.cause?.code ?? error.message) - this.updateStatus(InstanceStatus.ConnectionFailure, detail) - if (detail !== this.lastError) { - this.log('error', `MPC-HC request failed: ${detail}. Check the player Web Interface setting, host, and port.`) - } - this.lastError = detail - } - - refresh() { - const client = this.client - if (!client) return Promise.resolve() - if (this.pendingPoll) return this.pendingPoll - clearTimeout(this.pollTimer) - const pending = (async () => { - try { - const state = await client.status() - if (client !== this.client) return - this.publish(state) - this.lastError = undefined - this.updateStatus(InstanceStatus.Ok) - } catch (error) { - if (client === this.client) this.failed(error) - } finally { - if (client === this.client) { - this.pendingPoll = undefined - this.pollTimer = setTimeout(() => void this.refresh(), this.pollInterval) - } - } - })() - this.pendingPoll = pending - return pending - } - - async send(id) { - const client = this.client - if (!client) return - try { - await client.command(id) - // Read after command delivery, even if an earlier poll was already in flight. - await this.pendingPoll - if (client === this.client) await this.refresh() - } catch (error) { - if (client === this.client) this.failed(error) + async refresh() { + await Promise.allSettled([this.main?.refresh(), this.backup?.refresh()]) + } + + async send(id, target = 'both') { + 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))) } async destroy() { - clearTimeout(this.pollTimer) - this.client?.close() - this.client = undefined - this.pendingPoll = undefined + this.main?.close() + this.backup?.close() + this.main = undefined + this.backup = undefined } getConfigFields() { @@ -124,7 +137,7 @@ export default class MpcInstance extends InstanceBase { { type: 'textinput', id: 'host', - label: 'Player IP address or hostname', + label: 'Main player IP address or hostname', width: 8, default: '127.0.0.1', required: true, @@ -132,13 +145,46 @@ export default class MpcInstance extends InstanceBase { { type: 'number', id: 'port', - label: 'Web interface port', + label: 'Main web interface port', width: 4, default: 13579, min: 1, max: 65535, required: true, }, + { + type: 'textinput', + id: 'backup_host', + label: 'Backup IP address or hostname (optional)', + width: 8, + default: '', + }, + { + type: 'number', + id: 'backup_port', + label: 'Backup web interface port', + width: 4, + default: 13579, + min: 1, + max: 65535, + }, + { + type: 'number', + id: 'sync_tolerance', + label: 'Playback sync tolerance (milliseconds)', + width: 8, + default: 1000, + min: 100, + max: 10000, + required: true, + }, + { + type: 'checkbox', + id: 'compare_audio', + label: 'Include mute and volume in sync comparison', + width: 12, + default: false, + }, ] } } diff --git a/companion-modules/media-player-classic/src/player.js b/companion-modules/media-player-classic/src/player.js new file mode 100644 index 0000000..8ad4386 --- /dev/null +++ b/companion-modules/media-player-classic/src/player.js @@ -0,0 +1,62 @@ +import { MpcClient } from './client.js' + +// Each player owns its polling loop so an unavailable backup never delays the main. +export class Player { + constructor(config, interval, changed) { + this.client = new MpcClient(config, 2500) + this.interval = interval + this.changed = changed + this.state = null + this.active = true + } + + refresh() { + if (!this.active) return Promise.resolve() + if (this.pending) return this.pending + clearTimeout(this.timer) + this.pending = (async () => { + const started = performance.now() + try { + const state = await this.client.status() + if (!this.active) return + this.state = state + // Approximate when the remote snapshot was taken, not when it arrived. + this.sampledAt = (started + performance.now()) / 2 + this.error = null + this.changed(this) + } catch (error) { + if (this.active) this.failed(error) + } finally { + if (this.active) { + this.pending = undefined + this.timer = setTimeout(() => void this.refresh(), this.interval) + } + } + })() + return this.pending + } + + failed(error) { + this.state = null + this.error = String(error.cause?.code ?? error.message) + this.changed(this) + } + + async send(id) { + if (!this.active) return + try { + await this.client.command(id) + await this.pending + if (this.active) await this.refresh() + } catch (error) { + if (this.active) this.failed(error) + } + } + + close() { + this.active = false + clearTimeout(this.timer) + this.client.close() + this.state = null + } +} diff --git a/companion-modules/media-player-classic/src/redundancy.js b/companion-modules/media-player-classic/src/redundancy.js new file mode 100644 index 0000000..0effc88 --- /dev/null +++ b/companion-modules/media-player-classic/src/redundancy.js @@ -0,0 +1,75 @@ +import { variableDefinitions, variables } from './state.js' + +const result = (status, label, reason, offset = null) => ({ status, label, reason, offset }) + +function positionAt(player, now) { + const state = player.state + const advance = state.state === 'playing' ? Math.max(0, now - player.sampledAt) * (state.rate ?? 1) : 0 + const position = state.position + advance + return state.duration > 0 ? Math.min(position, state.duration) : position +} + +// Compare filenames rather than absolute paths: backup media can be on another drive. +const fileKey = (name) => name.split(/[\\/]/).at(-1).normalize('NFC').toLowerCase() + +export function comparePlayers(main, backup, options = {}, now = performance.now()) { + if (!options.configured) return result('no_backup', 'No backup', 'No backup address configured') + if (options.configError) return result('backup_config', 'Backup config', options.configError) + if (!backup?.state) return result('backup_offline', 'Backup offline', backup?.error ?? 'Waiting for backup status') + if (backup.state.state === 'idle' || !backup.state.file) + return result('backup_empty', 'Backup empty', 'No active media on backup') + if (!main?.state) return result('main_offline', 'Main offline', 'Main player status unavailable; cannot compare') + if (main.state.state === 'idle' || !main.state.file) + return result('main_empty', 'Main empty', 'No active media on main') + const staleAfter = (options.interval ?? 500) + 3000 + if ([main, backup].some((player) => !Number.isFinite(player.sampledAt) || now - player.sampledAt > staleAfter)) { + return result('checking', 'Checking', 'Waiting for fresh status from both players') + } + const tolerance = options.tolerance ?? 1000 + const offset = Math.round(positionAt(backup, now) - positionAt(main, now)) + const mismatch = [] + if (fileKey(main.state.file) !== fileKey(backup.state.file)) mismatch.push('Different files') + if (main.state.state !== backup.state.state) mismatch.push('Different playback states') + if (Math.abs(main.state.duration - backup.state.duration) > tolerance) mismatch.push('Different durations') + if (Math.abs((main.state.rate ?? 1) - (backup.state.rate ?? 1)) > 0.001) mismatch.push('Different playback speeds') + if (Math.abs(offset) > tolerance) mismatch.push(`Backup ${offset > 0 ? 'ahead' : 'behind'} by ${Math.abs(offset)} ms`) + if (options.compareAudio) { + if (main.state.muted !== backup.state.muted) mismatch.push('Different mute states') + if (main.state.volume !== backup.state.volume) mismatch.push('Different volumes') + } + return mismatch.length + ? result('out_of_sync', 'Out of sync', mismatch.join('; '), offset) + : result('in_sync', 'In sync', `Within ${tolerance} ms of main`, offset) +} + +export const redundancyDefinitions = { + ...Object.fromEntries( + Object.entries(variableDefinitions).map(([id, value]) => [`backup_${id}`, { name: `Backup: ${value.name}` }]), + ), + backup_configured: { name: 'Backup address is configured' }, + backup_status: { name: 'Backup availability: not_configured, config_error, offline, empty, or connected' }, + sync_status: { name: 'Redundancy comparison status (machine-readable)' }, + sync_label: { name: 'Redundancy comparison status for display' }, + sync_detail: { name: 'Redundancy comparison explanation' }, + backup_offset_ms: { name: 'Estimated backup position minus main position (milliseconds)' }, +} + +export function redundancyVariables(backup, options, sync) { + return { + ...Object.fromEntries(Object.entries(variables(backup?.state)).map(([id, value]) => [`backup_${id}`, value])), + backup_configured: !!options.configured, + backup_status: !options.configured + ? 'not_configured' + : options.configError + ? 'config_error' + : !backup?.state + ? 'offline' + : backup.state.state === 'idle' || !backup.state.file + ? 'empty' + : 'connected', + sync_status: sync.status, + sync_label: sync.label, + sync_detail: sync.reason, + backup_offset_ms: sync.offset, + } +} diff --git a/companion-modules/media-player-classic/test/lifecycle.test.js b/companion-modules/media-player-classic/test/lifecycle.test.js index e5dfa5c..cf3fe13 100644 --- a/companion-modules/media-player-classic/test/lifecycle.test.js +++ b/companion-modules/media-player-classic/test/lifecycle.test.js @@ -82,7 +82,8 @@ test('configuration changes and destroy cancel stale operations without overwrit const count = state.statuses.length await pending assert.equal(state.statuses.length, count) - assert.equal(module.client, undefined) + assert.equal(module.main, undefined) + assert.equal(module.backup, undefined) }) test('polling discovers external changes, retries failures, and stops on destroy', async (t) => { diff --git a/companion-modules/media-player-classic/test/redundancy.test.js b/companion-modules/media-player-classic/test/redundancy.test.js new file mode 100644 index 0000000..7a96c7f --- /dev/null +++ b/companion-modules/media-player-classic/test/redundancy.test.js @@ -0,0 +1,222 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { test } from 'node:test' +import { InstanceStatus } from '@companion-module/base' +import MpcInstance from '../src/main.js' +import { normalizeStatus } from '../src/state.js' +import { comparePlayers } from '../src/redundancy.js' +import { colors, redundancyStyle } from '../src/feedbacks.js' +import { status as sample } from './fixture.js' + +async function player(t) { + const mock = { data: { ...sample }, commands: [], statusCode: 200, commandCode: 200 } + const server = createServer((request, response) => { + if (request.url.startsWith('/command.html')) { + mock.commands.push(new URL(request.url, 'http://localhost').searchParams.get('wm_command')) + if (mock.holdCommands) { + mock.held = response + return + } + response.writeHead(mock.commandCode) + } else response.writeHead(mock.statusCode) + response.end(JSON.stringify(mock.data)) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + t.after(() => { + server.closeAllConnections() + server.close() + }) + mock.config = { host: '127.0.0.1', port: server.address().port } + return mock +} + +async function moduleFor(t, main, backup, extra = {}) { + const seen = { statuses: [] } + const module = new MpcInstance({ + _isInstanceContext: true, + id: 'test', + label: 'MPC_TEST', + setActionDefinitions: (value) => { + seen.actions = value + }, + setFeedbackDefinitions: () => {}, + setVariableDefinitions: () => {}, + setPresetDefinitions: () => {}, + setVariableValues: (value) => { + seen.variables = value + }, + checkAllFeedbacks: () => {}, + updateStatus: (status) => seen.statuses.push(status), + }) + t.after(() => module.destroy()) + const config = { + ...main.config, + ...(backup ? { backup_host: backup.config.host, backup_port: backup.config.port } : {}), + ...extra, + } + await module.init(config) + await module.refresh() + return { module, seen, config } +} + +const until = async (condition) => { + const end = Date.now() + 3000 + while (!condition()) { + assert.ok(Date.now() < end, 'Expected player update did not arrive') + await new Promise((resolve) => setTimeout(resolve, 10)) + } +} + +test('optional unconfigured backup stays neutral and existing actions default to both', async (t) => { + const main = await player(t) + const { module, seen } = await moduleFor(t, main, null, { backup_host: ' ', backup_port: 0 }) + await seen.actions['887'].callback({ options: {} }) + assert.deepEqual(main.commands, ['887']) + assert.equal(module.backup, undefined) + assert.equal(seen.variables.sync_status, 'no_backup') + assert.equal(seen.variables.backup_status, 'not_configured') + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) +}) + +test('main is authoritative and actions can target both, main, or backup', async (t) => { + const main = await player(t) + const backup = await player(t) + backup.data = { ...sample, state: 1, muted: true, position: 5000 } + const { module, seen } = await moduleFor(t, main, backup) + assert.equal(seen.variables.state, 'playing') + assert.equal(seen.variables.muted, false) + assert.equal(seen.variables.backup_state, 'paused') + assert.equal(seen.variables.backup_muted, true) + assert.equal(seen.variables.sync_status, 'out_of_sync') + await module.send('887') + await seen.actions['888'].callback({ options: { target: 'main' } }) + await seen.actions['890'].callback({ options: { target: 'backup' } }) + assert.deepEqual(main.commands, ['887', '888']) + assert.deepEqual(backup.commands, ['887', '890']) + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) +}) + +test('main command failure does not suppress backup delivery or replace authoritative feedback', async (t) => { + const main = await player(t) + const backup = await player(t) + const { module, seen } = await moduleFor(t, main, backup) + main.commandCode = 503 + await module.send('887') + assert.deepEqual(backup.commands, ['887']) + assert.equal(seen.variables.state, 'offline') + assert.equal(seen.variables.backup_state, 'playing') + assert.equal(seen.statuses.at(-1), InstanceStatus.ConnectionFailure) +}) + +test('backup failure and empty media do not mark the connection as failed, and recovery resumes comparison', async (t) => { + const main = await player(t) + const backup = await player(t) + backup.statusCode = 503 + const { module, seen } = await moduleFor(t, main, backup, { poll_interval: 250 }) + assert.equal(seen.variables.sync_status, 'backup_offline') + assert.equal(seen.variables.backup_muted, null) + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) + backup.commandCode = 503 + await module.send('909', 'backup') + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) + backup.statusCode = 200 + backup.data = { ...sample, state: -1 } + await until(() => seen.variables.sync_status === 'backup_empty') + backup.data = { ...sample } + await until(() => seen.variables.sync_status === 'in_sync') + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) +}) + +test('slow backup requests do not block main commands or status polling', async (t) => { + const main = await player(t) + const backup = await player(t) + const { module, seen } = await moduleFor(t, main, backup, { poll_interval: 250 }) + backup.holdCommands = true + main.data = { ...sample, state: 1 } + const sending = module.send('888') + await until(() => backup.held && seen.variables.state === 'paused') + assert.deepEqual(main.commands, ['888']) + main.data = { ...sample, state: 0 } + await until(() => seen.variables.state === 'stopped') + backup.held.end('ok') + await sending + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) +}) + +test('invalid or duplicate backup configuration leaves the main operational', async (t) => { + const main = await player(t) + for (const config of [ + { backup_host: 'localhost', backup_port: 0 }, + { backup_host: main.config.host, backup_port: main.config.port }, + ]) { + const { module, seen } = await moduleFor(t, main, null, config) + assert.equal(seen.variables.sync_status, 'backup_config') + assert.equal(seen.statuses.at(-1), InstanceStatus.Ok) + await module.send('887') + assert.equal(module.backup, undefined) + await module.destroy() + } + assert.deepEqual(main.commands, ['887', '887']) +}) + +test('reconfiguration cancels both old players and removes stale backup state', async (t) => { + const main = await player(t) + const backup = await player(t) + const { module, seen, config } = await moduleFor(t, main, backup) + const oldMain = module.main + const oldBackup = module.backup + backup.holdCommands = true + const pending = module.send('887', 'backup') + await until(() => backup.held) + await module.configUpdated({ ...config, backup_host: '' }) + await pending + await module.refresh() + assert.equal(oldMain.active, false) + assert.equal(oldBackup.active, false) + assert.equal(seen.variables.sync_status, 'no_backup') + assert.equal(seen.variables.backup_file, '') + assert.equal(seen.variables.backup_remaining_seconds, null) + await module.destroy() + assert.equal(module.main, undefined) + assert.equal(module.backup, undefined) +}) + +const snapshot = (patch = {}, sampledAt = 10000) => ({ state: normalizeStatus({ ...sample, ...patch }), sampledAt }) +const compare = (main, backup, options = {}) => comparePlayers(main, backup, { configured: true, ...options }, 10000) + +test('comparison handles optional, offline, idle, and stale players without claiming synchronization', () => { + assert.equal(comparePlayers(null, null).status, 'no_backup') + assert.equal(compare(snapshot(), null).status, 'backup_offline') + assert.equal(compare(null, snapshot()).status, 'main_offline') + assert.equal(compare(snapshot(), snapshot({ state: -1 })).status, 'backup_empty') + assert.equal(compare(snapshot({ state: -1 }), snapshot()).status, 'main_empty') + assert.equal(compare(snapshot(), snapshot({ file: '' })).status, 'backup_empty') + assert.equal(compare(snapshot({}, 1000), snapshot()).status, 'checking') + for (const status of ['no_backup', 'backup_offline', 'backup_empty']) + assert.notEqual(redundancyStyle({ status }).bgcolor, colors.red) +}) + +test('comparison accounts for sample time and rate, with configurable position tolerance', () => { + assert.equal(compare(snapshot({ position: 1000 }, 9000), snapshot({ position: 2000 })).status, 'in_sync') + assert.equal(compare(snapshot({ position: 1000, rate: 2 }, 9000), snapshot({ position: 3000, rate: 2 })).offset, 0) + assert.equal(compare(snapshot(), snapshot({ position: sample.position + 1001 })).status, 'out_of_sync') + assert.equal( + compare(snapshot(), snapshot({ position: sample.position + 1001 }), { tolerance: 1500 }).status, + 'in_sync', + ) + assert.equal(compare(snapshot(), snapshot({ position: sample.position - 2000 })).offset, -2000) + assert.equal(compare(snapshot({ state: 1 }, 9000), snapshot({ state: 1 })).offset, 0) +}) + +test('comparison checks media/state/rate; audio is optional and paths can differ', () => { + assert.equal( + compare(snapshot({ file: 'C:\\media\\Clip.mp4' }), snapshot({ file: 'D:\\backup\\clip.mp4' })).status, + 'in_sync', + ) + for (const patch of [{ file: 'other.mp4' }, { state: 1 }, { rate: 2 }, { duration: sample.duration + 2000 }]) { + assert.equal(compare(snapshot(), snapshot(patch)).status, 'out_of_sync') + } + assert.equal(compare(snapshot(), snapshot({ muted: true, volume: 0 })).status, 'in_sync') + assert.equal(compare(snapshot(), snapshot({ muted: true }), { compareAudio: true }).status, 'out_of_sync') + assert.equal(compare(snapshot(), snapshot({ volume: 0 }), { compareAudio: true }).status, 'out_of_sync') +})