Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(replay): measure the inactivity map's video axis during capture (#101761)

Tue Haulund0c19f4a972d1
diff --git a/common/replay-headless/src/__tests__/playback-controller.test.ts b/common/replay-headless/src/__tests__/playback-controller.test.ts
index 2f9cb95cfe31..535132106aba 100644
--- a/common/replay-headless/src/__tests__/playback-controller.test.ts
+++ b/common/replay-headless/src/__tests__/playback-controller.test.ts
@@ -15,7 +15,7 @@ function makeSegment(
}
function mockBridge(): HostBridge {
- return { signalEnded: jest.fn() } as unknown as HostBridge
+ return { signalEnded: jest.fn(), publishFrameTimeline: jest.fn() } as unknown as HostBridge
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -129,15 +129,35 @@ describe('PlaybackController', () => {
})
describe('inactivity skipping', () => {
- it('does not start skip loop without skipInactivity option', () => {
- const rafSpy = jest.spyOn(window, 'requestAnimationFrame')
+ it('records frames but skips nothing without skipInactivity option', () => {
+ // The loop runs either way: the frame timeline is what maps video positions back to the
+ // recording clock, and it is needed whether or not anything gets skipped.
+ const rafSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0)
+ const replayer = mockReplayer()
+ const bridge = mockBridge()
+ const segments = [makeSegment({ startTimestamp: 0, endTimestamp: 5000, isActive: false, kind: 'gap' })]
+ const controller = new PlaybackController(replayer as any, segments, 0, {}, bridge)
+
+ controller.start(0)
+ rafSpy.mock.calls[0][0](0)
+
+ expect(rafSpy).toHaveBeenCalled()
+ expect(replayer.play).toHaveBeenCalledTimes(1)
+ expect(controller.getFrameSessionMs()).toHaveLength(1)
+ rafSpy.mockRestore()
+ })
+
+ it('publishes the frame timeline when playback stops', () => {
+ const rafSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0)
const replayer = mockReplayer()
const bridge = mockBridge()
const controller = new PlaybackController(replayer as any, [], 0, {}, bridge)
controller.start(0)
+ rafSpy.mock.calls[0][0](0)
+ controller.stop()
- expect(rafSpy).not.toHaveBeenCalled()
+ expect(bridge.publishFrameTimeline).toHaveBeenCalledWith([0])
rafSpy.mockRestore()
})
diff --git a/common/replay-headless/src/host-bridge.ts b/common/replay-headless/src/host-bridge.ts
index 9bab5eee423f..158d75a81ca5 100644
--- a/common/replay-headless/src/host-bridge.ts
+++ b/common/replay-headless/src/host-bridge.ts
@@ -50,6 +50,10 @@ export class HostBridge {
this.emit({ type: 'inactivity_periods', periods })
}
+ publishFrameTimeline(frameSessionMs: number[]): void {
+ this.emit({ type: 'frame_timeline', frameSessionMs })
+ }
+
// --- Config ---
/**
diff --git a/common/replay-headless/src/playback-controller.ts b/common/replay-headless/src/playback-controller.ts
index e83ab624b0b9..75857c7fc2e1 100644
--- a/common/replay-headless/src/playback-controller.ts
+++ b/common/replay-headless/src/playback-controller.ts
@@ -4,6 +4,7 @@ import type { eventWithTime } from 'posthog-js/rrweb-types'
import type { RecordingSegment } from '@posthog/replay-shared'
import type { HostBridge } from './host-bridge'
+import { PLAYER_FRAME_TIMELINE_KEY } from './protocol'
/**
* Controls playback lifecycle: starts the replayer, skips inactive
@@ -12,6 +13,7 @@ import type { HostBridge } from './host-bridge'
*/
export class PlaybackController {
private stopped = false
+ private frameSessionMs: number[] = []
constructor(
private replayer: Replayer,
@@ -38,39 +40,54 @@ export class PlaybackController {
}
start(startOffset: number): void {
- if (this.options.skipInactivity) {
- this.startInactivitySkipLoop()
- }
+ this.startFrameLoop()
this.replayer.play(startOffset)
}
+ getFrameSessionMs(): number[] {
+ return this.frameSessionMs
+ }
+
stop(): void {
if (this.stopped) {
return
}
this.stopped = true
+ this.bridge.publishFrameTimeline(this.frameSessionMs)
this.bridge.signalEnded()
}
/**
- * Skip inactive segments by polling the current playback position
- * each frame. Under puppeteer-capture's virtual time, rAF fires
- * once per beginFrame call, so this is deterministic.
+ * Record where playback is on every captured frame, and skip inactive segments as they come up.
+ * Under puppeteer-capture's virtual time, rAF fires once per beginFrame call, so this is
+ * deterministic and each tick is exactly one frame of the rendered video.
+ *
+ * The sample is taken before the skip: a skip costs the frame it happens on, and recording the
+ * position after the jump would hide that frame from the timeline the same way computing video
+ * positions from segment durations alone does.
*/
- private startInactivitySkipLoop(): void {
- const checkAndSkip = (): void => {
+ private startFrameLoop(): void {
+ // Published by reference so the host can read it whenever capture ends. Trimmed and timed-out
+ // captures tear the page down without the replayer ever finishing, so waiting for stop() to
+ // push the timeline would leave exactly the long sessions this exists for without one.
+ ;(window as unknown as Record<string, number[]>)[PLAYER_FRAME_TIMELINE_KEY] = this.frameSessionMs
+ const onFrame = (): void => {
if (this.stopped) {
return
}
- const ts = this.firstTimestamp + this.replayer.getCurrentTime()
- const inactiveSeg = this.segments.find(
- (seg: RecordingSegment) => !seg.isActive && ts >= seg.startTimestamp && ts <= seg.endTimestamp
- )
- if (inactiveSeg) {
- this.replayer.play(inactiveSeg.endTimestamp - this.firstTimestamp)
+ const current = this.replayer.getCurrentTime()
+ this.frameSessionMs.push(Math.round(current))
+ if (this.options.skipInactivity) {
+ const ts = this.firstTimestamp + current
+ const inactiveSeg = this.segments.find(
+ (seg: RecordingSegment) => !seg.isActive && ts >= seg.startTimestamp && ts <= seg.endTimestamp
+ )
+ if (inactiveSeg) {
+ this.replayer.play(inactiveSeg.endTimestamp - this.firstTimestamp)
+ }
}
- requestAnimationFrame(checkAndSkip)
+ requestAnimationFrame(onFrame)
}
- requestAnimationFrame(checkAndSkip)
+ requestAnimationFrame(onFrame)
}
}
diff --git a/common/replay-headless/src/protocol.ts b/common/replay-headless/src/protocol.ts
index d856da47124e..d589e19f4544 100644
--- a/common/replay-headless/src/protocol.ts
+++ b/common/replay-headless/src/protocol.ts
@@ -53,9 +53,11 @@ export type PlayerMessage =
| { type: 'ended' }
| { type: 'error'; code: string; message: string; retryable: boolean }
| { type: 'inactivity_periods'; periods: InactivityPeriod[] }
+ | { type: 'frame_timeline'; frameSessionMs: number[] }
export const PLAYER_EMIT_FN = '__posthog_player_emit__'
export const PLAYER_CONFIG_KEY = '__posthog_player_config__'
+export const PLAYER_FRAME_TIMELINE_KEY = '__posthog_frame_timeline__'
// --- Event names (rasterizer → player) ---
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
index 812dcb4a067c..80733be8fc96 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
@@ -74,6 +74,9 @@ function baseRecordingResult(_videoPath: string, overrides: Partial<RecordingRes
frame_count: 72,
truncated: false,
inactivity_periods: [{ ts_from_s: 0, ts_to_s: 10, active: true }],
+ frame_session_ms: [],
+ pre_roll_frames: 0,
+ output_fps: 3,
timings: { setup_s: 1.5, capture_s: 3.2 },
...overrides,
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts
index 05268609d182..e5e13abcb95a 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts
@@ -64,6 +64,8 @@ function mockPlayer(overrides: Partial<Record<keyof PlayerController, any>> = {}
isEnded: jest.fn().mockReturnValue(false),
getError: jest.fn().mockReturnValue(null),
getInactivityPeriods: jest.fn().mockReturnValue([]),
+ getFrameSessionMs: jest.fn().mockReturnValue([]),
+ readFrameTimeline: jest.fn().mockResolvedValue([]),
waitForSettled: jest.fn().mockResolvedValue(undefined),
...overrides,
} as unknown as PlayerController
@@ -174,6 +176,8 @@ describe('capturePlayback', () => {
const player = mockPlayer({
isEnded: jest.fn().mockReturnValue(true),
getInactivityPeriods: jest.fn().mockReturnValue(periods),
+ getFrameSessionMs: jest.fn().mockReturnValue([]),
+ readFrameTimeline: jest.fn().mockResolvedValue([]),
})
const result = await capturePlayback(player, baseCaptureConfig(), outputPath, jest.fn())
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/postprocess.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/postprocess.test.ts
index 71817644ae85..487a1a31c4e4 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/postprocess.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/postprocess.test.ts
@@ -1,4 +1,4 @@
-import { computeVideoTimestamps } from '~/session-replay/recording-rasterizer/postprocess'
+import { computeVideoTimestamps, videoTimestampsFromFrames } from '~/session-replay/recording-rasterizer/postprocess'
import { InactivityPeriod } from '~/session-replay/recording-rasterizer/types'
describe('computeVideoTimestamps', () => {
@@ -86,3 +86,121 @@ describe('computeVideoTimestamps', () => {
expect(result[0].active).toBe(true)
})
})
+
+describe('videoTimestampsFromFrames', () => {
+ // 3 fps, so one frame is 1/3s of video. Playback runs 0-1s, skips to 5s, runs to 6s, and the skip
+ // costs the frame it happens on — the frame the predicted mapping never accounts for.
+ const periods: InactivityPeriod[] = [
+ { ts_from_s: 0, ts_to_s: 1, active: true },
+ { ts_from_s: 1, ts_to_s: 5, active: false },
+ { ts_from_s: 5, ts_to_s: 6, active: true },
+ ]
+ const frameSessionMs = [0, 333, 666, 1000, 5000, 5333, 5666]
+
+ it('places a period where the frames actually put it', () => {
+ const result = videoTimestampsFromFrames(periods, frameSessionMs, 3)
+
+ expect(result[0].recording_ts_from_s).toBe(0)
+ expect(result[0].recording_ts_to_s).toBeCloseTo(1)
+ // The resumed stretch starts on frame 4, not frame 3 as the durations alone would say.
+ expect(result[2].recording_ts_from_s).toBeCloseTo(4 / 3)
+ expect(result[2].recording_ts_to_s).toBeCloseTo(7 / 3)
+ })
+
+ it('does not understate the video the way the predicted mapping does', () => {
+ const measured = videoTimestampsFromFrames(periods, frameSessionMs, 3)
+ const predicted = computeVideoTimestamps(periods)
+
+ const measuredEnd = measured[2].recording_ts_to_s!
+ const predictedEnd = predicted[2].recording_ts_to_s!
+ expect(measuredEnd).toBeGreaterThan(predictedEnd)
+ expect(measuredEnd - predictedEnd).toBeCloseTo(1 / 3)
+ })
+
+ it('charges the skipped stretch the frame the skip cost', () => {
+ const result = videoTimestampsFromFrames(periods, frameSessionMs, 3)
+
+ expect(result[1].recording_ts_from_s).toBeCloseTo(1)
+ expect(result[1].recording_ts_to_s).toBeCloseTo(4 / 3)
+ expect(computeVideoTimestamps(periods)[1].recording_ts_to_s).toBe(
+ computeVideoTimestamps(periods)[1].recording_ts_from_s
+ )
+ })
+
+ it('offsets by the frames captured before playback started', () => {
+ // Capture runs while the player is still starting, and those frames carry no sample. Without the
+ // offset every period is reported early by that many frames.
+ const result = videoTimestampsFromFrames(periods, frameSessionMs, 3, 6)
+
+ expect(result[0].recording_ts_from_s).toBeCloseTo(2)
+ expect(result[2].recording_ts_to_s).toBeCloseTo(13 / 3)
+ })
+
+ it('anchors a stretch with no frames of its own at the frame playback resumed on', () => {
+ // A gap shorter than one frame interval is stepped over without any frame landing inside it.
+ // The resume frame sits exactly on the gap's end, so the search has to include it.
+ const shortGap: InactivityPeriod[] = [
+ { ts_from_s: 0, ts_to_s: 1, active: true },
+ { ts_from_s: 1, ts_to_s: 1.1, active: false },
+ { ts_from_s: 1.1, ts_to_s: 2, active: true },
+ ]
+ const frames = [0, 333, 666, 1100, 1433]
+
+ const result = videoTimestampsFromFrames(shortGap, frames, 3)
+
+ expect(result[1].recording_ts_from_s).toBeCloseTo(1)
+ expect(result[1].recording_ts_from_s).toBeLessThanOrEqual(result[2].recording_ts_from_s!)
+ })
+
+ it('holds a stretch the capture started inside to what the file shows', () => {
+ // start_offset_s renders from the middle of a session. The stretch still claims session time the
+ // file never shows, and a consumer interpolating across it reads every moment inside as later.
+ const spanning: InactivityPeriod[] = [{ ts_from_s: 0, ts_to_s: 60, active: true }]
+ const frames = [10_000, 10_333, 10_666]
+
+ const result = videoTimestampsFromFrames(spanning, frames, 3)
+
+ expect(result[0].ts_from_s).toBeCloseTo(10)
+ expect(result[0].ts_to_s).toBeCloseTo(10.666)
+ expect(result[0].recording_ts_from_s).toBe(0)
+ })
+
+ it('leaves a stretch the capture covered end to end alone', () => {
+ const result = videoTimestampsFromFrames(periods, frameSessionMs, 3)
+
+ expect(result[0].ts_from_s).toBe(0)
+ expect(result[0].ts_to_s).toBe(1)
+ expect(result[2].ts_from_s).toBe(5)
+ })
+
+ it('keeps every stretch of a heavily cut recording in order', () => {
+ // One cursor walks periods and samples together. If it over-advances, later stretches are
+ // starved of their frames and collapse onto the end of the file.
+ const many: InactivityPeriod[] = []
+ const frames: number[] = []
+ for (let i = 0; i < 100; i++) {
+ const base = i * 100
+ many.push({ ts_from_s: base, ts_to_s: base + 10, active: true })
+ many.push({ ts_from_s: base + 10, ts_to_s: base + 100, active: false })
+ for (let f = 0; f < 30; f++) {
+ frames.push((base + f / 3) * 1000)
+ }
+ }
+
+ const result = videoTimestampsFromFrames(many, frames, 3)
+
+ const actives = result.filter((p) => p.active)
+ expect(actives).toHaveLength(100)
+ for (const period of actives) {
+ expect(period.recording_ts_to_s).toBeGreaterThan(period.recording_ts_from_s!)
+ }
+ for (let i = 1; i < result.length; i++) {
+ expect(result[i].recording_ts_from_s).toBeGreaterThanOrEqual(result[i - 1].recording_ts_from_s!)
+ }
+ expect(actives[99].recording_ts_to_s).toBeCloseTo(frames.length / 3)
+ })
+
+ it('falls back to the predicted mapping when capture reported no timeline', () => {
+ expect(videoTimestampsFromFrames(periods, [], 3)).toEqual(computeVideoTimestamps(periods))
+ })
+})
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
index 95da63e8deae..b3587c56d17a 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
@@ -44,6 +44,8 @@ const baseCaptureResult = {
frame_count: 120,
truncated: false,
inactivity_periods: [],
+ frame_session_ms: [],
+ pre_roll_frames: 0,
timings: { setup_s: 0, capture_s: 2.5 },
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts b/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts
index fcaccb2224cc..afab4fd31b82 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts
@@ -21,7 +21,16 @@ export async function capturePlayback(
progress: RasterizationProgress | null = null,
log: Logger = createLogger()
): Promise<
- Pick<RecordingResult, 'capture_duration_s' | 'frame_count' | 'truncated' | 'inactivity_periods' | 'timings'>
+ Pick<
+ RecordingResult,
+ | 'capture_duration_s'
+ | 'frame_count'
+ | 'truncated'
+ | 'inactivity_periods'
+ | 'frame_session_ms'
+ | 'pre_roll_frames'
+ | 'timings'
+ >
> {
const captureStart = process.hrtime()
const ffmpegStderr: string[] = []
@@ -119,6 +128,7 @@ export async function capturePlayback(
let virtualElapsed = 0
let truncated = false
+ let preRollFrames = 0
try {
await recorder.start(outputPath)
const vp = page.viewport()
@@ -130,7 +140,10 @@ export async function capturePlayback(
await player.installCallbackErrorGuards()
await player.startPlayback()
- log.info('playback started')
+ // Frames captured before the player's loop exists have no sample, so the timeline starts here
+ // rather than at video second zero.
+ preRollFrames = frameCount
+ log.info({ pre_roll_frames: preRollFrames }, 'playback started')
const checkIntervalMs = 250
@@ -216,6 +229,8 @@ export async function capturePlayback(
frame_count: frameCount,
truncated,
inactivity_periods: inactivityPeriods,
+ frame_session_ms: await player.readFrameTimeline(),
+ pre_roll_frames: preRollFrames,
timings: { setup_s: 0, capture_s: elapsed(captureStart) },
}
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts b/nodejs/src/session-replay/recording-rasterizer/capture/player.ts
index 9a74530bea53..ff6a878ccbdf 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/player.ts
@@ -1,6 +1,11 @@
import type { Page } from 'puppeteer'
-import { PLAYER_CONFIG_KEY, PLAYER_EMIT_FN, PLAYER_START_EVENT } from '@posthog/replay-headless/protocol'
+import {
+ PLAYER_CONFIG_KEY,
+ PLAYER_EMIT_FN,
+ PLAYER_FRAME_TIMELINE_KEY,
+ PLAYER_START_EVENT,
+} from '@posthog/replay-headless/protocol'
import type { InactivityPeriod, PlayerConfig, PlayerMessage } from '@posthog/replay-headless/protocol'
import { RasterizationError, toRasterizationErrorCode } from '~/session-replay/recording-rasterizer/errors'
@@ -26,6 +31,7 @@ export class PlayerController {
private state = {
ended: false,
inactivityPeriods: [] as InactivityPeriod[],
+ frameSessionMs: [] as number[],
}
private startedResolve: (() => void) | null = null
@@ -89,6 +95,9 @@ export class PlayerController {
case 'inactivity_periods':
this.state.inactivityPeriods = msg.periods
break
+ case 'frame_timeline':
+ this.state.frameSessionMs = msg.frameSessionMs
+ break
}
}
@@ -239,6 +248,27 @@ export class PlayerController {
return this.state.inactivityPeriods
}
+ getFrameSessionMs(): number[] {
+ return this.state.frameSessionMs
+ }
+
+ /** Read the frame timeline off the page. Works for a capture that was trimmed or timed out, where
+ * the replayer never finished and so never pushed it. Falls back to whatever was pushed. */
+ async readFrameTimeline(): Promise<number[]> {
+ try {
+ const samples = await this.capturePage.page.evaluate(
+ (key: string) => (window as unknown as Record<string, number[]>)[key] ?? [],
+ PLAYER_FRAME_TIMELINE_KEY
+ )
+ if (samples.length > 0) {
+ return samples
+ }
+ } catch {
+ // Page already gone: use whatever the player managed to push before teardown.
+ }
+ return this.state.frameSessionMs
+ }
+
dispose(): void {
this.startedResolve = null
this.errorReject = null
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts
index 20515a30dd6d..e4f92e0005e1 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts
@@ -150,6 +150,9 @@ export async function rasterizeRecording(
frame_count: captureResult.frame_count,
truncated: captureResult.truncated,
inactivity_periods: captureResult.inactivity_periods,
+ frame_session_ms: captureResult.frame_session_ms,
+ pre_roll_frames: captureResult.pre_roll_frames,
+ output_fps: captureConfig.outputFps,
timings: { setup_s: setupS, capture_s: captureResult.timings.capture_s },
}
} finally {
diff --git a/nodejs/src/session-replay/recording-rasterizer/postprocess.ts b/nodejs/src/session-replay/recording-rasterizer/postprocess.ts
index 6c8e583340ea..583617f90936 100644
--- a/nodejs/src/session-replay/recording-rasterizer/postprocess.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/postprocess.ts
@@ -1,12 +1,79 @@
import { InactivityPeriod } from './types'
/**
- * Compute video-time positions for each inactivity period.
+ * Place each period on the video clock from the timeline measured during capture.
*
- * Active periods occupy real time in the video (their session duration maps
- * 1:1 to video duration after slowdown). Inactive periods are skipped by the
- * player and occupy zero video time — their recording_ts values point to the
- * same position where the previous active period ended.
+ * `frameSessionMs[i]` is where playback was on captured frame `i`, and one captured frame is one
+ * frame of the rendered video, so a period's video position is the frame range whose session times
+ * fall inside it. Measuring beats deriving: a skip costs the frame it happens on, and any frame
+ * spent elsewhere counts too, neither of which segment durations can predict.
+ */
+export function videoTimestampsFromFrames(
+ periods: InactivityPeriod[],
+ frameSessionMs: number[],
+ fps: number,
+ preRollFrames = 0
+): InactivityPeriod[] {
+ if (frameSessionMs.length === 0 || fps <= 0) {
+ return computeVideoTimestamps(periods)
+ }
+ // Sample `i` is the frame `preRollFrames + i` of the file: capture runs while the player is still
+ // starting, and those frames carry no sample.
+ const videoTimeOf = (sample: number): number => (preRollFrames + sample) / fps
+ const lastPeriod = periods.length - 1
+ // A render can start or stop partway through a stretch, via start_offset_s, a trim, or a timeout.
+ // The stretch then spans session time the file never shows, and a consumer interpolating across it
+ // reads every moment inside as later than it is. Hold those two edges to what was captured.
+ const firstSampleS = frameSessionMs[0] / 1000
+ const lastSampleS = frameSessionMs[frameSessionMs.length - 1] / 1000
+ // Periods run in order and samples never go backwards, so one cursor walks both. Rescanning the
+ // samples per period would be quadratic, and a long recording with many activity changes has
+ // hundreds of thousands of each.
+ let cursor = 0
+ return periods.map((period, index) => {
+ const fromMs = period.ts_from_s * 1000
+ const toMs = period.ts_to_s != null ? period.ts_to_s * 1000 : Number.POSITIVE_INFINITY
+ // Half-open, so a frame sitting exactly on a boundary belongs to the period it starts, not the
+ // one it ends. The last period takes its own end, or the final frame would belong to nothing.
+ const owns = (t: number): boolean => t >= fromMs && (t < toMs || (index === lastPeriod && t <= toMs))
+ while (cursor < frameSessionMs.length && frameSessionMs[cursor] < fromMs) {
+ cursor++
+ }
+ let first = -1
+ let last = -1
+ while (cursor < frameSessionMs.length && owns(frameSessionMs[cursor])) {
+ if (first === -1) {
+ first = cursor
+ }
+ last = cursor
+ cursor++
+ }
+ if (first === -1) {
+ // Never on screen: sit at the frame where playback resumed, which is where the cursor now
+ // rests. It stops on the first sample at or past this period's end, so the frame landing
+ // exactly on that end is taken rather than stepped over.
+ const at = videoTimeOf(cursor)
+ return { ...period, recording_ts_from_s: at, recording_ts_to_s: at }
+ }
+ // Only the stretch the capture began in, and the one it ended in, can be cut by it.
+ const startsMidPeriod =
+ firstSampleS > period.ts_from_s && (period.ts_to_s == null || firstSampleS < period.ts_to_s)
+ const endsMidPeriod = period.ts_to_s != null && lastSampleS < period.ts_to_s && lastSampleS >= period.ts_from_s
+ return {
+ ...period,
+ ts_from_s: startsMidPeriod ? firstSampleS : period.ts_from_s,
+ ts_to_s: endsMidPeriod ? lastSampleS : period.ts_to_s,
+ recording_ts_from_s: videoTimeOf(first),
+ recording_ts_to_s: videoTimeOf(last + 1),
+ }
+ })
+}
+
+/**
+ * Predicted video-time positions, used when no measured timeline is available.
+ *
+ * Assumes an inactive period costs no video time, which understates the real video by about a frame
+ * per skip. Prefer `videoTimestampsFromFrames`.
*/
export function computeVideoTimestamps(periods: InactivityPeriod[]): InactivityPeriod[] {
// Pass 1: compute raw video timestamps
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
index 1cc72c818b54..0b4f0705b90e 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
@@ -11,7 +11,7 @@ import { config } from '~/session-replay/recording-rasterizer/config'
import { asRasterizationError } from '~/session-replay/recording-rasterizer/errors'
import { createLogger } from '~/session-replay/recording-rasterizer/logger'
import { RasterizationMetrics } from '~/session-replay/recording-rasterizer/metrics'
-import { computeVideoTimestamps } from '~/session-replay/recording-rasterizer/postprocess'
+import { videoTimestampsFromFrames } from '~/session-replay/recording-rasterizer/postprocess'
import { uploadToS3 } from '~/session-replay/recording-rasterizer/storage'
import {
ActivityTimings,
@@ -133,7 +133,12 @@ async function rasterizeRecordingActivity(
RasterizationMetrics.observeSetup('success', timings.setup_s)
RasterizationMetrics.observeCapture('success', timings.capture_s)
- const periods = computeVideoTimestamps(result.inactivity_periods)
+ const periods = videoTimestampsFromFrames(
+ result.inactivity_periods,
+ result.frame_session_ms,
+ result.output_fps,
+ result.pre_roll_frames
+ )
progress.phase = 'upload'
onProgress()
diff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.ts
index b6d2ce521ae8..33be2fccb8e0 100644
--- a/nodejs/src/session-replay/recording-rasterizer/types.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts
@@ -86,5 +86,8 @@ export interface RecordingResult {
frame_count: number // total frames captured
truncated: boolean // true when max_virtual_time stopped the recording early
inactivity_periods: InactivityPeriod[]
+ frame_session_ms: number[] // session time at each captured frame, measured during capture
+ pre_roll_frames: number // frames captured before playback started, which carry no sample
+ output_fps: number // frames per second of the rendered file, so a frame index is a video position
timings: Pick<ActivityTimings, 'setup_s' | 'capture_s'>
}
diff --git a/products/replay_vision/backend/temporal/video_clock.py b/products/replay_vision/backend/temporal/video_clock.py
index b8e23a63886d..6fc9ad4ae0aa 100644
--- a/products/replay_vision/backend/temporal/video_clock.py
+++ b/products/replay_vision/backend/temporal/video_clock.py
@@ -5,7 +5,8 @@ behind the wall-clock moment it shows. Everything the model sees is on the video
is the clock it can index exactly; everything we persist is on the session clock, because that is
what the player seeks to.
-`clipTimeForMoment` in products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.ts
+A cut costs the frame the render spent performing it, so kept stretches are not contiguous on the video
+clock. `clipTimeForMoment` in products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.ts
is the TypeScript sibling of this mapping. The two have to change together.
"""