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

final-qa.ts

152 lines · 8.0 KB · TypeScript
import { type Aliases, round, strictTokens, tokenize, wordRecall } from './promo-text.ts'
import { type Loudness, countBlackRuns, parseEbur128 } from './media-logs.ts'

export type FinalQaTargets = {
	integratedLufs?: number
	lufsTolerance?: number
	maxTruePeakDbtp?: number
	minOverallRecall?: number
	minLineRecall?: number
	minFadeDropDb?: number
	fadeRiseToleranceDb?: number
	minTailSeconds?: number
	maxTailSeconds?: number
}

export type FinalQaInput = {
	probe: unknown
	decodedFrames: number
	blackdetectLog: string
	ebur128Log: string
	/** ebur128 log of the music-only intro (`-t <introEnd>`), reported, not judged. */
	introEbur128Log?: string
	lines: Array<{ id: string; script: string; heard: string }>
	/** 0.25 s RMS windows from the fade start. `sourceRmsDb` = the music source over the same media time. */
	fadeRms: Array<{ t: number; rmsDb: number | null; sourceRmsDb?: number | null }>
	fadeStartSeconds: number
	lastWordEndSeconds: number
	expect: { fps: number; width: number; height: number; durationSeconds: number }
	targets?: FinalQaTargets
	aliases?: Aliases
}

export const DEFAULT_TARGETS: Required<FinalQaTargets> = {
	integratedLufs: -15,
	lufsTolerance: 1.5,
	maxTruePeakDbtp: -1,
	minOverallRecall: 0.9,
	minLineRecall: 0.75,
	minFadeDropDb: 10,
	fadeRiseToleranceDb: 1,
	minTailSeconds: 0.8,
	maxTailSeconds: 2.5,
}

type Check = { name: string; ok: boolean; detail: string }

function rate(r: string | undefined) {
	if (!r) return undefined
	const [n, d] = r.split('/').map(Number)
	return d ? n / d : Number(r)
}

/**
 * Final machine QA for a rendered narrated promo MP4. Pure: pass the raw
 * measurements (ffprobe JSON, decoded frame count, blackdetect / ebur128 logs,
 * per-line transcripts of the FINAL MIX, fade RMS samples); the runner
 * `scripts/final-qa.mjs` collects all of them. Every threshold is echoed in
 * `params`. Never approves: `approved` and `listeningVerified` stay false.
 *
 * @param input - measurements plus expectations and optional targets
 * @returns checks, measurements, per-line speech recall, machinePass, approved:false
 *
 * @example
 * import finalQa from 'kody:@kody/skills/final-qa'
 *
 * const qa = await finalQa({
 *   probe, decodedFrames: 2592, blackdetectLog, ebur128Log,
 *   lines: [{ id: 'n01', script: 'One package.', heard: 'One package.' }],
 *   fadeRms: [{ t: 85.0, rmsDb: -30 }, { t: 85.25, rmsDb: -36 }],
 *   fadeStartSeconds: 85.0, lastWordEndSeconds: 85.0,
 *   expect: { fps: 30, width: 1920, height: 1080, durationSeconds: 86.4 },
 * })
 */
