@joplo-app/server 0.6.1 → 0.7.1
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/dist/asset-usage.d.ts +48 -0
- package/dist/asset-usage.js +174 -0
- package/dist/capture.d.ts +15 -0
- package/dist/capture.js +49 -0
- package/dist/checkpoint.d.ts +10 -0
- package/dist/checkpoint.js +75 -0
- package/dist/contract.d.ts +88 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +9 -4
- package/dist/export.d.ts +38 -3
- package/dist/export.js +71 -10
- package/dist/film.d.ts +10 -1
- package/dist/film.js +255 -36
- package/dist/index.d.ts +6 -1
- package/dist/index.js +4 -1
- package/dist/layout-audit-browser.js +114 -0
- package/dist/layout-audit.d.ts +94 -0
- package/dist/layout-audit.js +86 -0
- package/dist/local-resources.js +5 -3
- package/dist/media-check.d.ts +2 -0
- package/dist/media-check.js +31 -1
- package/dist/output-file.d.ts +3 -0
- package/dist/output-file.js +23 -0
- package/dist/project.d.ts +1 -0
- package/dist/project.js +34 -5
- package/dist/render.d.ts +2 -0
- package/dist/render.js +24 -10
- package/dist/timeline.d.ts +76 -0
- package/dist/timeline.js +139 -0
- package/dist/video-format.d.ts +2 -0
- package/dist/video-format.js +12 -0
- package/dist/vite-shared.d.ts +7 -1
- package/dist/vite-shared.js +39 -3
- package/dist/voice-http.js +2 -2
- package/dist/voice-run.d.ts +16 -1
- package/dist/voice-run.js +45 -6
- package/dist/voice.js +2 -2
- package/dist/watch-config.d.ts +3 -0
- package/dist/watch-config.js +10 -0
- package/package.json +4 -4
package/dist/export.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* - 图片:`POST /__joplo/p/<id>/export/image` `{ scenarioId, position, theme, font?, stroke? }` → PNG(当前步骤;尺寸跟随页面自己的 viewport,
|
|
5
5
|
* 手机页面带外框;D44 起不再选择设备;镜头用这一步的导演镜头)。Playwright 打开本看板的渲染路由(与 renderStep 同一条渲染路径),截取 `[data-jexport]`。
|
|
6
|
-
* - 视频(只在本机):`POST …/export/video` `{ scenarioId, theme, font?, stroke? }` → 202 `{ jobId }`(尺寸跟随场景起始页面的 viewport
|
|
6
|
+
* - 视频(只在本机):`POST …/export/video` `{ scenarioId, theme, font?, stroke?, voice? }` → 202 `{ jobId }`(尺寸跟随场景起始页面的 viewport;
|
|
7
|
+
* voice: true = 看板开着朗读,已生成的旁白混进音轨并按真实时长停留,#56);
|
|
7
8
|
* Playwright `recordVideo` 录下渲染路由的自动播放(含鼠标与字幕),保存为 `<项目>/exports/<场景>-<时间>.webm`。
|
|
8
9
|
* 进度:`GET …/export/video/events`(SSE,先发当前状态,之后每次变化一条,结束后关闭);`GET …/export/video` 取当前状态。
|
|
9
10
|
* 同一项目同时只能有一个视频任务(再提交返回 409);`DELETE …/export/video` 取消正在进行的任务(D55)。没有导出组件时图片返回 503 EXPORT_COMPONENT_MISSING、
|
|
@@ -17,6 +18,7 @@
|
|
|
17
18
|
*
|
|
18
19
|
* 字段流向:job(写入点:这里的 runJob)→ jobs Map(存储)→ SSE / GET(读取点)→ 看板的导出视频弹窗(消费者)。
|
|
19
20
|
*/
|
|
21
|
+
import { playbackTimeline } from "./timeline.js";
|
|
20
22
|
import { recordedCalibration } from "./media-calibration.js";
|
|
21
23
|
import { muxRecordedAudio } from "./media-mux.js";
|
|
22
24
|
import crypto from 'node:crypto';
|
|
@@ -34,6 +36,29 @@ export const EXPORT_SIZE = {
|
|
|
34
36
|
desktop: { width: 1280, height: 800 },
|
|
35
37
|
mobile: { width: 446 + 32, height: 934 + 32 },
|
|
36
38
|
};
|
|
39
|
+
/** 页面里记下的字幕变化 → 视频时间轴上的字幕条(originMs = 视频第 0 秒对应的页面时间)。纯函数。 */
|
|
40
|
+
export function videoCues(raw, originMs, endSeconds) {
|
|
41
|
+
const out = [];
|
|
42
|
+
for (let i = 0; i < raw.length; i++) {
|
|
43
|
+
const c = raw[i];
|
|
44
|
+
if (!c.text)
|
|
45
|
+
continue;
|
|
46
|
+
const start = Math.max(0, (c.at - originMs) / 1000);
|
|
47
|
+
const end = Math.min(endSeconds, i + 1 < raw.length ? (raw[i + 1].at - originMs) / 1000 : endSeconds);
|
|
48
|
+
if (end - start >= 0.05)
|
|
49
|
+
out.push({ start: Math.round(start * 1000) / 1000, end: Math.round(end * 1000) / 1000, text: c.text });
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
/** SubRip 字幕文件。纯函数。 */
|
|
54
|
+
export function srt(cues) {
|
|
55
|
+
const ts = (sec) => {
|
|
56
|
+
const ms = Math.max(0, Math.round(sec * 1000));
|
|
57
|
+
const p = (n, w = 2) => String(n).padStart(w, '0');
|
|
58
|
+
return `${p(Math.floor(ms / 3600000))}:${p(Math.floor(ms / 60000) % 60)}:${p(Math.floor(ms / 1000) % 60)},${p(ms % 1000, 3)}`;
|
|
59
|
+
};
|
|
60
|
+
return cues.map((c, i) => `${i + 1}\n${ts(c.start)} --> ${ts(c.end)}\n${c.text.replace(/\r?\n+/g, '\n')}\n`).join('\n');
|
|
61
|
+
}
|
|
37
62
|
const send = (res, status, body) => {
|
|
38
63
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
39
64
|
res.end(JSON.stringify(body));
|
|
@@ -60,7 +85,7 @@ function parseRequest(project, body, needPosition) {
|
|
|
60
85
|
const device = project.scenes[sceneId]?.viewport === 'mobile' ? 'mobile' : 'desktop';
|
|
61
86
|
// 主题(D51):请求里的主题名,没有或不合法时用项目配置的主题
|
|
62
87
|
const theme = typeof b.theme === 'string' && THEME_NAME.test(b.theme) ? b.theme : project.theme;
|
|
63
|
-
return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale), ...(exportLocale(b.contentLocale) ? { content: exportLocale(b.contentLocale) } : {}) } };
|
|
88
|
+
return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale), ...(exportLocale(b.contentLocale) ? { content: exportLocale(b.contentLocale) } : {}), ...(b.voice === true ? { voice: true } : {}) } };
|
|
64
89
|
}
|
|
65
90
|
const fileSafe = (s) => s.replace(/[^\w.-]+/g, '_').slice(0, 80) || 'scenario';
|
|
66
91
|
const stamp = (d = new Date()) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}${String(d.getSeconds()).padStart(2, '0')}`;
|
|
@@ -70,18 +95,35 @@ async function waitReady(page) {
|
|
|
70
95
|
if (err)
|
|
71
96
|
throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
|
|
72
97
|
}
|
|
73
|
-
/**
|
|
98
|
+
/**
|
|
99
|
+
* 缺省的录制:渲染路由的录制模式(window.__JOPLO_RECORD__)。
|
|
100
|
+
*
|
|
101
|
+
* 开播前的准备(载入、字体、解码配乐与旁白)不进视频(#57):Playwright 有 page.screencast 时,prepare() 之后才开始录屏,
|
|
102
|
+
* 视频从封面淡出 / 第一步开始;项目自带的旧版 Playwright 没有它时退回 recordVideo(从建页开始录)。
|
|
103
|
+
*/
|
|
74
104
|
export function defaultRecorder(load) {
|
|
75
105
|
return async ({ projectDir, url, size, out, progress, signal, maxMs = 5 * 60_000 }) => {
|
|
76
106
|
const pw = await load(projectDir);
|
|
77
107
|
const browser = await launch(pw);
|
|
78
108
|
const tmp = fs.mkdtempSync(path.join(path.dirname(out), '.rec-'));
|
|
79
109
|
try {
|
|
80
|
-
|
|
81
|
-
|
|
110
|
+
let ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 1 });
|
|
111
|
+
let page = await ctx.newPage();
|
|
112
|
+
const screencast = typeof page.screencast?.start === 'function';
|
|
113
|
+
if (!screencast) {
|
|
114
|
+
await ctx.close();
|
|
115
|
+
ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 1, recordVideo: { dir: tmp, size } });
|
|
116
|
+
page = await ctx.newPage();
|
|
117
|
+
}
|
|
82
118
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
83
119
|
await waitReady(page);
|
|
84
120
|
await page.waitForTimeout(400);
|
|
121
|
+
await page.evaluate(() => window.__JOPLO_RECORD__.prepare?.());
|
|
122
|
+
const file = path.join(tmp, 'screen.webm');
|
|
123
|
+
if (screencast)
|
|
124
|
+
await page.screencast.start({ path: file, size });
|
|
125
|
+
// 视频第 0 秒对应的页面时间:录屏刚开始时(recordVideo 从建页开始录,近似为导航开始 = 0)
|
|
126
|
+
let origin = screencast ? await page.evaluate(() => performance.now()) : 0;
|
|
85
127
|
await page.evaluate(() => window.__JOPLO_RECORD__.play());
|
|
86
128
|
const t0 = Date.now();
|
|
87
129
|
for (;;) {
|
|
@@ -98,13 +140,26 @@ export function defaultRecorder(load) {
|
|
|
98
140
|
await page.waitForTimeout(150);
|
|
99
141
|
}
|
|
100
142
|
await page.waitForTimeout(900); // 停留在结果画面
|
|
143
|
+
const endAt = await page.evaluate(() => performance.now());
|
|
101
144
|
const calibrated = await page.evaluate(() => window.__JOPLO_RECORD__.calibrate?.() ?? false);
|
|
145
|
+
const page_ = await page.evaluate(() => { const r = window.__JOPLO_RECORD__; return { cues: r.cues?.() ?? [], voice: r.voice?.() ?? { mode: 'off', missing: [] }, timeline: r.timeline?.(), flash: r.calibratedAt?.() ?? null }; });
|
|
102
146
|
const audio = await page.evaluate(() => window.__JOPLO_RECORD__.stopAudio?.() ?? null);
|
|
103
|
-
|
|
147
|
+
if (screencast)
|
|
148
|
+
await page.screencast.stop();
|
|
149
|
+
const video = screencast ? null : page.video();
|
|
104
150
|
await ctx.close();
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
151
|
+
if (screencast) {
|
|
152
|
+
if (!fs.existsSync(file))
|
|
153
|
+
throw new JoploError('EXPORT_FAILED', 'The browser did not generate a video');
|
|
154
|
+
fs.renameSync(file, out);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
if (!video)
|
|
158
|
+
throw new JoploError('EXPORT_FAILED', 'The browser did not generate a video');
|
|
159
|
+
await video.saveAs(out);
|
|
160
|
+
}
|
|
161
|
+
let endSeconds = (endAt - origin) / 1000;
|
|
162
|
+
let sync;
|
|
108
163
|
if (audio) {
|
|
109
164
|
if (!calibrated)
|
|
110
165
|
throw new Error('Audio/video calibration unavailable');
|
|
@@ -115,11 +170,17 @@ export function defaultRecorder(load) {
|
|
|
115
170
|
const bytes = Buffer.from(audio.data, 'base64');
|
|
116
171
|
const timing = await recordedCalibration(probe, out, bytes);
|
|
117
172
|
await muxRecordedAudio(out, bytes, timing.offsetSeconds, { videoEnd: timing.videoPTS, audioEnd: timing.audioPTS, audioDurations: timing.audioDurations });
|
|
173
|
+
// 校准闪屏:页面时间 flash ↔ 视频时间 videoPTS,比录屏开始时的估计更准;视频在闪屏处截断
|
|
174
|
+
if (page_.flash !== null)
|
|
175
|
+
origin = page_.flash - timing.videoPTS * 1000;
|
|
176
|
+
endSeconds = timing.videoPTS;
|
|
177
|
+
sync = { offsetMs: timing.offsetSeconds * 1000, videoEndMs: timing.videoPTS * 1000, audioEndMs: timing.audioPTS * 1000 };
|
|
118
178
|
}
|
|
119
179
|
finally {
|
|
120
180
|
await analysis.close();
|
|
121
181
|
}
|
|
122
182
|
}
|
|
183
|
+
return { cues: videoCues(page_.cues, origin, endSeconds), voice: page_.voice, ...(page_.timeline ? { timeline: playbackTimeline(page_.timeline, origin) } : {}), ...(sync ? { sync } : {}) };
|
|
123
184
|
}
|
|
124
185
|
finally {
|
|
125
186
|
await browser.close().catch(() => undefined);
|
|
@@ -244,7 +305,7 @@ export class ExportHub {
|
|
|
244
305
|
this.update(job, { phase: 'starting', percent: 2 });
|
|
245
306
|
await this.deps.recordVideo({
|
|
246
307
|
projectDir: dir,
|
|
247
|
-
url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), frame: '1', record: '1' }),
|
|
308
|
+
url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), ...(look.voice ? { voice: 'real' } : {}), frame: '1', record: '1' }),
|
|
248
309
|
size: EXPORT_SIZE[device],
|
|
249
310
|
out,
|
|
250
311
|
total,
|
package/dist/film.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ type Sample = {
|
|
|
12
12
|
scenarioId: string | null;
|
|
13
13
|
position: number;
|
|
14
14
|
activeStep: number | null;
|
|
15
|
+
stepId?: string | null;
|
|
15
16
|
jpg?: string;
|
|
16
17
|
};
|
|
17
18
|
/** 纯函数:从逐帧的相邻差找出硬切。changed[i] 是第 i 帧与第 i-1 帧之间变化像素的占比。 */
|
|
@@ -20,8 +21,16 @@ export declare function findCuts(samples: readonly Pick<Sample, 't' | 'changed'
|
|
|
20
21
|
export declare function findStills(samples: readonly Pick<Sample, 't' | 'still' | 'scenarioId' | 'position'>[], minMs: number): FilmStill[];
|
|
21
22
|
/** 纯函数:每次提交一步(或换场景)前后窗口里的最大相邻帧差,章节衔接是否硬切一眼可见。 */
|
|
22
23
|
export declare function stepBoundaries(samples: readonly Pick<Sample, 't' | 'diff' | 'changed' | 'scenarioId' | 'position'>[], before?: number, after?: number): FilmBoundary[];
|
|
23
|
-
/** 胶片条:按引擎时间逐帧定格取样。 */
|
|
24
24
|
export declare function renderFilm(opts: FilmOptions): Promise<FilmResult>;
|
|
25
25
|
/** 视频:与看板导出相同的录制器(真实时间)。 */
|
|
26
26
|
export declare function renderVideo(opts: VideoOptions): Promise<VideoResult>;
|
|
27
|
+
/** Public offline frame export. No audio synthesis or private browser bridge is needed by callers. */
|
|
28
|
+
export declare function renderFrames(opts: import('./contract.js').FramesOptions): Promise<{
|
|
29
|
+
directory: string;
|
|
30
|
+
timeline: string;
|
|
31
|
+
fps: number;
|
|
32
|
+
frames: number;
|
|
33
|
+
durationMs: number;
|
|
34
|
+
toleranceMs: number;
|
|
35
|
+
}>;
|
|
27
36
|
export {};
|
package/dist/film.js
CHANGED
|
@@ -4,22 +4,31 @@
|
|
|
4
4
|
* - renderFilm:Playwright 假时钟(page.clock)接管页面的 setTimeout / rAF / performance.now,演示控制器与引擎时钟
|
|
5
5
|
* 因此按固定步长(sampleMs,默认 50 ms ≈ 20 fps)逐帧前进;每帧截一张图、在辅助页里用 canvas 算与上一帧的像素差。
|
|
6
6
|
* 每隔 every(默认 250 ms)取一帧放进胶片条,标注时间、场景、步号与相邻帧差;同时客观地标出
|
|
7
|
-
* 硬切(单帧整屏突变,前后帧都平静)与长时间静止(≥ stillMs
|
|
8
|
-
* - renderVideo:复用看板导出的录制器(defaultRecorder
|
|
7
|
+
* 硬切(单帧整屏突变,前后帧都平静)与长时间静止(≥ stillMs 画面几乎不变)。加载耗时不进入采样时间;浏览器调度与栅格差异仍须实测复核。
|
|
8
|
+
* - renderVideo:复用看板导出的录制器(defaultRecorder,按真实时间),得到可以直接发布的 webm:
|
|
9
|
+
* 开播前的准备不进视频(#57);可指定输出分辨率(#55);已生成的旁白混进音轨(voice=real,#56);
|
|
10
|
+
* 可隐藏封面、鼠标、步骤标题条、字幕条,字幕另存为 .srt(#59)。
|
|
9
11
|
*
|
|
10
12
|
* 两者都走渲染路由的录制模式(record=1&frame=1):与看板导出视频同一套演示控制器、鼠标、字幕;
|
|
11
|
-
* chain=1
|
|
13
|
+
* chain=1 按发布站的顺序连续播放到方案的最后一个场景。胶片条用 voice=estimate:旁白按估算时长“读”(不出声、不调用朗读服务),
|
|
12
14
|
* 停留时间与开着朗读的发布站一致。
|
|
13
15
|
*/
|
|
14
16
|
import fs from 'node:fs';
|
|
17
|
+
import { createHash } from 'node:crypto';
|
|
15
18
|
import path from 'node:path';
|
|
16
|
-
import { JoploError, displaySceneId } from '@joplo-app/core';
|
|
19
|
+
import { JoploError, VIEWPORT_SIZE, displaySceneId } from '@joplo-app/core';
|
|
17
20
|
import { createDev } from "./dev.js";
|
|
18
21
|
import { realProjectDir } from "./vite-shared.js";
|
|
19
22
|
import { joploHome } from "./home.js";
|
|
20
23
|
import { loadPlaywright } from "./export-runtime.js";
|
|
21
|
-
import { launch } from "./render.js";
|
|
22
|
-
import {
|
|
24
|
+
import { assertNotProjectData, launch } from "./render.js";
|
|
25
|
+
import { encodeMp4 } from "./video-format.js";
|
|
26
|
+
import { commitOutput, writeOutput } from "./output-file.js";
|
|
27
|
+
import { createLayoutAuditSession } from "./layout-audit.js";
|
|
28
|
+
import { checkpointCommitsMatch, contentIdentity, exportRuntimeRoots } from "./checkpoint.js";
|
|
29
|
+
import { capture, geometryQuery } from "./capture.js";
|
|
30
|
+
import { frameTime, persistTimeline, playbackTimeline } from "./timeline.js";
|
|
31
|
+
import { EXPORT_SIZE, defaultRecorder, srt } from "./export.js";
|
|
23
32
|
/** 单帧整屏突变:变化像素占比至少这么多,且是前后帧的 CUT_RATIO 倍以上(排除持续的快速运镜)。 */
|
|
24
33
|
export const CUT_CHANGED = 0.3;
|
|
25
34
|
export const CUT_RATIO = 2.5;
|
|
@@ -27,6 +36,11 @@ export const CUT_RATIO = 2.5;
|
|
|
27
36
|
export const STILL_CHANGED = 0.004;
|
|
28
37
|
/** 一个像素的 RGB 平均差超过这个值才算“变了”(0–1)。 */
|
|
29
38
|
const PIXEL_THRESHOLD = 0.08;
|
|
39
|
+
function distinctOutputs(paths) {
|
|
40
|
+
const values = paths.filter((p) => !!p).map(p => path.resolve(p));
|
|
41
|
+
if (new Set(values).size !== values.length)
|
|
42
|
+
throw new JoploError('USAGE', 'Export output, timeline, subtitles and checkpoint paths must differ');
|
|
43
|
+
}
|
|
30
44
|
const MAX_MS = 10 * 60_000;
|
|
31
45
|
/** 纯函数:从逐帧的相邻差找出硬切。changed[i] 是第 i 帧与第 i-1 帧之间变化像素的占比。 */
|
|
32
46
|
export function findCuts(samples) {
|
|
@@ -76,25 +90,42 @@ const round = (n) => Math.round(n * 10000) / 10000;
|
|
|
76
90
|
const esc = (t) => t.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
77
91
|
/** 辅助页:解码 JPEG、裁掉字幕区,与上一帧、静止起点比较。状态留在页面里,每帧只传一次图片。 */
|
|
78
92
|
const DIFF_PAGE = `<!doctype html><canvas id=c></canvas><script>
|
|
79
|
-
let prev=null, anchor=null, anchorT=0;
|
|
93
|
+
let prev=null, anchor=null, anchorT=0, history=[];
|
|
80
94
|
async function load(b64){ const img=new Image(); img.src='data:image/jpeg;base64,'+b64; await img.decode(); return img; }
|
|
81
95
|
function pixels(img, h){ const c=document.getElementById('c'); c.width=img.width; c.height=h; const g=c.getContext('2d',{willReadFrequently:true}); g.drawImage(img,0,0); return g.getImageData(0,0,img.width,h).data; }
|
|
82
96
|
function compare(a,b,th){ let sum=0, changed=0; const n=a.length/4; for(let i=0;i<a.length;i+=4){ const d=(Math.abs(a[i]-b[i])+Math.abs(a[i+1]-b[i+1])+Math.abs(a[i+2]-b[i+2]))/765; sum+=d; if(d>th) changed++; } return { diff: sum/n, changed: changed/n }; }
|
|
97
|
+
window.dump = (back=0) => {const state=history[Math.max(0,history.length-1-back)]||{prev,anchor,anchorT};return {prev:Array.from(state.prev||[]),anchor:Array.from(state.anchor||[]),anchorT:state.anchorT};};
|
|
98
|
+
window.restore = (s) => {prev=new Uint8ClampedArray(s.prev);anchor=new Uint8ClampedArray(s.anchor);anchorT=s.anchorT;history=[{prev,anchor,anchorT}];};
|
|
83
99
|
window.step = async (b64, cropRatio, t, th, stillTh) => {
|
|
84
100
|
const img = await load(b64); const d = pixels(img, Math.max(1, Math.round(img.height*cropRatio)));
|
|
85
101
|
const adj = prev ? compare(prev, d, th) : { diff: 0, changed: 0 };
|
|
86
102
|
prev = d;
|
|
87
103
|
if (!anchor || compare(anchor, d, th).changed > stillTh) { anchor = d; anchorT = t; }
|
|
104
|
+
history.push({prev,anchor,anchorT}); if(history.length>12)history.shift();
|
|
88
105
|
return { ...adj, still: t - anchorT };
|
|
89
106
|
};
|
|
90
107
|
</script>`;
|
|
91
108
|
async function flush(page) {
|
|
92
|
-
// React
|
|
93
|
-
|
|
94
|
-
|
|
109
|
+
// React 的提交可能跨多轮 MessageChannel;连续三轮无 DOM 变化后才采样。
|
|
110
|
+
await page.evaluate(`() => new Promise((resolve, reject) => {
|
|
111
|
+
let changed = false, quiet = 0, turns = 0;
|
|
112
|
+
const observer = new MutationObserver(() => { changed = true; });
|
|
113
|
+
observer.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
114
|
+
const channel = new MessageChannel();
|
|
115
|
+
const finish = () => { observer.disconnect(); channel.port1.close(); channel.port2.close(); };
|
|
116
|
+
channel.port1.onmessage = () => {
|
|
117
|
+
quiet = changed ? 0 : quiet + 1;
|
|
118
|
+
changed = false;
|
|
119
|
+
if (quiet >= 3) { finish(); resolve(); }
|
|
120
|
+
else if (++turns >= 100) { finish(); reject(new Error('Render did not settle within 100 message turns')); }
|
|
121
|
+
else channel.port2.postMessage(0);
|
|
122
|
+
};
|
|
123
|
+
channel.port2.postMessage(0);
|
|
124
|
+
})`);
|
|
95
125
|
}
|
|
96
126
|
function check(opts) {
|
|
97
127
|
const out = path.resolve(opts.out);
|
|
128
|
+
assertNotProjectData(opts.projectDir, out);
|
|
98
129
|
if (fs.existsSync(out) && !opts.overwrite)
|
|
99
130
|
throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
|
|
100
131
|
const dataDir = path.join(realProjectDir(opts.projectDir), '.joplo');
|
|
@@ -106,25 +137,56 @@ async function compiled(projectDir) {
|
|
|
106
137
|
const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
|
|
107
138
|
const payload = server.payload();
|
|
108
139
|
if (!payload.project) {
|
|
109
|
-
await server.close();
|
|
140
|
+
await server.close().catch(() => undefined);
|
|
110
141
|
const errs = payload.diagnostics.filter((d) => d.severity === 'error');
|
|
111
142
|
throw new JoploError('INVALID_SCHEMA', `Project compilation failed: ${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('; ')}`, { diagnostics: payload.diagnostics });
|
|
112
143
|
}
|
|
113
144
|
return { server, project: payload.project };
|
|
114
145
|
}
|
|
146
|
+
/** 视频分辨率:2–4096 的偶数(VP8 / VP9 编码要求偶数边长)。 */
|
|
147
|
+
function videoDimension(name, v) {
|
|
148
|
+
if (!Number.isInteger(v) || v < 2 || v > 4096 || v % 2)
|
|
149
|
+
throw new JoploError('USAGE', `--${name} for --video must be an even number of pixels from 2 to 4096 (got ${v})`);
|
|
150
|
+
return v;
|
|
151
|
+
}
|
|
115
152
|
function recordUrl(base, projectId, project, o) {
|
|
116
153
|
if (!project.scenarios[o.scenarioId])
|
|
117
154
|
throw new JoploError('NOT_FOUND', `Scenario does not exist: ${o.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
|
|
118
155
|
if (o.content !== undefined && !project.i18n?.locales.includes(o.content))
|
|
119
156
|
throw new JoploError('USAGE', project.i18n ? `--content ${o.content} is not in config locales (${project.i18n.locales.join(', ')})` : `--content needs config({ locales }); this project has a single language`);
|
|
120
|
-
const
|
|
157
|
+
const voice = o.voice ?? 'estimate';
|
|
158
|
+
const q = new URLSearchParams({ render: '1', project: projectId, scenario: o.scenarioId, position: '0', theme: o.theme ?? project.theme ?? 'sketch', frame: '1', record: '1', ...(voice !== 'off' ? { voice } : {}), ...(o.chain ? { chain: '1' } : {}), ...(o.audio === false ? { audio: '0' } : {}), ...(o.locale ? { locale: o.locale } : {}), ...(o.content ? { content: o.content } : {}), ...(o.hide?.length ? { hide: o.hide.join(',') } : {}), ...geometryQuery(o), ...(o.canvas ? { w: String(o.canvas.width), h: String(o.canvas.height) } : {}) });
|
|
121
159
|
const device = project.scenes[displaySceneId(project, o.scenarioId, 0)]?.viewport === 'mobile' ? 'mobile' : 'desktop';
|
|
122
|
-
return { url: `${base}?${q}`, size: EXPORT_SIZE[device] };
|
|
160
|
+
return { url: `${base}?${q}`, size: o.logicalViewport ?? (o.noFrame ? VIEWPORT_SIZE[device] : EXPORT_SIZE[device]), device };
|
|
123
161
|
}
|
|
124
162
|
/** 胶片条:按引擎时间逐帧定格取样。 */
|
|
125
|
-
|
|
163
|
+
async function samplePlayback(opts) {
|
|
164
|
+
if (opts.auditLayout && opts.resume)
|
|
165
|
+
throw new JoploError('USAGE', 'Layout audit requires a fresh render; do not combine it with --resume');
|
|
166
|
+
if (opts.auditLayout && opts.framesOnly)
|
|
167
|
+
throw new JoploError('USAGE', 'Layout audit supports static screenshots and --film, not --frames-out');
|
|
168
|
+
const baselineRssBytes = process.memoryUsage().rss;
|
|
126
169
|
const projectDir = realProjectDir(opts.projectDir);
|
|
127
170
|
const out = check({ ...opts, projectDir });
|
|
171
|
+
const metadataOut = check({ projectDir, out: out.replace(/(\.png)?$/i, '.json'), overwrite: opts.overwrite });
|
|
172
|
+
if (opts.timeline) {
|
|
173
|
+
check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
|
|
174
|
+
assertNotProjectData(projectDir, path.join(`${path.resolve(opts.timeline).replace(/\.json$/i, '')}.assets`, '__asset.wav'));
|
|
175
|
+
}
|
|
176
|
+
distinctOutputs([out, metadataOut, opts.timeline, opts.checkpoint]);
|
|
177
|
+
geometryQuery(opts);
|
|
178
|
+
if (opts.voice && !['real', 'estimate', 'off'].includes(opts.voice))
|
|
179
|
+
throw new JoploError('USAGE', '--voice must be real, estimate or off');
|
|
180
|
+
if (opts.hide?.some(h => !['cover', 'cursor', 'title', 'subtitles'].includes(h)))
|
|
181
|
+
throw new JoploError('USAGE', 'Unknown hide item');
|
|
182
|
+
if (opts.chapterTimeoutMs !== undefined && (!Number.isFinite(opts.chapterTimeoutMs) || opts.chapterTimeoutMs <= 0))
|
|
183
|
+
throw new JoploError('USAGE', 'chapterTimeoutMs must be positive');
|
|
184
|
+
if (opts.sampleMs !== undefined && !Number.isFinite(opts.sampleMs))
|
|
185
|
+
throw new JoploError('USAGE', 'sampleMs must be finite');
|
|
186
|
+
if ((opts.width === undefined) !== (opts.height === undefined))
|
|
187
|
+
throw new JoploError('USAGE', 'Film width and height must be provided together');
|
|
188
|
+
if (opts.width !== undefined && ![opts.width, opts.height].every(n => Number.isInteger(n) && n > 0 && n <= 8192))
|
|
189
|
+
throw new JoploError('USAGE', 'Film dimensions must be integers from 1 to 8192');
|
|
128
190
|
const sampleMs = Math.max(20, Math.min(250, Math.round(opts.sampleMs ?? 50)));
|
|
129
191
|
const every = Math.max(sampleMs, Math.round((opts.every ?? 250) / sampleMs) * sampleMs);
|
|
130
192
|
const stillMs = opts.stillMs ?? 1500;
|
|
@@ -132,13 +194,40 @@ export async function renderFilm(opts) {
|
|
|
132
194
|
const cellWidth = Math.max(120, Math.min(640, Math.round(opts.cellWidth ?? 224)));
|
|
133
195
|
const playwright = await loadPlaywright({ home: joploHome(), projectDir });
|
|
134
196
|
const { server, project } = await compiled(projectDir);
|
|
197
|
+
let fingerprint = '';
|
|
198
|
+
const checkpointFile = opts.checkpoint ? path.resolve(opts.checkpoint) : null;
|
|
199
|
+
if (checkpointFile)
|
|
200
|
+
assertNotProjectData(projectDir, checkpointFile);
|
|
201
|
+
let checkpoint = null;
|
|
202
|
+
if (opts.resume) {
|
|
203
|
+
if (!checkpointFile) {
|
|
204
|
+
await server.close();
|
|
205
|
+
throw new JoploError('USAGE', '--resume requires --checkpoint');
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
checkpoint = JSON.parse(fs.readFileSync(checkpointFile, 'utf8'));
|
|
209
|
+
if (!checkpoint || typeof checkpoint.fingerprint !== 'string' || !Array.isArray(checkpoint.samples) || checkpoint.samples.length === 0 || !Array.isArray(checkpoint.commits) || checkpoint.commits.some(c => typeof c.stepId !== 'string' || !Number.isFinite(c.commitMs)))
|
|
210
|
+
throw new Error('Invalid checkpoint schema');
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
await server.close();
|
|
214
|
+
throw new JoploError('USAGE', 'Checkpoint is absent or invalid');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const startedAt = Date.now();
|
|
135
218
|
let browser = null;
|
|
136
219
|
try {
|
|
137
|
-
const
|
|
220
|
+
const audit = opts.auditLayout ? createLayoutAuditSession({ out, project, crop: opts.crop, options: opts.auditLayout, overwrite: opts.overwrite, sampleMs }) : null;
|
|
221
|
+
const canvas = opts.width && opts.height ? { width: opts.width, height: opts.height } : opts.logicalViewport;
|
|
222
|
+
const { url, size: defaultSize } = recordUrl(server.url, server.projectId, project, { ...opts, audio: false, voice: opts.voice ?? (opts.framesOnly ? 'real' : 'estimate'), ...(canvas ? { canvas } : {}) });
|
|
223
|
+
const size = canvas ?? defaultSize;
|
|
138
224
|
browser = await launch(playwright);
|
|
139
|
-
const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 0.5 });
|
|
225
|
+
const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: opts.framesOnly ? opts.frameScale ?? 1 : 0.5 });
|
|
140
226
|
const page = await ctx.newPage();
|
|
227
|
+
const captureSession = await ctx.newCDPSession(page);
|
|
141
228
|
await page.clock.install({ time: 0 });
|
|
229
|
+
// 先冻结空白页,避免读 now 与 pauseAt 两次调用之间的墙钟竞态。
|
|
230
|
+
await page.clock.pauseAt(86_400_000);
|
|
142
231
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
143
232
|
// 载入阶段:真实时间里等网络与字体,假时间一点点往前推,直到渲染路由报告就绪
|
|
144
233
|
const t0 = Date.now();
|
|
@@ -154,33 +243,96 @@ export async function renderFilm(opts) {
|
|
|
154
243
|
const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
|
|
155
244
|
if (err)
|
|
156
245
|
throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
await page.
|
|
246
|
+
// 加载期间也只按 16ms 网格推进;开播相位不随网络和字体加载耗时改变。
|
|
247
|
+
await flush(page);
|
|
248
|
+
await page.evaluate(() => window.__JOPLO_RECORD__.prepare());
|
|
249
|
+
if (checkpointFile) {
|
|
250
|
+
const excluded = [out, metadataOut, opts.timeline, opts.timeline ? opts.timeline.replace(/\.json$/i, '') + '.assets' : null, opts.frames, checkpointFile].filter((p) => !!p);
|
|
251
|
+
const outStem = path.basename(out).replace(/\.png$/i, '');
|
|
252
|
+
for (const name of fs.existsSync(path.dirname(out)) ? fs.readdirSync(path.dirname(out)) : [])
|
|
253
|
+
if (name.startsWith(outStem + '-') && name.endsWith('.png'))
|
|
254
|
+
excluded.push(path.join(path.dirname(out), name));
|
|
255
|
+
const sourceIdentity = contentIdentity([projectDir, ...exportRuntimeRoots(projectDir, server.payload().plugins ?? {})], excluded);
|
|
256
|
+
const { projectDir: _projectDir, out: _out, overwrite: _overwrite, resume: _resume, checkpoint: _checkpoint, timeline: _timeline, frames: _frames, ...rendering } = opts;
|
|
257
|
+
const voiceIdentity = await page.evaluate(() => window.__JOPLO_RECORD__.voiceIdentity());
|
|
258
|
+
fingerprint = createHash('sha256').update(JSON.stringify({ version: 2, browser: browser.version(), platform: process.platform, arch: process.arch, node: process.versions.node, project, voiceIdentity, sourceIdentity, rendering, sampleMs, every, stillMs, plugins: server.payload().plugins })).digest('hex');
|
|
259
|
+
if (checkpoint?.fingerprint !== undefined && checkpoint.fingerprint !== fingerprint)
|
|
260
|
+
throw new JoploError('USAGE', 'Checkpoint source, version or rendering options changed; start a fresh render');
|
|
261
|
+
}
|
|
160
262
|
const helper = await ctx.newPage();
|
|
161
263
|
await helper.setContent(DIFF_PAGE);
|
|
162
264
|
// 字幕与步骤标题条浮在画面上(D97):胶片条只看画面本身的运动,采样时把它们藏起来,文字换行不算镜头切换
|
|
163
265
|
await page.addStyleTag({ content: '[data-jsubtitle],[data-testid="step-title"]{visibility:hidden!important}' });
|
|
164
266
|
const stageRatio = 1;
|
|
165
267
|
const samples = [];
|
|
268
|
+
let lastChapter = null;
|
|
269
|
+
let chapterStartedAt = Date.now();
|
|
270
|
+
const rssSamples = [];
|
|
271
|
+
let nextMemoryAt = 0;
|
|
166
272
|
let tail = -1;
|
|
167
273
|
// 第一帧在开播之前采(封面 / 第 0 步):开播那一下的切换也要量到
|
|
168
|
-
|
|
169
|
-
|
|
274
|
+
let previousTime = 0;
|
|
275
|
+
for (let index = 0;; index++) {
|
|
276
|
+
const t = opts.frameFps ? frameTime(index, opts.frameFps) : index * sampleMs;
|
|
277
|
+
if (t > MAX_MS)
|
|
278
|
+
break;
|
|
279
|
+
if (index === 1) {
|
|
170
280
|
await page.evaluate(() => window.__JOPLO_RECORD__.play());
|
|
281
|
+
await flush(page);
|
|
282
|
+
}
|
|
171
283
|
if (t > 0)
|
|
172
|
-
await page.clock.runFor(
|
|
284
|
+
await page.clock.runFor(t - previousTime);
|
|
285
|
+
previousTime = t;
|
|
173
286
|
await flush(page);
|
|
174
287
|
const p = await page.evaluate(() => window.__JOPLO_RECORD__.progress);
|
|
175
288
|
if (p.error)
|
|
176
289
|
throw new JoploError('RENDER_FAILED', `Playback failed at ${t} ms: ${p.error}`);
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
290
|
+
if (p.scenarioId !== lastChapter)
|
|
291
|
+
chapterStartedAt = Date.now();
|
|
292
|
+
if (Date.now() - chapterStartedAt > (opts.chapterTimeoutMs ?? 180_000))
|
|
293
|
+
throw new JoploError('RENDER_FAILED', `Chapter ${p.scenarioId} timed out at ${t} ms (wall clock); completed checkpoint was preserved`);
|
|
294
|
+
if (t >= nextMemoryAt) {
|
|
295
|
+
rssSamples.push({ engineMs: t, rssBytes: process.memoryUsage().rss });
|
|
296
|
+
nextMemoryAt = t + 5000;
|
|
297
|
+
}
|
|
298
|
+
const restored = checkpoint?.samples[index];
|
|
299
|
+
if (restored) {
|
|
300
|
+
samples.push(restored);
|
|
301
|
+
if (index === checkpoint.samples.length - 1) {
|
|
302
|
+
const currentStep = p.scenarioId ? project.scenarios[p.scenarioId]?.steps[p.position - 1]?.id ?? null : null;
|
|
303
|
+
if (restored.scenarioId !== p.scenarioId || restored.position !== p.position || restored.activeStep !== p.activeStep || restored.stepId !== currentStep)
|
|
304
|
+
throw new JoploError('RENDER_FAILED', `Checkpoint stable state diverged at ${t} ms; rerun without --resume`);
|
|
305
|
+
const raw = await page.evaluate(() => window.__JOPLO_RECORD__.timeline());
|
|
306
|
+
const commits = playbackTimeline(raw).steps.map(s => ({ stepId: s.stepId, commitMs: s.commitMs }));
|
|
307
|
+
if (!checkpointCommitsMatch(checkpoint.commits, commits))
|
|
308
|
+
throw new JoploError('RENDER_FAILED', 'Checkpoint playback commits differ by more than 50 ms; rerun without --resume');
|
|
309
|
+
await helper.evaluate((state) => window.restore(state), checkpoint.diff);
|
|
310
|
+
}
|
|
311
|
+
lastChapter = p.scenarioId;
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
const jpg = (await capture(page, '[data-jexport]', opts.crop, 'jpeg', opts.framesOnly ? 95 : 72, captureSession, t)).toString('base64');
|
|
315
|
+
await audit?.sample(page, { atMs: t, scenarioId: p.scenarioId ?? opts.scenarioId, position: p.position, jpg });
|
|
316
|
+
const d = opts.framesOnly ? { diff: 0, changed: 0, still: 0 } : await helper.evaluate(([b64, crop, time, th, st]) => window.step(b64, crop, time, th, st), [jpg, stageRatio, t, PIXEL_THRESHOLD, STILL_CHANGED]);
|
|
317
|
+
samples.push({ t, ...d, scenarioId: p.scenarioId, position: p.position, activeStep: p.activeStep, stepId: p.scenarioId ? project.scenarios[p.scenarioId]?.steps[p.position - 1]?.id ?? null : null, ...(!opts.framesOnly && t % every === 0 ? { jpg } : {}) });
|
|
318
|
+
if (opts.frames && (opts.framesOnly || t % every === 0)) {
|
|
181
319
|
fs.mkdirSync(opts.frames, { recursive: true });
|
|
182
320
|
fs.writeFileSync(path.join(opts.frames, `${String(t).padStart(7, '0')}.jpg`), Buffer.from(jpg, 'base64'));
|
|
183
321
|
}
|
|
322
|
+
if (checkpointFile && lastChapter && lastChapter !== p.scenarioId && samples.length > 4) {
|
|
323
|
+
// Keep a stable final-state anchor before the seam. Its small tail is
|
|
324
|
+
// recomputed, so accepted one-sample scheduling jitter never reuses seam pixels.
|
|
325
|
+
const back = Math.min(10, Math.ceil(100 / sampleMs) + 1), prefix = samples.slice(0, -back);
|
|
326
|
+
const diff = await helper.evaluate(back => window.dump(back), back);
|
|
327
|
+
const raw = await page.evaluate(() => window.__JOPLO_RECORD__.timeline());
|
|
328
|
+
const cutoff = prefix.at(-1).t;
|
|
329
|
+
const commits = playbackTimeline({ ...raw, events: raw.events.filter(e => e.at - (raw.startedAt ?? 0) <= cutoff) }).steps.map(s => ({ stepId: s.stepId, commitMs: s.commitMs }));
|
|
330
|
+
fs.mkdirSync(path.dirname(checkpointFile), { recursive: true });
|
|
331
|
+
const temp = `${checkpointFile}.${process.pid}.tmp`;
|
|
332
|
+
fs.writeFileSync(temp, JSON.stringify({ fingerprint, samples: prefix, diff, commits }));
|
|
333
|
+
fs.renameSync(temp, checkpointFile);
|
|
334
|
+
}
|
|
335
|
+
lastChapter = p.scenarioId;
|
|
184
336
|
if (p.done && tail < 0)
|
|
185
337
|
tail = t + 1000;
|
|
186
338
|
if (tail >= 0 && t >= tail)
|
|
@@ -188,6 +340,11 @@ export async function renderFilm(opts) {
|
|
|
188
340
|
}
|
|
189
341
|
if (tail < 0)
|
|
190
342
|
throw new JoploError('RENDER_FAILED', `Playback did not finish within ${MAX_MS / 60000} minutes of engine time`);
|
|
343
|
+
const raw = await page.evaluate(() => window.__JOPLO_RECORD__.timeline());
|
|
344
|
+
if (opts.timeline) {
|
|
345
|
+
const file = check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
|
|
346
|
+
await persistTimeline(file, playbackTimeline(raw), project.mediaAssets ?? {}, server.url, opts.overwrite, server.token, project.mediaInfo);
|
|
347
|
+
}
|
|
191
348
|
const cuts = findCuts(samples);
|
|
192
349
|
const stills = findStills(samples, stillMs);
|
|
193
350
|
const boundaries = stepBoundaries(samples);
|
|
@@ -231,35 +388,97 @@ export async function renderFilm(opts) {
|
|
|
231
388
|
const png = await sheet.screenshot({ type: 'png', fullPage: true });
|
|
232
389
|
await sheet.close();
|
|
233
390
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
234
|
-
|
|
391
|
+
await writeOutput(file, png, opts.overwrite);
|
|
235
392
|
files.push(file);
|
|
236
393
|
}
|
|
237
394
|
await ctx.close();
|
|
238
|
-
const result = { path: files[0], files, durationMs, sampleMs, every, samples: samples.length, cuts, stills, boundaries, maxDiff: round(Math.max(0, ...samples.map((s) => s.diff))), warnings: [] };
|
|
395
|
+
const result = { ...(audit ? { audit: audit.finish() } : {}), path: files[0] ?? out, files, durationMs, sampleMs, every, samples: samples.length, cuts, stills, boundaries, maxDiff: round(Math.max(0, ...samples.map((s) => s.diff))), warnings: sampleMs > 50 ? ['Coarse analysis: transitions shorter than the computation interval may be missed; use 50 ms for final QA.'] : [], measurement: { baselineRssBytes, endRssBytes: process.memoryUsage().rss, memoryScope: 'node-process-lifetime', rssSamples, wallMs: Date.now() - startedAt, peakRssBytes: process.resourceUsage().maxRSS * 1024, resumedSamples: checkpoint?.samples.length ?? 0 } };
|
|
239
396
|
// 完整的判读数据(每一步提交前后的最大帧差、硬切、静止)放在胶片条旁边,评审时可以引用具体数字
|
|
240
|
-
|
|
397
|
+
await writeOutput(metadataOut, JSON.stringify({ ...result, frames: samples.map(({ jpg: _jpg, ...rest }) => rest) }, null, 1), opts.overwrite);
|
|
241
398
|
return result;
|
|
242
399
|
}
|
|
243
400
|
finally {
|
|
244
401
|
await browser?.close().catch(() => undefined);
|
|
245
|
-
await server.close();
|
|
402
|
+
await server.close().catch(() => undefined);
|
|
246
403
|
}
|
|
247
404
|
}
|
|
405
|
+
export function renderFilm(opts) { return samplePlayback(opts); }
|
|
406
|
+
const HIDE = ['cover', 'cursor', 'title', 'subtitles'];
|
|
248
407
|
/** 视频:与看板导出相同的录制器(真实时间)。 */
|
|
249
408
|
export async function renderVideo(opts) {
|
|
250
409
|
const projectDir = realProjectDir(opts.projectDir);
|
|
251
410
|
const out = check({ ...opts, projectDir });
|
|
411
|
+
distinctOutputs([out, opts.timeline, opts.srt]);
|
|
412
|
+
geometryQuery(opts);
|
|
413
|
+
if (opts.auditLayout)
|
|
414
|
+
throw new JoploError('USAGE', 'Layout audit supports static screenshots and --film, not --video');
|
|
415
|
+
if (opts.crop)
|
|
416
|
+
throw new JoploError('USAGE', 'Video crop is not supported; use --viewport/--no-frame or --frames-out with --crop');
|
|
417
|
+
if (opts.timeline) {
|
|
418
|
+
check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
|
|
419
|
+
assertNotProjectData(projectDir, path.join(`${path.resolve(opts.timeline).replace(/\.json$/i, '')}.assets`, '__asset.wav'));
|
|
420
|
+
}
|
|
421
|
+
if ((opts.width === undefined) !== (opts.height === undefined))
|
|
422
|
+
throw new JoploError('USAGE', 'Video width and height must be provided together');
|
|
423
|
+
const video = opts.width !== undefined ? { width: videoDimension('width', opts.width), height: videoDimension('height', opts.height) } : null;
|
|
424
|
+
const bad = (opts.hide ?? []).find((h) => !HIDE.includes(h));
|
|
425
|
+
if (bad)
|
|
426
|
+
throw new JoploError('USAGE', `Unknown --hide item ${JSON.stringify(bad)} (use ${HIDE.join(', ')})`);
|
|
427
|
+
const voice = opts.voice ?? 'real';
|
|
428
|
+
if (!['real', 'estimate', 'off'].includes(voice))
|
|
429
|
+
throw new JoploError('USAGE', `--voice must be real, estimate or off (got ${String(voice)})`);
|
|
430
|
+
const srtOut = opts.srt ? check({ out: opts.srt, overwrite: opts.overwrite, projectDir }) : null;
|
|
431
|
+
if (srtOut && srtOut === out)
|
|
432
|
+
throw new JoploError('USAGE', 'The subtitle file must differ from the video file');
|
|
252
433
|
const { server, project } = await compiled(projectDir);
|
|
434
|
+
let videoWork = null;
|
|
253
435
|
try {
|
|
254
|
-
|
|
436
|
+
// 输出分辨率(#55):视口就是视频分辨率,渲染路由把舞台等比缩放进这块画布(录屏按 CSS 像素取帧,deviceScaleFactor 不会让它更清晰)
|
|
437
|
+
const { url, size } = recordUrl(server.url, server.projectId, project, { ...opts, voice, hide: opts.hide ?? [], ...(video ? { canvas: video } : {}) });
|
|
255
438
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
256
|
-
if (opts.overwrite)
|
|
257
|
-
fs.rmSync(out, { force: true });
|
|
258
439
|
const started = Date.now();
|
|
259
|
-
|
|
260
|
-
|
|
440
|
+
const mp4 = path.extname(out).toLowerCase() === '.mp4';
|
|
441
|
+
videoWork = fs.mkdtempSync(path.join(path.dirname(out), '.joplo-video-'));
|
|
442
|
+
const recordingOut = path.join(videoWork, 'recording.webm');
|
|
443
|
+
const encodedOut = mp4 ? path.join(videoWork, 'encoded.mp4') : recordingOut;
|
|
444
|
+
const outcome = await defaultRecorder((dir) => loadPlaywright({ home: joploHome(), projectDir: dir }))({ projectDir, url, size: video ?? size, out: recordingOut, total: 0, progress: () => undefined, signal: new AbortController().signal, maxMs: MAX_MS });
|
|
445
|
+
if (mp4)
|
|
446
|
+
await encodeMp4(recordingOut, encodedOut);
|
|
447
|
+
if (srtOut) {
|
|
448
|
+
fs.mkdirSync(path.dirname(srtOut), { recursive: true });
|
|
449
|
+
fs.writeFileSync(srtOut, srt(outcome?.cues ?? []), opts.overwrite ? undefined : { flag: 'wx' });
|
|
450
|
+
}
|
|
451
|
+
if (opts.timeline && outcome?.timeline) {
|
|
452
|
+
const file = check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
|
|
453
|
+
await persistTimeline(file, outcome.timeline, project.mediaAssets ?? {}, server.url, opts.overwrite, server.token, project.mediaInfo);
|
|
454
|
+
}
|
|
455
|
+
await commitOutput(encodedOut, out, opts.overwrite);
|
|
456
|
+
return { ...(outcome?.sync ? { sync: outcome.sync } : {}), path: out, durationMs: Date.now() - started, size: video ?? size, srt: srtOut, voice: outcome?.voice ?? { mode: voice, missing: [] } };
|
|
261
457
|
}
|
|
262
458
|
finally {
|
|
263
|
-
|
|
459
|
+
if (videoWork)
|
|
460
|
+
fs.rmSync(videoWork, { recursive: true, force: true });
|
|
461
|
+
await server.close().catch(() => undefined);
|
|
264
462
|
}
|
|
265
463
|
}
|
|
464
|
+
/** Public offline frame export. No audio synthesis or private browser bridge is needed by callers. */
|
|
465
|
+
export async function renderFrames(opts) {
|
|
466
|
+
const fps = opts.fps ?? 30;
|
|
467
|
+
if (!Number.isFinite(fps) || fps < 1 || fps > 120)
|
|
468
|
+
throw new JoploError('USAGE', 'fps must be from 1 to 120');
|
|
469
|
+
if (opts.scale !== undefined && (!Number.isFinite(opts.scale) || opts.scale <= 0 || opts.scale > 4))
|
|
470
|
+
throw new JoploError('USAGE', 'Frame scale must be above 0 and at most 4');
|
|
471
|
+
const dir = path.resolve(opts.framesOut);
|
|
472
|
+
assertNotProjectData(opts.projectDir, path.join(dir, '__frame.jpg'));
|
|
473
|
+
if (dir === realProjectDir(opts.projectDir))
|
|
474
|
+
throw new JoploError('USAGE', 'Frame output directory must differ from the project root');
|
|
475
|
+
if (fs.existsSync(dir) && fs.readdirSync(dir).length && !opts.overwrite)
|
|
476
|
+
throw new JoploError('USAGE', 'Frame directory is not empty; use --overwrite');
|
|
477
|
+
const timeline = opts.timeline ?? path.join(dir, 'timeline.json');
|
|
478
|
+
if (opts.overwrite && fs.existsSync(dir))
|
|
479
|
+
for (const name of fs.readdirSync(dir))
|
|
480
|
+
if (/^\d{7}\.jpg$/.test(name))
|
|
481
|
+
fs.rmSync(path.join(dir, name));
|
|
482
|
+
const result = await samplePlayback({ ...opts, hide: opts.hide ?? ['cover', 'cursor', 'title', 'subtitles'], out: path.join(dir, 'film.png'), frames: dir, timeline, frameFps: fps, frameScale: opts.scale, framesOnly: true });
|
|
483
|
+
return { directory: dir, timeline, fps, frames: result.samples, durationMs: result.durationMs, toleranceMs: 50 };
|
|
484
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,9 +13,14 @@ export { startPreview, SITE_CONTENT_TYPES, type PreviewHandle } from './preview.
|
|
|
13
13
|
export { generateProjectVoice, type VoiceRunOptions, type VoiceRunResult } from './voice-run.js';
|
|
14
14
|
export type { CloudSpeechRequest, CloudSpeechResult, CloudVoice, CloudVoiceBridge, CloudVoiceCatalog, CloudVoiceInfo, CloudVoiceStatus, VoiceQuota } from './cloud.js';
|
|
15
15
|
export { renderSheet, renderStep } from './render.js';
|
|
16
|
-
export { renderFilm, renderVideo } from './film.js';
|
|
16
|
+
export { renderFilm, renderVideo, renderFrames } from './film.js';
|
|
17
17
|
export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime, type ExportRuntimeStatus, type InstallProgress, type InstallResult } from './export-runtime.js';
|
|
18
18
|
export { buildFeatureDiff, publicIRFromHtml, type DiffBuildOptions, type DiffBuildResult } from './feature-diff.js';
|
|
19
19
|
export { generateResources } from './resources-run.js';
|
|
20
20
|
export { LocalResources } from './local-resources.js';
|
|
21
21
|
export { inspectResources, mediaDiagnostics } from './media-check.js';
|
|
22
|
+
export { watchConfigDiagnostics } from './watch-config.js';
|
|
23
|
+
export { assetUsage, type AssetUsageReport, type AssetUsageEntry, type AssetUsageReference } from './asset-usage.js';
|
|
24
|
+
export type { ExportCrop, FramesOptions, FilmOptions, FilmResult, VideoOptions, VideoResult } from './contract.js';
|
|
25
|
+
export type { PlaybackTimeline, PlaybackEvent } from './timeline.js';
|
|
26
|
+
export { auditLayout, createLayoutAuditSession, type LayoutAuditOptions, type LayoutFinding, type LayoutAuditSample } from './layout-audit.js';
|