refactor: timer update

This commit is contained in:
Carlos Valente
2024-07-16 21:29:31 +02:00
committed by Carlos Valente
parent cb773ded9f
commit edc7f20d7a
7 changed files with 195 additions and 397 deletions
+20 -10
View File
@@ -4,6 +4,8 @@ import * as runtimeState from '../stores/runtimeState.js';
import type { UpdateResult } from '../stores/runtimeState.js'; import type { UpdateResult } from '../stores/runtimeState.js';
import { timerConfig } from '../config/config.js'; import { timerConfig } from '../config/config.js';
type UpdateCallbackFn = (updateResult: UpdateResult) => void;
/** /**
* Service manages Ontime's main timer * Service manages Ontime's main timer
*/ */
@@ -13,9 +15,9 @@ export class TimerService {
static _refreshInterval: number; static _refreshInterval: number;
/** when timer will be finished */ /** when timer will be finished */
private endCallback: NodeJS.Timeout; private endCallback: NodeJS.Timeout | undefined = undefined;
private onUpdateCallback: (updateResult: UpdateResult) => void; private onUpdateCallback: UpdateCallbackFn | undefined = undefined;
/** /**
* @constructor * @constructor
@@ -23,19 +25,21 @@ export class TimerService {
* @param {number} [timerConfig.updateInterval] how often we update the socket * @param {number} [timerConfig.updateInterval] how often we update the socket
* @param {function} [timerConfig.onUpdateCallback] how often we update the socket * @param {function} [timerConfig.onUpdateCallback] how often we update the socket
*/ */
constructor(timerConfig: { constructor(timerConfig: { refresh: number; updateInterval: number }) {
refresh: number;
updateInterval: number;
onUpdateCallback: (updateResult: UpdateResult) => void;
}) {
TimerService._refreshInterval = timerConfig.refresh; TimerService._refreshInterval = timerConfig.refresh;
this.onUpdateCallback = timerConfig.onUpdateCallback;
this._interval = setInterval(() => { this._interval = setInterval(() => {
this.update(); this.update();
}, TimerService._refreshInterval); }, TimerService._refreshInterval);
} }
/**
* Allows setting a callback for when the timer updates
* @param callback
*/
setOnUpdateCallback(callback: (updateResult: UpdateResult) => void) {
this.onUpdateCallback = callback;
}
start() { start() {
if (!runtimeState.start()) { if (!runtimeState.start()) {
return false; return false;
@@ -79,6 +83,12 @@ export class TimerService {
// renew end callback // renew end callback
clearTimeout(this.endCallback); clearTimeout(this.endCallback);
const state = runtimeState.getState(); const state = runtimeState.getState();
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
if (state.timer.expectedFinish === null) {
throw new Error('TimerService.addTime: expectedFinish is negative');
}
}
this.endCallback = setTimeout(() => this.update(), state.timer.expectedFinish); this.endCallback = setTimeout(() => this.update(), state.timer.expectedFinish);
return true; return true;
} }
@@ -89,7 +99,7 @@ export class TimerService {
update() { update() {
const updateResult = runtimeState.update(); const updateResult = runtimeState.update();
// pass the result to the parent // pass the result to the parent
this.onUpdateCallback(updateResult); this.onUpdateCallback?.(updateResult);
} }
/** /**
@@ -10,7 +10,6 @@ import {
getTotalDuration, getTotalDuration,
normaliseEndTime, normaliseEndTime,
skippedOutOfEvent, skippedOutOfEvent,
updateRoll,
} from '../timerUtils.js'; } from '../timerUtils.js';
import { RuntimeState } from '../../stores/runtimeState.js'; import { RuntimeState } from '../../stores/runtimeState.js';
@@ -1237,196 +1236,6 @@ test('normaliseEndTime()', () => {
expect(normaliseEndTime(t3.start, t3.end)).toBe(t3_expected); expect(normaliseEndTime(t3.start, t3.end)).toBe(t3_expected);
}); });
describe('updateRoll()', () => {
it('it updates running events correctly', () => {
const timers = {
eventNow: {
id: '1',
},
clock: 11,
timer: {
current: 10,
expectedFinish: 100,
secondaryTimer: null,
startedAt: 1,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: 100 - 11,
updatedSecondaryTimer: null, // usually clock - expectedFinish
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
// test that it can jump time
timers.timer.expectedFinish = 1000;
timers.clock = 600;
expected.updatedTimer = 1000 - 600;
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('it updates secondary timer', () => {
const timers = {
eventNow: null,
clock: 11,
timer: {
current: null,
expectedFinish: null,
secondaryTimer: 1,
},
_timer: {
secondaryTarget: 15,
},
} as RuntimeState;
const expected = {
updatedTimer: null,
updatedSecondaryTimer: 15 - 11, // countdown to secondary
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('flags an event end', () => {
const timers = {
eventNow: {
id: '1',
},
clock: 12,
timer: {
startedAt: 0,
current: 10,
expectedFinish: 11,
secondaryTimer: null,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: -1,
updatedSecondaryTimer: null,
doRollLoad: true,
isFinished: true,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('secondary events do not trigger event ends', () => {
const timers = {
eventNow: null,
clock: 16,
timer: {
startedAt: null,
current: null,
expectedFinish: null,
secondaryTimer: 1,
},
_timer: {
secondaryTarget: 15,
},
} as RuntimeState;
const expected = {
updatedTimer: null,
updatedSecondaryTimer: -1,
doRollLoad: true,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('when a secondary timer is finished, it prompts for new event load', () => {
const timers = {
eventNow: null,
clock: 15,
timer: {
current: null,
expectedFinish: null,
secondaryTimer: 0,
},
_timer: {
secondaryTarget: 15,
},
} as RuntimeState;
const expected = {
updatedTimer: null,
updatedSecondaryTimer: 0,
doRollLoad: true,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('counts over midnight', () => {
const timers = {
eventNow: {
id: '1',
},
clock: dayInMs - 10,
timer: {
current: 25,
expectedFinish: 10,
startedAt: 1000,
secondaryTimer: null,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: 20,
updatedSecondaryTimer: null,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('rolls over midnight', () => {
const timers = {
eventNow: {
id: '1',
},
clock: 10,
timer: {
current: dayInMs,
expectedFinish: 10,
startedAt: 1000,
secondaryTimer: null,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: dayInMs,
updatedSecondaryTimer: null,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
});
describe('getRuntimeOffset()', () => { describe('getRuntimeOffset()', () => {
it('is the difference between scheduled and when we actually started', () => { it('is the difference between scheduled and when we actually started', () => {
const state = { const state = {
@@ -1554,7 +1363,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null, secondaryTimer: null,
startedAt: null, startedAt: null,
}, },
_timer: { pausedAt: null, secondaryTarget: null }, _timer: { pausedAt: null },
} as RuntimeState; } as RuntimeState;
const offset = getRuntimeOffset(state); const offset = getRuntimeOffset(state);
@@ -1595,7 +1404,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null, secondaryTimer: null,
startedAt: null, startedAt: null,
}, },
_timer: { pausedAt: null, secondaryTarget: null }, _timer: { pausedAt: null },
} as RuntimeState; } as RuntimeState;
const offset = getRuntimeOffset(state); const offset = getRuntimeOffset(state);
@@ -1630,7 +1439,7 @@ describe('getRuntimeOffset()', () => {
runtime: { runtime: {
selectedEventIndex: 0, selectedEventIndex: 0,
numEvents: 1, numEvents: 1,
offset: null, offset: 0,
plannedStart: 77400000, // 21:30:00 plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00 plannedEnd: 81000000, // 22:30:00
actualStart: 78000000, // 21:40:00 actualStart: 78000000, // 21:40:00
@@ -1647,7 +1456,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null, secondaryTimer: null,
startedAt: 78000000, startedAt: 78000000,
}, },
_timer: { pausedAt: null, secondaryTarget: null }, _timer: { pausedAt: null },
} as RuntimeState; } as RuntimeState;
const offset = getRuntimeOffset(state); const offset = getRuntimeOffset(state);
@@ -1682,7 +1491,7 @@ describe('getRuntimeOffset()', () => {
runtime: { runtime: {
selectedEventIndex: 0, selectedEventIndex: 0,
numEvents: 1, numEvents: 1,
offset: null, offset: 0,
plannedStart: 77400000, // 21:30:00 plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00 plannedEnd: 81000000, // 22:30:00
actualStart: 78000000, // 21:40:00 actualStart: 78000000, // 21:40:00
@@ -1699,7 +1508,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null, secondaryTimer: null,
startedAt: 78000000, startedAt: 78000000,
}, },
_timer: { pausedAt: null, secondaryTarget: null }, _timer: { pausedAt: null },
} as RuntimeState; } as RuntimeState;
const offset = getRuntimeOffset(state); const offset = getRuntimeOffset(state);
@@ -1722,7 +1531,7 @@ describe('getRuntimeOffset()', () => {
runtime: { runtime: {
selectedEventIndex: 0, selectedEventIndex: 0,
numEvents: 1, numEvents: 1,
offset: null, offset: 0,
plannedStart: 77400000, // 21:30:00 plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00 plannedEnd: 81000000, // 22:30:00
actualStart: 82000000, // 22:46:40 <--- started now actualStart: 82000000, // 22:46:40 <--- started now
@@ -1739,7 +1548,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null, secondaryTimer: null,
startedAt: 82000000, // <--- started now startedAt: 82000000, // <--- started now
}, },
_timer: { pausedAt: null, secondaryTarget: null }, _timer: { pausedAt: null },
} as RuntimeState; } as RuntimeState;
const updateCurrent = getCurrent(state); const updateCurrent = getCurrent(state);
@@ -1887,7 +1696,7 @@ describe('getTimerPhase()', () => {
runtime: { runtime: {
selectedEventIndex: null, selectedEventIndex: null,
numEvents: 1, numEvents: 1,
offset: null, offset: 0,
plannedStart: 55860000, plannedStart: 55860000,
plannedEnd: 55880000, plannedEnd: 55880000,
actualStart: null, actualStart: null,
@@ -1909,7 +1718,6 @@ describe('getTimerPhase()', () => {
forceFinish: null, forceFinish: null,
totalDelay: 0, totalDelay: 0,
pausedAt: null, pausedAt: null,
secondaryTarget: 55860000,
}, },
} as RuntimeState; } as RuntimeState;
@@ -1927,7 +1735,7 @@ describe('getTimerPhase()', () => {
runtime: { runtime: {
selectedEventIndex: null, selectedEventIndex: null,
numEvents: 1, numEvents: 1,
offset: null, offset: 0,
plannedStart: 55860000, plannedStart: 55860000,
plannedEnd: 55880000, plannedEnd: 55880000,
actualStart: null, actualStart: null,
@@ -1949,7 +1757,6 @@ describe('getTimerPhase()', () => {
forceFinish: null, forceFinish: null,
totalDelay: 0, totalDelay: 0,
pausedAt: null, pausedAt: null,
secondaryTarget: 55860000,
}, },
} as RuntimeState; } as RuntimeState;
@@ -29,7 +29,9 @@ import {
getEventWithId, getEventWithId,
getPlayableEvents, getPlayableEvents,
} from '../rundown-service/rundownUtils.js'; } from '../rundown-service/rundownUtils.js';
import { skippedOutOfEvent } from '../timerUtils.js';
import { integrationService } from '../integration-service/IntegrationService.js'; import { integrationService } from '../integration-service/IntegrationService.js';
import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './rundownService.utils.js'; import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './rundownService.utils.js';
/** /**
@@ -37,18 +39,21 @@ import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './ru
* Coordinating with necessary services * Coordinating with necessary services
*/ */
class RuntimeService { class RuntimeService {
private eventTimer: TimerService | null = null; private eventTimer: TimerService;
private lastIntegrationClockUpdate = -1; private lastIntegrationClockUpdate = -1;
private lastIntegrationTimerValue = -1; private lastIntegrationTimerValue = -1;
/** last time we updated the socket */ /** last time we updated the socket */
static previousTimerUpdate: number; static previousTimerUpdate: number;
static previousTimerValue: MaybeNumber; static previousTimerValue: MaybeNumber; // previous timer value, could be null
static previousClockUpdate: number; static previousClockUpdate: number;
/** last known state */ /** last known state */
static previousState: RuntimeState; static previousState: RuntimeState;
constructor() { constructor(timerService: TimerService) {
this.eventTimer = timerService;
RuntimeService.previousTimerUpdate = -1; RuntimeService.previousTimerUpdate = -1;
RuntimeService.previousTimerValue = -1; RuntimeService.previousTimerValue = -1;
RuntimeService.previousClockUpdate = -1; RuntimeService.previousClockUpdate = -1;
@@ -59,7 +64,45 @@ class RuntimeService {
@broadcastResult @broadcastResult
checkTimerUpdate({ shouldCallRoll, hasTimerFinished }: runtimeState.UpdateResult) { checkTimerUpdate({ shouldCallRoll, hasTimerFinished }: runtimeState.UpdateResult) {
const newState = runtimeState.getState(); const newState = runtimeState.getState();
if (hasTimerFinished) {
// 1. find if we need to dispatch integrations related to the phase
const timerPhaseChanged = RuntimeService.previousState.timer?.phase !== newState.timer.phase;
if (timerPhaseChanged) {
if (newState.timer.phase === TimerPhase.Warning) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onWarning);
});
} else if (newState.timer.phase === TimerPhase.Danger) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onDanger);
});
}
}
// 2. handle edge cases related to roll
if (newState.timer.playback === Playback.Roll) {
// check if we need to call roll again
const needsEvent =
newState.eventNow === null
? true
: skippedOutOfEvent(newState, this.lastIntegrationClockUpdate, timerConfig.skipLimit);
const hasFinishedRoll = hasTimerFinished && shouldCallRoll;
if (shouldCallRoll || needsEvent) {
if (hasFinishedRoll) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onFinish);
});
}
// we dont call this.roll because we need to bypass the checks
const rundown = getPlayableEvents();
// TODO: by not calling roll, we dont get the events
this.eventTimer.roll(rundown);
}
}
// 3. find if we need to process actions related to the timer finishing
if (newState.timer.playback !== Playback.Roll && hasTimerFinished) {
process.nextTick(() => { process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onFinish); integrationService.dispatch(TimerLifeCycle.onFinish);
}); });
@@ -77,10 +120,8 @@ class RuntimeService {
} }
} }
const hasRunningTimer = Boolean(newState.eventNow) && newState.timer.playback === Playback.Play; // 4. find if we need to update the timer
const shouldUpdateTimer = const shouldUpdateTimer = getShouldTimerUpdate(this.lastIntegrationTimerValue, newState.timer.current);
hasRunningTimer && getShouldTimerUpdate(this.lastIntegrationTimerValue, newState.timer.current);
if (shouldUpdateTimer) { if (shouldUpdateTimer) {
process.nextTick(() => { process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onUpdate); integrationService.dispatch(TimerLifeCycle.onUpdate);
@@ -89,6 +130,7 @@ class RuntimeService {
this.lastIntegrationTimerValue = newState.timer.current ?? -1; this.lastIntegrationTimerValue = newState.timer.current ?? -1;
} }
// 5. find if we need to update the clock
const shouldUpdateClock = getShouldClockUpdate(this.lastIntegrationClockUpdate, newState.clock); const shouldUpdateClock = getShouldClockUpdate(this.lastIntegrationClockUpdate, newState.clock);
if (shouldUpdateClock) { if (shouldUpdateClock) {
process.nextTick(() => { process.nextTick(() => {
@@ -97,42 +139,12 @@ class RuntimeService {
this.lastIntegrationClockUpdate = newState.clock; this.lastIntegrationClockUpdate = newState.clock;
} }
if (shouldCallRoll) {
// we dont call this.roll because we need to bypass the checks
const rundown = getPlayableEvents();
this.eventTimer.roll(rundown);
}
const timerPhaseChanged = RuntimeService.previousState.timer?.phase !== newState.timer.phase;
if (timerPhaseChanged) {
switch (newState.timer.phase) {
case TimerPhase.Warning:
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onWarning);
});
break;
case TimerPhase.Danger:
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onDanger);
});
break;
default:
break;
}
}
} }
/** delay initialisation until we have a restore point */ /** delay initialisation until we have a restore point */
init(resumable: RestorePoint | null) { init(resumable: RestorePoint | null) {
logger.info(LogOrigin.Server, 'Runtime service started'); logger.info(LogOrigin.Server, 'Runtime service started');
// calculate at 30fps, refresh at 1fps this.eventTimer.setOnUpdateCallback((updateResult) => this.checkTimerUpdate(updateResult));
this.eventTimer = new TimerService({
refresh: timerConfig.updateRate,
updateInterval: timerConfig.notificationRate,
onUpdateCallback: (updateResult) => this.checkTimerUpdate(updateResult),
});
if (resumable) { if (resumable) {
this.resume(resumable); this.resume(resumable);
@@ -553,8 +565,16 @@ class RuntimeService {
} }
} }
export const runtimeService = new RuntimeService(); // calculate at 30fps, refresh at 1fps
const eventTimer = new TimerService({
refresh: timerConfig.updateRate,
updateInterval: timerConfig.notificationRate,
});
export const runtimeService = new RuntimeService(eventTimer);
/**
* Decorator manages side effects from updating the runtime
*/
function broadcastResult(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) { function broadcastResult(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value; const originalMethod = descriptor.value;
+22 -51
View File
@@ -1,7 +1,6 @@
import { MaybeNumber, MaybeString, OntimeEvent, Playback, TimerPhase, TimerType } from 'ontime-types'; import { MaybeNumber, MaybeString, OntimeEvent, Playback, TimerPhase, TimerType } from 'ontime-types';
import { dayInMs } from 'ontime-utils'; import { dayInMs } from 'ontime-utils';
import { RuntimeState } from '../stores/runtimeState.js'; import { RuntimeState } from '../stores/runtimeState.js';
import { timerConfig } from '../config/config.js';
/** /**
* handle events that span over midnight * handle events that span over midnight
@@ -56,6 +55,12 @@ export function getExpectedFinish(state: RuntimeState): MaybeNumber {
*/ */
export function getCurrent(state: RuntimeState): number { export function getCurrent(state: RuntimeState): number {
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
if (state.eventNow === null || state.timer.duration === null) {
throw new Error('timerUtils.getCurrent: invalid state received');
}
}
const { startedAt, duration, addedTime } = state.timer; const { startedAt, duration, addedTime } = state.timer;
const { timerType, timeStart, timeEnd } = state.eventNow; const { timerType, timeStart, timeEnd } = state.eventNow;
const { pausedAt } = state._timer; const { pausedAt } = state._timer;
@@ -88,6 +93,12 @@ export function getCurrent(state: RuntimeState): number {
* @returns {boolean} * @returns {boolean}
*/ */
export function skippedOutOfEvent(state: RuntimeState, previousTime: number, skipLimit: number): boolean { export function skippedOutOfEvent(state: RuntimeState, previousTime: number, skipLimit: number): boolean {
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
if (state.timer.expectedFinish === null || state.timer.startedAt === null) {
throw new Error('timerUtils.skippedOutOfEvent: invalid state received');
}
}
const { startedAt, expectedFinish } = state.timer; const { startedAt, expectedFinish } = state.timer;
const { clock } = state; const { clock } = state;
@@ -246,54 +257,6 @@ export const getRollTimers = (rundown: OntimeEvent[], timeNow: number, currentIn
}; };
}; };
/**
* @description Implements update functions for roll mode
* @param {RuntimeState}
* @returns object with selection variables
*/
export const updateRoll = (state: RuntimeState) => {
const { current, expectedFinish, startedAt, secondaryTimer } = state.timer;
const { secondaryTarget } = state._timer;
const { clock } = state;
const selectedEventId = state.eventNow?.id ?? null;
// timers
let updatedTimer = current;
let updatedSecondaryTimer = secondaryTimer;
// whether rollLoad should be called: force reload of events
let doRollLoad = false;
// whether finished event should trigger
let isPrimaryFinished = false;
if (selectedEventId && current !== null) {
// if we have something selected and a timer, we are running
const finishAt = expectedFinish >= startedAt ? expectedFinish : expectedFinish + dayInMs;
updatedTimer = finishAt - clock;
if (updatedTimer > dayInMs) {
updatedTimer -= dayInMs;
}
if (updatedTimer <= timerConfig.triggerAhead) {
isPrimaryFinished = true;
// we need a new event
doRollLoad = true;
}
} else if (secondaryTimer >= 0) {
// if secondaryTimer is running we are in waiting to roll
updatedSecondaryTimer = secondaryTarget - clock;
if (updatedSecondaryTimer <= 0) {
// we need a new event
doRollLoad = true;
}
}
return { updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished: isPrimaryFinished };
};
/** /**
* Calculates difference between the runtime and the schedule of an event * Calculates difference between the runtime and the schedule of an event
* Positive offset is time ahead * Positive offset is time ahead
@@ -305,6 +268,14 @@ export function getRuntimeOffset(state: RuntimeState): number {
return 0; return 0;
} }
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
// we know current exists as long as eventNow exists
if (state.timer.current === null) {
throw new Error('timerUtils.calculate: current must be set');
}
}
const { clock } = state; const { clock } = state;
const { timeStart, timerType } = state.eventNow; const { timeStart, timerType } = state.eventNow;
const { addedTime, current, startedAt } = state.timer; const { addedTime, current, startedAt } = state.timer;
@@ -356,7 +327,7 @@ export function getTotalDuration(firstStart: number, lastEnd: number, daySpan: n
*/ */
export function getExpectedEnd(state: RuntimeState): MaybeNumber { export function getExpectedEnd(state: RuntimeState): MaybeNumber {
// there is no expected end if we havent started // there is no expected end if we havent started
if (state.runtime.actualStart === null) { if (state.runtime.actualStart === null || state.runtime.plannedEnd === null) {
return null; return null;
} }
return state.runtime.plannedEnd - state.runtime.offset + state._timer.totalDelay; return state.runtime.plannedEnd - state.runtime.offset + state._timer.totalDelay;
@@ -367,7 +338,7 @@ export function getExpectedEnd(state: RuntimeState): MaybeNumber {
* @param state * @param state
* @returns * @returns
*/ */
function isPlaybackActive(state: RuntimeState): boolean { export function isPlaybackActive(state: RuntimeState): boolean {
return ( return (
state.timer.playback === Playback.Play || state.timer.playback === Playback.Play ||
state.timer.playback === Playback.Pause || state.timer.playback === Playback.Pause ||
@@ -36,7 +36,6 @@ const mockState = {
}, },
_timer: { _timer: {
pausedAt: null, pausedAt: null,
secondaryTarget: null,
}, },
} as RuntimeState; } as RuntimeState;
+65 -83
View File
@@ -1,9 +1,8 @@
import { MaybeNumber, OntimeEvent, Playback, Runtime, TimerPhase, TimerState, TimerType } from 'ontime-types'; import { MaybeNumber, OntimeEvent, Playback, Runtime, TimerPhase, TimerState } from 'ontime-types';
import { calculateDuration, dayInMs } from 'ontime-utils'; import { calculateDuration, dayInMs } from 'ontime-utils';
import { clock } from '../services/Clock.js'; import { clock } from '../services/Clock.js';
import { RestorePoint } from '../services/RestoreService.js'; import { RestorePoint } from '../services/RestoreService.js';
import { import {
getCurrent, getCurrent,
getExpectedEnd, getExpectedEnd,
@@ -11,32 +10,32 @@ import {
getRollTimers, getRollTimers,
getRuntimeOffset, getRuntimeOffset,
getTimerPhase, getTimerPhase,
skippedOutOfEvent, isPlaybackActive,
updateRoll,
} from '../services/timerUtils.js'; } from '../services/timerUtils.js';
import { timerConfig } from '../config/config.js'; import { timerConfig } from '../config/config.js';
const initialRuntime: Runtime = { const initialRuntime: Runtime = {
selectedEventIndex: null, selectedEventIndex: null, // changes if rundown changes or we load a new event
numEvents: 0, numEvents: 0, // change initiated by user
offset: 0, offset: 0, // changes at runtime
plannedStart: 0, plannedStart: 0, // only changes if event changes
plannedEnd: 0, plannedEnd: 0, // only changes if event changes
actualStart: null, actualStart: null, // set once we start the timer
expectedEnd: null, expectedEnd: null, // changes with runtime, based on offset
} as const; } as const;
const initialTimer: TimerState = { const initialTimer: TimerState = {
addedTime: 0, addedTime: 0,
current: null, current: null, // changes on every update
duration: null, duration: null, // only changes if event changes
elapsed: null, elapsed: null, // changes on every update
expectedFinish: null, // TODO: expected finish could account for midnight, we cleanup in the clients // TODO: expected finish could account for midnight, we cleanup in the clients
finishedAt: null, expectedFinish: null, // change can only be initiated by user
phase: TimerPhase.None, finishedAt: null, // can change on update or user action
playback: Playback.Stop, phase: TimerPhase.None, // can change on update or user action
secondaryTimer: null, playback: Playback.Stop, // change initiated by user
startedAt: null, secondaryTimer: null, // change on every update
startedAt: null, // change can only be initiated by user
} as const; } as const;
export type RuntimeState = { export type RuntimeState = {
@@ -49,10 +48,9 @@ export type RuntimeState = {
timer: TimerState; timer: TimerState;
// private properties of the timer calculations // private properties of the timer calculations
_timer: { _timer: {
forceFinish: MaybeNumber; forceFinish: MaybeNumber; // wether we should declare an event as finished, will contain the finish time
totalDelay: number; // this value comes from rundown service totalDelay: number; // this value comes from rundown service
pausedAt: MaybeNumber; pausedAt: MaybeNumber;
secondaryTarget: MaybeNumber;
}; };
}; };
@@ -68,7 +66,6 @@ const runtimeState: RuntimeState = {
forceFinish: null, forceFinish: null,
totalDelay: 0, totalDelay: 0,
pausedAt: null, pausedAt: null,
secondaryTarget: null,
}, },
}; };
@@ -93,7 +90,6 @@ export function clear() {
// we maintain the total delay // we maintain the total delay
runtimeState._timer.pausedAt = null; runtimeState._timer.pausedAt = null;
runtimeState._timer.secondaryTarget = null;
} }
/** /**
@@ -125,7 +121,8 @@ export function updateRundownData(rundownData: RundownData) {
runtimeState.runtime.numEvents = rundownData.numEvents; runtimeState.runtime.numEvents = rundownData.numEvents;
runtimeState.runtime.plannedStart = rundownData.firstStart; runtimeState.runtime.plannedStart = rundownData.firstStart;
runtimeState.runtime.plannedEnd = rundownData.firstStart + rundownData.totalDuration; runtimeState.runtime.plannedEnd =
rundownData.firstStart === null ? null : rundownData.firstStart + rundownData.totalDuration;
runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState); runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState);
} }
@@ -282,7 +279,6 @@ export function start(state: RuntimeState = runtimeState): boolean {
} }
state.clock = clock.timeNow(); state.clock = clock.timeNow();
state.timer.secondaryTimer = null; state.timer.secondaryTimer = null;
state._timer.secondaryTarget = null;
// add paused time if it exists // add paused time if it exists
if (state._timer.pausedAt) { if (state._timer.pausedAt) {
@@ -374,73 +370,60 @@ export type UpdateResult = {
}; };
export function update(): UpdateResult { export function update(): UpdateResult {
let hasTimerFinished = false; // 0. there are some things we always do
let shouldCallRoll = false; // we also need to call roll if a secondary timer has finished runtimeState.clock = clock.timeNow(); // we update the clock on every update call
const previousTime = runtimeState.clock; // 1. is playback idle?
runtimeState.clock = clock.timeNow(); if (!isPlaybackActive(runtimeState)) {
return updateIfIdle();
// we call integrations if we update timers
if (runtimeState.timer.playback === Playback.Roll) {
const result = onRollUpdate();
shouldCallRoll = result.doRoll;
hasTimerFinished = result.isFinished;
} else if (runtimeState.timer.startedAt !== null) {
// we only update timer if a timer has been started
const result = onPlayUpdate();
hasTimerFinished = result.isFinished;
} else if (runtimeState.eventNow?.timerType === TimerType.TimeToEnd) {
// or if we are in a time-to-end timer
runtimeState.timer.current = getCurrent(runtimeState);
runtimeState.timer.duration = runtimeState.timer.current;
} }
// update timer phase // 2. are we waiting to roll?
runtimeState.timer.phase = getTimerPhase(runtimeState); if (runtimeState.timer.playback === Playback.Roll && runtimeState.timer.secondaryTimer !== null) {
return updateIfWaitingToRoll(runtimeState.timer.secondaryTimer);
}
// update offset // 3. at this point we know that we are playing an event
// reset data
runtimeState.timer.secondaryTimer = null;
// update timer state
if (!runtimeState.timer.duration) {
throw new Error('Timer duration is not set');
}
runtimeState.timer.current = getCurrent(runtimeState);
runtimeState.timer.expectedFinish = getExpectedFinish(runtimeState);
runtimeState.timer.phase = getTimerPhase(runtimeState);
runtimeState.timer.elapsed = runtimeState.timer.duration - runtimeState.timer.current;
// update runtime, needs up-to-date timer state
runtimeState.runtime.offset = getRuntimeOffset(runtimeState); runtimeState.runtime.offset = getRuntimeOffset(runtimeState);
runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState); runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState);
return { const finishedNow =
hasTimerFinished, Boolean(runtimeState._timer.forceFinish) ||
shouldCallRoll, (runtimeState.timer.current <= timerConfig.triggerAhead && runtimeState.timer.finishedAt === null);
};
function onRollUpdate() { if (finishedNow) {
const hasSkippedOutOfEvent = skippedOutOfEvent(runtimeState, previousTime, timerConfig.skipLimit); // reset state
if (hasSkippedOutOfEvent) { runtimeState._timer.forceFinish;
return { doRoll: true }; runtimeState.timer.finishedAt = runtimeState._timer.forceFinish ?? runtimeState.clock;
} } else {
const { updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished } = updateRoll(runtimeState); runtimeState.timer.expectedFinish = getExpectedFinish(runtimeState);
runtimeState.timer.current = updatedTimer;
runtimeState.timer.secondaryTimer = updatedSecondaryTimer;
runtimeState.timer.elapsed = runtimeState.timer.duration - runtimeState.timer.current;
return { doRoll: doRollLoad, isFinished };
} }
function onPlayUpdate() { return { hasTimerFinished: finishedNow, shouldCallRoll: finishedNow };
let isFinished = false;
runtimeState.timer.current = getCurrent(runtimeState);
const shouldForceFinish = runtimeState._timer.forceFinish !== null;
const finishedNow =
shouldForceFinish ||
(runtimeState.timer.current <= timerConfig.triggerAhead && runtimeState.timer.finishedAt === null);
if (runtimeState.timer.playback === Playback.Play && finishedNow) { function updateIfIdle() {
runtimeState.timer.finishedAt = runtimeState._timer.forceFinish ?? runtimeState.clock; // if nothing is running, nothing to do
isFinished = true; return { hasTimerFinished: false, shouldCallRoll: false };
} else { }
runtimeState.timer.expectedFinish = getExpectedFinish(runtimeState);
}
if (shouldForceFinish) { function updateIfWaitingToRoll(targetTime: number) {
runtimeState._timer.forceFinish = null; runtimeState.timer.secondaryTimer = targetTime - runtimeState.clock;
} runtimeState.timer.phase = TimerPhase.Pending;
runtimeState.timer.elapsed = runtimeState.timer.duration - runtimeState.timer.current; return { hasTimerFinished: false, shouldCallRoll: runtimeState.timer.secondaryTimer < 0 };
return { isFinished };
} }
} }
@@ -454,7 +437,6 @@ export function roll(rundown: OntimeEvent[]) {
if (currentEvent) { if (currentEvent) {
// there is something running, load // there is something running, load
runtimeState.timer.secondaryTimer = null; runtimeState.timer.secondaryTimer = null;
runtimeState._timer.secondaryTarget = null;
// account for event that finishes the day after // account for event that finishes the day after
const endTime = const endTime =
@@ -475,8 +457,8 @@ export function roll(rundown: OntimeEvent[]) {
// account for day after // account for day after
const nextStart = nextEvent.timeStart < runtimeState.clock ? nextEvent.timeStart + dayInMs : nextEvent.timeStart; const nextStart = nextEvent.timeStart < runtimeState.clock ? nextEvent.timeStart + dayInMs : nextEvent.timeStart;
// nothing now, but something coming up // nothing now, but something coming up
runtimeState.timer.phase = TimerPhase.Pending;
runtimeState.timer.secondaryTimer = nextStart - runtimeState.clock; runtimeState.timer.secondaryTimer = nextStart - runtimeState.clock;
runtimeState._timer.secondaryTarget = nextStart;
} }
runtimeState.timer.playback = Playback.Roll; runtimeState.timer.playback = Playback.Roll;
@@ -7,18 +7,27 @@ export enum TimerPhase {
Warning = 'warning', Warning = 'warning',
Danger = 'danger', Danger = 'danger',
Overtime = 'overtime', Overtime = 'overtime',
Pending = 'pending', // used for waiting to roll /** used for waiting to roll */
Pending = 'pending',
} }
export type TimerState = { export type TimerState = {
addedTime: number; // time added by user, can be negative /** time added by user, can be negative */
current: MaybeNumber; // running countdown addedTime: number;
duration: MaybeNumber; // normalised duration of current event /** running countdown */
elapsed: MaybeNumber; // elapsed time in current timer current: MaybeNumber;
expectedFinish: MaybeNumber; // time we expect timer to finish /** normalised duration of current event */
finishedAt: MaybeNumber; // only if timer has already finished duration: MaybeNumber;
/** elapsed time in current timer */
elapsed: MaybeNumber;
/** time we expect timer to finish */
expectedFinish: MaybeNumber;
/** only if timer has already finished */
finishedAt: MaybeNumber;
phase: TimerPhase; phase: TimerPhase;
playback: Playback; playback: Playback;
secondaryTimer: MaybeNumber; // used for roll mode /** used for roll mode */
startedAt: MaybeNumber; // only if timer has already started secondaryTimer: MaybeNumber;
/** only if timer has already started */
startedAt: MaybeNumber;
}; };