dsh-drawai 0.4.0 → 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.
- package/LICENSE +430 -418
- package/README.md +96 -249
- package/lib/audio-media.js +5 -2
- package/lib/client.js +45 -12
- package/lib/drawing-runner.js +6 -4
- package/lib/ffmpeg-manager.js +1056 -0
- package/lib/index.js +7719 -7396
- package/lib/motion/apply.js +4 -3
- package/lib/motion/asset-pack.js +394 -335
- package/lib/motion/assets.js +4 -3
- package/lib/motion/beats.js +3 -2
- package/lib/motion/collect.js +3 -1
- package/lib/motion/delivery.js +29 -1
- package/lib/motion/demo-assets-lock.js +10 -0
- package/lib/motion/ffmpeg.js +5 -4
- package/lib/motion/jobs.js +5 -1
- package/lib/motion/mgstyles/vendor/README.md +28 -0
- package/lib/motion/mgstyles/vendor/modules/d3/LICENSE +13 -0
- package/lib/motion/mgstyles/vendor/modules/d3/dist/d3.min.js +2 -0
- package/lib/motion/mgstyles/vendor/modules/opentype.js/LICENSE +20 -0
- package/lib/motion/mgstyles/vendor/modules/opentype.js/dist/opentype.mjs +14460 -0
- package/lib/motion/mgstyles/vendor/modules/simplex-noise/LICENSE +21 -0
- package/lib/motion/mgstyles/vendor/modules/simplex-noise/dist/esm/simplex-noise.js +466 -0
- package/lib/motion/mgstyles/vendor/modules/topojson-client/LICENSE +13 -0
- package/lib/motion/mgstyles/vendor/modules/topojson-client/dist/topojson-client.min.js +2 -0
- package/lib/motion/preview.js +13 -4
- package/lib/motion/render.js +179 -159
- package/lib/motion/runtime/package-lock.json +3058 -0
- package/lib/motion/runtime/package.json +16 -0
- package/lib/motion/style-frames.js +306 -268
- package/lib/motion/sync.js +214 -214
- package/lib/motion/video-runtime.js +192 -0
- package/lib/motion-capture.js +2 -1
- package/lib/motion-film-review.js +2 -2
- package/lib/motion-project.js +105 -79
- package/lib/motion-render-worker.js +174 -144
- package/lib/motion-vision.js +3 -2
- package/lib/routing/router.js +222 -211
- package/lib/routing/vendor/README.md +96 -96
- package/lib/routing/vendor/libavoid-routing.js +753 -753
- package/lib/routing/vendor/libavoid.min.js +59 -59
- package/lib/shotcard-reference.js +2 -2
- package/lib/style-kernel.js +16 -6
- package/lib/video-export.js +32 -20
- package/package.json +17 -12
package/lib/motion/sync.js
CHANGED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Isolated video dependencies: no Remotion/esbuild is loaded or installed at plugin startup.
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { homedir } from 'node:os'
|
|
7
|
+
import { dirname, isAbsolute, join, relative, resolve, parse } from 'node:path'
|
|
8
|
+
import { fileURLToPath } from 'node:url'
|
|
9
|
+
|
|
10
|
+
const localRequire = createRequire(import.meta.url)
|
|
11
|
+
const MANIFEST = fileURLToPath(new URL('./runtime/package.json', import.meta.url))
|
|
12
|
+
const LOCK = fileURLToPath(new URL('./runtime/package-lock.json', import.meta.url))
|
|
13
|
+
const fingerprint = createHash('sha256').update(readFileSync(LOCK)).digest('hex')
|
|
14
|
+
const spec = JSON.parse(readFileSync(MANIFEST, 'utf8'))
|
|
15
|
+
const key = `v1-${process.platform}-${process.arch}-node${process.versions.node.split('.')[0]}-${fingerprint.slice(0, 12)}`
|
|
16
|
+
const pending = new Map()
|
|
17
|
+
|
|
18
|
+
function waitForInitialization(work, signal) {
|
|
19
|
+
if (!signal) return work
|
|
20
|
+
signal.throwIfAborted()
|
|
21
|
+
return new Promise((done, fail) => {
|
|
22
|
+
const abort = () => fail(signal.reason || new Error('已取消视频环境初始化'))
|
|
23
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
24
|
+
work.then(done, fail).finally(() => signal.removeEventListener('abort', abort))
|
|
25
|
+
})
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function videoRuntimeDirectory() {
|
|
29
|
+
const directory = resolve(process.env.DRAWAI_VIDEO_RUNTIME_DIR || join(homedir(), '.dsh', 'drawai-video-runtime', key))
|
|
30
|
+
if ([parse(directory).root, resolve(homedir()), resolve(process.cwd())].includes(directory))
|
|
31
|
+
throw new Error('视频运行环境必须使用独立子目录')
|
|
32
|
+
return directory
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function videoRuntimeRequire(directory = videoRuntimeDirectory()) {
|
|
36
|
+
return createRequire(join(directory, 'package.json'))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function validate(directory, native = false) {
|
|
40
|
+
const require = videoRuntimeRequire(directory)
|
|
41
|
+
for (const [name, version] of Object.entries(spec.dependencies)) {
|
|
42
|
+
let file
|
|
43
|
+
try { file = require.resolve(name + '/package.json') } catch (error) {
|
|
44
|
+
if (error.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw error
|
|
45
|
+
let parent = dirname(require.resolve(name))
|
|
46
|
+
while (dirname(parent) !== parent) {
|
|
47
|
+
const candidate = join(parent, 'package.json')
|
|
48
|
+
if (existsSync(candidate) && JSON.parse(readFileSync(candidate, 'utf8')).name === name) { file = candidate; break }
|
|
49
|
+
parent = dirname(parent)
|
|
50
|
+
}
|
|
51
|
+
if (!file) throw new Error('缺少视频依赖清单:' + name)
|
|
52
|
+
}
|
|
53
|
+
const rel = relative(realpathSync(join(directory, 'node_modules')), realpathSync(file))
|
|
54
|
+
if (isAbsolute(rel) || rel === '..' || rel.startsWith('..' + (process.platform === 'win32' ? '\\' : '/')))
|
|
55
|
+
throw new Error('视频依赖未安装在独立目录:' + name)
|
|
56
|
+
if (JSON.parse(readFileSync(file, 'utf8')).version !== version) throw new Error('视频依赖版本不匹配:' + name)
|
|
57
|
+
}
|
|
58
|
+
if (!native) return
|
|
59
|
+
// Validate in a child so Windows DLL handles and cached module paths don't
|
|
60
|
+
// pin the staging directory while it is atomically renamed into the cache.
|
|
61
|
+
const checked = spawnSync(process.execPath, ['-e',
|
|
62
|
+
"const r=require('node:module').createRequire(process.argv[1]);const b=r('@remotion/bundler');r('@remotion/renderer');if(!b.BundlerInternals.esbuild.transformSync('const n: number = 1',{loader:'ts'}).code)process.exit(1)",
|
|
63
|
+
join(directory, 'package.json')], { windowsHide: true, encoding: 'utf8', timeout: 90000,
|
|
64
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } })
|
|
65
|
+
if (checked.status !== 0) throw new Error('视频二进制验证失败:' + (checked.error?.message || checked.stderr))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function videoRuntimeState() {
|
|
69
|
+
const directory = videoRuntimeDirectory()
|
|
70
|
+
try {
|
|
71
|
+
const ready = JSON.parse(readFileSync(join(directory, '.ready.json'), 'utf8'))
|
|
72
|
+
if (ready.fingerprint !== fingerprint || ready.key !== key) return { ready: false, directory }
|
|
73
|
+
validate(directory)
|
|
74
|
+
return { ready: true, directory }
|
|
75
|
+
} catch { return { ready: false, directory } }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function install(directory, { signal, onProgress }) {
|
|
79
|
+
const cli = join(dirname(localRequire.resolve('npm/package.json')), 'bin', 'npm-cli.js')
|
|
80
|
+
const registry = process.env.DRAWAI_RUNTIME_REGISTRY || 'https://registry.npmjs.org'
|
|
81
|
+
const url = new URL(registry)
|
|
82
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('视频依赖 registry 地址无效')
|
|
83
|
+
return new Promise((done, fail) => {
|
|
84
|
+
const child = spawn(process.execPath, [cli, 'ci', '--ignore-scripts', '--include=optional', '--no-audit', '--no-fund',
|
|
85
|
+
'--registry=' + url.href, '--fetch-retries=1', '--fetch-timeout=30000', '--loglevel=error'], {
|
|
86
|
+
cwd: directory, windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'],
|
|
87
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', NODE_ENV: 'production', npm_config_ignore_scripts: 'true' },
|
|
88
|
+
})
|
|
89
|
+
let stderr = '', settled = false
|
|
90
|
+
const abort = () => child.kill()
|
|
91
|
+
const timer = setTimeout(() => child.kill(), 10 * 60000)
|
|
92
|
+
const progress = setInterval(() => onProgress?.({ phase: 'runtime-installing', message: '正在下载和校验视频依赖,首次初始化可能需要数分钟' }), 5000)
|
|
93
|
+
const finish = error => {
|
|
94
|
+
if (settled) return
|
|
95
|
+
settled = true; clearTimeout(timer); clearInterval(progress); signal?.removeEventListener('abort', abort)
|
|
96
|
+
if (signal?.aborted) fail(signal.reason || new Error('已取消视频环境初始化'))
|
|
97
|
+
else if (error) fail(error)
|
|
98
|
+
else done()
|
|
99
|
+
}
|
|
100
|
+
child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-3000) })
|
|
101
|
+
child.on('error', finish)
|
|
102
|
+
child.on('close', code => finish(code === 0 ? null : new Error('视频依赖安装失败(' + code + '):' + stderr)))
|
|
103
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
104
|
+
if (signal?.aborted) abort()
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function initialize({ signal, onProgress }) {
|
|
109
|
+
const directory = videoRuntimeDirectory(), lock = directory + '.lock'
|
|
110
|
+
if (existsSync(directory)) {
|
|
111
|
+
const previous = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'))
|
|
112
|
+
if (previous.name !== spec.name) throw new Error('缓存位置包含其他文件,请指定独立目录')
|
|
113
|
+
}
|
|
114
|
+
mkdirSync(dirname(directory), { recursive: true })
|
|
115
|
+
// Coordinate independent render workers. A dead owner's lock is recoverable.
|
|
116
|
+
let ownsLock = false
|
|
117
|
+
const deadline = Date.now() + 11 * 60000
|
|
118
|
+
while (!ownsLock) {
|
|
119
|
+
signal?.throwIfAborted()
|
|
120
|
+
try {
|
|
121
|
+
mkdirSync(lock)
|
|
122
|
+
ownsLock = true
|
|
123
|
+
writeFileSync(join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, at: Date.now() }))
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (ownsLock || error.code !== 'EEXIST') throw error
|
|
126
|
+
try {
|
|
127
|
+
const owner = JSON.parse(readFileSync(join(lock, 'owner.json'), 'utf8'))
|
|
128
|
+
if (!Number.isInteger(owner.pid) || owner.pid <= 0) throw new Error('invalid lock owner')
|
|
129
|
+
try { process.kill(owner.pid, 0) } catch (e) {
|
|
130
|
+
if (e.code === 'ESRCH') { rmSync(lock, { recursive: true, force: true }); continue }
|
|
131
|
+
}
|
|
132
|
+
} catch {
|
|
133
|
+
// Recover if the installer crashed between mkdir and writing its owner.
|
|
134
|
+
if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > 30000) {
|
|
135
|
+
rmSync(lock, { recursive: true, force: true }); continue
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (Date.now() > deadline) throw new Error('等待其他视频环境初始化超时,请重试')
|
|
139
|
+
onProgress?.({ phase: 'runtime-installing', message: '正在等待共享视频运行环境就绪' })
|
|
140
|
+
await new Promise(done => setTimeout(done, 500))
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const staging = directory + '.tmp-' + randomUUID()
|
|
144
|
+
try {
|
|
145
|
+
if (videoRuntimeState().ready) return directory
|
|
146
|
+
onProgress?.({ phase: 'runtime-installing', message: '首次使用:正在初始化独立视频运行环境' })
|
|
147
|
+
signal?.throwIfAborted()
|
|
148
|
+
mkdirSync(staging)
|
|
149
|
+
writeFileSync(join(staging, 'package.json'), readFileSync(MANIFEST))
|
|
150
|
+
writeFileSync(join(staging, 'package-lock.json'), readFileSync(LOCK))
|
|
151
|
+
await install(staging, { signal, onProgress })
|
|
152
|
+
signal?.throwIfAborted()
|
|
153
|
+
onProgress?.({ phase: 'runtime-checking', message: '正在验证视频运行环境' })
|
|
154
|
+
validate(staging, true)
|
|
155
|
+
writeFileSync(join(staging, '.ready.json'), JSON.stringify({ fingerprint, key }))
|
|
156
|
+
// Only replace this cache after installation and native-binary validation succeed.
|
|
157
|
+
if (existsSync(directory)) {
|
|
158
|
+
const previous = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'))
|
|
159
|
+
if (previous.name !== spec.name) throw new Error('缓存位置包含其他文件,请指定独立目录')
|
|
160
|
+
rmSync(directory, { recursive: true, force: true })
|
|
161
|
+
}
|
|
162
|
+
renameSync(staging, directory)
|
|
163
|
+
onProgress?.({ phase: 'runtime-ready', message: '视频运行环境已就绪,后续离线复用' })
|
|
164
|
+
return directory
|
|
165
|
+
} finally {
|
|
166
|
+
rmSync(staging, { recursive: true, force: true })
|
|
167
|
+
rmSync(lock, { recursive: true, force: true })
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function ensureVideoRuntime(options = {}) {
|
|
172
|
+
options.signal?.throwIfAborted()
|
|
173
|
+
const state = videoRuntimeState()
|
|
174
|
+
if (state.ready) return state.directory
|
|
175
|
+
// A caller's cancellation must not cancel another caller's shared initialization.
|
|
176
|
+
if (pending.has(state.directory)) {
|
|
177
|
+
try { await waitForInitialization(pending.get(state.directory), options.signal) } catch { /* Another caller may have cancelled. */ }
|
|
178
|
+
options.signal?.throwIfAborted()
|
|
179
|
+
return ensureVideoRuntime(options)
|
|
180
|
+
}
|
|
181
|
+
const work = initialize({ ...options, onProgress: options.onProgress || (event => console.error('[drawai] ' + event.message)) }).catch(error => {
|
|
182
|
+
throw new Error('视频运行环境未就绪:' + error.message + '\n联网后重试当前操作即可重新初始化。可用 DRAWAI_RUNTIME_REGISTRY 设置镜像,DRAWAI_VIDEO_RUNTIME_DIR 设置缓存目录。', { cause: error })
|
|
183
|
+
}).finally(() => pending.delete(state.directory))
|
|
184
|
+
pending.set(state.directory, work)
|
|
185
|
+
return work
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function loadVideoModule(name, options = {}) {
|
|
189
|
+
if (!Object.hasOwn(spec.dependencies, name)) throw new Error('不支持的视频模块:' + name)
|
|
190
|
+
const directory = await ensureVideoRuntime(options)
|
|
191
|
+
return videoRuntimeRequire(directory)(name)
|
|
192
|
+
}
|