Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/skills

Store, retrieve, edit, version, and revert reusable agent skill documents via skill_list then skill_get.

FollowFork

Files

retime.ts

236 lines · 6.9 KB · TypeScript
export type RetimeSceneInput = {
	id: string
	start: number
	end?: number
}

export type RetimeConfig = {
	fps: number
	pace: number
	baseEnd?: number
	scenes: RetimeSceneInput[]
	html?: string
	musicId?: string
}

export type RetimedScene = {
	id: string
	baseStart: number
	baseDuration: number
	start: number
	duration: number
	startFrame: number
	durationFrames: number
}

export type RetimeResult = {
	fps: number
	pace: number
	frames: number
	durationSeconds: number
	scenes: RetimedScene[]
	html?: string
}

function assertFinitePositive(name: string, value: number) {
	if (!Number.isFinite(value) || value <= 0) {
		throw new Error(`${name} must be a finite number > 0`)
	}
}

function escapeRegExp(value: string) {
	return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

function secondsFromFrames(frames: number, fps: number) {
	return Number((frames / fps).toFixed(5))
}

function validateConfig(config: RetimeConfig) {
	if (!config || typeof config !== 'object') {
		throw new Error('config is required')
	}
	assertFinitePositive('fps', config.fps)
	assertFinitePositive('pace', config.pace)
	if (!Array.isArray(config.scenes) || config.scenes.length === 0) {
		throw new Error('scenes must be a non-empty array')
	}
	const ids = new Set<string>()
	for (const scene of config.scenes) {
		if (!scene || typeof scene.id !== 'string' || !scene.id.trim()) {
			throw new Error('each scene needs a non-empty id')
		}
		if (ids.has(scene.id)) {
			throw new Error(`duplicate scene id: ${scene.id}`)
		}
		ids.add(scene.id)
		if (!Number.isFinite(scene.start) || scene.start < 0) {
			throw new Error(`scene ${scene.id} start must be a finite number >= 0`)
		}
		if (scene.end !== undefined) {
			if (!Number.isFinite(scene.end) || scene.end <= scene.start) {
				throw new Error(`scene ${scene.id} end must be > start`)
			}
		}
	}
	if (config.scenes[0].start !== 0) {
		throw new Error('first scene start must be 0')
	}
	for (let i = 1; i < config.scenes.length; i++) {
		const prev = config.scenes[i - 1]
		const cur = config.scenes[i]
		const prevEnd = prev.end ?? cur.start
		if (cur.start < prev.start) {
			throw new Error(`scene starts must be non-decreasing (${prev.id} → ${cur.id})`)
		}
		if (prev.end !== undefined && cur.start < prev.end) {
			throw new Error(`scene ${cur.id} overlaps ${prev.id}`)
		}
		if (prev.end === undefined && cur.start !== prevEnd) {
			// ok — next start defines previous end
		}
	}
	if (config.baseEnd !== undefined) {
		assertFinitePositive('baseEnd', config.baseEnd)
		const last = config.scenes[config.scenes.length - 1]
		const lastEnd = last.end ?? config.baseEnd
		if (config.baseEnd < lastEnd || config.baseEnd <= last.start) {
			throw new Error('baseEnd must be >= last scene end and > last start')
		}
	} else {
		const last = config.scenes[config.scenes.length - 1]
		if (last.end === undefined) {
			throw new Error('baseEnd is required when the last scene has no end')
		}
	}
	if (config.html !== undefined && typeof config.html !== 'string') {
		throw new Error('html must be a string when provided')
	}
	if (config.musicId !== undefined) {
		if (typeof config.musicId !== 'string' || !config.musicId.trim()) {
			throw new Error('musicId must be a non-empty string when provided')
		}
	}
}

function resolveBaseBounds(config: RetimeConfig) {
	const baseEnd =
		config.baseEnd ??
		config.scenes[config.scenes.length - 1].end!
	const starts = config.scenes.map((scene, index) => {
		const next = config.scenes[index + 1]
		const end = scene.end ?? next?.start ?? baseEnd
		return { id: scene.id, start: scene.start, end }
	})
	for (const row of starts) {
		if (!(row.end > row.start)) {
			throw new Error(`scene ${row.id} needs a positive duration`)
		}
	}
	if (!(baseEnd > starts[starts.length - 1].start)) {
		throw new Error('baseEnd must exceed the last scene start')
	}
	return { baseEnd, starts }
}

function retimeHtml(
	html: string,
	scenes: RetimedScene[],
	durationSeconds: number,
	musicId: string,
) {
	let next = html
	for (const scene of scenes) {
		const id = escapeRegExp(scene.id)
		const re = new RegExp(
			`(<[^>]*\\bid="${id}"[^>]*?)\\sdata-start="[^"]*"\\sdata-duration="[^"]*"`,
		)
		if (!re.test(next)) {
			throw new Error(`host element id="${scene.id}" with data-start/data-duration not found`)
		}
		next = next.replace(
			re,
			`$1 data-start="${scene.start}" data-duration="${scene.duration}"`,
		)
	}
	const rootRe = /(id="root"[^>]*?data-duration=")[^"]*(")/
	if (!rootRe.test(next)) {
		throw new Error('root element with data-duration not found')
	}
	next = next.replace(rootRe, `$1${durationSeconds}$2`)
	const musicRe = new RegExp(
		`(<(?:audio|div)[^>]*\\bid="${escapeRegExp(musicId)}"[^>]*?data-duration=")[^"]*(")`,
	)
	if (musicRe.test(next)) {
		next = next.replace(musicRe, `$1${durationSeconds}$2`)
	}
	return next
}

/**
 * Scale HyperFrames scene slots and optional host HTML by a pace factor.
 * Use for product promo pacing: snap starts to whole frames, regenerate
 * durations from adjacent bounds, and update root/audio data-duration.
 * Does not parse arbitrary JS timelines — pair with skills/.../assets/pace.js.
 *
 * @param input - `{ config }` with fps, pace, scenes, optional baseEnd/html/musicId
 * @returns Retimed frame totals, scene table, and optional rewritten HTML
 *
 * @example
 * import retime from 'kody:@kody/skills/retime'
 *
 * const result = await retime({
 *   config: {
 *     fps: 30,
 *     pace: 1.3,
 *     baseEnd: 90,
 *     scenes: [{ id: 'intro', start: 0, end: 8 }],
 *     html: '<div id="intro" data-start="0" data-duration="8"></div><div id="root" data-duration="90"></div>',
 *   },
 * })
 */
export default function retime(input: { config: RetimeConfig }): RetimeResult {
	if (!input || typeof input !== 'object' || !('config' in input)) {
		throw new Error('expected { config }')
	}
	const unknown = Object.keys(input).filter((key) => key !== 'config')
	if (unknown.length) {
		throw new Error(`unknown input key(s): ${unknown.join(', ')}`)
	}
	validateConfig(input.config)
	const { fps, pace } = input.config
	const { baseEnd, starts } = resolveBaseBounds(input.config)
	const toFrame = (seconds: number) => Math.round((seconds * fps) / pace)
	const bounds = [...starts.map((row) => toFrame(row.start)), toFrame(baseEnd)]
	const scenes: RetimedScene[] = starts.map((row, index) => {
		const startFrame = bounds[index]
		const durationFrames = bounds[index + 1] - bounds[index]
		return {
			id: row.id,
			baseStart: row.start,
			baseDuration: row.end - row.start,
			startFrame,
			durationFrames,
			start: secondsFromFrames(startFrame, fps),
			duration: secondsFromFrames(durationFrames, fps),
		}
	})
	const frames = bounds[bounds.length - 1]
	const durationSeconds = secondsFromFrames(frames, fps)
	const result: RetimeResult = {
		fps,
		pace,
		frames,
		durationSeconds,
		scenes,
	}
	if (input.config.html !== undefined) {
		result.html = retimeHtml(
			input.config.html,
			scenes,
			durationSeconds,
			input.config.musicId ?? 'music',
		)
	}
	return result
}