mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 12:44:11 -10:00
Shane on Dutch (11-29): words faded and cut in two, lines too quiet to hear, effects no one hears, and text laid over the people and the dog the shot is about. - raea sound check VIDEO (server/sound.ts): each voice clip's edit points against the take's words and its sound. A cut inside a word or on a word's sound is an error, and the message names the pause (or the boundary) to move it to. Lines more than 6 dB from the cut's median are an error, with the gainDb that evens them. An effect 10 dB or more under the voice is an error, since no one hears it. Buried or fighting music is a warning. offload.ts runs it after every render that has a manifest. - The farm's POST /v1/scene (deploy/modal/farm_scene.py) reads a frame: people as a mask, faces, COCO's things, and words in the shot (four small OpenCV zoo models on the CPU, each pinned by its hash). - server/place.ts turns a scene into costs. raea frames check now fails text over a face, a dog or a person when a clear place of its size exists, and names that place. raea frames place FILE lists the clear places in a take. Stacked lines move as one block, our own text isn't counted as the shot's words, and passers-by's small faces don't count. - The farm wrote a split render's probe manifest (frame 0 only) as the render's. Each run now writes its own and the farm joins them, so the checks see every frame and every clip. Tests: test/sound.ts (7), test/place.ts (4, on scene reads of three interview frames, boxes only), test/farm_plan.py (the joined manifest). Co-authored-by: shinyobjectz <[email protected]>
299 lines
18 KiB
TypeScript
299 lines
18 KiB
TypeScript
// `raea sound check` on a raea cloud box: what a cut's sound gets wrong that a listener hears at once, measured from the
|
||
// edit itself (its render manifest) against each source take's own words and sound, so it can't be passed by editing
|
||
// what the cut is "meant" to say (11-29, Shane on Dutch: "a lot of it is audio cuts, fading out words, putting in audio
|
||
// that is too low to hear but whisper picks up ... i dont really hear any sound effects being used").
|
||
//
|
||
// raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json]
|
||
// edit points: each voice clip's in and out against its take's words (TAKE.words.json beside the take; heard by
|
||
// the farm's Whisper when it has none) and its take's own level every 10 ms. A clip that starts or ends inside
|
||
// a word, or on sound (a word's tail, its first consonant), is an error, with the nearest gap to move it to.
|
||
// levels: each voice clip's speech level (its take's, plus its gainDb) against the cut's other lines: 6 dB or
|
||
// more apart is an error (a line too quiet to hear, that a transcriber still hears), 4 dB a warning; the
|
||
// gainDb that evens it is said.
|
||
// effects and music: an effect 10 dB or more under the voice is an error (no one hears it); music more than
|
||
// 26 dB under the voice, or within 6 dB of it, a warning.
|
||
// Exit 1 on any error. The report is VIDEO.sound-check.json beside it.
|
||
import { spawnSync } from "node:child_process"
|
||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||
import os from "node:os"
|
||
import path from "node:path"
|
||
import { pathToFileURL } from "node:url"
|
||
import { hear, levels, type Word } from "./words.ts"
|
||
|
||
/** a voice clip's speech level is its take's loud 10 ms frames (the 90th percentile) inside the clip */
|
||
const SPEECH_Q = 0.9
|
||
/** at a cut point, sound this close to the speech level (dB) is speech still going: a word's tail or first consonant */
|
||
const ON_SOUND = 10
|
||
/** a gap to cut in: 40 ms at least this far under the speech level (dB), or, in a noisy take (a street), within
|
||
* GAP_FLOOR of its own quietest sound, but never closer than GAP_LEAST to the speech */
|
||
const GAP = 18
|
||
const GAP_FLOOR = 6
|
||
const GAP_LEAST = 8
|
||
/** a take's floor: its quietest 10 ms frames (the 10th percentile) around the clip */
|
||
const FLOOR_Q = 0.1
|
||
/** how far either side of a cut point a gap is looked for (s) */
|
||
const NEAR = 0.4
|
||
/** lines this far apart (dB) are an error, a warning */
|
||
const LEVEL_ERROR = 6
|
||
const LEVEL_WARN = 4
|
||
/** an effect this far under the voice (dB) isn't heard */
|
||
const SFX_UNDER = 10
|
||
/** music: further under than this isn't heard, closer than this fights the words */
|
||
const MUSIC_LOST = 26
|
||
const MUSIC_FIGHTS = 6
|
||
|
||
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
|
||
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
|
||
export type Manifest = { fps?: number; length?: number; frames?: unknown[]; sounds?: { fps?: number; clips?: Clip[] } }
|
||
/** a take's level every 10 ms (dB) from `start` s on */
|
||
export type Levels = { start: number; db: number[] }
|
||
|
||
const MUSIC = /music|bed|score/i
|
||
const SFX = /sfx|fx|effect|foley|sting/i
|
||
export const busOf = (c: Clip): "voice" | "music" | "sfx" => (c.bus && MUSIC.test(c.bus) ? "music" : c.bus && SFX.test(c.bus) ? "sfx" : c.bus === "voice" || !c.bus ? (SFX.test(path.basename(c.src)) ? "sfx" : MUSIC.test(path.basename(c.src)) ? "music" : "voice") : "voice")
|
||
|
||
const pct = (xs: number[], q: number) => {
|
||
if (!xs.length) return -100
|
||
const s = [...xs].sort((a, b) => a - b)
|
||
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
|
||
}
|
||
const at = (l: Levels, t: number) => l.db[Math.round((t - l.start) * 100)] ?? -100
|
||
/** the loudest 10 ms frame in [a, b] */
|
||
const peak = (l: Levels, a: number, b: number) => {
|
||
let m = -100
|
||
for (let t = a; t <= b + 1e-9; t += 0.01) m = Math.max(m, at(l, t))
|
||
return m
|
||
}
|
||
const secs = (t: number) => `${t.toFixed(2)} s`
|
||
|
||
/** the speech level of a clip's stretch of its take: its loud frames, inside its words when it has any */
|
||
export function speechLevel(l: Levels, a: number, b: number, words: Word[]): number {
|
||
const inWords = words.filter((w) => w.end > a && w.start < b)
|
||
const frames: number[] = []
|
||
for (let t = a; t < b; t += 0.01) if (!inWords.length || inWords.some((w) => t >= w.start && t <= w.end)) frames.push(at(l, t))
|
||
return pct(frames, SPEECH_Q)
|
||
}
|
||
|
||
/** the nearest time to `t` (within NEAR, never past `limit` on the clip's inside) that is a gap: 40 ms around it at
|
||
* least GAP dB under the speech level and inside no word */
|
||
/** the level under which a take is quiet enough to cut in: GAP under the speech, or near the take's own floor */
|
||
export const quietUnder = (l: Levels, ref: number) => Math.min(ref - GAP_LEAST, Math.max(ref - GAP, pct(l.db, FLOOR_Q) + GAP_FLOOR))
|
||
|
||
export function nearestGap(l: Levels, t: number, ref: number, words: Word[], inside: 1 | -1, limit: number): number | null {
|
||
const under = quietUnder(l, ref)
|
||
const quiet = (c: number) => (inside === 1 ? c <= limit : c >= limit) && peak(l, c - 0.02, c + 0.02) <= under && !words.some((w) => c > w.start - 0.01 && c < w.end + 0.01)
|
||
for (let d = 0; d <= NEAR + 1e-9; d += 0.01) {
|
||
for (const s of d ? [-1, 1] : [1]) {
|
||
const c = t + s * d
|
||
if (!quiet(c)) continue
|
||
// the middle of the gap it's in (a cut at a gap's edge takes a breath or a consonant with it), kept near t
|
||
let a = c
|
||
let b = c
|
||
while (a - 0.01 >= t - NEAR && quiet(a - 0.01)) a -= 0.01
|
||
while (b + 0.01 <= t + NEAR && quiet(b + 0.01)) b += 0.01
|
||
return Math.round(((a + b) / 2) * 100) / 100
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
/** how close (s) a cut is to a boundary between two words that run together to count as on it (word timings are good
|
||
* to about 30 ms) */
|
||
const SEAM = 0.03
|
||
/** boundaries between words with no pause (under 80 ms) between them */
|
||
export function seams(words: Word[]): { at: number; before: string; after: string }[] {
|
||
const out: { at: number; before: string; after: string }[] = []
|
||
for (let i = 1; i < words.length; i++) {
|
||
const a = words[i - 1]
|
||
const b = words[i]
|
||
if (b.start - a.end < 0.08) out.push({ at: Math.round(((a.end + b.start) / 2) * 1000) / 1000, before: a.text, after: b.text })
|
||
}
|
||
return out
|
||
}
|
||
|
||
/** a voice clip's in and out: inside a word, or on sound */
|
||
export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Finding[] {
|
||
const out: Finding[] = []
|
||
const dur = (c.to - c.from) / fps
|
||
const tin = c.at
|
||
const tout = c.at + dur
|
||
const ref = speechLevel(l, tin, tout, words)
|
||
const name = path.basename(c.src)
|
||
for (const [edge, t, cutAt, inside] of [["in", tin, c.from / fps, 1], ["out", tout, c.to / fps, -1]] as const) {
|
||
const where = `the ${edge === "in" ? "start" : "end"} of the clip at ${secs(cutAt)} (${name} ${secs(t)})`
|
||
// speech that runs on with no pause still has its boundaries between words: a cut on one is tight, not a cut word
|
||
const seam = seams(words).find((x) => Math.abs(x.at - t) <= SEAM)
|
||
if (seam) {
|
||
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
|
||
if (here >= ref - ON_SOUND)
|
||
out.push({ level: "warn", kind: "edit-on-sound", at: cutAt, says: `${where} is between “${seam.before}” and “${seam.after}” with no pause: a tight cut. Look at it on the waveform, or move it to a pause if one is near` })
|
||
continue
|
||
}
|
||
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
|
||
const gap = nearestGap(l, t, ref, words, inside, inside === 1 ? tout - 0.1 : tin + 0.1)
|
||
const ms = (x: number) => `${x >= t ? "+" : ""}${Math.round((x - t) * 1000)} ms`
|
||
const bound = gap === null ? seams(words).filter((x) => Math.abs(x.at - t) <= NEAR && (inside === 1 ? x.at < tout - 0.1 : x.at > tin + 0.1)).sort((p, q) => Math.abs(p.at - t) - Math.abs(q.at - t))[0] : undefined
|
||
const move =
|
||
gap !== null
|
||
? `move it to ${secs(gap)} in ${name} (${ms(gap)}), the gap ${edge === "in" ? "before" : "after"} the words`
|
||
: bound
|
||
? `there's no pause within ${NEAR * 1000} ms; the nearest boundary between words is ${secs(bound.at)} in ${name} (${ms(bound.at)}, between “${bound.before}” and “${bound.after}”): cut there, or at another pause`
|
||
: `no pause or word boundary within ${NEAR * 1000} ms: cut at another pause, or take another line`
|
||
if (word) {
|
||
out.push({ level: "error", kind: "edit-in-word", at: cutAt, says: `${where} cuts “${word.text}” (${secs(word.start)}–${secs(word.end)}) in two: ${move}` })
|
||
continue
|
||
}
|
||
// the 10 ms just inside the cut: a word's onset a frame or two after an in point is a tight cut, not a cut one
|
||
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
|
||
if (here >= Math.max(ref - ON_SOUND, pct(l.db, FLOOR_Q) + GAP_FLOOR + 2)) {
|
||
const near = words.reduce<Word | null>((b, w) => (Math.min(Math.abs(w.start - t), Math.abs(w.end - t)) < (b ? Math.min(Math.abs(b.start - t), Math.abs(b.end - t)) : 9) ? w : b), null)
|
||
out.push({ level: "error", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
export type Heard = { clip: Clip; kind: "voice" | "music" | "sfx"; level: number }
|
||
|
||
/** each voice line against the cut's others; effects and music against the voice */
|
||
export function balance(heard: Heard[], fps: number): Finding[] {
|
||
const out: Finding[] = []
|
||
const voice = heard.filter((h) => h.kind === "voice" && (h.clip.to - h.clip.from) / fps >= 0.4)
|
||
if (!voice.length) return out
|
||
const mid = pct(voice.map((h) => h.level), 0.5)
|
||
for (const h of voice) {
|
||
const d = h.level - mid
|
||
if (Math.abs(d) < LEVEL_WARN) continue
|
||
const g = (h.clip.gainDb ?? 0) - d
|
||
out.push({ level: Math.abs(d) >= LEVEL_ERROR ? "error" : "warn", kind: "level", at: h.clip.from / fps, says: `the line at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)} ${secs(h.clip.at)}) is ${Math.abs(d).toFixed(0)} dB ${d < 0 ? "under" : "over"} the cut's other lines${d < 0 ? ": too quiet to hear, though a transcriber still hears it" : ""}. Set its gainDb to ${g.toFixed(1)} (now ${(h.clip.gainDb ?? 0).toFixed(1)})` })
|
||
}
|
||
for (const h of heard.filter((x) => x.kind === "sfx")) {
|
||
const d = h.level - mid
|
||
if (d <= -SFX_UNDER)
|
||
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
|
||
}
|
||
for (const h of heard.filter((x) => x.kind === "music")) {
|
||
const d = h.level - mid
|
||
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
|
||
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
|
||
}
|
||
return out
|
||
}
|
||
|
||
/** the take a manifest names, on this box: its own path, or the part after a farm job's work/ under the project */
|
||
export function onBox(src: string, roots: string[]): string | null {
|
||
if (existsSync(src)) return src
|
||
const rel = src.includes("/work/") ? src.slice(src.lastIndexOf("/work/") + 6) : src.replace(/^\/+/, "")
|
||
for (const r of roots) {
|
||
const p = path.resolve(r, rel)
|
||
if (existsSync(p)) return p
|
||
}
|
||
return null
|
||
}
|
||
|
||
const wordsOf = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
|
||
|
||
async function takeWords(file: string): Promise<Word[]> {
|
||
for (const p of [wordsOf(file), `${file}.words.json`]) {
|
||
if (existsSync(p)) {
|
||
const raw = JSON.parse(readFileSync(p, "utf8")) as ({ text: string; start_ms: number; end_ms: number } | Word)[] | { words: { text: string; start_ms: number; end_ms: number }[] }
|
||
const list = Array.isArray(raw) ? raw : raw.words
|
||
return list.map((w) => ("start_ms" in w ? { text: w.text, start: w.start_ms / 1000, end: w.end_ms / 1000 } : w))
|
||
}
|
||
}
|
||
const heard = await hear(file)
|
||
writeFileSync(wordsOf(file), `${JSON.stringify(heard.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) })))}\n`)
|
||
return heard
|
||
}
|
||
|
||
/** a take's level every 10 ms over [a, b] */
|
||
function takeLevels(file: string, a: number, b: number): Levels {
|
||
const start = Math.max(0, a)
|
||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-sound-"))
|
||
try {
|
||
const raw = path.join(dir, "a.raw")
|
||
const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String(start), "-t", String(Math.max(0.05, b - start)), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw], { encoding: "utf8" })
|
||
if (r.status !== 0 || !existsSync(raw)) return { start, db: [] }
|
||
const buf = readFileSync(raw)
|
||
return { start, db: levels(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2))) }
|
||
} finally {
|
||
rmSync(dir, { recursive: true, force: true })
|
||
}
|
||
}
|
||
|
||
function flag(args: string[], name: string): string | undefined {
|
||
const i = args.indexOf(name)
|
||
return i >= 0 ? args[i + 1] : undefined
|
||
}
|
||
|
||
const stem = (v: string) => v.slice(0, v.length - path.extname(v).length)
|
||
/** the render's manifest: --manifest, else VIDEO.render.json (what raea cloud writes), else VIDEO.manifest.json */
|
||
export const manifestFor = (video: string, given?: string) => given ?? [`${stem(video)}.render.json`, `${stem(video)}.manifest.json`].find(existsSync) ?? `${stem(video)}.render.json`
|
||
|
||
export async function check(video: string, manifestPath: string, roots: string[]): Promise<{ findings: Finding[]; voice: number }> {
|
||
const m = JSON.parse(readFileSync(manifestPath, "utf8")) as Manifest
|
||
const fps = m.sounds?.fps ?? m.fps ?? 30
|
||
const found: Finding[] = []
|
||
const length = m.length ?? 0
|
||
const frames = m.frames?.length ?? 0
|
||
if (length > 1 && frames < length * 0.9)
|
||
found.push({ level: "error", kind: "manifest", at: null, says: `${path.basename(manifestPath)} holds ${frames} of the cut's ${length} frames, so its edit can't be checked: render the cut again (a render on raea cloud's GPUs before 11-29 kept frame 0's alone)` })
|
||
const clips = m.sounds?.clips ?? []
|
||
const heard: Heard[] = []
|
||
let voice = 0
|
||
for (const c of clips) {
|
||
const kind = busOf(c)
|
||
const file = onBox(c.src, roots)
|
||
if (!file) {
|
||
found.push({ level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this box: its clip at ${secs(c.from / fps)} isn't checked` })
|
||
continue
|
||
}
|
||
const dur = (c.to - c.from) / fps
|
||
if (kind === "voice") {
|
||
voice++
|
||
const words = await takeWords(file)
|
||
const l = takeLevels(file, c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1)
|
||
found.push(...editPoints(c, fps, words, l))
|
||
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
|
||
} else {
|
||
const l = takeLevels(file, c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20))
|
||
const level = kind === "sfx" ? pct(l.db, 0.98) : pct(l.db.filter((x) => x > -70), 0.5)
|
||
heard.push({ clip: c, kind, level: level + (c.gainDb ?? 0) })
|
||
}
|
||
}
|
||
found.push(...balance(heard, fps))
|
||
return { findings: found.sort((a, b) => (a.at ?? -1) - (b.at ?? -1)), voice }
|
||
}
|
||
|
||
export async function main(args: string[]): Promise<number> {
|
||
const a = args[0] === "check" ? args.slice(1) : args
|
||
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
|
||
if (!video || !existsSync(video)) {
|
||
console.error("usage: raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json] (edit points inside words or on sound, lines too quiet to hear, effects no one hears)")
|
||
return 2
|
||
}
|
||
const man = manifestFor(video, flag(a, "--manifest"))
|
||
if (!existsSync(man)) {
|
||
console.error(`raea sound check: no manifest for ${path.basename(video)} (${path.basename(man)}): render it with --manifest, or on raea cloud, which writes VIDEO.render.json`)
|
||
return 2
|
||
}
|
||
// the project the takes are under: here, and each folder above the video up to here
|
||
const roots = [process.cwd()]
|
||
for (let d = path.dirname(path.resolve(video)); d.startsWith(process.cwd()) && d !== process.cwd(); d = path.dirname(d)) roots.push(d)
|
||
const { findings, voice } = await check(video, man, roots)
|
||
for (const x of findings) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
|
||
const errors = findings.filter((x) => x.level === "error").length
|
||
const report = flag(a, "-o") ?? `${stem(video)}.sound-check.json`
|
||
writeFileSync(report, `${JSON.stringify({ object: "sound.check", video, manifest: man, voice_clips: voice, passed: errors === 0, errors, warnings: findings.length - errors, findings }, null, 1)}\n`)
|
||
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${voice} voice clips, ${errors} errors, ${findings.length - errors} warnings; ${path.basename(report)}`)
|
||
return errors ? 1 : 0
|
||
}
|
||
|
||
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
||
const a = process.argv.slice(2)
|
||
main(a[0] === "sound" ? a.slice(1) : a).then(
|
||
(c) => process.exit(c),
|
||
(e) => (console.error(`raea sound: ${(e as Error).message}`), process.exit(1)),
|
||
)
|
||
}
|