dsh-drawai 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,214 +1,214 @@
1
- // One source of truth: source-music seconds -> edit events -> source SFX peaks.
2
- import { createHash } from 'node:crypto'
3
- import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, unlinkSync } from 'node:fs'
4
- import { join, resolve, relative, isAbsolute } from 'node:path'
5
- import { decodePcm } from './beats.js'
6
- import { runFfmpeg } from './ffmpeg.js'
7
- import { parseProjectJson } from './json.js'
8
-
9
- const number = (value, name) => {
10
- if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(name + ' 必须是有限数字')
11
- return value
12
- }
13
- export function assetPath(dir, file) {
14
- const root = resolve(dir, 'assets'), path = resolve(root, file || '')
15
- const rel = relative(root, path)
16
- if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith('..' + (process.platform === 'win32' ? '\\' : '/'))) throw new Error('同步音频必须位于工程 assets 内')
17
- return path
18
- }
19
- export const syncKey = (timeline) => createHash('sha256').update(JSON.stringify(timeline)).digest('hex')
20
- export function syncRevision(dir, timeline) {
21
- const music = timeline.audio?.find((cue) => cue.id === timeline.sync?.musicCueId)
22
- if (timeline.sync?.analysisSourceHash && (!music || timeline.sync.analysisSourceHash !== filmHash(assetPath(dir, music.file)))) throw new Error('音乐文件已变更,请重新 motion_sync bind 分析后绑定')
23
- const hash = createHash('sha256').update(syncKey(timeline))
24
- for (const shot of timeline.shots) {
25
- const file = join(dir, shot.file || '')
26
- if (shot.file && existsSync(file)) hash.update(readFileSync(file))
27
- }
28
- for (const cue of timeline.audio || []) hash.update(readFileSync(assetPath(dir, cue.file)))
29
- const walk = (path) => {
30
- if (!existsSync(path)) return
31
- for (const entry of readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
32
- const file = join(path, entry.name)
33
- if (entry.isDirectory()) walk(file)
34
- else if (entry.isFile()) hash.update(entry.name).update(readFileSync(file))
35
- }
36
- }
37
- walk(join(dir, 'components'))
38
- walk(join(dir, 'assets'))
39
- for (const entry of readdirSync(dir).sort()) if (/\.(tsx?|jsx?)$/.test(entry) && !/^index\./.test(entry)) hash.update(entry).update(readFileSync(join(dir, entry)))
40
- return hash.digest('hex')
41
- }
42
- export const filmHash = (file) => createHash('sha256').update(readFileSync(file)).digest('hex')
43
-
44
- export function resolveSync(input) {
45
- const timeline = structuredClone(input), sync = timeline.sync
46
- if (!sync) return timeline
47
- const fps = number(timeline.fps, 'fps')
48
- if (sync.toleranceFrames !== undefined && (number(sync.toleranceFrames, 'toleranceFrames') < 0 || sync.toleranceFrames > 3)) throw new Error('toleranceFrames 必须在0–3内')
49
- if (fps <= 0 || !Array.isArray(sync.anchors) || !sync.anchors.length || sync.anchors.length > 200) throw new Error('sync 需要 1–200 个 anchors')
50
- const music = timeline.audio?.find((cue) => cue.id === sync.musicCueId)
51
- if (!music || music.loop) throw new Error('sync.musicCueId 必须指向不循环的音乐轨')
52
- const offset = sync.outputOffsetSeconds === undefined ? 0 : number(sync.outputOffsetSeconds, 'outputOffsetSeconds')
53
- if (Math.abs(offset) > 1) throw new Error('输出偏移超出 ±1 秒')
54
- const ids = new Set(), targets = new Set(), cueIds = new Set()
55
- const rows = sync.anchors.map((anchor) => {
56
- if (typeof anchor.id !== 'string' || !anchor.id || ids.has(anchor.id)) throw new Error('anchor.id 必须唯一')
57
- ids.add(anchor.id)
58
- if (anchor.visual) visualPeak(Buffer.alloc(0), 1, 1, 0, anchor.visual)
59
- if (anchor.sfx !== undefined && !Array.isArray(anchor.sfx)) throw new Error('sfx 必须是绑定数组')
60
- if (!['cut', 'action'].includes(anchor.type)) throw new Error('anchor.type 必须是 cut/action')
61
- const shot = timeline.shots.find((item) => item.id === anchor.shotId)
62
- if (!shot) throw new Error('锚点引用了不存在的镜头:' + anchor.shotId)
63
- const targetKey = anchor.type + ':' + anchor.shotId + ':' + (anchor.type === 'action' ? anchor.name : '')
64
- if (targets.has(targetKey)) throw new Error('同一个切镜或动作不能重复绑定')
65
- targets.add(targetKey)
66
- if (anchor.type === 'action' && (typeof anchor.name !== 'string' || !anchor.name)) throw new Error('动作锚点需要 name')
67
- if ((anchor.at === undefined) === (anchor.beat === undefined)) throw new Error('锚点必须且只能给 at(源音乐秒)或 beat(0 起拍号)')
68
- let sourceSeconds
69
- if (anchor.at !== undefined) sourceSeconds = number(anchor.at, 'at')
70
- else {
71
- const grid = sync.analysis?.grid
72
- if (!grid || ![grid.t0, grid.periodMs, grid.residualMs, grid.coverage].every(Number.isFinite) || grid.periodMs <= 0 || grid.residualMs > 15 || grid.coverage < 0.45) throw new Error('按拍号绑定需要通过验收的音乐网格;否则使用 at 实测瞬态')
73
- const beat = number(anchor.beat, 'beat')
74
- if (beat < 0) throw new Error('beat 必须从0起')
75
- sourceSeconds = grid.t0 + beat * grid.periodMs / 1000
76
- }
77
- const musicLocal = sourceSeconds - (music.trimStart || 0)
78
- if (musicLocal < 0 || musicLocal * fps >= music.durationInFrames) throw new Error('拍点超出音乐播放窗口:' + anchor.id)
79
- const seconds = music.from / fps + musicLocal + offset
80
- const frame = Math.round(seconds * fps)
81
- if (frame < 0 || frame >= timeline.durationInFrames) throw new Error('锚点超出影片范围:' + anchor.id)
82
- if (anchor.type === 'cut') shot.startFrame = frame
83
- return { ...anchor, sourceSeconds, seconds, frame, quantizationMs: (frame / fps - seconds) * 1000 }
84
- })
85
- for (let i = 0; i < timeline.shots.length; i++) {
86
- const shot = timeline.shots[i], end = timeline.shots[i + 1]?.startFrame ?? timeline.durationInFrames
87
- if (shot.startFrame < 0 || end <= shot.startFrame) throw new Error('切镜绑定导致镜头倒序或长度为零')
88
- shot.durationFrames = end - shot.startFrame
89
- shot.anchors = Object.create(null)
90
- }
91
- for (const row of rows) {
92
- const shot = timeline.shots.find((item) => item.id === row.shotId)
93
- if (row.frame < shot.startFrame || row.frame >= shot.startFrame + shot.durationFrames) throw new Error('动作锚点不在所属镜头内:' + row.id)
94
- if (row.type === 'action') shot.anchors[row.name] = row.frame - shot.startFrame
95
- for (const sfx of row.sfx || []) {
96
- if (cueIds.has(sfx.cueId) || sfx.cueId === music.id) throw new Error('音效轨不能重复绑定或绑定音乐自身')
97
- cueIds.add(sfx.cueId)
98
- const cue = timeline.audio.find((item) => item.id === sfx.cueId)
99
- if (!cue || cue.loop) throw new Error('音效绑定需要存在且不循环的 cueId')
100
- const lag = number(sfx.peakSeconds, 'peakSeconds') - (cue.trimStart || 0)
101
- if (lag < 0 || lag * fps >= cue.durationInFrames) throw new Error('音效峰值超出裁剪窗口')
102
- const from = Math.round(row.frame - (lag + offset) * fps)
103
- if (from < 0 || from + cue.durationInFrames > timeline.durationInFrames) throw new Error('音效绑定超出影片范围,不会静默截断')
104
- cue.from = from
105
- }
106
- }
107
- sync.resolved = rows
108
- return timeline
109
- }
110
-
111
- // Normalized waveform matching around an expected transient. Low/ambiguous
112
- // matches remain unverified; absence of evidence must never become a pass.
113
- export function matchTransient(source, output, sourceAt, expectedAt, sampleRate, searchSeconds = 0.2) {
114
- const radius = Math.round(sampleRate * 0.025), center = Math.round(sourceAt * sampleRate)
115
- const step = 4, template = []
116
- for (let i = -radius; i <= radius; i += step) template.push(source[center + i] || 0)
117
- const norm = Math.sqrt(template.reduce((sum, x) => sum + x * x, 0))
118
- if (!norm) return null
119
- let best = { score: -1, at: 0 }, second = -1
120
- const scores = []
121
- const start = Math.max(radius, Math.round((expectedAt - searchSeconds) * sampleRate)), end = Math.min(output.length - radius - 1, Math.round((expectedAt + searchSeconds) * sampleRate))
122
- for (let at = start; at <= end; at++) {
123
- let dot = 0, energy = 0
124
- for (let i = 0; i < template.length; i++) { const x = output[at - radius + i * step]; dot += template[i] * x; energy += x * x }
125
- const score = energy ? dot / (norm * Math.sqrt(energy)) : 0
126
- scores.push({ at, score })
127
- if (score > best.score) best = { at, score }
128
- }
129
- for (const candidate of scores) if (Math.abs(candidate.at - best.at) > sampleRate * 0.01) second = Math.max(second, candidate.score)
130
- return best.score >= 0.45 && best.score - second >= 0.05 ? { at: best.at / sampleRate, confidence: best.score } : null
131
- }
132
- function samples(decoded) {
133
- return Float64Array.from({ length: decoded.pcm.length / 2 }, (_, i) => decoded.pcm.readInt16LE(i * 2) / 32768)
134
- }
135
-
136
- export function visualPeak(bytes, width, height, firstFrame, visual = {}) {
137
- if (visual.metric !== undefined && !['change', 'brightness'].includes(visual.metric)) throw new Error('visual.metric 必须为 change/brightness')
138
- if (visual.minSignal !== undefined && (number(visual.minSignal, 'minSignal') <= 0 || visual.minSignal > 255)) throw new Error('minSignal 必须在0–255内')
139
- const size = width * height, count = Math.floor(bytes.length / size), scores = []
140
- const roi = visual.roi || { x: 0, y: 0, w: 1, h: 1 }
141
- for (const key of ['x', 'y', 'w', 'h']) number(roi[key], 'visual.roi.' + key)
142
- if (roi.x < 0 || roi.y < 0 || roi.w <= 0 || roi.h <= 0 || roi.x + roi.w > 1 || roi.y + roi.h > 1) throw new Error('ROI 必须在 0–1 内')
143
- for (let f = 1; f < count; f++) {
144
- let sum = 0, n = 0
145
- for (let y = Math.floor(roi.y * height); y < Math.ceil((roi.y + roi.h) * height); y++) for (let x = Math.floor(roi.x * width); x < Math.ceil((roi.x + roi.w) * width); x++) {
146
- const i = y * width + x
147
- sum += visual.metric === 'brightness' ? bytes[f * size + i] : Math.abs(bytes[f * size + i] - bytes[(f - 1) * size + i]); n++
148
- }
149
- scores.push({ frame: firstFrame + f, score: sum / n })
150
- }
151
- scores.sort((a, b) => b.score - a.score)
152
- const best = scores[0], other = scores.find((item) => Math.abs(item.frame - best?.frame) > 1)
153
- return best && best.score >= (visual.minSignal ?? 8) && (!other || best.score > other.score * 1.15) ? best : null
154
- }
155
-
156
- export async function verifySync(dir, film, input) {
157
- const timeline = resolveSync(input), sync = timeline.sync
158
- if (!sync?.resolved?.length) throw new Error('尚未绑定锚点,先 motion_sync bind')
159
- const revision = syncRevision(dir, timeline)
160
- const receiptPath = film + '.sync.json'
161
- const receipt = existsSync(receiptPath) ? parseProjectJson(readFileSync(receiptPath, 'utf8')) : null
162
- if (receipt && receipt.revision !== revision) throw new Error('成片与当前绑定或场景版本不一致,请重新渲染后验收')
163
- if (receipt && receipt.filmHash !== filmHash(film)) throw new Error('成片文件与渲染回执不一致,请重新渲染')
164
- const out = join(dir, '.out', 'qa', 'sync'); mkdirSync(out, { recursive: true })
165
- const decoded = await decodePcm(film), output = samples(decoded), rate = decoded.sampleRate
166
- const cache = new Map()
167
- const load = async (cue) => {
168
- const path = assetPath(dir, cue.file)
169
- if (!cache.has(path)) cache.set(path, samples(await decodePcm(path)))
170
- return cache.get(path)
171
- }
172
- const music = timeline.audio.find((cue) => cue.id === sync.musicCueId), musicSource = await load(music)
173
- const rows = [], offsets = []
174
- for (const [index, anchor] of sync.resolved.entries()) {
175
- const heard = matchTransient(musicSource, output, anchor.sourceSeconds, anchor.seconds, rate)
176
- if (heard) offsets.push(heard.at - (music.from / timeline.fps + anchor.sourceSeconds - (music.trimStart || 0)))
177
- let visual = null
178
- // A cut is an observable frame difference. Continuous actions need an
179
- // explicitly selected metric/ROI; do not infer their semantic peak.
180
- if (anchor.type === 'cut' || anchor.visual) {
181
- const first = Math.max(0, anchor.frame - 6), last = Math.min(timeline.durationInFrames - 1, anchor.frame + 6)
182
- const path = join(out, 'anchor-' + index + '.gray')
183
- try {
184
- await runFfmpeg(['-loglevel', 'error', '-i', film, '-vf', 'select=between(n\\,' + first + '\\,' + last + '),scale=96:54,format=gray', '-vsync', '0', '-f', 'rawvideo', path], { cwd: dir, log: join(out, 'visual.log') })
185
- visual = visualPeak(readFileSync(path), 96, 54, first, anchor.visual)
186
- unlinkSync(join(out, 'visual.log'))
187
- } finally {
188
- if (existsSync(path)) unlinkSync(path)
189
- }
190
- }
191
- const sfxRows = []
192
- for (const binding of anchor.sfx || []) {
193
- const cue = timeline.audio.find((item) => item.id === binding.cueId)
194
- const match = await load(cue).then((source) => matchTransient(source, output, binding.peakSeconds, anchor.frame / timeline.fps, rate))
195
- sfxRows.push({ cueId: cue.id, measuredSeconds: match?.at ?? null, confidence: match?.confidence ?? null,
196
- errorFrames: match && heard ? (match.at - heard.at) * timeline.fps : null })
197
- }
198
- const error = heard && visual ? visual.frame - heard.at * timeline.fps : null
199
- const tolerance = sync.toleranceFrames ?? 2
200
- const status = error === null || sfxRows.some((item) => item.errorFrames === null) ? 'unverified'
201
- : Math.abs(error) > tolerance || sfxRows.some((item) => Math.abs(item.errorFrames) > tolerance) ? 'fail' : 'pass'
202
- rows.push({ id: anchor.id, type: anchor.type, plannedFrame: anchor.frame, quantizationMs: anchor.quantizationMs,
203
- measuredMusicSeconds: heard?.at ?? null, musicConfidence: heard?.confidence ?? null, measuredVisualFrame: visual?.frame ?? null,
204
- audiovisualErrorFrames: error, sfx: sfxRows, status })
205
- }
206
- offsets.sort((a, b) => a - b)
207
- const report = { version: 1, film, timelineKey: revision, renderReceipt: !!receipt, fps: timeline.fps, generatedAt: new Date().toISOString(),
208
- status: rows.some((row) => row.status === 'fail') ? 'fail' : rows.some((row) => row.status === 'unverified') ? 'unverified' : 'pass',
209
- measuredOutputOffsetSeconds: offsets.length >= 3 && offsets.at(-1) - offsets[0] < 0.015 ? offsets[Math.floor(offsets.length / 2)] : null,
210
- rows }
211
- if (!receipt) report.status = report.status === 'fail' ? 'fail' : 'unverified'
212
- writeFileSync(join(out, 'report.json'), JSON.stringify(report, null, 2))
213
- return report
214
- }
1
+ // One source of truth: source-music seconds -> edit events -> source SFX peaks.
2
+ import { createHash } from 'node:crypto'
3
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, unlinkSync } from 'node:fs'
4
+ import { join, resolve, relative, isAbsolute } from 'node:path'
5
+ import { decodePcm } from './beats.js'
6
+ import { runFfmpeg } from './ffmpeg.js'
7
+ import { parseProjectJson } from './json.js'
8
+
9
+ const number = (value, name) => {
10
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(name + ' 必须是有限数字')
11
+ return value
12
+ }
13
+ export function assetPath(dir, file) {
14
+ const root = resolve(dir, 'assets'), path = resolve(root, file || '')
15
+ const rel = relative(root, path)
16
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith('..' + (process.platform === 'win32' ? '\\' : '/'))) throw new Error('同步音频必须位于工程 assets 内')
17
+ return path
18
+ }
19
+ export const syncKey = (timeline) => createHash('sha256').update(JSON.stringify(timeline)).digest('hex')
20
+ export function syncRevision(dir, timeline) {
21
+ const music = timeline.audio?.find((cue) => cue.id === timeline.sync?.musicCueId)
22
+ if (timeline.sync?.analysisSourceHash && (!music || timeline.sync.analysisSourceHash !== filmHash(assetPath(dir, music.file)))) throw new Error('音乐文件已变更,请重新 motion_sync bind 分析后绑定')
23
+ const hash = createHash('sha256').update(syncKey(timeline))
24
+ for (const shot of timeline.shots) {
25
+ const file = join(dir, shot.file || '')
26
+ if (shot.file && existsSync(file)) hash.update(readFileSync(file))
27
+ }
28
+ for (const cue of timeline.audio || []) hash.update(readFileSync(assetPath(dir, cue.file)))
29
+ const walk = (path) => {
30
+ if (!existsSync(path)) return
31
+ for (const entry of readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
32
+ const file = join(path, entry.name)
33
+ if (entry.isDirectory()) walk(file)
34
+ else if (entry.isFile()) hash.update(entry.name).update(readFileSync(file))
35
+ }
36
+ }
37
+ walk(join(dir, 'components'))
38
+ walk(join(dir, 'assets'))
39
+ for (const entry of readdirSync(dir).sort()) if (/\.(tsx?|jsx?)$/.test(entry) && !/^index\./.test(entry)) hash.update(entry).update(readFileSync(join(dir, entry)))
40
+ return hash.digest('hex')
41
+ }
42
+ export const filmHash = (file) => createHash('sha256').update(readFileSync(file)).digest('hex')
43
+
44
+ export function resolveSync(input) {
45
+ const timeline = structuredClone(input), sync = timeline.sync
46
+ if (!sync) return timeline
47
+ const fps = number(timeline.fps, 'fps')
48
+ if (sync.toleranceFrames !== undefined && (number(sync.toleranceFrames, 'toleranceFrames') < 0 || sync.toleranceFrames > 3)) throw new Error('toleranceFrames 必须在0–3内')
49
+ if (fps <= 0 || !Array.isArray(sync.anchors) || !sync.anchors.length || sync.anchors.length > 200) throw new Error('sync 需要 1–200 个 anchors')
50
+ const music = timeline.audio?.find((cue) => cue.id === sync.musicCueId)
51
+ if (!music || music.loop) throw new Error('sync.musicCueId 必须指向不循环的音乐轨')
52
+ const offset = sync.outputOffsetSeconds === undefined ? 0 : number(sync.outputOffsetSeconds, 'outputOffsetSeconds')
53
+ if (Math.abs(offset) > 1) throw new Error('输出偏移超出 ±1 秒')
54
+ const ids = new Set(), targets = new Set(), cueIds = new Set()
55
+ const rows = sync.anchors.map((anchor) => {
56
+ if (typeof anchor.id !== 'string' || !anchor.id || ids.has(anchor.id)) throw new Error('anchor.id 必须唯一')
57
+ ids.add(anchor.id)
58
+ if (anchor.visual) visualPeak(Buffer.alloc(0), 1, 1, 0, anchor.visual)
59
+ if (anchor.sfx !== undefined && !Array.isArray(anchor.sfx)) throw new Error('sfx 必须是绑定数组')
60
+ if (!['cut', 'action'].includes(anchor.type)) throw new Error('anchor.type 必须是 cut/action')
61
+ const shot = timeline.shots.find((item) => item.id === anchor.shotId)
62
+ if (!shot) throw new Error('锚点引用了不存在的镜头:' + anchor.shotId)
63
+ const targetKey = anchor.type + ':' + anchor.shotId + ':' + (anchor.type === 'action' ? anchor.name : '')
64
+ if (targets.has(targetKey)) throw new Error('同一个切镜或动作不能重复绑定')
65
+ targets.add(targetKey)
66
+ if (anchor.type === 'action' && (typeof anchor.name !== 'string' || !anchor.name)) throw new Error('动作锚点需要 name')
67
+ if ((anchor.at === undefined) === (anchor.beat === undefined)) throw new Error('锚点必须且只能给 at(源音乐秒)或 beat(0 起拍号)')
68
+ let sourceSeconds
69
+ if (anchor.at !== undefined) sourceSeconds = number(anchor.at, 'at')
70
+ else {
71
+ const grid = sync.analysis?.grid
72
+ if (!grid || ![grid.t0, grid.periodMs, grid.residualMs, grid.coverage].every(Number.isFinite) || grid.periodMs <= 0 || grid.residualMs > 15 || grid.coverage < 0.45) throw new Error('按拍号绑定需要通过验收的音乐网格;否则使用 at 实测瞬态')
73
+ const beat = number(anchor.beat, 'beat')
74
+ if (beat < 0) throw new Error('beat 必须从0起')
75
+ sourceSeconds = grid.t0 + beat * grid.periodMs / 1000
76
+ }
77
+ const musicLocal = sourceSeconds - (music.trimStart || 0)
78
+ if (musicLocal < 0 || musicLocal * fps >= music.durationInFrames) throw new Error('拍点超出音乐播放窗口:' + anchor.id)
79
+ const seconds = music.from / fps + musicLocal + offset
80
+ const frame = Math.round(seconds * fps)
81
+ if (frame < 0 || frame >= timeline.durationInFrames) throw new Error('锚点超出影片范围:' + anchor.id)
82
+ if (anchor.type === 'cut') shot.startFrame = frame
83
+ return { ...anchor, sourceSeconds, seconds, frame, quantizationMs: (frame / fps - seconds) * 1000 }
84
+ })
85
+ for (let i = 0; i < timeline.shots.length; i++) {
86
+ const shot = timeline.shots[i], end = timeline.shots[i + 1]?.startFrame ?? timeline.durationInFrames
87
+ if (shot.startFrame < 0 || end <= shot.startFrame) throw new Error('切镜绑定导致镜头倒序或长度为零')
88
+ shot.durationFrames = end - shot.startFrame
89
+ shot.anchors = Object.create(null)
90
+ }
91
+ for (const row of rows) {
92
+ const shot = timeline.shots.find((item) => item.id === row.shotId)
93
+ if (row.frame < shot.startFrame || row.frame >= shot.startFrame + shot.durationFrames) throw new Error('动作锚点不在所属镜头内:' + row.id)
94
+ if (row.type === 'action') shot.anchors[row.name] = row.frame - shot.startFrame
95
+ for (const sfx of row.sfx || []) {
96
+ if (cueIds.has(sfx.cueId) || sfx.cueId === music.id) throw new Error('音效轨不能重复绑定或绑定音乐自身')
97
+ cueIds.add(sfx.cueId)
98
+ const cue = timeline.audio.find((item) => item.id === sfx.cueId)
99
+ if (!cue || cue.loop) throw new Error('音效绑定需要存在且不循环的 cueId')
100
+ const lag = number(sfx.peakSeconds, 'peakSeconds') - (cue.trimStart || 0)
101
+ if (lag < 0 || lag * fps >= cue.durationInFrames) throw new Error('音效峰值超出裁剪窗口')
102
+ const from = Math.round(row.frame - (lag + offset) * fps)
103
+ if (from < 0 || from + cue.durationInFrames > timeline.durationInFrames) throw new Error('音效绑定超出影片范围,不会静默截断')
104
+ cue.from = from
105
+ }
106
+ }
107
+ sync.resolved = rows
108
+ return timeline
109
+ }
110
+
111
+ // Normalized waveform matching around an expected transient. Low/ambiguous
112
+ // matches remain unverified; absence of evidence must never become a pass.
113
+ export function matchTransient(source, output, sourceAt, expectedAt, sampleRate, searchSeconds = 0.2) {
114
+ const radius = Math.round(sampleRate * 0.025), center = Math.round(sourceAt * sampleRate)
115
+ const step = 4, template = []
116
+ for (let i = -radius; i <= radius; i += step) template.push(source[center + i] || 0)
117
+ const norm = Math.sqrt(template.reduce((sum, x) => sum + x * x, 0))
118
+ if (!norm) return null
119
+ let best = { score: -1, at: 0 }, second = -1
120
+ const scores = []
121
+ const start = Math.max(radius, Math.round((expectedAt - searchSeconds) * sampleRate)), end = Math.min(output.length - radius - 1, Math.round((expectedAt + searchSeconds) * sampleRate))
122
+ for (let at = start; at <= end; at++) {
123
+ let dot = 0, energy = 0
124
+ for (let i = 0; i < template.length; i++) { const x = output[at - radius + i * step]; dot += template[i] * x; energy += x * x }
125
+ const score = energy ? dot / (norm * Math.sqrt(energy)) : 0
126
+ scores.push({ at, score })
127
+ if (score > best.score) best = { at, score }
128
+ }
129
+ for (const candidate of scores) if (Math.abs(candidate.at - best.at) > sampleRate * 0.01) second = Math.max(second, candidate.score)
130
+ return best.score >= 0.45 && best.score - second >= 0.05 ? { at: best.at / sampleRate, confidence: best.score } : null
131
+ }
132
+ function samples(decoded) {
133
+ return Float64Array.from({ length: decoded.pcm.length / 2 }, (_, i) => decoded.pcm.readInt16LE(i * 2) / 32768)
134
+ }
135
+
136
+ export function visualPeak(bytes, width, height, firstFrame, visual = {}) {
137
+ if (visual.metric !== undefined && !['change', 'brightness'].includes(visual.metric)) throw new Error('visual.metric 必须为 change/brightness')
138
+ if (visual.minSignal !== undefined && (number(visual.minSignal, 'minSignal') <= 0 || visual.minSignal > 255)) throw new Error('minSignal 必须在0–255内')
139
+ const size = width * height, count = Math.floor(bytes.length / size), scores = []
140
+ const roi = visual.roi || { x: 0, y: 0, w: 1, h: 1 }
141
+ for (const key of ['x', 'y', 'w', 'h']) number(roi[key], 'visual.roi.' + key)
142
+ if (roi.x < 0 || roi.y < 0 || roi.w <= 0 || roi.h <= 0 || roi.x + roi.w > 1 || roi.y + roi.h > 1) throw new Error('ROI 必须在 0–1 内')
143
+ for (let f = 1; f < count; f++) {
144
+ let sum = 0, n = 0
145
+ for (let y = Math.floor(roi.y * height); y < Math.ceil((roi.y + roi.h) * height); y++) for (let x = Math.floor(roi.x * width); x < Math.ceil((roi.x + roi.w) * width); x++) {
146
+ const i = y * width + x
147
+ sum += visual.metric === 'brightness' ? bytes[f * size + i] : Math.abs(bytes[f * size + i] - bytes[(f - 1) * size + i]); n++
148
+ }
149
+ scores.push({ frame: firstFrame + f, score: sum / n })
150
+ }
151
+ scores.sort((a, b) => b.score - a.score)
152
+ const best = scores[0], other = scores.find((item) => Math.abs(item.frame - best?.frame) > 1)
153
+ return best && best.score >= (visual.minSignal ?? 8) && (!other || best.score > other.score * 1.15) ? best : null
154
+ }
155
+
156
+ export async function verifySync(dir, film, input) {
157
+ const timeline = resolveSync(input), sync = timeline.sync
158
+ if (!sync?.resolved?.length) throw new Error('尚未绑定锚点,先 motion_sync bind')
159
+ const revision = syncRevision(dir, timeline)
160
+ const receiptPath = film + '.sync.json'
161
+ const receipt = existsSync(receiptPath) ? parseProjectJson(readFileSync(receiptPath, 'utf8')) : null
162
+ if (receipt && receipt.revision !== revision) throw new Error('成片与当前绑定或场景版本不一致,请重新渲染后验收')
163
+ if (receipt && receipt.filmHash !== filmHash(film)) throw new Error('成片文件与渲染回执不一致,请重新渲染')
164
+ const out = join(dir, '.out', 'qa', 'sync'); mkdirSync(out, { recursive: true })
165
+ const decoded = await decodePcm(film), output = samples(decoded), rate = decoded.sampleRate
166
+ const cache = new Map()
167
+ const load = async (cue) => {
168
+ const path = assetPath(dir, cue.file)
169
+ if (!cache.has(path)) cache.set(path, samples(await decodePcm(path)))
170
+ return cache.get(path)
171
+ }
172
+ const music = timeline.audio.find((cue) => cue.id === sync.musicCueId), musicSource = await load(music)
173
+ const rows = [], offsets = []
174
+ for (const [index, anchor] of sync.resolved.entries()) {
175
+ const heard = matchTransient(musicSource, output, anchor.sourceSeconds, anchor.seconds, rate)
176
+ if (heard) offsets.push(heard.at - (music.from / timeline.fps + anchor.sourceSeconds - (music.trimStart || 0)))
177
+ let visual = null
178
+ // A cut is an observable frame difference. Continuous actions need an
179
+ // explicitly selected metric/ROI; do not infer their semantic peak.
180
+ if (anchor.type === 'cut' || anchor.visual) {
181
+ const first = Math.max(0, anchor.frame - 6), last = Math.min(timeline.durationInFrames - 1, anchor.frame + 6)
182
+ const path = join(out, 'anchor-' + index + '.gray')
183
+ try {
184
+ await runFfmpeg(['-loglevel', 'error', '-i', film, '-vf', 'select=between(n\\,' + first + '\\,' + last + '),scale=96:54,format=gray', '-vsync', '0', '-f', 'rawvideo', path], { cwd: dir, log: join(out, 'visual.log') })
185
+ visual = visualPeak(readFileSync(path), 96, 54, first, anchor.visual)
186
+ unlinkSync(join(out, 'visual.log'))
187
+ } finally {
188
+ if (existsSync(path)) unlinkSync(path)
189
+ }
190
+ }
191
+ const sfxRows = []
192
+ for (const binding of anchor.sfx || []) {
193
+ const cue = timeline.audio.find((item) => item.id === binding.cueId)
194
+ const match = await load(cue).then((source) => matchTransient(source, output, binding.peakSeconds, anchor.frame / timeline.fps, rate))
195
+ sfxRows.push({ cueId: cue.id, measuredSeconds: match?.at ?? null, confidence: match?.confidence ?? null,
196
+ errorFrames: match && heard ? (match.at - heard.at) * timeline.fps : null })
197
+ }
198
+ const error = heard && visual ? visual.frame - heard.at * timeline.fps : null
199
+ const tolerance = sync.toleranceFrames ?? 2
200
+ const status = error === null || sfxRows.some((item) => item.errorFrames === null) ? 'unverified'
201
+ : Math.abs(error) > tolerance || sfxRows.some((item) => Math.abs(item.errorFrames) > tolerance) ? 'fail' : 'pass'
202
+ rows.push({ id: anchor.id, type: anchor.type, plannedFrame: anchor.frame, quantizationMs: anchor.quantizationMs,
203
+ measuredMusicSeconds: heard?.at ?? null, musicConfidence: heard?.confidence ?? null, measuredVisualFrame: visual?.frame ?? null,
204
+ audiovisualErrorFrames: error, sfx: sfxRows, status })
205
+ }
206
+ offsets.sort((a, b) => a - b)
207
+ const report = { version: 1, film, timelineKey: revision, renderReceipt: !!receipt, fps: timeline.fps, generatedAt: new Date().toISOString(),
208
+ status: rows.some((row) => row.status === 'fail') ? 'fail' : rows.some((row) => row.status === 'unverified') ? 'unverified' : 'pass',
209
+ measuredOutputOffsetSeconds: offsets.length >= 3 && offsets.at(-1) - offsets[0] < 0.015 ? offsets[Math.floor(offsets.length / 2)] : null,
210
+ rows }
211
+ if (!receipt) report.status = report.status === 'fail' ? 'fail' : 'unverified'
212
+ writeFileSync(join(out, 'report.json'), JSON.stringify(report, null, 2))
213
+ return report
214
+ }