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,161 +1,179 @@
1
- // 渲染入口:把"工程目录 + 一个操作"翻译成一次 worker 调用。
2
- //
3
- // 三条规则(对应之前 58 分钟里最贵的三个坑):
4
- // 1. 永远异步:调用方拿到 jobId 就返回,不要把对话卡在 await 上;
5
- // 2. 永远复用 bundle:预览和全片共用 .out/bundle/.drawai-bundle-key;
6
- // 3. 永远先出图:预览走 renderStill,几秒钟,不跑全片。
7
-
8
- import { videoRuntimeDirectory } from './video-runtime.js'
9
- import { fork } from 'node:child_process'
10
- import { fileURLToPath } from 'node:url'
11
- import { createHash } from 'node:crypto'
12
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
13
- import { join } from 'node:path'
14
- import { buildComposition, readTimeline } from './project.js'
15
- import { assetsHash } from './assets.js'
16
- import { normalizeMix } from './audiomix.js'
17
- import { writeBundledFonts } from './fonts.js'
18
- import { syncRevision, filmHash } from './sync.js'
19
- import { resolveRenderSettings, timeoutFor, describeRenderSettings } from './render-settings.js'
20
-
21
- const WORKER = fileURLToPath(new URL('../motion-render-worker.js', import.meta.url))
22
- // entry.jsx 是打包入口:它改了(比如加了 <Audio>)也必须重建 bundle,
23
- // 否则会拿旧缓存渲染出一条没有声音的片子。
24
- const ENTRY = fileURLToPath(new URL('./entry.jsx', import.meta.url))
25
-
26
- export function outputPath(dir, name = 'film.mp4') {
27
- return join(dir, '.out', name)
28
- }
29
-
30
- // bundle 的缓存键 = 所有场景源码 + 时间轴 + 尺寸 + 素材指纹。改任何一个字节就重建一次。
31
- export function bundleKey(composition, projectDir) {
32
- const hash = createHash('sha256')
33
- hash.update(JSON.stringify({
34
- width: composition.width, height: composition.height, fps: composition.fps,
35
- durationFrames: composition.durationFrames,
36
- shots: composition.shots.map((shot) => [shot.id, shot.startFrame, shot.durationFrames]),
37
- assets: projectDir ? assetsHash(projectDir) : '',
38
- }))
39
- for (const shot of composition.shots) hash.update(shot.sceneSource)
40
- if (projectDir && existsSync(projectDir)) {
41
- const walk = (rel = '') => {
42
- for (const entry of readdirSync(join(projectDir, rel), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
43
- if (entry.isDirectory() && ['.out', 'assets', 'node_modules', '.git'].includes(entry.name)) continue
44
- const next = rel ? join(rel, entry.name) : entry.name
45
- if (entry.isDirectory()) walk(next)
46
- else if (entry.isSymbolicLink()) throw new Error('视频工程源码目录不支持符号链接:' + next)
47
- else if (entry.isFile() && /\.(?:[cm]?[jt]sx?|css|json|svg|wasm)$/i.test(entry.name)) {
48
- const content = readFileSync(join(projectDir, next))
49
- hash.update(JSON.stringify([next.replace(/\\/g, '/'), content.length])).update(content)
50
- }
51
- }
52
- }
53
- walk()
54
- }
55
- hash.update(readFileSync(ENTRY))
56
- hash.update(videoRuntimeDirectory())
57
- return hash.digest('hex')
58
- }
59
-
60
- function prepare(dir, options) {
61
- writeBundledFonts(dir)
62
- const composition = options.composition || buildComposition(dir)
63
- if (!options.composition) composition.bundledFonts = true
64
- const outDirectory = join(dir, '.out')
65
- mkdirSync(outDirectory, { recursive: true })
66
- const publicDir = join(dir, 'assets')
67
- return { composition, outDirectory, publicDir: existsSync(publicDir) ? publicDir : undefined }
68
- }
69
-
70
- // 起一个 render worker。返回 { promise, cancel }:
71
- // promise 在 done/error/exit 时结算,不阻塞调用方。
72
- export function renderProject(dir, options = {}) {
73
- const { composition, outDirectory, publicDir } = prepare(dir, options)
74
- const timeline = readTimeline(dir)
75
- const syncReceipt = timeline.sync ? { revision: syncRevision(dir, timeline), fps: timeline.fps } : null
76
- const operation = options.operation || 'still'
77
- // 预览永远按 1× 渲:我们要看的是构图和字,不是锯齿;超采样留给成片。
78
- const settings = resolveRenderSettings(timeline, options.render)
79
- const render = operation === 'still' ? { ...settings, scale: 1, samples: 1, estimatedCost: 1 } : settings
80
- const output = options.output || outputPath(dir, operation === 'still' ? 'still.mp4' : 'film.mp4')
81
- // 场景拿到的 plan.render 必须是**夹取后的**值:只透传时间轴原值的话,
82
- // 没写 render 的工程在场景里看到的是 {},默认采样数就丢了。
83
- composition.render = render
84
- const bundleDir = join(outDirectory, 'bundle')
85
- const request = {
86
- composition,
87
- projectDirectory: dir,
88
- output,
89
- publicDir,
90
- bundleDir,
91
- bundleKey: bundleKey(composition, dir),
92
- reuseBundle: options.reuseBundle !== false,
93
- keepBundle: true,
94
- preserveSources: true,
95
- operation,
96
- assets: options.assets || {},
97
- render,
98
- frames: operation === 'still' ? (options.frames || []).map((frame) => Math.round(Number(frame))) : undefined,
99
- frameRange: options.frameRange,
100
- qaDirectory: join(outDirectory, 'qa'),
101
- poster: join(outDirectory, 'poster.png'),
102
- }
103
- if (operation === 'still' && !request.frames.length) throw new Error('预览需要至少一帧,例如 frames:[0,60,120]')
104
- if (operation === 'still' && request.frames.some((frame) => !Number.isInteger(frame) || frame < 0 || frame >= composition.durationFrames))
105
- throw new Error('预览帧超出 0–' + (composition.durationFrames - 1))
106
-
107
- const child = fork(WORKER, [], { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe', 'ipc'], execArgv: [] })
108
- let settled = false
109
- let cancelTimer
110
- const rendered = new Promise((resolve, reject) => {
111
- const finish = (fn, value) => { if (settled) return; settled = true; clearTimeout(cancelTimer); fn(value) }
112
- const timeout = setTimeout(() => { child.kill(); finish(reject, new Error('渲染超过 ' + Math.round(timeoutFor(render, composition.durationFrames) / 60000) + ' 分钟,请拆小场景或在 timeline.json 的 render.timeoutMs 里放大预算')) }, options.timeoutMs || (timeoutFor(render, composition.durationFrames) + 11 * 60000))
113
- let stderr = ''
114
- child.stderr.on('data', (bytes) => { stderr = (stderr + bytes).slice(-4000) })
115
- child.on('message', (message) => {
116
- if (message.type === 'progress') options.onProgress?.(message)
117
- if (message.type === 'done') { clearTimeout(timeout); finish(resolve, { ...message, output, bundleDir }) }
118
- if (message.type === 'error') { clearTimeout(timeout); finish(reject, new Error(message.error)) }
119
- })
120
- child.on('error', (error) => { clearTimeout(timeout); finish(reject, error) })
121
- child.on('exit', (code) => {
122
- clearTimeout(timeout)
123
- if (!settled) finish(reject, new Error('渲染进程退出(' + code + '):' + stderr))
124
- })
125
- child.send(request)
126
- })
127
- const cancel = () => {
128
- if (child.connected) child.send({ type: 'cancel' })
129
- cancelTimer = setTimeout(() => child.kill(), 5000)
130
- }
131
- // 渲完之后再过一遍响度归一 + 限幅。
132
- // 只对整片做:切片渲染(frameRange)归一化会把片段当整条量,结果是错的。
133
- // 归一化的目标可以在 timeline.json 的 audioMix 里改,也可以在调用时用 options.mix 覆盖。
134
- const promise = rendered.then(async (result) => {
135
- if (operation !== 'full' || options.frameRange) return result
136
- if (!(composition.audio || []).length) return result
137
- let config = {}
138
- try { config = { ...(readTimeline(dir).audioMix || {}) } } catch { config = {} }
139
- config = { ...config, ...(options.mix || {}) }
140
- if (config.normalize === false) return result
141
- options.onProgress?.({ type: 'progress', phase: 'mixing', progress: 0.97 })
142
- try {
143
- const mix = await normalizeMix(output, { ...config, cwd: outDirectory, log: join(outDirectory, 'mix.log'), timeoutMs: 180000 })
144
- return { ...result, mix }
145
- } catch (error) {
146
- // 混音后级失败不该让一条已经渲好的片子作废:带着错误回去,由调用方提示。
147
- return { ...result, mixError: error.message }
148
- }
149
- })
150
- const completed = promise.then((result) => {
151
- if (operation === 'full' && !options.frameRange && syncReceipt) writeFileSync(output + '.sync.json', JSON.stringify({ ...syncReceipt, filmHash: filmHash(output) }))
152
- return { ...result, render, renderSummary: describeRenderSettings(render) }
153
- })
154
- return { promise: completed, cancel, output, bundleDir, render }
155
- }
156
-
157
- export function outputInfo(file) {
158
- if (!existsSync(file)) return null
159
- const stat = statSync(file)
160
- return { path: file, bytes: stat.size, at: stat.mtime.toISOString() }
161
- }
1
+ // 渲染入口:把"工程目录 + 一个操作"翻译成一次 worker 调用。
2
+ //
3
+ // 三条规则(对应之前 58 分钟里最贵的三个坑):
4
+ // 1. 永远异步:调用方拿到 jobId 就返回,不要把对话卡在 await 上;
5
+ // 2. 永远复用 bundle:预览和全片共用 .out/bundle/.drawai-bundle-key;
6
+ // 3. 永远先出图:预览走 renderStill,几秒钟,不跑全片。
7
+
8
+ import { videoRuntimeDirectory } from './video-runtime.js'
9
+ import { fork } from 'node:child_process'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { createHash } from 'node:crypto'
12
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { buildComposition, readTimeline } from './project.js'
15
+ import { assetsHash } from './assets.js'
16
+ import { normalizeMix } from './audiomix.js'
17
+ import { writeBundledFonts } from './fonts.js'
18
+ import { syncRevision, filmHash } from './sync.js'
19
+ import { resolveRenderSettings, timeoutFor, describeRenderSettings } from './render-settings.js'
20
+
21
+ const WORKER = fileURLToPath(new URL('../motion-render-worker.js', import.meta.url))
22
+ // entry.jsx 是打包入口:它改了(比如加了 <Audio>)也必须重建 bundle,
23
+ // 否则会拿旧缓存渲染出一条没有声音的片子。
24
+ const ENTRY = fileURLToPath(new URL('./entry.jsx', import.meta.url))
25
+
26
+ export function outputPath(dir, name = 'film.mp4') {
27
+ return join(dir, '.out', name)
28
+ }
29
+
30
+ // bundle 的缓存键 = 所有场景源码 + 时间轴 + 尺寸 + 素材指纹。改任何一个字节就重建一次。
31
+ export function bundleKey(composition, projectDir) {
32
+ const hash = createHash('sha256')
33
+ hash.update(JSON.stringify({
34
+ width: composition.width, height: composition.height, fps: composition.fps,
35
+ durationFrames: composition.durationFrames,
36
+ shots: composition.shots.map((shot) => [shot.id, shot.startFrame, shot.durationFrames]),
37
+ assets: projectDir ? assetsHash(projectDir) : '',
38
+ }))
39
+ for (const shot of composition.shots) hash.update(shot.sceneSource)
40
+ if (projectDir && existsSync(projectDir)) {
41
+ const walk = (rel = '') => {
42
+ for (const entry of readdirSync(join(projectDir, rel), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
43
+ if (entry.isDirectory() && ['.out', 'assets', 'node_modules', '.git'].includes(entry.name)) continue
44
+ const next = rel ? join(rel, entry.name) : entry.name
45
+ if (entry.isDirectory()) walk(next)
46
+ else if (entry.isSymbolicLink()) throw new Error('视频工程源码目录不支持符号链接:' + next)
47
+ else if (entry.isFile() && /\.(?:[cm]?[jt]sx?|css|json|svg|wasm)$/i.test(entry.name)) {
48
+ const content = readFileSync(join(projectDir, next))
49
+ hash.update(JSON.stringify([next.replace(/\\/g, '/'), content.length])).update(content)
50
+ }
51
+ }
52
+ }
53
+ walk()
54
+ }
55
+ hash.update(readFileSync(ENTRY))
56
+ hash.update(videoRuntimeDirectory())
57
+ return hash.digest('hex')
58
+ }
59
+
60
+ function prepare(dir, options) {
61
+ writeBundledFonts(dir)
62
+ const composition = options.composition || buildComposition(dir)
63
+ if (!options.composition) composition.bundledFonts = true
64
+ const outDirectory = join(dir, '.out')
65
+ mkdirSync(outDirectory, { recursive: true })
66
+ const publicDir = join(dir, 'assets')
67
+ return { composition, outDirectory, publicDir: existsSync(publicDir) ? publicDir : undefined }
68
+ }
69
+
70
+ // 起一个 render worker。返回 { promise, cancel }:
71
+ // promise 在 done/error/exit 时结算,不阻塞调用方。
72
+ export function renderProject(dir, options = {}) {
73
+ const { composition, outDirectory, publicDir } = prepare(dir, options)
74
+ const timeline = readTimeline(dir)
75
+ const syncReceipt = timeline.sync ? { revision: syncRevision(dir, timeline), fps: timeline.fps } : null
76
+ const operation = options.operation || 'still'
77
+ // 预览永远按 1× 渲:我们要看的是构图和字,不是锯齿;超采样留给成片。
78
+ const settings = resolveRenderSettings(timeline, options.render)
79
+ const render = operation === 'still' ? { ...settings, scale: 1, samples: 1, estimatedCost: 1 } : settings
80
+ const output = options.output || outputPath(dir, operation === 'still' ? 'still.mp4' : 'film.mp4')
81
+ // 场景拿到的 plan.render 必须是**夹取后的**值:只透传时间轴原值的话,
82
+ // 没写 render 的工程在场景里看到的是 {},默认采样数就丢了。
83
+ composition.render = render
84
+ const bundleDir = join(outDirectory, 'bundle')
85
+ const request = {
86
+ composition,
87
+ projectDirectory: dir,
88
+ output,
89
+ publicDir,
90
+ bundleDir,
91
+ bundleKey: bundleKey(composition, dir),
92
+ reuseBundle: options.reuseBundle !== false,
93
+ keepBundle: true,
94
+ preserveSources: true,
95
+ operation,
96
+ assets: options.assets || {},
97
+ render,
98
+ frames: operation === 'still' ? (options.frames || []).map((frame) => Math.round(Number(frame))) : undefined,
99
+ frameRange: options.frameRange,
100
+ qaDirectory: join(outDirectory, 'qa'),
101
+ poster: join(outDirectory, 'poster.png'),
102
+ }
103
+ if (operation === 'still' && !request.frames.length) throw new Error('预览需要至少一帧,例如 frames:[0,60,120]')
104
+ if (operation === 'still' && request.frames.some((frame) => !Number.isInteger(frame) || frame < 0 || frame >= composition.durationFrames))
105
+ throw new Error('预览帧超出 0–' + (composition.durationFrames - 1))
106
+
107
+ // 临时目录放进工程里,别用系统的 %TEMP%(issue #26)。
108
+ //
109
+ // Windows 上 `.dsh` 可能带 Low 完整性标签:DSH 的沙箱会给自己当工作区用过的目录打
110
+ // Low 标签,标签可继承,于是 `.dsh` 里的 ffmpeg.exe 以 Low IL 运行,而 Low IL 受
111
+ // no-write-up 约束,写不了 Medium 的 `C:\Users\…\AppData\Local\Temp`。renderMedia 的
112
+ // 中间文件 `pre-encode.mp4` 恰好写在 `os.tmpdir()`(@remotion/renderer 里硬编码,
113
+ // 没有参数可改),正片渲到几十帧就 `Error opening output … Permission denied`。
114
+ //
115
+ // 指到工程目录下就没这个问题:那是工作区,Low IL 也写得进去(motion_preview 一直好使,
116
+ // 因为 renderStill 只往 `.out/qa/` 写)。fork 时通过 env 传,子进程里的 os.tmpdir()
117
+ // 会先读 TMP/TEMP。
118
+ const tempDirectory = join(outDirectory, 'tmp')
119
+ mkdirSync(tempDirectory, { recursive: true })
120
+ const child = fork(WORKER, [], {
121
+ windowsHide: true,
122
+ stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
123
+ execArgv: [],
124
+ env: { ...process.env, TEMP: tempDirectory, TMP: tempDirectory },
125
+ })
126
+ let settled = false
127
+ let cancelTimer
128
+ const rendered = new Promise((resolve, reject) => {
129
+ const finish = (fn, value) => { if (settled) return; settled = true; clearTimeout(cancelTimer); fn(value) }
130
+ const timeout = setTimeout(() => { child.kill(); finish(reject, new Error('渲染超过 ' + Math.round(timeoutFor(render, composition.durationFrames) / 60000) + ' 分钟,请拆小场景或在 timeline.json 的 render.timeoutMs 里放大预算')) }, options.timeoutMs || (timeoutFor(render, composition.durationFrames) + 11 * 60000))
131
+ let stderr = ''
132
+ child.stderr.on('data', (bytes) => { stderr = (stderr + bytes).slice(-4000) })
133
+ child.on('message', (message) => {
134
+ if (message.type === 'progress') options.onProgress?.(message)
135
+ if (message.type === 'done') { clearTimeout(timeout); finish(resolve, { ...message, output, bundleDir }) }
136
+ if (message.type === 'error') { clearTimeout(timeout); finish(reject, new Error(message.error)) }
137
+ })
138
+ child.on('error', (error) => { clearTimeout(timeout); finish(reject, error) })
139
+ child.on('exit', (code) => {
140
+ clearTimeout(timeout)
141
+ if (!settled) finish(reject, new Error('渲染进程退出(' + code + '):' + stderr))
142
+ })
143
+ child.send(request)
144
+ })
145
+ const cancel = () => {
146
+ if (child.connected) child.send({ type: 'cancel' })
147
+ cancelTimer = setTimeout(() => child.kill(), 5000)
148
+ }
149
+ // 渲完之后再过一遍响度归一 + 限幅。
150
+ // 只对整片做:切片渲染(frameRange)归一化会把片段当整条量,结果是错的。
151
+ // 归一化的目标可以在 timeline.json 的 audioMix 里改,也可以在调用时用 options.mix 覆盖。
152
+ const promise = rendered.then(async (result) => {
153
+ if (operation !== 'full' || options.frameRange) return result
154
+ if (!(composition.audio || []).length) return result
155
+ let config = {}
156
+ try { config = { ...(readTimeline(dir).audioMix || {}) } } catch { config = {} }
157
+ config = { ...config, ...(options.mix || {}) }
158
+ if (config.normalize === false) return result
159
+ options.onProgress?.({ type: 'progress', phase: 'mixing', progress: 0.97 })
160
+ try {
161
+ const mix = await normalizeMix(output, { ...config, cwd: outDirectory, log: join(outDirectory, 'mix.log'), timeoutMs: 180000 })
162
+ return { ...result, mix }
163
+ } catch (error) {
164
+ // 混音后级失败不该让一条已经渲好的片子作废:带着错误回去,由调用方提示。
165
+ return { ...result, mixError: error.message }
166
+ }
167
+ })
168
+ const completed = promise.then((result) => {
169
+ if (operation === 'full' && !options.frameRange && syncReceipt) writeFileSync(output + '.sync.json', JSON.stringify({ ...syncReceipt, filmHash: filmHash(output) }))
170
+ return { ...result, render, renderSummary: describeRenderSettings(render) }
171
+ })
172
+ return { promise: completed, cancel, output, bundleDir, render }
173
+ }
174
+
175
+ export function outputInfo(file) {
176
+ if (!existsSync(file)) return null
177
+ const stat = statSync(file)
178
+ return { path: file, bytes: stat.size, at: stat.mtime.toISOString() }
179
+ }