browser-webm-recording-smoke.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { app, BrowserWindow, webContents } from "electron";
  2. import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { pathToFileURL } from "node:url";
  6. import { createElectronBrowserWebmRecorder } from "../out/main/browserWebmRecorder.js";
  7. const OUTPUT_PATH = process.env.ZCODE_WEBM_SMOKE_OUTPUT_PATH;
  8. const CAPTURE_MS = Number(process.env.ZCODE_WEBM_SMOKE_CAPTURE_MS) || 1_500;
  9. function htmlDataUrl(html) {
  10. return `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
  11. }
  12. function targetHtml() {
  13. return `<!doctype html>
  14. <html>
  15. <head>
  16. <style>
  17. html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }
  18. body { background: #172554; }
  19. #box {
  20. position: absolute;
  21. top: 120px;
  22. left: 80px;
  23. width: 160px;
  24. height: 160px;
  25. background: #22d3ee;
  26. animation: travel 1s linear infinite alternate;
  27. }
  28. @keyframes travel { to { transform: translateX(720px) rotate(180deg); background: #f97316; } }
  29. </style>
  30. </head>
  31. <body><div id="box"></div></body>
  32. </html>`;
  33. }
  34. function hostHtml(targetUrl) {
  35. return `<!doctype html>
  36. <html>
  37. <head>
  38. <style>
  39. html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }
  40. #guest { display: block; width: 1280px; height: 720px; }
  41. </style>
  42. </head>
  43. <body>
  44. <webview id="guest" src="${targetUrl}"></webview>
  45. <script>
  46. const guest = document.querySelector("#guest");
  47. window.guestReady = new Promise((resolve) => {
  48. guest.addEventListener("dom-ready", () => resolve(guest.getWebContentsId()), { once: true });
  49. });
  50. </script>
  51. </body>
  52. </html>`;
  53. }
  54. async function validatePlayback(root, outputPath) {
  55. const validationHtmlPath = join(root, "validate.html");
  56. await writeFile(
  57. validationHtmlPath,
  58. `<!doctype html><video id="video" src="${pathToFileURL(outputPath).href}" muted></video>`,
  59. "utf8",
  60. );
  61. const validationWindow = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: false } });
  62. try {
  63. await validationWindow.loadFile(validationHtmlPath);
  64. return await validationWindow.webContents.executeJavaScript(`(async () => {
  65. const video = document.querySelector("#video");
  66. await new Promise((resolve, reject) => {
  67. const timer = setTimeout(() => reject(new Error("WebM playback metadata timeout")), 10000);
  68. video.addEventListener("loadedmetadata", () => { clearTimeout(timer); resolve(); }, { once: true });
  69. video.addEventListener("error", () => {
  70. clearTimeout(timer);
  71. reject(new Error(video.error?.message || "WebM playback failed"));
  72. }, { once: true });
  73. video.load();
  74. });
  75. const width = video.videoWidth;
  76. const height = video.videoHeight;
  77. const seek = (time) => new Promise((resolve, reject) => {
  78. const timer = setTimeout(() => reject(new Error("WebM seek timeout at " + time)), 10000);
  79. video.addEventListener("seeked", () => { clearTimeout(timer); resolve(); }, { once: true });
  80. video.currentTime = time;
  81. });
  82. // MediaRecorder 的流式 WebM 不写 Duration 头,video.duration 是 Infinity。
  83. // seek 到超大时间点让 Chromium 定位真实末尾,再读回可播放时长。
  84. await seek(1e7);
  85. const durationSeconds = video.currentTime;
  86. if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) {
  87. throw new Error("WebM has no seekable duration: " + String(durationSeconds));
  88. }
  89. const canvas = document.createElement("canvas");
  90. canvas.width = width;
  91. canvas.height = height;
  92. const context = canvas.getContext("2d", { willReadFrequently: true });
  93. const grabFrame = async (time) => {
  94. await seek(Math.max(0, Math.min(time, durationSeconds - 0.01)));
  95. context.drawImage(video, 0, 0, width, height);
  96. return context.getImageData(0, 0, width, height).data;
  97. };
  98. const samples = [
  99. await grabFrame(durationSeconds * 0.1),
  100. await grabFrame(durationSeconds * 0.5),
  101. await grabFrame(durationSeconds * 0.9),
  102. ];
  103. const pixels = width * height;
  104. const changedRatio = (left, right) => {
  105. let changed = 0;
  106. for (let index = 0; index < left.length; index += 4) {
  107. const delta = Math.abs(left[index] - right[index])
  108. + Math.abs(left[index + 1] - right[index + 1])
  109. + Math.abs(left[index + 2] - right[index + 2]);
  110. if (delta > 24) changed += 1;
  111. }
  112. return changed / pixels;
  113. };
  114. const changedPixelRatio = Math.max(
  115. changedRatio(samples[0], samples[1]),
  116. changedRatio(samples[1], samples[2]),
  117. changedRatio(samples[0], samples[2]),
  118. );
  119. let litPixels = 0;
  120. for (let index = 0; index < samples[1].length; index += 4) {
  121. if (samples[1][index] + samples[1][index + 1] + samples[1][index + 2] > 24) litPixels += 1;
  122. }
  123. // 实际解码帧率:统计一段真实播放里的 video frame callback 次数。
  124. await seek(0);
  125. let sampledFrames = 0;
  126. let sampledMs = 0;
  127. await new Promise((resolve) => {
  128. const startedAt = performance.now();
  129. const finish = () => { sampledMs = performance.now() - startedAt; resolve(); };
  130. const onFrame = () => {
  131. sampledFrames += 1;
  132. if (performance.now() - startedAt >= 1000) { finish(); return; }
  133. video.requestVideoFrameCallback(onFrame);
  134. };
  135. video.requestVideoFrameCallback(onFrame);
  136. setTimeout(finish, 4000);
  137. void video.play();
  138. });
  139. video.pause();
  140. return {
  141. width,
  142. height,
  143. durationSeconds,
  144. changedPixelRatio,
  145. litPixelRatio: litPixels / pixels,
  146. sampledFrames,
  147. sampledFps: sampledMs > 0 ? sampledFrames / (sampledMs / 1000) : 0,
  148. };
  149. })()`);
  150. } finally {
  151. if (!validationWindow.isDestroyed()) validationWindow.destroy();
  152. }
  153. }
  154. async function run() {
  155. let hostWindow;
  156. let root;
  157. let exitCode = 0;
  158. try {
  159. await app.whenReady();
  160. root = await mkdtemp(join(tmpdir(), "zcode-browser-webm-smoke-"));
  161. const outputPath = OUTPUT_PATH || join(root, "recording.webm");
  162. hostWindow = new BrowserWindow({
  163. show: true,
  164. focusable: false,
  165. skipTaskbar: true,
  166. width: 1280,
  167. height: 720,
  168. useContentSize: true,
  169. webPreferences: { webviewTag: true, backgroundThrottling: false },
  170. });
  171. hostWindow.showInactive();
  172. await hostWindow.loadURL(htmlDataUrl(hostHtml(htmlDataUrl(targetHtml()))));
  173. const guestId = await hostWindow.webContents.executeJavaScript("window.guestReady", true);
  174. const guest = webContents.fromId(guestId);
  175. if (!guest) throw new Error(`target guest ${guestId} was not found`);
  176. await hostWindow.webContents.executeJavaScript(
  177. "new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
  178. );
  179. guest.debugger.attach("1.3");
  180. await guest.debugger.sendCommand("Emulation.setDeviceMetricsOverride", {
  181. width: 1280,
  182. height: 720,
  183. deviceScaleFactor: 1,
  184. mobile: false,
  185. dontSetVisibleSize: true,
  186. });
  187. const hostRect = await hostWindow.webContents.executeJavaScript(
  188. `(() => { const r = document.querySelector("#guest").getBoundingClientRect(); return { width: r.width, height: r.height, dpr: devicePixelRatio }; })()`,
  189. );
  190. const guestViewport = await guest.executeJavaScript(
  191. `({ width: innerWidth, height: innerHeight, dpr: devicePixelRatio })`,
  192. );
  193. process.stderr.write(
  194. `[browser-recording] smoke target guestId=${guestId} frame=${guest.mainFrame.processId}:${guest.mainFrame.routingId} hostRect=${JSON.stringify(hostRect)} guestViewport=${JSON.stringify(guestViewport)}\n`,
  195. );
  196. const controller = new AbortController();
  197. const recorder = await createElectronBrowserWebmRecorder(
  198. {
  199. outputPath,
  200. targetFrame: guest.mainFrame,
  201. viewport: { width: 1280, height: 720 },
  202. fps: 25,
  203. signal: controller.signal,
  204. },
  205. (message) => process.stderr.write(`${message}\n`),
  206. );
  207. const captureStartedAt = Date.now();
  208. await new Promise((resolve) => setTimeout(resolve, CAPTURE_MS));
  209. await recorder.stop();
  210. const capturedMs = Date.now() - captureStartedAt;
  211. const info = await stat(outputPath);
  212. const header = (await readFile(outputPath)).subarray(0, 4).toString("hex");
  213. if (info.size <= 4 || header !== "1a45dfa3") {
  214. throw new Error(`invalid WebM artifact: size=${info.size}, header=${header}`);
  215. }
  216. const playback = await validatePlayback(root, outputPath);
  217. if (playback.width !== 1280 || playback.height !== 720) {
  218. throw new Error(`WebM dimensions mismatch: ${JSON.stringify(playback)}`);
  219. }
  220. // 时长必须来自真实容器,而不是 main 侧推算:偏离取景 wall clock 太多说明丢帧或提前截断。
  221. const durationMs = playback.durationSeconds * 1000;
  222. if (durationMs < capturedMs * 0.5 || durationMs > capturedMs * 1.5 + 500) {
  223. throw new Error(
  224. `WebM duration ${durationMs.toFixed(0)}ms is not consistent with ${capturedMs}ms of capture`,
  225. );
  226. }
  227. // 只验证尺寸会让全黑或全静止的录制也通过;这里要求画面真的在动且不是黑屏。
  228. if (playback.changedPixelRatio < 0.02) {
  229. throw new Error(
  230. `recorded frames are static: changedPixelRatio=${playback.changedPixelRatio.toFixed(4)}`,
  231. );
  232. }
  233. if (playback.litPixelRatio < 0.5) {
  234. throw new Error(`recorded frames are mostly black: litPixelRatio=${playback.litPixelRatio.toFixed(4)}`);
  235. }
  236. if (playback.sampledFps < 8) {
  237. throw new Error(
  238. `decoded frame rate too low: ${playback.sampledFps.toFixed(1)}fps over ${playback.sampledFrames} frames`,
  239. );
  240. }
  241. console.log(JSON.stringify({ ok: true, path: outputPath, size: info.size, capturedMs, ...playback }));
  242. } catch (error) {
  243. exitCode = 1;
  244. await new Promise((resolve) => process.stderr.write(`${error.stack ?? error}\n`, resolve));
  245. } finally {
  246. for (const contents of webContents.getAllWebContents()) {
  247. if (contents.getType() === "webview" && contents.debugger.isAttached()) {
  248. try {
  249. contents.debugger.detach();
  250. } catch {
  251. // smoke 已进入退出清理,不覆盖更早的验证错误。
  252. }
  253. }
  254. }
  255. if (hostWindow && !hostWindow.isDestroyed()) hostWindow.destroy();
  256. if (root && !OUTPUT_PATH) await rm(root, { recursive: true, force: true });
  257. process.exitCode = exitCode;
  258. app.exit(exitCode);
  259. }
  260. }
  261. void run();