export default function finalQa(input: FinalQaInput) {
	if (!input || typeof input !== 'object') throw new Error('input object is required')
	const allowed = new Set(['probe', 'decodedFrames', 'blackdetectLog', 'ebur128Log', 'introEbur128Log', 'lines', 'fadeRms', 'fadeStartSeconds', 'lastWordEndSeconds', 'expect', 'targets', 'aliases'])
	const unknown = Object.keys(input).filter((k) => !allowed.has(k))
	if (unknown.length) throw new Error(`unknown input key(s): ${unknown.join(', ')}`)
	for (const k of ['probe', 'blackdetectLog', 'ebur128Log', 'lines', 'fadeRms', 'expect'] as const) {
		if (input[k] === undefined) throw new Error(`${k} is required`)
	}
	const t = { ...DEFAULT_TARGETS, ...input.targets }
	const probe = input.probe as { streams?: Array<Record<string, string | number>>; format?: Record<string, string> }
	const v = probe.streams?.find((s) => s.codec_type === 'video')
	const a = probe.streams?.find((s) => s.codec_type === 'audio')
	const duration = Number(probe.format?.duration)
	const fps = rate((v?.avg_frame_rate ?? v?.r_frame_rate) as string | undefined)
	const checks: Check[] = []
	const add = (name: string, ok: boolean, detail: string) => checks.push({ name, ok, detail })

	add('video', Boolean(v) && v!.width === input.expect.width && v!.height === input.expect.height && fps !== undefined && Math.abs(fps - input.expect.fps) < 0.01,
		`${v?.codec_name ?? 'none'} ${v?.width}x${v?.height} @ ${fps}`)
	add('audio', Boolean(a), a ? `${a.codec_name} ${a.sample_rate} Hz ${a.channels} ch` : 'no audio stream')
	add('duration', Math.abs(duration - input.expect.durationSeconds) <= 1 / input.expect.fps + 0.05, `${duration}s, expect ${input.expect.durationSeconds}s`)
	const expectedFrames = Math.round(input.expect.durationSeconds * input.expect.fps)
	add('decode', Math.abs(input.decodedFrames - expectedFrames) <= 1, `${input.decodedFrames} frames decoded, expect ${expectedFrames}`)
	const black = countBlackRuns(input.blackdetectLog)
	add('black', black === 0, `${black} black run(s) >= 0.1 s`)

	const loud: Loudness = parseEbur128(input.ebur128Log)
	add('loudness', Math.abs(loud.integratedLufs - t.integratedLufs) <= t.lufsTolerance, `${loud.integratedLufs} LUFS, target ${t.integratedLufs} ± ${t.lufsTolerance}`)
	add('truePeak', loud.truePeakDbtp <= t.maxTruePeakDbtp, `${loud.truePeakDbtp} dBTP, max ${t.maxTruePeakDbtp}`)
	const intro = input.introEbur128Log ? parseEbur128(input.introEbur128Log) : null

	const lines = input.lines.map((l) => {
		const norm = wordRecall(tokenize(l.script, input.aliases), tokenize(l.heard, input.aliases))
		const strict = wordRecall(strictTokens(l.script), strictTokens(l.heard))
		return { id: l.id, script: l.script, heard: l.heard, scriptWords: norm.scriptWords, strictMatched: strict.matchedWords, matched: norm.matchedWords, recall: norm.recall, notHeard: norm.notHeard }
	})
	const words = lines.reduce((n, l) => n + l.scriptWords, 0)
	const matched = lines.reduce((n, l) => n + l.matched, 0)
	const strictMatched = lines.reduce((n, l) => n + l.strictMatched, 0)
	const overall = words ? round(matched / words) : 0
	const weak = lines.filter((l) => l.recall < t.minLineRecall)
	add('speechOverall', overall >= t.minOverallRecall, `${matched}/${words} words (${overall}), strict ${strictMatched}/${words}; min ${t.minOverallRecall}`)
	add('speechLines', weak.length === 0 && lines.every((l) => l.heard.trim()), weak.length ? `below ${t.minLineRecall}: ${weak.map((l) => `${l.id}=${l.recall}`).join(', ')}` : `all ${lines.length} lines >= ${t.minLineRecall}`)

	const tail = round(duration - input.lastWordEndSeconds)
	add('endHold', tail >= t.minTailSeconds && tail <= t.maxTailSeconds, `${tail}s after the last word (range ${t.minTailSeconds}-${t.maxTailSeconds})`)
	// Fade: judged on mix minus source-music RMS when the source is sampled (removes the track's own dynamics).
	const window = input.fadeRms.filter((x) => x.t >= input.fadeStartSeconds - 0.001 && x.rmsDb !== null)
	const vsSource = window.length > 0 && window.every((x) => typeof x.sourceRmsDb === 'number')
	const fade = window.map((x) => round((x.rmsDb as number) - (vsSource ? (x.sourceRmsDb as number) : 0), 1))
	const nonIncreasing = fade.every((x, i) => i === 0 || x <= fade[i - 1] + t.fadeRiseToleranceDb)
	const drop = fade.length > 1 ? round(fade[0] - fade[fade.length - 1], 1) : 0
	add('fade', fade.length > 1 && nonIncreasing && drop >= t.minFadeDropDb,
		`${drop} dB drop over ${fade.length} samples, ${nonIncreasing ? 'non-increasing' : 'RISES'} (min drop ${t.minFadeDropDb}); ${vsSource ? 'mix minus source music' : 'raw mix RMS: includes the track\'s own dynamics, pass sourceRmsDb to judge the fade itself'}`)

	const failed = checks.filter((c) => !c.ok)
	return {
		machinePass: failed.length === 0,
		checks,
		measurements: {
			durationSeconds: duration,
			decodedFrames: input.decodedFrames,
			blackRuns: black,
			loudness: loud,
			introLoudness: intro,
			speech: { scriptWords: words, matchedWords: matched, strictMatchedWords: strictMatched, recall: overall, linesAtOrAboveMin: lines.length - weak.length },
			endHoldSeconds: tail,
			fade: { samples: fade.length, dropDb: drop, nonIncreasing, method: vsSource ? 'mix_minus_source' : 'raw_mix', envelopeDb: fade },
		},
		lines,
		reviewStatus: 'pending_human_inspection' as const,
		approved: false as const,
		listeningVerified: false as const,
		next: failed.length
			? `Fix: ${failed.map((c) => c.name).join(', ')}. See references/troubleshooting.md.`
			: 'Machine checks pass. Inspect stills and play the MP4; listening and visual approval stay with a person.',
		params: t,
	}
}