Repository navigation
feat: rundown timing calculated on the server - #1843
jesperstarkar wants to merge 57 commits into
Conversation
Moves the rundown timing calculator, RundownTimingContext and helpers from the webui into @sofie-automation/meteor-lib, so that the same implementation can be used by the meteor server (for an upcoming timing publication). The webui module is now a thin backwards-compatible wrapper: it re-exports everything and keeps the getCurrentTime() default for getPlaylistTimingDiff, so no other client code changes. The test suite moves with the code, and gains coverage for getPlaylistTimingDiff (previously untested) across all four PlaylistTimingTypes, including the deactivated-after-playout special cases. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Hoists TimerState (and its evaluators) out of the T-timers module into a generic corelib home (dataModel/TimerState.ts), re-exported from TTimers for compatibility. Adds PlaylistTimingStateDoc (corelib/dataModel/TimingState.ts): the document shape for an upcoming playlistTimingState publication. Every timing value is a TimerState - a piecewise-linear function of wall-clock time - so consumers evaluate values locally and the server only publishes on actual state changes. The doc is a discriminated union envelope, ready for per-segment/per-part shapes to join the same collection later. Adds calculatePlaylistTimingStates (meteor-lib/rundownTiming): derives the TimerStates from the RundownTimingCalculator output plus the single piecewise breakpoint (the moment the on-air part or segment budget overruns). The over/under balance is expressed as a target/projected TimerState pair (like T-timer projections), since a single TimerState cannot express 'constant while on schedule, pushing once overrunning'. Equivalence tests assert that the published states, evaluated at arbitrary times between state changes, exactly match the old calculator + PlaylistTiming helpers + getPlaylistTimingDiff - including across the overrun breakpoint, for all four timing types, segment budgets and deactivated-after-playout playlists. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Addresses review feedback on the previous commit: the TimerState values are no longer derived by a parallel reimplementation of the calculator's branches - there is now exactly one implementation of each formula. - RundownTimingCalculator builds the on-air countdown AS a TimerState at the formula sites: the Math.max(..., now - startedPlayback) expressions for remaining/as-played (part and segment-budget variants) are deleted, and the numeric aggregates are computed by evaluating that state with timerStateToDuration/timerStateToZeroTime. The untouched numeric test expectations therefore certify the state semantics. - RundownTimingContext exposes remainingPlaylistDurationState + livePushTime; the numeric remainingPlaylistDuration is the state's evaluation at now. - PlaylistTiming.getRemainingDuration/getEstimatedEnd (corelib) are now evaluations of new getRemainingDurationState/getEstimatedEndState builders. - getPlaylistTimingDiff's formula is deleted: it evaluates the over/under target/projected TimerState pair at now. Its hand-value unit tests now pin the state-based implementation. - findLiveMotion (the branch-mirroring breakpoint derivation) is deleted; playlistTimingState.ts only assembles the published doc from states the calculator and corelib builders produce. This also fixes a bug findLiveMotion had: an untimed on-air part inside a budgeted segment incorrectly suppressed the live motion. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Adds a corelib-declared custom publication (CorelibPubSub.playlistTimingState) that publishes a PlaylistTimingStateDoc per playlist: all the rundown-header playlist timing values expressed as TimerStates, recomputed only when playout/ingest state changes (no server ticking - the states self-advance on consumers). - prepareTimingPartInstances (meteor-lib): the part-instance overlay/sort/ quickloop-dedup input preparation, extracted from RundownTimingProvider and now shared verbatim by the client provider and the publication, so both feed the calculator identical inputs. - The publication follows the optimizedObserver pattern (per-playlist content cache of playlist/segments/parts/partInstances/studio-settings, any change invalidates the single doc). All timing math stays in meteor-lib/corelib. - The PartInstance projection deliberately matches the client provider's (no partPlayoutTimings), so both compute identical numbers. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The four playlist-timing header components (Plan. Start/Started/Start In,
Plan. Dur/Rem. Dur, Plan. End/Est. End, Over/Under) now read the
server-published TimerStates instead of computing values via the client
timing context:
- PlaylistTimingStates client collection + rundown view subscription
- usePlaylistTimingValue(playlistId, timer, {tickResolution}): fetches a
single timer from the published doc (reactivity scoped to that field) and
ticks 'now' at the caller's chosen resolution (default Synced/1Hz)
- Components evaluate the states locally with timerStateToDuration /
timerStateToZeroTime; formatting is unchanged
- The Over/Under hide rule is now owned by the server (overUnder omitted
when not meaningful)
Everything else (On Air/Seg. Budg., shelf panels, director screen, the
segment timeline) stays on the RundownTimingProvider for now.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The published collection is one discriminated union covering everything within a playlist (per-area documents: the playlist today, per-segment and per-partInstance to follow), but the surrounding code did not yet hold up its end of that: - usePlaylistTimingValue cast findOne straight to PlaylistTimingStateDoc, bypassing the discriminator, and its projection omitted 'type' so the discriminator could not have been checked at all. Once a second document shape lands, that cast reads a segment/part document as a playlist one. It now projects 'type' and narrows via a guard. - Adds isPlaylistTimingStateDoc() in corelib as the supported way to narrow. - Doc comments on the union, the publication and the client collection now state the scope (everything within a playlist) and the narrowing contract, rather than implying a playlist-only collection. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Each TimerState variant now carries the timestamp of its transition into the other state, so a transition whose time is known in advance never depends on a new state being published at that moment (which costs accuracy - the value would be stale until the message lands, then jump): - running: pauseTime, when it freezes (unchanged) - paused: resumesAt, when it starts running (new) resumesAt needs no direction flag: it produces exactly the trajectory that resuming at that instant would, so a countdown counts down and a count-up (freeRun) timer keeps accumulating in negative territory, as before. pauseTime was previously declared on the paused variant too, where both evaluators ignored it entirely - the only producer set it to null explicitly. It is kept for shape uniformity (a stable key set across both variants keeps Mongo diffing simple) but is now typed 'null', as is resumesAt on the running variant, so the type enforces which one is meaningless. This keeps a state at two pieces at most. Anything with further transitions relies on an updated state being published in between, which has a multi-second window in practice. Adds the first unit tests for the two evaluators, covering all four shapes in both readings either side of the breakpoint, count-up timers, degenerate values, and the resumesAt-equals-immediate-resume property. Those caught a real inconsistency: timerStateToZeroTime tested pauseTime for truthiness while timerStateToDuration tested it against null, so the two readings of a state with a pauseTime of 0 disagreed. Both now use != null. The LSG API schema is updated to match. The inapplicable field is declared there as nullable-number rather than null, with a TODO explaining why: the type generator renders a null-only property as 'any'. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The hook handed back a raw TimerState plus a 'now', leaving every caller to apply the right evaluator itself. It now takes the reading mode and returns the number (or null when that timer is not published): usePlaylistTimingValue(playlistId, 'plannedEnd', TimerValueMode.Timestamp) The header components no longer import the evaluators at all - they are pure display code again. PlaylistTimerKey is derived from the document type, so it stays in step as more timers are published. Over/under no longer needs a bespoke hook. It was published as a target/projected TimerState pair because a single TimerState could not express 'constant while on schedule, then burning down once pushing' - which is precisely the transition resumesAt just added. It is now one TimerState whose duration read is the time in hand (positive = under, negative = over), so it flows through the same generic hook as every other value. The pair survives as an internal step in deriving that state, but is not published: in the duration-compared timing modes its two timestamps are virtual anchors with no real-world meaning, and publishing them would invite consumers to render a planned end for a playlist that has none. The meaningful end times are already published separately as plannedEnd and estimatedEnd. The equivalence tests, which check the published states against the numeric reference at many times either side of the breakpoint, cover the collapsed state unchanged. They also caught getPlaylistTimingDiff returning -0 for a perfectly balanced playlist, now fixed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Adds the coverage that was missing across the new timing code: - prepareTimingPartInstances had none at all, despite being shared by the client provider and the server publication. Covers the PartInstance overlay, ordering, QuickLoop marking and dedup, and that it does not reorder the caller's arrays. - calculatePlaylistTimingStates gains untimed parts, autonext, QuickLoop, and a set of tests asserting the document is *identical* when recomputed at a later time from unchanged inputs - the property the low-volume publication depends on, previously untested. - The publication gains a take sequence, a segment-budget case, and the same stability property exercised through the content cache. - usePlaylistTimingValue is now tested: both reading modes, null when a timer is absent, recomputation on tick, freezing at a breakpoint, honouring the requested tick resolution, ignoring another area's document, and cleaning up its listener. The autonext tests documented a real limitation rather than hiding it: when a scheduled start passes, the calculator stops counting that part towards the remaining pool, which is a second transition that a TimerState cannot carry. In practice the autonext also writes to the database, so the publication recomputes and the stale window is one round-trip; the test pins the size of the staleness so the boundary stays visible. Testing the hook exposed a circular import: RundownTiming.ts (an events enum) imported PartUi from SegmentTimelineContainer, which imported computeSegmentDisplayDuration back from it - dragging the whole segment timeline tree into anything that wanted the event names. That helper had a single consumer, so it moves there and the cycle goes away. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Custom publications could only be consumed by a DDP subscriber, because CustomPublish had a single implementation that pushed to a session. Anything server-side that needed the same computed data had to re-derive it from the raw collections, which drifts from what the UI is actually given. Adds CustomPublishToCollection, a CustomPublish that maintains an InMemoryMongoCollection instead, and observeCustomPublication, which wraps it in the same LiveQueryHandleSync that Mongo observers return - so a custom publication can be observed and torn down exactly like a Mongo one: await observeCustomPublication(cache.Parts, (receiver) => ...) Subscribing with the upstream publication's own identifier means the consumer joins the existing optimized observer rather than starting a second one, so nothing is computed twice and it sees precisely the documents DDP subscribers see. The DDP field semantics (a changed field of undefined means unset) are not reimplemented: the receiver delegates to InMemoryMongoCollection.link(), which already implements them. onChanged fires once per batch rather than once per document, so a consumer can trigger its own update without fanning out. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The timing publication read the Parts and PartInstances collections, but the UI computes its timings from the uiParts and uiPartInstances publications, and those are not the same documents: modifyPartForQuickLoop rewrites expectedDuration/expectedDurationWithTransition to fallbackPartDuration (and can mark Parts invalid) when a QuickLoop has forced auto-next. On such a playlist the server would have published different numbers to the ones on screen. partsUI and partInstancesUI now expose observeUIParts/observeUIPartInstances, built on observeCustomPublication, and the timing publication's content observer uses those in place of the Mongo observers. Both go through the same subscribe function the DDP publications use, with the same identifier, so there is one optimized observer per playlist shared with the UI subscribers rather than a second copy of the work. uiPartInstances is keyed on the playlist activation, so the subscription has to follow it: PartInstancesForActivationObserver resubscribes when the activation changes and holds none while the playlist is inactive - which also matches the UI, whose subscription is disabled without an activation. Adds a regression test pinning that raw and UI part durations really do differ under a forced-auto-next QuickLoop, and that the published document follows the UI ones. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The receiver tests drove it by hand, so they proved nothing about how it behaves as an actual subscriber. Adds tests against a real setUpCollectionOptimizedObserver covering the claims that matter: that a consumer receives the observer output and subsequent updates, that a second consumer joins the existing observer rather than starting another (one setupObservers call, two subscribers), and that stopping the handle really does unsubscribe. Those exposed a rough edge. A subscriber joining an observer that is already running is initialised on a later tick, so observeCustomPublication resolved with the collection still empty and the consumer would compute once from no data - publishing a document full of zeroes before correcting itself a few milliseconds later. It now waits for the initial documents, so it resolves populated, as a Mongo observer does. Stopping resolves that wait too, so a subscription torn down before it is ready cannot hang. Also covers PartInstancesForActivationObserver, which was the most stateful new code and had no tests: subscribing per activation, resubscribing and discarding the previous instances when the activation changes, clearing and notifying on deactivation, ignoring a repeated activation, and the two disposal races - disposing while a subscribe is in flight, and disposing before the debounce elapses. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…torn view Two ways the published states could be wrong in a running studio. The on-air part was only recognised once its planned start had passed. Multi- gateway studios schedule the start a little into the future (getNowInPlayout adds the gateway latency), so for a moment after every take the calculator saw a playlist with nothing playing: remaining went constant, which makes the projected end push along with the clock and the schedule balance burn down. Worse, that shape was then frozen into a published document - nothing recomputes at the planned start, so it stayed wrong until the gateway reported playback, and indefinitely if it never did. The on-air part's countdown is now anchored on the planned start whether or not it has been reached, so before the start it evaluates to the part duration plus the remaining wait. That holds the projected end fixed across the take and needs no extra breakpoint, leaving pauseTime free to freeze the pool when the part overruns. The states are correct through all three phases from a single computation. Note this slightly changes the remaining duration during the wait - it counts down through it rather than holding - which is also what makes the projected end come out right. Separately, the playlist and its PartInstances are written concurrently by the job worker and reach the publication through separate observers, so the cache can briefly hold a playlist naming a PartInstance that has not arrived. The calculator carries a deliberate cross-call bridge for that gap, which cannot work here because the publication builds a fresh calculator each time. Rather than keeping an instance alive - which would also inherit its per-part maps, which are never pruned - the publication now declines to compute from a torn view and republishes when the missing document lands. A test shows why: with an unresolvable next PartInstance, every unplayed budgeted segment silently drops out of the remaining pool. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Adds the two remaining rundown-header timers - "On Air" and "Seg. Budg." - to the playlist timing document, along with the on-air part and segment ids that consumers guard on. Both are anchors rather than numbers, following the existing pattern: the calculator now builds remainingTimeOnCurrentPart and remainingBudgetOnCurrentSegment as TimerStates at the point the formula lives, and the numeric fields are their evaluation at that time. The part timer is the first real use of resumesAt: the previous Math.min(start, now) + duration - now is exactly a timer that holds at the full duration until the part starts, which matters for the window after every take in a multi-gateway studio. The budget timer only counts down from a known segment start; without one it is a constant, not a countdown anchored at whenever the document happened to be built. The staleness guard moves into usePlaylistTimingValue as forPartInstanceId / forSegmentId options, so a component rendering a specific part cannot show another part's numbers in the moment after a take when the published state and the playlist disagree - the same rule the timing context needed, in one place rather than at each call site. CurrentPartOrSegmentRemaining reads the playlist from the timing provider's context rather than a new prop, since it is used from nine places; the sign flip, speech and vibration all stay client-side. The whole-context test helper now asserts each state against its own numeric counterpart instead of restating it as a literal, so the numbers verified against the original client behaviour remain the source of truth. Two preserved behaviours are pinned by tests rather than fixed: the budget timer is not produced when the on-air segment is the last in the playlist, and the part timer holds rather than counts during a scheduled start. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Adds the second shape to the timing state union: one document per segment, carrying its planned duration, how much has played out, and what is left. That is exactly the three modes the segment duration display offers, so SegmentDuration becomes three hook calls and its formatting - it no longer sums part durations or reaches into the timing context. The publication now emits the playlist document plus one per segment. The calculator runs once and both assemblies read the same context, so the extra documents cost no extra timing work, and the array observer already diffs per document so nothing else in the plumbing changes. Segment documents need no staleness guard: each describes its own segment whether or not it is on air, so the "is this the current segment" branch the display used to run disappears. The guard options stay on the playlist hook, where the on-air timers genuinely are about whichever part is live. useSegmentTimingValue joins usePlaylistTimingValue over a shared internal implementation - two typed entry points, one body, with the key types derived from their document shapes so they stay in step as more timers are published. Equivalence tests reproduce the display's own arithmetic and check the states against it at several times either side of the overrun, plus the usual stability tests that a document recomputed later from unchanged inputs is identical. One quirk is preserved and pinned rather than fixed: a budgeted segment reports no played-out time, because the value was only ever accumulated in the non-budget branch. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…tion Ports the consumers whose values the publication already carries, plus the ones that never wanted timing data at all. useTimingNow is the tick loop that was inside usePlaylistTimingValue, exposed on its own. Six consumers only ever read currentTime from the timing context - a wall clock, two T-timer displays, a countdown to a rundown marker, a break countdown, and one component subscribing purely to force a re-render. None of them need the calculator, only the clock, so they now take that and nothing else. OverUnderChip reads the published overUnder rather than recomputing the diff. That is the highest-leverage one: it is rendered from six places, so they all come off the calculator together. DirectorScreenTop drops its own getEstimatedEnd/getRemainingDuration calls in favour of the published estimatedEnd and remainingDuration, and PresenterScreen and OverlayScreen take the on-air timers added in the previous commit. PresenterScreen no longer threads the whole timing context down to its inner component as a prop, since that component can read the two values it wants directly. Two are deliberately left alone rather than half-ported: - PlaylistEndTiming needs partCountdown for its "Next Loop at" line, which is per-part and not published yet. Porting only its diff would split the component across two sources of timing for no benefit. - RundownHeader's simplified/advanced toggle sums partExpectedDurations as a fallback for untimed playlists. remainingDuration is not a faithful substitute - it is what is left rather than the total, so the toggle would disappear once an untimed playlist had played out. It needs the playlist total published before it can move. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The per-part duration resolution — expected/display/played durations and the display-duration-group pool — was inlined in `updateDurations`. Lift it into `resolvePartTimings.ts` and have the calculator call it, so the publication and the client can later resolve the same numbers without a second implementation. Pure lift: no behaviour change, the existing suites are the guard. It is an object rather than a pure function because display-duration groups are a shared mutable pool whose members are matched by adjacency in playout order, so a member cannot be resolved without its predecessors. The drain is a separate call because the caller overrides the display duration for invalid parts between the two. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The per-part countdowns were each computed as "static wait + currentRemaining", with currentRemaining recomputed from `now` inline. Turn currentRemaining into a TimerState, run the countdown loop in offsets from it, and produce both the states and the numbers by shifting that one state. Adds `offsetTimerState` to corelib: shifting a state by a constant is how a family of timers that differ only by a fixed head start is expressed as offsets from a single running one, so they cannot drift apart. The breakpoint is not shifted - the slope changes at the same moment for all of them. `partCountdownStates` joins the timing context. The existing assertion helper strips it and proves every entry evaluates to the matching `partCountdown` number, so all 97 scenarios now guard the states too. No numeric output changed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Third shape in the TimingStateDoc union, carrying the *resolved* per-part durations plus the countdown, played time and live display duration as TimerStates. An LSG client can take the number it wants without knowing the fallback cascade that produced it, which is the point of publishing these. Count-ups (played, liveDisplayDuration) are published negated: a TimerState's duration read can hold or fall but never rise, so a growing quantity is a falling one. This is the convention the Segment document's playedOut already uses; it is now stated explicitly on the type. `countsTowardsTiming`, `partDisplayDurationsNoPlayback` and `partCountdownStates` join the timing context so the assembly reads them rather than recomputing. Two behaviour details found by the equivalence tests and fixed: - A current part whose planned start is still in the future (the window after a take in a multi-gateway studio) now carries that start as `resumesAt`, so the countdowns are right the moment it passes rather than a republish later. This is the same fix already applied to remainingOnCurrentPart. Nothing changes at the instant of publication, so the existing scenarios are unaffected. - An invalid part is pinned to the default duration and its played time to zero, so it must not be treated as growing while on air. Tests evaluate every published state at ten instants either side of the overrun breakpoint and compare against a calculator run at that instant, and assert the documents are unchanged when recomputed later from unchanged inputs. The one case where that stability does not hold - display-duration groups, whose pool is drained by the on-air part's live duration - is pinned by its own test rather than glossed over. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Feeds the per-part states from the same calculator run that already produces the playlist and segment documents, so all three are one view of one computation. Kept `setUpOptimizedObserverArray` rather than switching to the collection observer as planned. The switch would not have helped: `replace()` marks a document dirty unconditionally and `commitChanges` then deep-diffs it, so recomputing and replacing every part costs exactly what the array observer's diff already costs. Skipping that work would require knowing which documents changed, which requires the comparison. Churn tests pin what a subscriber actually sees: - recomputing later from unchanged inputs sends nothing (the property the whole low-volume design rests on), except that the playlist document re-encodes once it passes its breakpoint - same values, plainer state - editing one part's duration touches that part and the ones after it, not the ones before - a take moves every part's countdown. That is inherent rather than a defect: each countdown is an offset from the one that is running, and any absolute per-part time depends on the durations accumulated before it. Worth measuring against a real rundown. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
PartCountdown, CurrentPartElapsed, OvertimeShadow and the camera screen's Part now take their countdown, played time and live display duration from the published part documents through a new `usePartTimingValue`, rather than from the client calculator's maps. These lose nothing to publication latency: they are TimerStates, evaluated locally at whatever rate the component renders, so the shadow and the elapsed clock still move at 60Hz from a state the server only sends on a take. Adds a `CountUp` value mode. A TimerState's duration read can hold or fall but never rise, so `played` and `liveDisplayDuration` are published as falling negatives; the mode flips them back so no caller negates by hand. Also fixes a bug from an earlier chunk: the clock views read this publication through `usePlaylistTimingValue` but never subscribed to it, so the director and overlay screens' timing values were coming back empty. Subscribed in the director, presenter and camera views. `OvertimeShadow` and `LiveLineIsPast` took a part-instance timing id, which the part documents are not keyed by; both now take a PartId. `LiveLineIsPast` has no callers at all - left in place rather than deleted here, but worth removing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
MediaStatusPopUpItem (countdown), VTThumbnailRenderer (played, live display duration) and LinePart/StoryboardPart (quickloop membership) now read the published part documents instead of the client calculator's maps. Adds `usePartTimingField` for the non-timer fields. Those do not vary with the clock, so unlike the timer hook it does not tick - the caller re-renders only when the published value changes, rather than on every timing event as the withTiming filter did. Note: `tsc -p packages/webui/tsconfig.json` typechecks nothing - that config has `files: []` and only project references. The real one is tsconfig.app.json. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`useOrderedPartIds` returns the playlist's parts in playout order, sorted on the `rank` the publication resolved. OrderedPartsProvider, PlaylistLoopingHeader and PlaylistEndTiming used `Object.keys(partCountdown)` for this - relying on the insertion order of a plain object to mean "the playlist in order", which it happened to be but was never guaranteed. PartDuration now takes its budget and played-out time from the published part document. The untimed/orphaned gating stays in the component, where it was. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The planned start/end/duration are already published as TimerStates, so the remaining in-view components no longer need to normalise `playlist.timing` themselves. PlaylistStartTiming's `expectedEnd - expectedDuration` fallback is what the server already applies when assembling `plannedStart`, and its "Expected Start" branch was unreachable for every PlaylistTimingType (it required getExpectedStart to be undefined while both end and duration were defined), so both are dropped. Likewise PlaylistEndTiming's `(expectedStart || now) + remainingPlaylistDuration` clock is exactly the published `estimatedEnd`, which retires its last use of the client timing calculator and of getPlaylistTimingDiff. RundownName and WarningDisplay were not rendered anywhere; REHEARSAL_MARGIN moves to its only consumer. RundownHeader keeps reading `playlist.timing` for now: it uses those values to pick between the simplified and advanced layouts, and a published value cannot distinguish "no planned times" from "document not arrived yet", which would flip the header's mode on load. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
AutoNextStatus, HeaderFreezeFrameIcon, RundownHeader, OnAirLine and the examples page no longer read the client calculator's timing context. What remains on it is exactly the segment-timeline geometry cluster. Three additions to support them: - `currentPartWillAutoNext` on the playlist document, with a `usePlaylistTimingField` hook for non-timer playlist fields - `duration` back on the part document (dropped in G2), with its static anchor `durationNoPlayback` exposed from the resolver and the context - `usePartsTotalExpectedDuration`, summing the published part documents Found by the equivalence tests: an invalid part's *display* duration and played time are pinned to preset values and so never grow, but its plain duration is not pinned and does. The two conditions are now separate. RundownHeader's untimed-playlist fallback total changes behaviour deliberately. It summed `partExpectedDurations`, which the calculator never prunes, so it kept counting parts that an ingest had removed. Summing the published documents counts the parts that exist. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`useSegmentPartTimings(segmentId)` returns a segment's parts with their published display duration and duration evaluated, and the within-segment offsets accumulated. SegmentTimeline and SegmentTimelineSmallPartFlag now use it instead of the client calculator's `partDisplayStartsAt`/`partDisplayDurations`. The offsets are segment-relative because that is all anything needs: every one of the eight places the old playlist-wide `partDisplayStartsAt` was read, it was read as a difference between two parts of the same segment. One segment's geometry therefore never depends on another's. The hook is deliberately nothing but published data plus a running total - it is exactly what an external consumer of the publication would write. If this is not enough to render the timeline, the publication is missing something, and that is the property worth having: the webui is the canary for the LSG clients. `SegmentTimeline` loses its `withTiming` HOC for a small function wrapper. Its class is now unaware of where geometry comes from. `SegmentTimelineSmallPartFlag`'s `firstPartInSegment` prop existed only to subtract one offset from another; it is gone. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
SegmentTimelinePart, SegmentTimelineContainer and TimelineGrid now take their durations, offsets and quickloop membership from the published part documents. Nothing in the client reads the timing calculator's context any more. `SegmentTimelinePart` loses its `withTiming` HOC; its statics take the segment's published timings instead of the calculator's context. `SegmentTimelineContainer` and `TimelineGrid` lose their `static contextType` for a prop passed down from the function component that already wraps them. `computeSegmentDuration` moves out of meteor-lib and alongside `computeSegmentDisplayDuration`: it is now a sum over published display durations rather than anything the calculator has to provide. Two `partDurations` reads doubled as "has the calculator run yet?" gates. Those become ordinary map misses, so a part with nothing published falls back to its own renderedDuration rather than to zero. The DEBUG_MODE overlay's `partStartsAt` was the map's only reader; it now shows the same segment-relative offset everything else uses. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`RundownTimingProvider` no longer constructs a RundownTimingCalculator, tracks
Parts and PartInstances, or computes anything. It dispatches the timing ticks and
names the playlist; every value below it comes from the `playlistTimingState`
publication and is evaluated locally from the published TimerStates.
$ grep -rn 'new RundownTimingCalculator()' --include=*.ts --include=*.tsx \
packages meteor | grep -v __tests__
packages/meteor-lib/src/rundownTiming/playlistTimingState.ts:59
meteor/server/publications/playlistTimingState/publication.ts:230
That is the point of the whole exercise: an external client - the Live Status
Gateway, or anything written against it - needs `timerStateToDuration` and
`timerStateToZeroTime` (nine lines each) plus a running sum for part offsets, and
gets exactly the numbers the Sofie UI shows. None of the duration cascade,
display-duration-group pooling, quickloop dedup or countdown accumulation has to
be reimplemented, because none of it happens client-side any more.
Removed: `useTiming`, `withTiming`, `TimingDataResolution`, `TimingFilterFunction`,
`WithTimingOptions`, `RundownTiming.InjectedROTimingProps`, `getPlaylistTimingDiff`
and meteor-lib's `computeSegmentDuration`. `withTiming.tsx` keeps only the tick
resolution enum, the event mapping and `useTimingPlaylistId`.
The provider also loses its `defaultDuration` prop at all four mount sites - the
Studio's default display duration is applied server-side, in the resolver.
`componentDidUpdate` still forces an immediate tick on a take, now triggered off
the playlist's current/next PartInstance rather than the part list it no longer
tracks.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`RundownTimingProviderContext` stopped being about timing when the calculator moved server-side: nothing reads the tick through it (ticks go via window events), so it carried a playlist id and nothing else under a name that promised otherwise. `RundownPlaylistContext` takes over, at `ui/` rather than under `ui/RundownView/` - it is mounted by the rundown view, the prompter and all four clock views, and its readers render in several of those, so belonging to any one view would be wrong. (The camera screen having had to declare its own `StudioContext` is that same problem already playing out.) It carries only the id, and the module says why: a RundownPlaylist changes on every take, and a context re-renders *every* consumer whenever its value changes, so putting the playlist in here would re-render all of these on each take to deliver a value that has not moved. Components needing more should do a scoped read of the fields they actually use. Only the two consumers that are genuinely deep use it -`AutoNextStatus` and `CurrentPartOrSegmentRemaining`, reached through part renderers that do not carry the playlist. `OrderedPartsProvider` and `PlaylistLoopingHeader` take a prop instead; their callers already had the playlist in hand. Not merged with `StudioContext` despite the two being mounted and invalidated together: no component reads both. Its eight readers are piece and layer renderers; these are timers. `RundownTimingProvider` accordingly provides no context at all - it is a side-effect component that dispatches the timing clock. `withTiming.tsx` is deleted; `TimingTickResolution` and `rundownTimingEventFromTickResolution` move into `RundownTiming.ts`, next to the events they name. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
It re-exported the calculator and its helpers into the client. Nothing imports it any more - the calculator is server-side and the identity helpers went with the components that used them. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The design, how to read the timing, what changed for gateway consumers, the differences from main, and the known limitations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important Review skippedToo many files! This PR contains 187 files, which is 87 over the limit of 100. To get a review, reduce the PR to 100 files or fewer by splitting it into smaller PRs or changing its base branch. Upgrade to a paid plan to raise the limit. This review couldn't start because sufficient usage credits or metered capacity aren't available. Add credits or update usage-based reviews in the billing tab, then retry.
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…ain numbers The gateway added up the part documents to get a segment's content length, which needed the part documents to carry `untimed` and `orphaned` only so that it could apply the server's rules itself. The segment document now publishes that length as `expectedDuration`, and the two flags are gone. The segment's `plannedDuration` is renamed `targetDuration`: it is the budget when there is one, otherwise the length of the parts, and is what `remaining` counts down from. The playlist's `plannedDuration` is unchanged. Lengths that never move with the clock are now plain milliseconds rather than always-paused TimerStates: the playlist's `plannedDuration`, the segment's `targetDuration` and `expectedDuration`, and the part's `expectedDuration` and `displayDuration`. Consumers no longer evaluate them at an arbitrary instant. The published values are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ication The header's fallback for an untimed playlist added up the expected duration of every part document on the client. That counted untimed parts, and the parts of budgeted segments instead of the budgets, so it was not the length the calculator works with. The playlist document now publishes the calculator's total as `targetDuration`: each segment's budget, or its timed parts when it has none. This is the same rule as the segment's `targetDuration`, added up over the playlist. The header reads it, and usePartsTotalExpectedDuration is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…array publication setUpOptimizedObserverArray kept a clone of each document it sent, which has no undefined fields, and diffed the next result of manipulateData against it as it came. A field set to undefined, at the top level or nested, so read as changed on every recompute, and the document was sent to every subscriber again for nothing. Each new document is now stripped of its undefined fields once, then diffed and kept, as customPublishCollection already does. A publication no longer has to leave such fields out itself. The take churn test now counts changes through the publication's own diff, rather than by comparing JSON, which could not have caught this. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…plain literals Now that the publication's diff treats an undefined field as left out, the timing states no longer need to add each optional field only when it has a value. Each part state also carries the PartInstance it was resolved from, so the part documents take their identity from it, rather than from a second map looked up with guards for a case that cannot happen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A part document is keyed by its PartId, so a Part with several PartInstances, such as one taken again, is described by the last of them, and the ranks of the others are not used. The Map does this by replacing the earlier state; that is now said where it happens, and the doc comment's misplaced sentence is back after its @PARAM. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reference rundown for the timing tests was kept twice, in job-worker's mocks and in sofie-core's timing tests, because test code is not built into any package, and the two copies had to be changed together. It is now in corelib, in `testing/referenceRundown`, which is built and shipped with corelib so that every package's tests can import it. It is light test data. A lint rule refuses an import of corelib's testing folder from anything but test code, so production code cannot come to depend on it. job-worker keeps only setupReferenceRundown, which makes the playlist and rundown documents from its mock studio and show style, and takes the segments and parts from corelib's builder rather than building them a second time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jest could not load a stylesheet, so each test of a component that imports one mocked the stylesheet, or replaced the component with a stand-in: the countdown was drawn as plain text, and the Prompter's chip, status bar, screen saver and buttons were left out. Every css, scss and sass import is now mapped to an empty module, since a component only imports its stylesheet for the side effect and the webui uses no CSS modules. The tests render the real components again, and find a countdown by its visible label rather than by an attribute the stand-in added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fore's Sofie calculates the timing a moment after a take. Until then the playlist's On Air countdown is still that of the part before, and activePlaylist sent its end as the new part's currentPart.timing.projectedEndTime: the timing was checked to be of the playlist, not of the part. The countdown is now used only while the timing's currentPartInstanceId is the on-air PartInstance. In that moment the end is the start plus the expected duration, which is also what Sofie publishes for a part that has just been taken, and what main sent. The fields stay numbers, so a consumer has nothing to handle. The comparison with main reads the gateway's part timing as the gateway does, so it applies the same check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…of its own The timing of each part was in resolvedPlaylist, as rundownTiming. The timing publication changes a moment after the playlist and the PartInstances, so each take built resolvedPlaylist one more time. That build takes seconds at 1,000 parts, as on main, mostly in the search for each part's pieces, and the other topics wait behind it. The timing adds little to one build, but its message after a take had the new on-air part with the timing of the part before, and a consumer could not tell. resolvedPlaylist is back to structure only, as on main, and no longer builds on a change of the timing alone. The new partTimings topic sends each part's timing, in Sofie's order, made from the timing publication alone: 372 kB in under a millisecond at 1,000 parts. A message is one calculation of Sofie's, so its values agree with each other; its currentPartInstanceId says which on-air part it describes, so a consumer can see when it is behind a take. The component PartRundownTiming is renamed PartTiming, as "rundown" means one Rundown of the playlist in this API, and it carries the part's ids and rank. rundownTiming was not released, so the API stays at 3.0.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s topic of its own" This reverts commit cadbcd0. The split worked around the slow resolvedPlaylist build, which is a bug to fix in its own right, rather than a reason to shape the API. Each part's timing goes back into resolvedPlaylist as rundownTiming. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since 27dce28 the gateway no longer sends the end of the part before as the current part's projectedEndTime; until the new part's timing arrives it is the start plus the expected duration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A camera part is drawn on each frame while its piece moves, and drew its countdown and its duration again with it: 60 times a second, each with its own timing hooks, where main's children were cheap to draw. Its own values were also read on each frame while they held, and while they were not used: the On Air countdown for the parts that are not on air, and the part's own values for the part that is. PartCountdown and PartDisplayDuration are memoised, as they draw themselves again when their second changes. The camera part reads only the values it draws from, and a value that holds does not draw it again. Its piece still moves on each frame while its countdown runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The timing tests' playout script had its own copy of playout (the take, set next, activate, reset, deactivate, hold and playback jobs, the PartInstance timing setters, pruning and the gateway's timeline), so a change to playout left them testing the old behaviour. They now play their shows through the job worker's real jobs and MockJobContext, which sofie-core's jest loads from the job worker's source, and the copy is gone. The shows are played by a driver shared with the job worker's timing inputs test, in the job worker's __mocks__, which also holds the one model of what a playout gateway reports and when. Reads of a script are now async, and name PartInstances by labels such as A1#2 rather than by made-up ids. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
imaretic
left a comment
There was a problem hiding this comment.
LGTM. Tested, old timing bugs are fixed, and everything works as expected.
|
I'll try to get some time end of this week/beginning of next to try and test this & compare against the current calculations. |
|
@jstarpl We're confident in the simplest use cases, but less so on combinations with more advanced features: Intra-rundown quickloop, full-rundown quickloop, timing groups across parts, and the above in combination with segment timing budgets. |
That's good to know. We do use blueprint-defined looping rundowns (which now are implemented using QuickLoop in Core, AFAIK) + the part timing groups. I can't help with Segment timing or intra-rundown quickloop though. |
|
Correct, a looping rundown uses the quickloop implementation underneath. NRK specifically asked for the ability to see the count to segments on the next round of the loop (segments "behind you", coming up again), which there should be a specific rule for implemented. Please check this specifically. |
| */ | ||
| export function getPartTimingStateDocId(partId: PartId): TimingStateDocId { | ||
| return protectString(`part_${partId}`) | ||
| } |
There was a problem hiding this comment.
I would prefer these to be a bit less generic than playlist_, segment_ and part_.
playlistTiming_, segmentTiming_ and partTiming_ would make reading ids in logs easier at a glance
| startedPlayback: 1728895750727 | ||
| expectedStart: 1728895750727 | ||
| expectedDurationMs: 180000 | ||
| remainingDuration: |
There was a problem hiding this comment.
We should use a reference to the timer state example, so if something changes we only need to update the schema in one place.
| isInQuickLoop: false | ||
| countsTowardsTiming: true | ||
| countdown: | ||
| paused: false |
There was a problem hiding this comment.
We should also use a reference here.
| budgetDurationMs: 20000 | ||
| countdownType: segment_budget_duration | ||
| playedOut: | ||
| paused: true |
There was a problem hiding this comment.
Examples should use references
There was a problem hiding this comment.
I think the descriptions are a bit too long, it is a lot of text to read and fit into the IDE context pop-ups.
There was a problem hiding this comment.
I think the descriptions are a bit too long, it is a lot of text to read and fit into the IDE context pop-ups.
| isInQuickLoop: false | ||
| countsTowardsTiming: true | ||
| countdown: | ||
| paused: false |
There was a problem hiding this comment.
We should also use a reference here.
About the Contributor
This pull request is posted on behalf of the BBC
Type of Contribution
This is a: Feature / Code improvement
Current Behavior
The Sofie UI is responsible for interpreting various timing numbers for parts & segments, and converting those into timers. It is the one that knows how each property combines and affects a Part.
This is a lot of undocumented knowledge, that makes it incredibly hard to build another UI off the LSG that reaches the same numbers.
New Behavior
playlistTimingState).Before, each browser calculated it, and the Live Status Gateway had its own, different code.
This is built off the timers representation used for t-timers. By representing each timer in this way, we minimise the amount of updates needed over the publication, and allow timers to update much more accurately.
Largely, this PR has moved the UI's computation logic into the backend, and adjusted it to produce these timer states instead of concrete values.
(15,800, of which 2,100 are generated text) and docs.
value with main. The copies are test-only and do not change. They can go one release after this PR.
other modes. The comparison with main covers most of them.
Testing
Affected areas
How it is proven
The true value does not come from the code of this PR. The checker calculates it from the definition of each value
and from the real takes and part starts in the database.
After a take or a part start, the check gives each screen and the gateway 1 s to show the new values. The real
gateway delay was 0.15–0.37 s (median of each show), 0.6 s at most.
The faults that the check counts apart are the short moments around a take in "Known limitations".
The end-to-end tools are not in this PR. The reports of the run are available on request.
Load, on the same two stacks (300 parts, unless given):
activePlaylistafter a takeWhat the user sees
of each second.
Time Frame
Other Information
Known limitations
on and back.
resolvedPlaylistper take (main: 1.6 MB), andactivePlaylistcomesabout 4 s after a take (main: 0.15 s). See feat: shared mongo matcher #1847 and perf: index the resolvedPlaylist lookups instead of scanning the playlist #1846 for fixes for this
increase comes with the fix that draws each countdown at its own second. The cause is not found yet.
How to review
In commit order. Commits 1–3 do not build alone: commit 1 changes the timing types, and commits 2–4 change the code
that reads them. From commit 4, each commit builds and all tests pass. Commit 6 is the largest (about 9,900 lines), but about
2,100 lines of it are generated text. Start with its comparison table,
comparisonWithMain.txt. The calculator is inpackages/sofie-core/src/publications/playlistTimingState/rundownTiming/. Thecomparison test and its table are next to it, in
__tests__/timing/. The docs page ispackages/documentation/docs/for-developers/rundown-timing.md.Status