Add MPC-HC playback feedback and transport presets
This commit is contained in:
parent
12c7eadc27
commit
116bce6253
|
|
@ -57,6 +57,8 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
|||
Include upstream notices/provenance, never commit binaries.
|
||||
|
||||
- `companion-modules/media-player-classic/` is the local MPC-HC module for Companion 5.1.
|
||||
Prefer JSON status with HTML fallback; drive feedback from player state,
|
||||
clear stale state on failures, and keep polling serialized and cancellable.
|
||||
Preserve numeric action IDs and upstream MIT attribution. Use Node.js 22.20+
|
||||
(22.x); run `npm test`, `npm run check`, and `npm run package` in the module.
|
||||
`setup.py` installs locked dependencies and can back up/configure the launcher.
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@
|
|||
|
||||
A local development port of the original Media Player Classic module for
|
||||
**Companion 5.1.0**, using Companion module API 2 and Node.js 22. It preserves
|
||||
all 138 original numeric command IDs and provides matching button presets.
|
||||
all 138 original numeric command IDs, adds live player feedback, and provides
|
||||
transport and timing presets.
|
||||
See [UPSTREAM.md](UPSTREAM.md) for provenance and [LICENSE](LICENSE) for attribution.
|
||||
|
||||
## Install on this computer
|
||||
|
|
@ -40,6 +41,67 @@ The module appears in Connections; a development module need not appear as an
|
|||
installed store version on the Modules page. Existing connections remain on
|
||||
their selected version until you explicitly change them.
|
||||
|
||||
## Transport presets and feedback
|
||||
|
||||
Open **Presets → MPC_DEV → Transport & timing** and drag the buttons onto a
|
||||
spare page. These presets already include their feedback and variable references:
|
||||
|
||||
| Preset | Behavior |
|
||||
| --------------------- | --------------------------------------------------------------- |
|
||||
| ▶ Play | Play command; green while playing, amber while paused |
|
||||
| ■ Stop | Stop command; red while the player reports stopped |
|
||||
| ◀◀ Previous / ▶▶ Next | Previous/next **playlist item**, not chapter or seek |
|
||||
| Mute | Toggle mute; red **MUTED** when the player mute switch is on |
|
||||
| Pause | Pause command; amber while paused |
|
||||
| Remaining | Live media countdown and progress bar |
|
||||
| Elapsed | Live elapsed media time and progress bar |
|
||||
| Playback state | Playing, paused, stopped, idle, or offline with matching colors |
|
||||
|
||||
The progress bar fills from left to right. It turns amber with 10 seconds left
|
||||
and red with 5 seconds left. Timing displays are passive: pressing them does
|
||||
not send a player command. Transport presets use symbols, colors, and labels;
|
||||
all original text presets remain in **All commands**.
|
||||
|
||||
Feedback comes from the player, including changes made using the mouse,
|
||||
keyboard, or another controller. It never assumes a command succeeded merely
|
||||
because a button was pressed. A successful HTTP command response alone does
|
||||
not change playback or mute feedback. The next player status determines it.
|
||||
|
||||
Status uses `/status.json` where available (verified on MPC-HC **2.8.5.0**),
|
||||
with automatic `/variables.html` fallback for older builds. The module polls
|
||||
at **500 ms** by default, configurable from **250–5000 ms**, and refreshes after
|
||||
commands. Requests do not overlap, and polling resumes after network failures.
|
||||
|
||||
On a failed status request, active state feedback and stale timing values are
|
||||
cleared; transport presets show **OFFLINE**. Requests time out after 2.5 seconds.
|
||||
There can therefore be a polling interval plus timeout before loss is shown.
|
||||
`idle` means MPC reports no active media graph; it is distinct from `stopped`.
|
||||
Unknown duration shows `--:--` with no bar. Countdown reflects media time, pauses
|
||||
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.
|
||||
|
||||
## Variables and custom feedback
|
||||
|
||||
These are connection/module variables, not button-local variables. With the
|
||||
connection labelled `MPC_DEV`, use `$(MPC_DEV:remaining)` in button text.
|
||||
Presets are wired automatically to the connection label.
|
||||
|
||||
| Variables | Values |
|
||||
| ---------------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| `state`, `connected` | Playback state string and status availability boolean |
|
||||
| `playing`, `stopped`, `paused`, `muted` | Booleans; null when status is unavailable |
|
||||
| `volume`, `file`, `version`, `rate` | Volume percent, filename, player version, playback rate |
|
||||
| `elapsed`, `duration`, `remaining` | Formatted time (`MM:SS` or `H:MM:SS`); `--:--` when unknown |
|
||||
| `elapsed_seconds`, `duration_seconds`, `remaining_seconds` | Numeric media seconds; null when unknown |
|
||||
| `progress` | Percentage from 0 to 100; null when duration is unknown |
|
||||
|
||||
Mute is separate from volume zero: `muted` follows MPC's mute switch.
|
||||
For existing/custom buttons, add **Playing**, **Stopped**, **Paused**, **Audio
|
||||
muted**, **No active media (idle)**, **Status unavailable**, or **Playback progress
|
||||
bar** from the module's Feedbacks list. Existing buttons are not rewritten;
|
||||
replace them with transport presets or add feedback manually.
|
||||
|
||||
## Edit, test, and update
|
||||
|
||||
On this machine, use the bundled runtime in a terminal:
|
||||
|
|
@ -50,7 +112,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.1.0-dev.0.tgz
|
||||
npm run package # produce media-player-classic-1.2.0-dev.0.tgz
|
||||
```
|
||||
|
||||
Companion watches the developer folder and reloads the module after source
|
||||
|
|
@ -73,13 +135,16 @@ No fork, publishing, or additional update server is required for local use.
|
|||
- `src/client.js`: HTTP transport, timeout, and cancellation.
|
||||
- `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.
|
||||
- `src/feedbacks.js`: state feedback and RGBA progress graphics.
|
||||
- `test/`: mock HTTP integration tests; never contact the real player.
|
||||
- `companion/HELP.md`: help displayed inside Companion.
|
||||
|
||||
## Battle-testing checklist
|
||||
|
||||
Automated tests exercise all 138 command URLs against a mock server, HTTP errors,
|
||||
redirect refusal, timeout, cancellation, and configuration validation. They do
|
||||
redirect refusal, timeout, cancellation, JSON/HTML parsing, feedback states,
|
||||
countdown/progress edge cases, polling recovery, 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:
|
||||
|
|
@ -94,9 +159,9 @@ On a spare page with a disposable media file:
|
|||
- Test existing button compatibility before moving your normal MPC connection to dev.
|
||||
- Import and smoke-test a packaged build before upstreaming.
|
||||
|
||||
Initialization probes `/variables.html`; status afterward reflects the last HTTP
|
||||
request. There is no continuous health polling or playback-state feedback yet.
|
||||
A successful HTTP response confirms delivery, not that MPC-HC performed a command.
|
||||
Live validation reads status and renders presets inside Companion without
|
||||
sending playback commands. Use the checklist above to test actual playback,
|
||||
mute/unmute, seeks, end-of-file behavior, and playlist navigation on your media.
|
||||
Open File opens the player's dialog; it does not accept or upload a path.
|
||||
|
||||
To roll back, select the official version for any connection using dev, or remove
|
||||
|
|
@ -109,3 +174,6 @@ is stopped. Your normal button configuration is not changed by the helper.
|
|||
- [Companion developer folders](https://companion.free/for-developers/module-development/local-modules/)
|
||||
- [Module packaging](https://companion.free/for-developers/module-development/module-lifecycle/module-packaging/)
|
||||
- [Original MPC module](https://github.com/bitfocus/companion-module-media-player-classic)
|
||||
|
||||
- [MPC-HC status endpoints](https://github.com/clsid2/mpc-hc/blob/develop/src/mpc-hc/WebClientSocket.cpp)
|
||||
- [Ontime progress feedback reference](https://github.com/bitfocus/companion-module-getontime-ontime/blob/main/src/feedbacks/progress.ts)
|
||||
|
|
|
|||
|
|
@ -2,16 +2,43 @@
|
|||
|
||||
Enable **View → Options → Player → Web Interface → Listen on port** in MPC-HC.
|
||||
The default port is **13579**. Enter the player computer's IP address and port
|
||||
in this connection. For a remote player, allow connections from the Companion
|
||||
computer in the player settings and firewall.
|
||||
in this connection. Allow remote access from the Companion computer if needed.
|
||||
|
||||
This module preserves the original 138 command actions and provides a preset
|
||||
for each. Commands such as Open File open a dialog on the player computer;
|
||||
they do not upload a file from Companion. Available commands depend on the
|
||||
MPC-HC build. A successful HTTP response confirms delivery, not playback state.
|
||||
## Ready-to-use presets
|
||||
|
||||
Connection initialization checks `/variables.html`. Actions update connection
|
||||
status on success or failure. There is no periodic polling, playback feedback,
|
||||
or automatic command retry. Re-enable the connection to repeat the initial check.
|
||||
Choose **Transport & timing** in this connection's Presets:
|
||||
|
||||
This is a local test build. Select the **dev** module version to use it.
|
||||
- **Play**: green while playing; amber while paused. Press to play/resume.
|
||||
- **Stop**: red while stopped.
|
||||
- **Previous / Next**: navigate playlist items.
|
||||
- **Mute**: red **MUTED** when the player mute switch is on.
|
||||
- **Pause**: amber while paused.
|
||||
- **Remaining / Elapsed**: live time with a progress bar (passive displays).
|
||||
- **Playback state**: current state with matching color.
|
||||
|
||||
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.
|
||||
|
||||
## Live state
|
||||
|
||||
Feedback follows MPC-HC, including changes made outside Companion. The module
|
||||
prefers `/status.json`, falling back to `/variables.html` for older versions.
|
||||
Status polling defaults to 500 ms (configurable 250–5000 ms). Commands also
|
||||
request fresh status. No command is automatically retried.
|
||||
|
||||
Unavailable status clears active feedback; presets show **OFFLINE**. Requests
|
||||
have a 2.5-second timeout and polling recovers automatically. Idle (no active
|
||||
media graph) is distinct from stopped. Unknown duration displays `--:--` and
|
||||
hides the bar. Countdown is remaining media time, not a prediction adjusted
|
||||
for playback speed. Mute state is separate from a volume setting of zero.
|
||||
|
||||
For custom buttons use connection variables, for example
|
||||
`$(MPC_DEV:remaining)`, `$(MPC_DEV:elapsed)`, `$(MPC_DEV:state)`, or
|
||||
`$(MPC_DEV:progress)` (replace MPC_DEV with your connection label).
|
||||
Numeric seconds, volume, mute, filename, rate, version, and connection status
|
||||
are also exposed. State/audio booleans become null when unavailable.
|
||||
Add the module's boolean state feedbacks or **Playback progress bar** to
|
||||
existing buttons; they are not modified automatically.
|
||||
|
||||
This is a local test build. Select **dev** as the connection's module version.
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
"name": "Media Player Classic (local development)",
|
||||
"shortname": "MPC",
|
||||
"description": "Local MPC-HC development module",
|
||||
"version": "1.1.0-dev.0",
|
||||
"version": "1.2.0-dev.0",
|
||||
"license": "MIT",
|
||||
"maintainers": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "media-player-classic",
|
||||
"version": "1.1.0-dev.0",
|
||||
"version": "1.2.0-dev.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "media-player-classic",
|
||||
"version": "1.1.0-dev.0",
|
||||
"version": "1.2.0-dev.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@companion-module/base": "2.1.3"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "media-player-classic",
|
||||
"version": "1.1.0-dev.0",
|
||||
"version": "1.2.0-dev.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/main.js",
|
||||
|
|
@ -9,7 +9,7 @@
|
|||
"node": "^22.20"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test",
|
||||
"test": "node --test test/*.test.js",
|
||||
"check": "prettier --check .",
|
||||
"format": "prettier --write .",
|
||||
"package": "companion-module-build"
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { normalizeStatus, parseVariables } from './state.js'
|
||||
|
||||
export function endpoint(config) {
|
||||
const host = String(config.host ?? '').trim()
|
||||
const port = Number(config.port ?? 13579)
|
||||
|
|
@ -15,13 +17,19 @@ export class MpcClient {
|
|||
this.abort = new AbortController()
|
||||
}
|
||||
|
||||
async request(path) {
|
||||
async request(path, readBody = false) {
|
||||
const response = await fetch(new URL(path, this.url), {
|
||||
signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(this.timeout)]),
|
||||
redirect: 'error',
|
||||
})
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel()
|
||||
const error = new Error(`MPC-HC returned HTTP ${response.status}`)
|
||||
error.status = response.status
|
||||
throw error
|
||||
}
|
||||
if (readBody) return response.text()
|
||||
await response.body?.cancel()
|
||||
if (!response.ok) throw new Error(`MPC-HC returned HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
async command(id) {
|
||||
|
|
@ -29,8 +37,28 @@ export class MpcClient {
|
|||
await this.request(`/command.html?wm_command=${id}`)
|
||||
}
|
||||
|
||||
async status() {
|
||||
if (this.statusSource !== 'html') {
|
||||
try {
|
||||
const body = await this.request('/status.json', true)
|
||||
// Older servers can return the home page with HTTP 200 for unknown paths.
|
||||
if (!body.trimStart().startsWith('<')) {
|
||||
const state = normalizeStatus(JSON.parse(body))
|
||||
this.statusSource = 'json'
|
||||
return state
|
||||
}
|
||||
} catch (error) {
|
||||
if (![404, 405, 501].includes(error.status)) throw error
|
||||
}
|
||||
const state = parseVariables(await this.request('/variables.html', true))
|
||||
this.statusSource = 'html'
|
||||
return state
|
||||
}
|
||||
return parseVariables(await this.request('/variables.html', true))
|
||||
}
|
||||
|
||||
async probe() {
|
||||
await this.request('/variables.html')
|
||||
return this.status()
|
||||
}
|
||||
|
||||
close() {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { commands } from './commands.js'
|
||||
import { colors } from './feedbacks.js'
|
||||
|
||||
export function actions(send) {
|
||||
return Object.fromEntries(
|
||||
|
|
@ -13,8 +14,8 @@ export function actions(send) {
|
|||
)
|
||||
}
|
||||
|
||||
export function presets() {
|
||||
return Object.fromEntries(
|
||||
export function presets(label = 'MPC_DEV') {
|
||||
const catalog = Object.fromEntries(
|
||||
Object.entries(commands).map(([id, name]) => [
|
||||
id,
|
||||
{
|
||||
|
|
@ -26,4 +27,56 @@ export function presets() {
|
|||
},
|
||||
]),
|
||||
)
|
||||
|
||||
const offline = {
|
||||
feedbackId: 'offline',
|
||||
options: {},
|
||||
style: { text: 'OFFLINE', bgcolor: colors.dark, color: 0x889099 },
|
||||
}
|
||||
const active = (feedbackId, bgcolor, text) => ({
|
||||
feedbackId,
|
||||
options: {},
|
||||
style: { bgcolor, color: colors.white, ...(text ? { text } : {}) },
|
||||
})
|
||||
const button = (name, text, id, feedback = []) => ({
|
||||
type: 'simple',
|
||||
name,
|
||||
style: { text, size: '18', color: colors.white, bgcolor: colors.dark, show_topbar: false },
|
||||
steps: [{ down: id ? [{ actionId: id, options: {} }] : [], up: [] }],
|
||||
feedbacks: [...feedback, offline],
|
||||
})
|
||||
const transport = {
|
||||
transport_play: button('Play — green while playing', '▶\nPLAY', '887', [
|
||||
active('playing', colors.green),
|
||||
active('paused', colors.amber, 'Ⅱ\nPAUSED'),
|
||||
]),
|
||||
transport_stop: button('Stop — red while stopped', '■\nSTOP', '890', [active('stopped', colors.red)]),
|
||||
transport_previous: button('Previous playlist item', '◀◀\nPREV', '918'),
|
||||
transport_next: button('Next playlist item', '▶▶\nNEXT', '919'),
|
||||
transport_mute: button('Toggle mute — red while muted', 'MUTE', '909', [active('muted', colors.red, 'MUTED')]),
|
||||
transport_pause: button('Pause — amber while paused', 'Ⅱ\nPAUSE', '888', [active('paused', colors.amber)]),
|
||||
transport_remaining: button('Remaining time and progress', `LEFT\n$(${label}:remaining)`, null, [
|
||||
{ feedbackId: 'progress_bar', options: {} },
|
||||
]),
|
||||
transport_elapsed: button('Elapsed time and progress', `ELAPSED\n$(${label}:elapsed)`, null, [
|
||||
{ feedbackId: 'progress_bar', options: {} },
|
||||
]),
|
||||
transport_state: button('Playback state', `$(${label}:state)`, null, [
|
||||
active('playing', colors.green),
|
||||
active('paused', colors.amber),
|
||||
active('stopped', colors.red),
|
||||
]),
|
||||
}
|
||||
return { ...transport, ...catalog }
|
||||
}
|
||||
|
||||
export function presetSections(buttons) {
|
||||
return [
|
||||
{
|
||||
id: 'transport',
|
||||
name: 'Transport & timing',
|
||||
definitions: Object.keys(buttons).filter((id) => id.startsWith('transport_')),
|
||||
},
|
||||
{ id: 'commands', name: 'All commands', definitions: Object.keys(commands) },
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,61 @@
|
|||
export const colors = {
|
||||
dark: 0x17212b,
|
||||
green: 0x159447,
|
||||
red: 0xba2936,
|
||||
amber: 0xe09b20,
|
||||
blue: 0x286ba8,
|
||||
white: 0xffffff,
|
||||
}
|
||||
|
||||
export function progressBar(state, image) {
|
||||
if (!image) return {}
|
||||
const width = Math.max(1, Math.min(2048, Math.floor(image.width)))
|
||||
const height = Math.max(1, Math.min(2048, Math.floor(image.height)))
|
||||
if (!Number.isFinite(width) || !Number.isFinite(height)) return {}
|
||||
const pixels = Buffer.alloc(width * height * 4)
|
||||
if (state?.progress != null) {
|
||||
const filled = Math.round((width * state.progress) / 100)
|
||||
const color = state.remaining <= 5000 ? colors.red : state.remaining <= 10000 ? colors.amber : colors.green
|
||||
const barHeight = Math.min(height, Math.max(2, Math.round(height / 9)))
|
||||
for (let y = height - barHeight; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const offset = (y * width + x) * 4
|
||||
const shade = x < filled ? color : 0x46505a
|
||||
pixels[offset] = (shade >> 16) & 255
|
||||
pixels[offset + 1] = (shade >> 8) & 255
|
||||
pixels[offset + 2] = shade & 255
|
||||
pixels[offset + 3] = 255
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
imageBuffer: pixels.toString('base64'),
|
||||
imageBufferEncoding: { pixelFormat: 'RGBA' },
|
||||
imageBufferPosition: { x: 0, y: 0, width, height },
|
||||
}
|
||||
}
|
||||
|
||||
export function feedbacks(getState) {
|
||||
const boolean = (name, callback, color) => ({
|
||||
type: 'boolean',
|
||||
name,
|
||||
options: [],
|
||||
defaultStyle: { color: colors.white, bgcolor: color },
|
||||
callback,
|
||||
})
|
||||
return {
|
||||
playing: boolean('Playing', () => getState()?.state === 'playing', colors.green),
|
||||
stopped: boolean('Stopped', () => getState()?.state === 'stopped', colors.red),
|
||||
paused: boolean('Paused', () => getState()?.state === 'paused', colors.amber),
|
||||
idle: boolean('No active media (idle)', () => getState()?.state === 'idle', colors.dark),
|
||||
muted: boolean('Audio muted', () => getState()?.muted === true, colors.red),
|
||||
offline: boolean('Status unavailable', () => !getState(), colors.dark),
|
||||
progress_bar: {
|
||||
type: 'advanced',
|
||||
name: 'Playback progress bar',
|
||||
options: [],
|
||||
affectedProperties: ['imageBuffer'],
|
||||
callback: (feedback) => progressBar(getState(), feedback.image),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,56 +1,118 @@
|
|||
import { InstanceBase, InstanceStatus } from '@companion-module/base'
|
||||
import { MpcClient } from './client.js'
|
||||
import { actions, presets } from './definitions.js'
|
||||
import { actions, presets, presetSections } from './definitions.js'
|
||||
import { feedbacks } from './feedbacks.js'
|
||||
import { variableDefinitions, variables } from './state.js'
|
||||
|
||||
export const UpgradeScripts = []
|
||||
|
||||
export default class MpcInstance extends InstanceBase {
|
||||
async init(config) {
|
||||
this.setActionDefinitions(actions((id) => this.send(id)))
|
||||
const buttons = presets()
|
||||
this.setPresetDefinitions([{ id: 'commands', name: 'Commands', definitions: Object.keys(buttons) }], buttons)
|
||||
this.setFeedbackDefinitions(feedbacks(() => this.state))
|
||||
this.setVariableDefinitions(variableDefinitions)
|
||||
const buttons = presets(this.label)
|
||||
this.setPresetDefinitions(presetSections(buttons), buttons)
|
||||
await this.configUpdated(config)
|
||||
}
|
||||
|
||||
publish(state) {
|
||||
this.state = state
|
||||
this.setVariableValues(variables(state))
|
||||
this.checkAllFeedbacks()
|
||||
}
|
||||
|
||||
async configUpdated(config) {
|
||||
clearTimeout(this.pollTimer)
|
||||
this.client?.close()
|
||||
this.client = undefined
|
||||
this.pendingPoll = undefined
|
||||
this.publish(null)
|
||||
try {
|
||||
this.client = new MpcClient(config)
|
||||
this.pollInterval = Number(config.poll_interval ?? 500)
|
||||
if (!Number.isInteger(this.pollInterval) || this.pollInterval < 250 || this.pollInterval > 5000) {
|
||||
throw new Error('Status polling must be between 250 and 5000 milliseconds.')
|
||||
}
|
||||
this.client = new MpcClient(config, 2500)
|
||||
} catch (error) {
|
||||
this.updateStatus(InstanceStatus.BadConfig, error.message)
|
||||
return
|
||||
}
|
||||
this.lastError = undefined
|
||||
// Rebuild variable references if the connection label changed.
|
||||
const buttons = presets(this.label)
|
||||
this.setPresetDefinitions(presetSections(buttons), buttons)
|
||||
this.updateStatus(InstanceStatus.Connecting)
|
||||
// Do not block module initialization on an unavailable player.
|
||||
void this.perform((client) => client.probe())
|
||||
void this.refresh()
|
||||
}
|
||||
|
||||
async perform(operation) {
|
||||
const client = this.client
|
||||
if (!client) return
|
||||
try {
|
||||
await operation(client)
|
||||
if (client === this.client) this.updateStatus(InstanceStatus.Ok)
|
||||
} catch (error) {
|
||||
if (client !== this.client) return
|
||||
const detail = error.cause?.code ?? error.message
|
||||
this.updateStatus(InstanceStatus.ConnectionFailure, String(detail))
|
||||
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) {
|
||||
await this.perform((client) => client.command(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 destroy() {
|
||||
clearTimeout(this.pollTimer)
|
||||
this.client?.close()
|
||||
this.client = undefined
|
||||
this.pendingPoll = undefined
|
||||
}
|
||||
|
||||
getConfigFields() {
|
||||
return [
|
||||
{
|
||||
type: 'number',
|
||||
id: 'poll_interval',
|
||||
label: 'Status polling interval (milliseconds)',
|
||||
width: 12,
|
||||
default: 500,
|
||||
min: 250,
|
||||
max: 5000,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
type: 'static-text',
|
||||
id: 'info',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,106 @@
|
|||
const names = { '-1': 'idle', 0: 'stopped', 1: 'paused', 2: 'playing' }
|
||||
|
||||
function number(value, name) {
|
||||
if (value === '' || value === null || value === undefined || !Number.isFinite(Number(value))) {
|
||||
throw new Error(`Invalid MPC-HC status field: ${name}`)
|
||||
}
|
||||
return Number(value)
|
||||
}
|
||||
|
||||
export function normalizeStatus(data) {
|
||||
if (!data || typeof data !== 'object') throw new Error('Invalid MPC-HC status response')
|
||||
const code = number(data.state, 'state')
|
||||
if (!(code in names)) throw new Error(`Unknown MPC-HC playback state: ${code}`)
|
||||
const position = Math.max(0, number(data.position, 'position'))
|
||||
const duration = Math.max(0, number(data.duration, 'duration'))
|
||||
const volume = number(data.volume, 'volume')
|
||||
if (typeof data.muted !== 'boolean' || volume < 0 || volume > 100) throw new Error('Invalid MPC-HC audio status')
|
||||
return {
|
||||
state: names[code],
|
||||
file: typeof data.file === 'string' ? data.file : '',
|
||||
position,
|
||||
duration,
|
||||
remaining: duration > 0 ? Math.max(0, duration - position) : null,
|
||||
progress: duration > 0 ? Math.min(100, (position / duration) * 100) : null,
|
||||
volume,
|
||||
muted: data.muted,
|
||||
rate: data.rate === undefined ? null : number(data.rate, 'rate'),
|
||||
version: typeof data.version === 'string' ? data.version : '',
|
||||
}
|
||||
}
|
||||
|
||||
function decode(text) {
|
||||
const named = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }
|
||||
return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (match, key) => {
|
||||
if (!key.startsWith('#')) return named[key.toLowerCase()]
|
||||
const code = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : Number(key.slice(1))
|
||||
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match
|
||||
})
|
||||
}
|
||||
|
||||
export function parseVariables(html) {
|
||||
const fields = {}
|
||||
for (const match of html.matchAll(/<p\b[^>]*\bid\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/p\s*>/gi)) {
|
||||
fields[match[1]] = decode(match[2].trim())
|
||||
}
|
||||
if (!['0', '1'].includes(fields.muted)) throw new Error('Invalid MPC-HC status field: muted')
|
||||
return normalizeStatus({
|
||||
...fields,
|
||||
volume: fields.volumelevel,
|
||||
muted: fields.muted === '1',
|
||||
rate: fields.playbackrate,
|
||||
})
|
||||
}
|
||||
|
||||
export function clock(milliseconds, roundUp = false) {
|
||||
if (milliseconds === null || milliseconds === undefined) return '--:--'
|
||||
const seconds = Math.max(0, (roundUp ? Math.ceil : Math.floor)(milliseconds / 1000))
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
const minutes = String(Math.floor(seconds / 60) % 60).padStart(2, '0')
|
||||
const remainder = String(seconds % 60).padStart(2, '0')
|
||||
return hours ? `${hours}:${minutes}:${remainder}` : `${minutes}:${remainder}`
|
||||
}
|
||||
|
||||
export const variableDefinitions = Object.fromEntries(
|
||||
Object.entries({
|
||||
connected: 'Status data is available',
|
||||
state: 'Playback state: playing, paused, stopped, idle, or offline',
|
||||
playing: 'Player reports playing',
|
||||
stopped: 'Player reports stopped (idle is separate)',
|
||||
paused: 'Player reports paused',
|
||||
muted: 'Player mute switch (independent of volume)',
|
||||
volume: 'Volume percent',
|
||||
file: 'Current filename',
|
||||
elapsed: 'Elapsed media time',
|
||||
duration: 'Media duration',
|
||||
remaining: 'Remaining media time',
|
||||
elapsed_seconds: 'Elapsed media time in seconds',
|
||||
duration_seconds: 'Media duration in seconds',
|
||||
remaining_seconds: 'Remaining media time in seconds',
|
||||
progress: 'Media progress percent (0–100)',
|
||||
rate: 'Playback rate',
|
||||
version: 'MPC-HC version',
|
||||
}).map(([id, name]) => [id, { name }]),
|
||||
)
|
||||
|
||||
export function variables(state) {
|
||||
return {
|
||||
connected: !!state,
|
||||
state: state?.state ?? 'offline',
|
||||
playing: state ? state.state === 'playing' : null,
|
||||
stopped: state ? state.state === 'stopped' : null,
|
||||
paused: state ? state.state === 'paused' : null,
|
||||
muted: state?.muted ?? null,
|
||||
volume: state?.volume ?? null,
|
||||
file: state?.file ?? '',
|
||||
elapsed: clock(state?.position),
|
||||
duration: clock(state && state.duration > 0 ? state.duration : null, true),
|
||||
remaining: clock(state?.remaining, true),
|
||||
elapsed_seconds: state ? state.position / 1000 : null,
|
||||
duration_seconds: state && state.duration > 0 ? state.duration / 1000 : null,
|
||||
remaining_seconds: state?.remaining == null ? null : state.remaining / 1000,
|
||||
progress: state?.progress == null ? null : Math.round(state.progress * 10) / 10,
|
||||
rate: state?.rate ?? null,
|
||||
version: state?.version ?? '',
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { createServer } from 'node:http'
|
|||
import { test } from 'node:test'
|
||||
import { MpcClient, endpoint } from '../src/client.js'
|
||||
import { actions, presets } from '../src/definitions.js'
|
||||
import { status, htmlStatus } from './fixture.js'
|
||||
|
||||
async function server(t, handler) {
|
||||
const server = createServer(handler)
|
||||
|
|
@ -19,7 +20,7 @@ test('all original actions and presets dispatch their numeric command IDs', asyn
|
|||
const client = new MpcClient(
|
||||
await server(t, (req, res) => {
|
||||
paths.push(req.url)
|
||||
res.end('ok')
|
||||
res.end(JSON.stringify(status))
|
||||
}),
|
||||
)
|
||||
t.after(() => client.close())
|
||||
|
|
@ -31,7 +32,7 @@ test('all original actions and presets dispatch their numeric command IDs', asyn
|
|||
assert.equal(presets()[id].steps[0].down[0].actionId, id)
|
||||
}
|
||||
await client.probe()
|
||||
assert.equal(paths.at(-1), '/variables.html')
|
||||
assert.equal(paths.at(-1), '/status.json')
|
||||
})
|
||||
|
||||
test('HTTP failures and redirects fail rather than reporting success', async (t) => {
|
||||
|
|
@ -72,3 +73,44 @@ test('reject invalid configuration and command injection', async () => {
|
|||
await assert.rejects(client.command('887&extra=1'))
|
||||
client.close()
|
||||
})
|
||||
|
||||
test('prefer JSON, fall back once for unavailable endpoints, and decode HTML entities', async (t) => {
|
||||
for (const unavailable of [404, 200]) {
|
||||
const paths = []
|
||||
const client = new MpcClient(
|
||||
await server(t, (req, res) => {
|
||||
paths.push(req.url)
|
||||
if (req.url === '/status.json') {
|
||||
res.writeHead(unavailable)
|
||||
res.end('<html>Home</html>')
|
||||
} else res.end(htmlStatus({ ...status, file: 'A & B 🎬', muted: true }))
|
||||
}),
|
||||
)
|
||||
t.after(() => client.close())
|
||||
const first = await client.status()
|
||||
assert.equal(first.file, 'A & B 🎬')
|
||||
assert.equal(first.muted, true)
|
||||
assert.equal(first.state, 'playing')
|
||||
await client.status()
|
||||
assert.deepEqual(paths, ['/status.json', '/variables.html', '/variables.html'])
|
||||
}
|
||||
})
|
||||
|
||||
test('malformed status and server failures are not hidden by HTML fallback', async (t) => {
|
||||
for (const body of ['garbage', '{}', JSON.stringify({ ...status, muted: 'false' })]) {
|
||||
const client = new MpcClient(await server(t, (_, res) => res.end(body)))
|
||||
t.after(() => client.close())
|
||||
await assert.rejects(client.status())
|
||||
}
|
||||
let count = 0
|
||||
const client = new MpcClient(
|
||||
await server(t, (_, res) => {
|
||||
count++
|
||||
res.writeHead(503)
|
||||
res.end()
|
||||
}),
|
||||
)
|
||||
t.after(() => client.close())
|
||||
await assert.rejects(client.status())
|
||||
assert.equal(count, 1)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,16 @@
|
|||
export const status = {
|
||||
file: 'Test clip.mp4',
|
||||
state: 2,
|
||||
position: 12500,
|
||||
duration: 60000,
|
||||
volume: 75,
|
||||
muted: false,
|
||||
rate: 1,
|
||||
version: '2.8.5.0',
|
||||
}
|
||||
|
||||
export function htmlStatus(data = status) {
|
||||
return Object.entries({ ...data, volumelevel: data.volume, muted: data.muted ? 1 : 0, playbackrate: data.rate })
|
||||
.map(([key, value]) => `<p id="${key}">${value}</p>`)
|
||||
.join('\n')
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { createServer } from 'node:http'
|
|||
import { test } from 'node:test'
|
||||
import { InstanceStatus } from '@companion-module/base'
|
||||
import MpcInstance from '../src/main.js'
|
||||
import { status as sample } from './fixture.js'
|
||||
|
||||
function instance() {
|
||||
const state = { statuses: [] }
|
||||
|
|
@ -17,6 +18,14 @@ function instance() {
|
|||
state.sections = sections
|
||||
state.presets = presets
|
||||
},
|
||||
setFeedbackDefinitions: (feedbacks) => {
|
||||
state.feedbacks = feedbacks
|
||||
},
|
||||
setVariableDefinitions: () => {},
|
||||
setVariableValues: (variables) => {
|
||||
state.variables = variables
|
||||
},
|
||||
checkAllFeedbacks: () => {},
|
||||
updateStatus: (status) => state.statuses.push(status),
|
||||
})
|
||||
return { module, state }
|
||||
|
|
@ -26,7 +35,7 @@ test('initialization registers API 2 presets; successful actions recover failed
|
|||
let status = 200
|
||||
const server = createServer((_, response) => {
|
||||
response.writeHead(status)
|
||||
response.end()
|
||||
response.end(JSON.stringify(sample))
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const { module, state } = instance()
|
||||
|
|
@ -39,11 +48,16 @@ test('initialization registers API 2 presets; successful actions recover failed
|
|||
await module.send('887')
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||
assert.equal(Object.keys(state.actions).length, 138)
|
||||
assert.deepEqual(state.sections[0].definitions, Object.keys(state.presets))
|
||||
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)
|
||||
assert.ok(Object.values(state.presets).every((preset) => preset.type === 'simple'))
|
||||
status = 503
|
||||
await module.send('887')
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.ConnectionFailure)
|
||||
assert.equal(state.variables.state, 'offline')
|
||||
assert.equal(state.variables.muted, null)
|
||||
assert.equal(state.feedbacks.playing.callback(), false)
|
||||
status = 200
|
||||
await module.send('888')
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||
|
|
@ -70,3 +84,53 @@ test('configuration changes and destroy cancel stale operations without overwrit
|
|||
assert.equal(state.statuses.length, count)
|
||||
assert.equal(module.client, undefined)
|
||||
})
|
||||
|
||||
test('polling discovers external changes, retries failures, and stops on destroy', async (t) => {
|
||||
let data = { ...sample }
|
||||
let code = 200
|
||||
let requests = 0
|
||||
let active = 0
|
||||
let maximum = 0
|
||||
const server = createServer((_, response) => {
|
||||
requests++
|
||||
active++
|
||||
maximum = Math.max(maximum, active)
|
||||
setTimeout(() => {
|
||||
active--
|
||||
response.writeHead(code)
|
||||
response.end(JSON.stringify(data))
|
||||
}, 15)
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const { module, state } = instance()
|
||||
t.after(async () => {
|
||||
await module.destroy()
|
||||
server.closeAllConnections()
|
||||
server.close()
|
||||
})
|
||||
const until = async (condition) => {
|
||||
const deadline = Date.now() + 3000
|
||||
while (!condition()) {
|
||||
assert.ok(Date.now() < deadline, 'polling did not reach expected state')
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
}
|
||||
}
|
||||
await module.init({ host: '127.0.0.1', port: server.address().port, poll_interval: 250 })
|
||||
await Promise.all(Array.from({ length: 10 }, () => module.refresh()))
|
||||
assert.equal(maximum, 1)
|
||||
assert.equal(requests, 1)
|
||||
data = { ...sample, state: 1, muted: true, position: 20000 }
|
||||
await until(() => state.variables.paused && state.variables.muted)
|
||||
assert.equal(state.variables.remaining, '00:40')
|
||||
code = 503
|
||||
await until(() => state.variables.state === 'offline')
|
||||
assert.equal(state.variables.remaining, '--:--')
|
||||
code = 200
|
||||
data = { ...sample, state: 0, position: 0 }
|
||||
await until(() => state.variables.stopped)
|
||||
assert.equal(state.feedbacks.stopped.callback(), true)
|
||||
await module.destroy()
|
||||
const lastCount = requests
|
||||
await new Promise((resolve) => setTimeout(resolve, 350))
|
||||
assert.equal(requests, lastCount)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,86 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { normalizeStatus, parseVariables, variables, clock } from '../src/state.js'
|
||||
import { feedbacks, progressBar } from '../src/feedbacks.js'
|
||||
import { presets } from '../src/definitions.js'
|
||||
import { status, htmlStatus } from './fixture.js'
|
||||
|
||||
test('playback feedback follows numeric player state, not localized strings or button presses', () => {
|
||||
for (const [code, name] of [
|
||||
[-1, 'idle'],
|
||||
[0, 'stopped'],
|
||||
[1, 'paused'],
|
||||
[2, 'playing'],
|
||||
]) {
|
||||
const state = normalizeStatus({ ...status, state: code, stateString: 'Localized text' })
|
||||
const definitions = feedbacks(() => state)
|
||||
for (const id of ['playing', 'stopped', 'paused', 'idle']) assert.equal(definitions[id].callback(), id === name)
|
||||
assert.equal(definitions.muted.callback(), false)
|
||||
}
|
||||
assert.equal(feedbacks(() => normalizeStatus({ ...status, volume: 0 })).muted.callback(), false)
|
||||
assert.equal(feedbacks(() => normalizeStatus({ ...status, muted: true })).muted.callback(), true)
|
||||
assert.equal(feedbacks(() => null).offline.callback(), true)
|
||||
assert.equal(feedbacks(() => null).stopped.callback(), false)
|
||||
})
|
||||
|
||||
test('timing uses milliseconds, clamps end/seek overshoot, and handles unknown duration', () => {
|
||||
const state = normalizeStatus(status)
|
||||
assert.equal(state.remaining, 47500)
|
||||
assert.equal(variables(state).remaining, '00:48')
|
||||
assert.equal(variables(state).elapsed, '00:12')
|
||||
assert.equal(variables(state).progress, 20.8)
|
||||
assert.equal(clock(3661000), '1:01:01')
|
||||
assert.equal(clock(0), '00:00')
|
||||
const ended = normalizeStatus({ ...status, position: 61000 })
|
||||
assert.equal(ended.remaining, 0)
|
||||
assert.equal(ended.progress, 100)
|
||||
const unknown = normalizeStatus({ ...status, duration: 0 })
|
||||
assert.equal(variables(unknown).remaining, '--:--')
|
||||
assert.equal(unknown.progress, null)
|
||||
assert.equal(variables(null).remaining_seconds, null)
|
||||
assert.equal(variables(null).connected, false)
|
||||
assert.equal(variables(null).muted, null)
|
||||
})
|
||||
|
||||
test('HTML parsing rejects incomplete/error pages and does not evaluate scripts', () => {
|
||||
assert.deepEqual(parseVariables(htmlStatus()), normalizeStatus(status))
|
||||
assert.throws(() => parseVariables('<html>Authentication required</html>'))
|
||||
assert.throws(() => parseVariables(htmlStatus().replace('<p id="state">2</p>', '')))
|
||||
assert.throws(() => normalizeStatus({ ...status, state: 42 }))
|
||||
assert.throws(() => normalizeStatus({ ...status, duration: 'NaN' }))
|
||||
})
|
||||
|
||||
test('transport presets use playlist commands and state feedback; time displays are passive', () => {
|
||||
const buttons = presets('MY_PLAYER')
|
||||
for (const [preset, command] of [
|
||||
['play', '887'],
|
||||
['stop', '890'],
|
||||
['previous', '918'],
|
||||
['next', '919'],
|
||||
['mute', '909'],
|
||||
]) {
|
||||
assert.equal(buttons[`transport_${preset}`].steps[0].down[0].actionId, command)
|
||||
assert.equal(buttons[`transport_${preset}`].feedbacks.at(-1).feedbackId, 'offline')
|
||||
}
|
||||
assert.equal(buttons.transport_play.feedbacks[0].feedbackId, 'playing')
|
||||
assert.equal(buttons.transport_stop.feedbacks[0].feedbackId, 'stopped')
|
||||
assert.equal(buttons.transport_mute.feedbacks[0].feedbackId, 'muted')
|
||||
assert.equal(buttons.transport_remaining.style.text, 'LEFT\n$(MY_PLAYER:remaining)')
|
||||
assert.deepEqual(buttons.transport_remaining.steps[0].down, [])
|
||||
})
|
||||
|
||||
test('progress graphic fills the bottom proportionally and clears when state is unavailable', () => {
|
||||
const bar = progressBar(normalizeStatus({ ...status, position: 30000 }), { width: 72, height: 72 })
|
||||
const pixels = Buffer.from(bar.imageBuffer, 'base64')
|
||||
assert.equal(pixels.length, 72 * 72 * 4)
|
||||
assert.equal(pixels[3], 0)
|
||||
assert.equal(pixels[71 * 72 * 4 + 3], 255)
|
||||
assert.notDeepEqual(
|
||||
pixels.subarray((71 * 72 + 35) * 4, (71 * 72 + 36) * 4),
|
||||
pixels.subarray((71 * 72 + 36) * 4, (71 * 72 + 37) * 4),
|
||||
)
|
||||
assert.ok(
|
||||
Buffer.from(progressBar(null, { width: 72, height: 72 }).imageBuffer, 'base64').every((value) => value === 0),
|
||||
)
|
||||
assert.deepEqual(progressBar(null, undefined), {})
|
||||
})
|
||||
Loading…
Reference in New Issue