@lunagerm-studio/video-cut-skill 0.0.0-stage → 1.0.0

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.
Files changed (146) hide show
  1. package/README.md +13 -2
  2. package/package.json +12 -4
  3. package/skills/ai-video-opening/SKILL.md +62 -0
  4. package/skills/ai-video-opening/references/export-and-validation.md +9 -0
  5. package/skills/ai-video-opening/references/motion-and-layout.md +7 -0
  6. package/skills/ai-video-opening/references/series-cases.md +7 -0
  7. package/skills/blue-white-ui-motion/SKILL.md +30 -0
  8. package/skills/blue-white-ui-motion/agents/openai.yaml +2 -0
  9. package/skills/blue-white-ui-motion/references/review.md +25 -0
  10. package/skills/chengfeng-videocut-skills/LICENSE +201 -0
  11. package/skills/chengfeng-videocut-skills/NOTICE.md +27 -0
  12. package/skills/chengfeng-videocut-skills/README.md +265 -0
  13. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/SKILL.md +37 -0
  14. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/agents/openai.yaml +2 -0
  15. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/cut_video.sh +182 -0
  16. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/detect_en_stutter.js +49 -0
  17. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/generate_review.js +1484 -0
  18. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/generate_srt_for_video.sh +75 -0
  19. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/generate_subtitles.js +141 -0
  20. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/review_server.js +381 -0
  21. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/volcengine_transcribe.sh +224 -0
  22. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255/scripts/watch_cut_done.js +86 -0
  23. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/1-/346/240/270/345/277/203/345/216/237/345/210/231.md +56 -0
  24. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/10-/345/210/240/351/231/244/351/243/216/351/231/251/345/210/206/345/261/202.md +44 -0
  25. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/11-/345/217/243/346/222/255/347/250/277/345/257/271/351/275/220.md +40 -0
  26. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/2-/350/257/255/346/260/224/350/257/215/346/243/200/346/265/213.md +30 -0
  27. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/3-/351/235/231/351/237/263/346/256/265/345/244/204/347/220/206.md +56 -0
  28. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/4-/351/207/215/345/244/215/346/243/200/346/265/213.md +77 -0
  29. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/5-/345/215/241/351/241/277/350/257/215.md +48 -0
  30. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/7-/350/277/236/347/273/255/350/257/255/346/260/224/350/257/215.md +32 -0
  31. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/9-/346/256/213/345/217/245/346/243/200/346/265/213.md +79 -0
  32. package/skills/chengfeng-videocut-skills//345/211/252/345/217/243/346/222/255//347/224/250/346/210/267/344/271/240/346/203/257/README.md +35 -0
  33. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/SKILL.md +32 -0
  34. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/agents/openai.yaml +2 -0
  35. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/references/artifact-contracts.md +168 -0
  36. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/animation_style.cjs +53 -0
  37. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/export_final_video.cjs +200 -0
  38. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/serve_range_preview.cjs +128 -0
  39. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/user_config.cjs +80 -0
  40. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207/scripts/write_render_mode.cjs +149 -0
  41. package/skills/chengfeng-videocut-skills//345/217/243/346/222/255/346/210/220/347/211/207//347/224/250/346/210/267/351/205/215/347/275/256/default.json +4 -0
  42. package/skills/chengfeng-videocut-skills//350/207/252/350/277/233/345/214/226/README.md +23 -0
  43. package/skills/chengfeng-videocut-skills//350/207/252/350/277/233/345/214/226/SKILL.md +126 -0
  44. package/skills/continuous-collage-motion/SKILL.md +30 -0
  45. package/skills/continuous-collage-motion/agents/openai.yaml +4 -0
  46. package/skills/continuous-collage-motion/references/reference-motion.md +32 -0
  47. package/skills/continuous-collage-motion/references/shot-plan.md +31 -0
  48. package/skills/continuous-collage-motion/references/style-check.md +17 -0
  49. package/skills/table-video/LICENSES/ATTRIBUTION.md +31 -0
  50. package/skills/table-video/LICENSES/CC-BY-4.0.txt +396 -0
  51. package/skills/table-video/LICENSES/MIT.txt +21 -0
  52. package/skills/table-video/SKILL.md +32 -0
  53. package/skills/table-video/SOURCES.md +61 -0
  54. package/skills/table-video/agents/openai.yaml +2 -0
  55. package/skills/table-video/references/complete-motion.md +97 -0
  56. package/skills/table-video/references/examples/01_/344/270/244/346/256/265/346/274/224/347/244/272.md +73 -0
  57. package/skills/table-video/references/examples/02_/347/224/237/345/233/276/347/224/237/350/247/206/351/242/221/346/217/220/347/244/272/350/257/215/347/244/272/344/276/213.md +50 -0
  58. package/skills/table-video/references/examples/03_DESIGN/345/241/253/345/206/231/347/244/272/344/276/213.md +333 -0
  59. package/skills/table-video/references/examples/04_/350/277/236/347/273/255MG/346/255/243/345/217/215/350/277/207/347/250/213.md +101 -0
  60. package/skills/table-video/references/examples/05_/345/256/214/346/225/264/350/277/207/347/250/213/346/272/220/347/240/201.md +55 -0
  61. package/skills/table-video/references/examples/05_/346/205/242/351/225/234/345/244/264/344/270/216/345/220/214/346/236/204/345/233/276/345/233/236/345/275/222.md +35 -0
  62. package/skills/table-video/references/experience//345/255/227/345/271/225/344/270/216/345/260/201/351/235/242.md +30 -0
  63. package/skills/table-video/references/experience//345/275/225/345/261/217/345/211/252/350/276/221.md +31 -0
  64. package/skills/table-video/references/experience//346/211/213/345/212/250/347/224/237/345/233/276/347/224/237/350/247/206/351/242/221.md +53 -0
  65. package/skills/table-video/references/experience//350/247/206/350/247/211/345/217/231/344/272/213/344/270/216/350/277/236/347/273/255MG.md +102 -0
  66. package/skills/table-video/references/experience//351/225/234/345/244/264/346/216/250/350/277/233/344/270/216/350/275/254/345/234/272.md +178 -0
  67. package/skills/table-video/references/intake.md +84 -0
  68. package/skills/table-video/references/library.md +26 -0
  69. package/skills/table-video/references/motion-check-method.md +147 -0
  70. package/skills/table-video/references/planning.md +62 -0
  71. package/skills/table-video/references/production.md +70 -0
  72. package/skills/table-video/references/project-rules.md +26 -0
  73. package/skills/table-video/references/review-and-repair.md +64 -0
  74. package/skills/table-video/references/self-diagnosis.md +46 -0
  75. package/skills/table-video/references/sop/01_/345/277/253/351/200/237/345/274/200/345/247/213.md +55 -0
  76. package/skills/table-video/references/sop/02_/345/210/266/344/275/234SOP.md +77 -0
  77. package/skills/table-video/references/sop/03_/347/233/256/345/275/225/344/270/216/345/271/266/350/241/214/345/215/217/344/275/234.md +72 -0
  78. package/skills/table-video/references/sop/04_/351/252/214/346/224/266/344/270/216/350/277/224/344/277/256.md +146 -0
  79. package/skills/table-video/references/sop/05_/346/226/207/346/241/210/346/243/200/346/237/245_/345/217/257/351/200/211.md +55 -0
  80. package/skills/table-video/references/sop/06_/351/237/263/346/225/210/344/270/216/351/205/215/344/271/220_/345/217/257/351/200/211.md +138 -0
  81. package/skills/table-video/references/sop/07_/345/267/245/345/205/267/344/270/216/347/216/257/345/242/203.md +52 -0
  82. package/skills/table-video/references/sop/08_/346/235/245/346/272/220/344/270/216/350/256/270/345/217/257.md +36 -0
  83. package/skills/table-video/references/sop/09_DESIGN/345/273/272/347/253/213/344/270/216/346/240/241/351/252/214.md +52 -0
  84. package/skills/table-video/references/state-contract.md +267 -0
  85. package/skills/table-video/references/style-and-motion.md +163 -0
  86. package/skills/table-video/schemas/request.schema.json +44 -0
  87. package/skills/table-video/schemas/state.schema.json +140 -0
  88. package/skills/table-video/scripts/cli.mjs +35 -0
  89. package/skills/table-video/scripts/core.mjs +977 -0
  90. package/skills/table-video/scripts/gain-proof.mjs +48 -0
  91. package/skills/table-video/scripts/init-project.mjs +7 -0
  92. package/skills/table-video/scripts/motion-audit.mjs +589 -0
  93. package/skills/table-video/scripts/motion-check.mjs +345 -0
  94. package/skills/table-video/scripts/motion-gates.mjs +997 -0
  95. package/skills/table-video/scripts/motion-observation.cjs +204 -0
  96. package/skills/table-video/scripts/preflight.mjs +24 -0
  97. package/skills/table-video/scripts/process-locate.mjs +57 -0
  98. package/skills/table-video/scripts/render-motion-example.mjs +143 -0
  99. package/skills/table-video/scripts/save-reference-image.mjs +249 -0
  100. package/skills/table-video/scripts/schema.mjs +71 -0
  101. package/skills/table-video/scripts/stillness.mjs +386 -0
  102. package/skills/table-video/scripts/storage.mjs +328 -0
  103. package/skills/table-video/scripts/workflow.mjs +24 -0
  104. package/skills/talking-head-motion-workflow/SKILL.md +36 -0
  105. package/skills/talking-head-motion-workflow/agents/openai.yaml +4 -0
  106. package/skills/talking-head-motion-workflow/references/cinematic-motion-and-sync.md +72 -0
  107. package/skills/talking-head-motion-workflow/references/classic-ui.md +11 -0
  108. package/skills/talking-head-motion-workflow/references/history-coverage.md +50 -0
  109. package/skills/talking-head-motion-workflow/references/layered-assets-and-characters.md +39 -0
  110. package/skills/talking-head-motion-workflow/references/layout-references.md +41 -0
  111. package/skills/talking-head-motion-workflow/references/lens-shot-selection.md +138 -0
  112. package/skills/talking-head-motion-workflow/references/live-interface-motion.md +69 -0
  113. package/skills/talking-head-motion-workflow/references/motion-recipes.md +40 -0
  114. package/skills/talking-head-motion-workflow/references/mouse-meter2-case.md +113 -0
  115. package/skills/talking-head-motion-workflow/references/pop-collage.md +61 -0
  116. package/skills/talking-head-motion-workflow/references/portable-production.md +32 -0
  117. package/skills/talking-head-motion-workflow/references/production-requirements.md +85 -0
  118. package/skills/talking-head-motion-workflow/references/reference-library.md +41 -0
  119. package/skills/talking-head-motion-workflow/references/safe-areas-and-sound.md +47 -0
  120. package/skills/talking-head-motion-workflow/references/scene-illustrations.md +19 -0
  121. package/skills/talking-head-motion-workflow/references/sfx-presets.md +57 -0
  122. package/skills/talking-head-motion-workflow/references/style-13-github-production.md +33 -0
  123. package/skills/talking-head-motion-workflow/references/style-13-scene-performance.md +76 -0
  124. package/skills/talking-head-motion-workflow/references/style-presets.md +111 -0
  125. package/skills/talking-head-motion-workflow/references/table-video-spatial-mg.md +36 -0
  126. package/skills/talking-head-motion-workflow/scripts/extract_docx.py +19 -0
  127. package/skills/talking-head-motion-workflow/scripts/generate_foley.py +93 -0
  128. package/skills/talking-head-motion-workflow/scripts/render_sfx.py +135 -0
  129. package/skills/video-production-review/SKILL.md +30 -0
  130. package/skills/video-production-review/agents/openai.yaml +2 -0
  131. package/skills/video-production-review/references/episode-review-desk.md +30 -0
  132. package/skills/video-production-review/references/motion-adjustment-review.md +21 -0
  133. package/skills/video-production-workflow/SKILL.md +76 -0
  134. package/skills/video-production-workflow/agents/openai.yaml +2 -0
  135. package/skills/video-production-workflow/references/table-video-ep09.md +17 -0
  136. package/skills/video-production-workflow/scripts/check_motion_project.py +83 -0
  137. package/skills/video-reference-analysis/SKILL.md +32 -0
  138. package/skills/video-reference-analysis/agents/openai.yaml +2 -0
  139. package/skills/video-reference-analysis/references/case-format.md +95 -0
  140. package/skills/video-reference-analysis/references/production-method.md +21 -0
  141. package/skills/video-reference-analysis/scripts/library.py +371 -0
  142. package/skills/video-resource-access/SKILL.md +35 -0
  143. package/skills/video-resource-access/online.enabled +1 -0
  144. package/skills/video-resource-access/scripts/asset_client.py +159 -0
  145. package/skills/video-resource-access/scripts/remote_library.py +50 -0
  146. package//345/256/211/350/243/205/350/257/264/346/230/216.txt +5 -0
@@ -0,0 +1,345 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: MIT
3
+ // Motion diagnostics locate suspect intervals; they never certify visual quality.
4
+ import fs from 'node:fs/promises';
5
+ import { createReadStream } from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { createHash } from 'node:crypto';
9
+ import { spawn } from 'node:child_process';
10
+
11
+ const HELP = `Usage: node motion-check.mjs --input <video> --out <NEW directory>
12
+ [--ranges 4:8,22:28] [--overview-frames 48] [--dense-fps 10]
13
+ [--min-freeze 0.75] [--threshold-db -55] [--ffmpeg ffmpeg] [--ffprobe ffprobe]
14
+ [--purpose-at 2] [--rework-over 3]
15
+ [--audit <source-bound motion-audit/motion-gates report.json>]
16
+ The output parent must exist. Existing output directories are never overwritten.
17
+ Uses existing FFmpeg/FFprobe, no installation. Duration thresholds flag intervals
18
+ for review against project requirements; small meaningful motion may look static
19
+ to the detector. Thresholds alone do not decide whether an interval needs rework.
20
+ These diagnostics cannot establish camera movement, visual meaning, or quality.`;
21
+
22
+ function options(args) {
23
+ if (args.includes('--help')) return { help: true };
24
+ const accepted = new Set(['input', 'out', 'ranges', 'overview-frames', 'dense-fps', 'min-freeze', 'threshold-db', 'purpose-at', 'rework-over', 'ffmpeg', 'ffprobe', 'audit']);
25
+ const o = {};
26
+ for (let i = 0; i < args.length; i += 2) {
27
+ const key = args[i].replace(/^--/, '');
28
+ if (!args[i].startsWith('--') || !accepted.has(key) || i + 1 >= args.length || Object.hasOwn(o, key)) throw new Error(`Unknown, repeated, or incomplete option: ${args[i]}`);
29
+ o[key] = args[i + 1];
30
+ }
31
+ if (!o.input || !o.out) throw new Error('--input and --out are required');
32
+ for (const [key, value, min, max] of [
33
+ ['overview-frames', 48, 1, 96], ['dense-fps', 10, 1, 30],
34
+ ['min-freeze', 0.75, 0.05, 60], ['threshold-db', -55, -120, -1],
35
+ ['purpose-at', 2, 0.05, 600], ['rework-over', 3, 0.05, 600],
36
+ ]) {
37
+ o[key] = Number(o[key] ?? value);
38
+ if (!Number.isFinite(o[key]) || o[key] < min || o[key] > max) throw new Error(`Invalid ${key}: expected ${min}..${max}`);
39
+ }
40
+ if (!Number.isInteger(o['overview-frames'])) throw new Error('overview-frames must be an integer');
41
+ if (o['purpose-at'] > o['rework-over']) throw new Error('purpose-at must not exceed rework-over');
42
+ return o;
43
+ }
44
+
45
+ async function command(executable, args, logPath) {
46
+ const result = await new Promise((resolve, reject) => {
47
+ const proc = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
48
+ let stdout = '', stderr = '', overflow = false;
49
+ const limit = 16 * 1024 * 1024;
50
+ const collect = (kind, chunk) => {
51
+ if (kind === 'out') stdout += chunk.toString('utf8'); else stderr += chunk.toString('utf8');
52
+ if (stdout.length + stderr.length > limit) { overflow = true; proc.kill(); }
53
+ };
54
+ proc.stdout.on('data', b => collect('out', b));
55
+ proc.stderr.on('data', b => collect('err', b));
56
+ proc.on('error', error => reject(new Error(`Cannot run ${executable}: ${error.code ?? error.message}`)));
57
+ proc.on('close', code => resolve({ code, stdout, stderr, overflow }));
58
+ });
59
+ if (logPath) await fs.writeFile(logPath, result.stderr || result.stdout, { encoding: 'utf8', flag: 'wx' });
60
+ if (result.code !== 0 || result.overflow) throw new Error(`${executable} failed (${result.overflow ? 'output limit' : result.code}): ${result.stderr.slice(-1600)}`);
61
+ return result;
62
+ }
63
+
64
+ function rational(value) {
65
+ const [a, b = '1'] = String(value ?? '').split('/').map(Number);
66
+ return Number.isFinite(a / b) && a / b > 0 ? a / b : null;
67
+ }
68
+ const rounded = n => Math.round(n * 1e6) / 1e6;
69
+ const timestamp = n => `${String(Math.floor(n / 60)).padStart(2, '0')}:${(n % 60).toFixed(3).padStart(6, '0')}`;
70
+
71
+ export function parseFreezes(log, duration, { purposeAt = 2, reworkOver = 3 } = {}) {
72
+ let start = null;
73
+ const intervals = [];
74
+ function append(end, closedAtEof) {
75
+ if (start === null) throw new Error('Malformed freeze log: end without start');
76
+ const boundedEnd = Math.min(duration, end);
77
+ if (start < 0 || boundedEnd < start) throw new Error('Malformed freeze interval');
78
+ const seconds = rounded(boundedEnd - start);
79
+ intervals.push({ start: rounded(start), end: rounded(boundedEnd), duration: seconds, closedAtEof,
80
+ review: seconds > reworkOver ? 'default-rework' : seconds >= purposeAt ? 'purpose-review-required' : 'locate-only' });
81
+ start = null;
82
+ }
83
+ for (const match of log.matchAll(/lavfi\.freezedetect\.freeze_(start|end):\s*([-+\d.eE]+)/g)) {
84
+ const value = Number(match[2]);
85
+ if (!Number.isFinite(value)) throw new Error('Malformed freeze timestamp');
86
+ if (match[1] === 'start') {
87
+ if (start !== null) throw new Error('Malformed freeze log: repeated start');
88
+ start = value;
89
+ } else append(value, false);
90
+ }
91
+ if (start !== null) append(duration, true);
92
+ return intervals;
93
+ }
94
+
95
+ async function sha256(filename) {
96
+ const hash = createHash('sha256');
97
+ for await (const chunk of createReadStream(filename)) hash.update(chunk);
98
+ return hash.digest('hex');
99
+ }
100
+ async function json(filename, value) { await fs.writeFile(filename, JSON.stringify(value, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' }); }
101
+
102
+ export function exactFrameFilter(frame) {
103
+ if (!Number.isSafeInteger(frame) || frame < 0) throw new Error('Invalid source frame index');
104
+ return `select=eq(n\\,${frame})`;
105
+ }
106
+
107
+ // Decode-frame PTS, not nominal fps or -ss rounding, is authoritative for selected evidence.
108
+ export function planAuditFrames(report, videoHash, pts, {lastFrameDuration=0}={}) {
109
+ const audit=report.engineeringAudit??report;
110
+ if (!audit.locks?.video?.sha256 || audit.locks.video.sha256!==videoHash) throw new Error('Audit/video hash mismatch or missing binding');
111
+ if (!Array.isArray(pts)||!pts.length||pts.some((t,i)=>!Number.isFinite(t)||(i>0&&t<pts[i-1]))) throw new Error('Invalid decoded frame PTS');
112
+ if (!Number.isFinite(lastFrameDuration)||lastFrameDuration<0) throw new Error('Invalid decoded final-frame duration');
113
+ const risks=[...(audit.motionObservations?.reviewFrames??[])];
114
+ for (const drift of report.gates?.find(g=>g.id===2)?.measured?.fixedDrift ?? []) {
115
+ if (report.locks?.video?.sha256!==videoHash) throw new Error('Fixed-camera measurement/video hash mismatch');
116
+ if (!(Number.isFinite(drift.fps) && drift.fps>0)) throw new Error('Fixed-camera evidence lacks an encoded frame rate');
117
+ for (const frame of drift.reviewFrames) {
118
+ if (!Number.isInteger(frame) || frame<0) throw new Error('Invalid fixed-camera evidence frame');
119
+ risks.push({frame,time:frame/drift.fps,objects:['camera'],reasons:['fixed-camera-drift: '+drift.id]});
120
+ }
121
+ }
122
+ for (const f of audit.findings??[]) for (const time of [f.time,f.start,f.end]) if (Number.isFinite(time)) risks.push({time,reasons:[f.code],objects:[f.objectId].filter(Boolean)});
123
+ if (!risks.length) return [];
124
+ const origin=pts[0],coverageEnd=pts.at(-1)-origin+lastFrameDuration,selected=new Map();
125
+ for (const risk of risks) {
126
+ if (!Number.isFinite(risk.time)||risk.time<0) throw new Error('Invalid audit review time');
127
+ // One microsecond only absorbs FFprobe decimal timestamp rounding. Never trust adapter duration.
128
+ if (risk.time>coverageEnd+1e-6) throw new Error(`Audit review time ${risk.time}s outside decoded video coverage 0..${coverageEnd}s`);
129
+ const target=origin+risk.time;
130
+ let lo=0,hi=pts.length-1;while(lo<hi){const mid=Math.floor((lo+hi)/2);if(pts[mid]<target)lo=mid+1;else hi=mid;}
131
+ const index=lo>0&&Math.abs(pts[lo-1]-target)<=Math.abs(pts[lo]-target)?lo-1:lo;
132
+ const row=selected.get(index)??{sourceFrame:index,sourcePtsSeconds:pts[index],relativeSeconds:pts[index]-origin,requestedTimes:[],requestedProductionFrames:[],objects:[],reasons:[]};
133
+ for (const [key,values] of [['requestedTimes',[risk.time]],['requestedProductionFrames',Number.isInteger(risk.frame)?[risk.frame]:[]],['objects',risk.objects??[]],['reasons',risk.reasons??[]]]) for (const value of values) if(!row[key].includes(value))row[key].push(value);
134
+ selected.set(index,row);
135
+ }
136
+ return [...selected.values()].sort((a,b)=>a.sourceFrame-b.sourceFrame);
137
+ }
138
+
139
+ // The production entry already measured the clip. Decode only its selected
140
+ // evidence in one FFmpeg pass; packet PTS are cheap to read and every chosen
141
+ // timestamp is checked against the decoder before we publish an index.
142
+ export async function extractReviewFrames({input, out, report, ffmpeg = 'ffmpeg', ffprobe = 'ffprobe'}) {
143
+ const audit = report.engineeringAudit ?? report;
144
+ const observations = audit.motionObservations ?? {};
145
+ const reviewFrames = (observations.reviewFrames ?? []).filter(row => row.reasons.some(reason => reason !== 'motion-sample'));
146
+ const findings = (audit.findings ?? []).filter(row => [row.time,row.start,row.end].some(Number.isFinite));
147
+ const drift = report.gates?.find(gate => gate.id === 2)?.measured?.fixedDrift ?? [];
148
+ if (!reviewFrames.length && !findings.length && !drift.length) return {status:'no-targets', count:0};
149
+ const hash = await sha256(input);
150
+ const probe = await command(ffprobe, ['-v','error','-select_streams','v:0','-show_packets','-show_streams',
151
+ '-show_entries','stream=time_base:packet=pts,duration','-of','json', input]);
152
+ const metadata = JSON.parse(probe.stdout);
153
+ const tick = rational(metadata.streams?.[0]?.time_base);
154
+ const packets = (metadata.packets ?? []).sort((a,b) => a.pts-b.pts);
155
+ if (!(tick > 0) || !packets.length || packets.some((p,i) => !Number.isSafeInteger(p.pts) || (i && p.pts === packets[i-1].pts))) {
156
+ throw Error('Unable to resolve distinct video presentation timestamps for risk frames.');
157
+ }
158
+ const pts = packets.map(p => p.pts*tick);
159
+ const risks = {...report, engineeringAudit:{...audit, locks:audit.locks ?? report.locks,
160
+ motionObservations:{...observations,reviewFrames}, findings}};
161
+ const targets = planAuditFrames(risks, hash, pts, {lastFrameDuration:(packets.at(-1).duration ?? 0)*tick});
162
+ const selected = new Map();
163
+ for (const row of targets) {
164
+ for (const n of [row.sourceFrame-1,row.sourceFrame,row.sourceFrame+1]) {
165
+ if (n < 0 || n >= pts.length) continue;
166
+ if (!selected.has(n)) selected.set(n, {sourceFrame:n, sourcePtsSeconds:pts[n], objects:new Set(), reasons:new Set()});
167
+ const entry = selected.get(n);
168
+ row.objects.forEach(id => entry.objects.add(id));
169
+ row.reasons.forEach(reason => entry.reasons.add(reason));
170
+ }
171
+ }
172
+ const frames = [...selected.values()].sort((a,b) => a.sourceFrame-b.sourceFrame);
173
+ if (!frames.length) return {status:'no-targets', count:0};
174
+ await fs.mkdir(out);
175
+ const filter = path.join(out,'select.txt');
176
+ const ranges = [];
177
+ for (const {sourceFrame} of frames) {
178
+ const previous = ranges.at(-1);
179
+ if (previous?.end === sourceFrame-1) previous.end = sourceFrame;
180
+ else ranges.push({start:sourceFrame,end:sourceFrame});
181
+ }
182
+ const terms = ranges.map(({start,end}) => start === end ? `eq(n\\,${start})` : `between(n\\,${start}\\,${end})`);
183
+ await fs.writeFile(filter,'select='+terms.join('+')+',showinfo=checksum=0');
184
+ const rendered = await command(ffmpeg, ['-hide_banner','-nostdin','-nostats','-n','-copyts','-i',input,'-map','0:v:0','-an',
185
+ '-filter_script:v',filter,'-fps_mode','passthrough',path.join(out,'frame-%07d.png')]);
186
+ const base = rendered.stderr.match(/config in time_base:\s*([\d/]+)/);
187
+ const decoderTick = rational(base?.[1]);
188
+ const timestamps = [...rendered.stderr.matchAll(/\bn:\s*\d+\s+pts:\s*(-?\d+)\s+pts_time:/g)].map(match => Number(match[1])*decoderTick);
189
+ if (!(decoderTick > 0) || timestamps.length !== frames.length ||
190
+ frames.some((row,i) => Math.abs(timestamps[i]-row.sourcePtsSeconds) > 1e-7) || await sha256(input) !== hash) {
191
+ throw Error('Decoded frame timestamps or video hash differ from the bound risk selection.');
192
+ }
193
+ const rows = frames.map((row,i) => ({...row,objects:[...row.objects], reasons:[...row.reasons],
194
+ sourcePtsSeconds:timestamps[i], relativeSeconds:timestamps[i]-pts[0], path:'frame-'+String(i+1).padStart(7,'0')+'.png'}));
195
+ const index = path.join(out,'frame-index.json');
196
+ await json(index,{videoSha256:hash, sampling:'original-size decoded frames verified against presentation timestamps',frames:rows});
197
+ const escape = s => String(s).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;');
198
+ const images = rows.map(row => `<figure><a href="${row.path}"><img width="320" src="${row.path}"></a><figcaption>F${row.sourceFrame} · ${timestamp(row.relativeSeconds)} · ${escape(row.objects.join(', '))} · ${escape(row.reasons.join(', '))}</figcaption></figure>`);
199
+ await fs.writeFile(path.join(out,'frames.html'),'<!doctype html><meta charset="utf-8"><title>运动疑点帧</title>'+images.join('\n'),{flag:'wx'});
200
+ return {status:'extracted', count:rows.length, index, gallery:path.join(out,'frames.html')};
201
+ }
202
+
203
+ export async function motionCheck(o) {
204
+ const source = await fs.realpath(path.resolve(o.input));
205
+ const sourceStat = await fs.stat(source);
206
+ if (!sourceStat.isFile() || !sourceStat.size) throw new Error('Input must be a nonempty regular video file');
207
+ const requestedOut = path.resolve(o.out);
208
+ const outputParent = await fs.realpath(path.dirname(requestedOut));
209
+ const out = path.join(outputParent, path.basename(requestedOut));
210
+ try { await fs.lstat(out); throw new Error(`Output already exists; choose a new directory: ${out}`); }
211
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
212
+ const ffmpeg = o.ffmpeg ?? 'ffmpeg', ffprobe = o.ffprobe ?? 'ffprobe';
213
+ const versions = await Promise.all([command(ffmpeg, ['-version']), command(ffprobe, ['-version'])]);
214
+ const probe = await command(ffprobe, ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', source]);
215
+ const metadata = JSON.parse(probe.stdout);
216
+ const video = metadata.streams?.find(s => s.codec_type === 'video' && !s.disposition?.attached_pic);
217
+ if (!video) throw new Error('Input has no playable video stream');
218
+ const duration = Number(video.duration ?? metadata.format?.duration);
219
+ const fps = rational(video.avg_frame_rate) ?? rational(video.r_frame_rate);
220
+ if (!(duration > 0) || !Number.isFinite(duration) || !fps) throw new Error('Video duration/frame rate is unavailable');
221
+ const ranges = o.ranges ? o.ranges.split(',').map((range, i) => {
222
+ const parts = range.split(':');
223
+ if (parts.length !== 2 || parts.some(p => !p.trim())) throw new Error(`Invalid range: ${range}`);
224
+ const [start, end] = parts.map(Number);
225
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start || end > duration) throw new Error(`Range outside video: ${range}`);
226
+ return { id: i + 1, start, end };
227
+ }) : [];
228
+ if (ranges.reduce((n, r) => n + r.end - r.start, 0) > 300) throw new Error('Dense ranges exceed 300 seconds; split the review into separate runs');
229
+ const sourceHash = await sha256(source);
230
+ const auditFile=o.audit?await fs.realpath(path.resolve(o.audit)):null;
231
+ const auditReport=auditFile?JSON.parse(await fs.readFile(auditFile,'utf8')):null;
232
+ const auditHash=auditFile?await sha256(auditFile):null;
233
+ let exactPlan=[],exactCoverage=null;
234
+ if (auditReport) {
235
+ const probeFrames=await command(ffprobe,['-v','error','-select_streams',String(video.index),'-show_frames','-show_entries','frame=best_effort_timestamp_time,duration_time,pkt_duration_time','-of','json',source]);
236
+ const decoded=JSON.parse(probeFrames.stdout).frames,pts=decoded?.map(f=>Number(f.best_effort_timestamp_time));
237
+ const last=decoded?.at(-1),durationField=['duration_time','pkt_duration_time'].find(key=>Number.isFinite(Number(last?.[key]))&&Number(last[key])>0);
238
+ const lastFrameDuration=durationField?Number(last[durationField]):0;
239
+ exactPlan=planAuditFrames(auditReport,sourceHash,pts,{lastFrameDuration});
240
+ exactCoverage={firstPtsSeconds:pts[0],lastPtsSeconds:pts.at(-1),lastFrameDurationSeconds:lastFrameDuration,durationBasis:durationField??'unavailable; coverage ends at final PTS',relativeEndSeconds:pts.at(-1)-pts[0]+lastFrameDuration};
241
+ }
242
+ await fs.mkdir(out); // Atomic exclusive creation protects against races and overwrite.
243
+ const eventPath = path.join(out, 'events.jsonl');
244
+ const started = new Date().toISOString();
245
+ let stage = 'start', logQueue = Promise.resolve(), heartbeat;
246
+ const event = (type, details = {}) => {
247
+ logQueue = logQueue.then(() => fs.appendFile(eventPath, JSON.stringify({ time: new Date().toISOString(), type, stage, ...details }) + '\n', 'utf8'));
248
+ return logQueue;
249
+ };
250
+ const commands = [];
251
+ const run = async (name, args, log = false) => {
252
+ stage = name;
253
+ commands.push({ stage, executable: ffmpeg, args });
254
+ return command(ffmpeg, ['-hide_banner', '-nostdin', '-nostats', '-n', ...args], log ? path.join(out, `${name}.log`) : undefined);
255
+ };
256
+ try {
257
+ await event('start', { source, sourceHash, output: out });
258
+ console.error(`Motion diagnostics started. Status and heartbeat: ${eventPath}`);
259
+ heartbeat = setInterval(() => { event('heartbeat').catch(error => console.error(error.message)); }, 60000);
260
+ await json(path.join(out, 'probe.json'), metadata);
261
+ const filter = `setpts=PTS-STARTPTS,freezedetect=n=${o['threshold-db']}dB:d=${o['min-freeze']}`;
262
+ const detected = await run('freeze', ['-i', source, '-map', `0:${video.index}`, '-an', '-vf', filter, '-f', 'null', '-'], true);
263
+ const freezes = parseFreezes(detected.stderr, duration, { purposeAt: o['purpose-at'], reworkOver: o['rework-over'] });
264
+ const overviewDir = path.join(out, 'overview');
265
+ await fs.mkdir(overviewDir);
266
+ const count = Math.min(o['overview-frames'], Math.max(1, Math.floor(duration * fps)));
267
+ const last = Math.max(0, duration - Math.max(1 / fps, 0.05));
268
+ const overview = [];
269
+ for (let i = 0; i < count; i++) {
270
+ const second = rounded(count === 1 ? 0 : i * last / (count - 1));
271
+ const name = `frame-${String(i + 1).padStart(3, '0')}.jpg`;
272
+ await run(`overview-${i + 1}`, ['-ss', String(second), '-i', source, '-map', `0:${video.index}`, '-an', '-frames:v', '1', '-vf', 'scale=480:-2', '-q:v', '3', path.join(overviewDir, name)]);
273
+ if (!(await fs.stat(path.join(overviewDir, name))).size) throw new Error(`No overview frame at ${second}`);
274
+ overview.push({ frame: i + 1, requestedSourceSecond: second, timestamp: timestamp(second), path: `overview/${name}` });
275
+ }
276
+ await run('overview-sheets', ['-framerate', '1', '-start_number', '1', '-i', path.join(overviewDir, 'frame-%03d.jpg'), '-vf', 'tile=4x4:padding=6:margin=6:color=white', '-frames:v', String(Math.ceil(count / 16)), '-q:v', '3', path.join(out, 'overview-page-%02d.jpg')]);
277
+ const dense = [];
278
+ for (const range of ranges) {
279
+ const relative = `dense-${String(range.id).padStart(2, '0')}`, folder = path.join(out, relative);
280
+ await fs.mkdir(folder);
281
+ await run(relative, ['-ss', String(range.start), '-i', source, '-map', `0:${video.index}`, '-an', '-t', String(range.end - range.start), '-vf', `fps=${o['dense-fps']},scale=480:-2`, '-q:v', '3', path.join(folder, 'frame-%05d.jpg')]);
282
+ const names = (await fs.readdir(folder)).filter(n => /^frame-\d+\.jpg$/.test(n)).sort();
283
+ if (!names.length) throw new Error(`No frames extracted for range ${range.id}`);
284
+ dense.push({ ...range, frames: names.map((name, i) => ({ frame: i + 1,
285
+ requestedSourceSecond: rounded(range.start + i / o['dense-fps']), timestamp: timestamp(range.start + i / o['dense-fps']), path: `${relative}/${name}` })) });
286
+ }
287
+ const exact=[];
288
+ if (exactPlan.length) {
289
+ const folder=path.join(out,'audit-frames');await fs.mkdir(folder);
290
+ for (const row of exactPlan) {
291
+ const name=`frame-${String(row.sourceFrame).padStart(7,'0')}.png`;
292
+ await run(`audit-frame-${row.sourceFrame}`,['-i',source,'-map',`0:${video.index}`,'-an','-vf',exactFrameFilter(row.sourceFrame),'-frames:v','1','-fps_mode','passthrough',path.join(folder,name)]);
293
+ if (!(await fs.stat(path.join(folder,name))).size) throw new Error('Missing exact decoded frame '+row.sourceFrame);
294
+ exact.push({...row,path:`audit-frames/${name}`,timestamp:timestamp(row.relativeSeconds),frame:row.sourceFrame});
295
+ }
296
+ }
297
+ if (auditFile&&await sha256(auditFile)!==auditHash) throw new Error('Audit report changed during extraction');
298
+ const finishStat = await fs.stat(source);
299
+ if (finishStat.size !== sourceStat.size || finishStat.mtimeMs !== sourceStat.mtimeMs || await sha256(source) !== sourceHash) throw new Error('Source changed during diagnostics; rerun on a stable source');
300
+ const nearStaticSeconds = rounded(freezes.reduce((n, f) => n + f.duration, 0));
301
+ const summary = {
302
+ schemaVersion: 1, status: 'analysis-complete', qualityAssessment: 'not-performed', started, finished: new Date().toISOString(),
303
+ source: { path: source, sha256: sourceHash, bytes: sourceStat.size, videoStream: video.index, width: video.width, height: video.height,
304
+ duration, fps, frameRate: video.avg_frame_rate, audioStreams: metadata.streams.filter(s => s.codec_type === 'audio').length },
305
+ parameters: { minFreezeSeconds: o['min-freeze'], thresholdDb: o['threshold-db'], purposeReviewSeconds: o['purpose-at'], defaultReworkOverSeconds: o['rework-over'], ptsOrigin: 'video-first-frame', overviewFrames: count, denseFps: o['dense-fps'], ranges },
306
+ tools: { ffmpeg: versions[0].stdout.split(/\r?\n/)[0], ffprobe: versions[1].stdout.split(/\r?\n/)[0] },
307
+ freezes, totals: { nearStaticSeconds, nearStaticRatio: rounded(nearStaticSeconds / duration), longestSeconds: Math.max(0, ...freezes.map(f => f.duration)), purposeReviewCount: freezes.filter(f => f.duration >= o['purpose-at']).length, defaultReworkCount: freezes.filter(f => f.duration > o['rework-over']).length },
308
+ evidence: { freezeLog: 'freeze.log', index: 'frame-index.json', overviewPages: Math.ceil(count / 16), denseFrameCount: dense.reduce((n, r) => n + r.frames.length, 0),auditFrameCount:exact.length,...(auditFile?{audit:{path:auditFile,sha256:auditHash,videoAssociation:'sha256-matched',sampling:'decoded-frame-index-and-best-effort-PTS'}}:{}) },
309
+ limitations: ['近静止检测定位疑点,不等于逐像素静止。', `>=${o['purpose-at']}秒需说明阅读/理解用途;>${o['rework-over']}秒标为默认返修疑点。最终按项目DESIGN及必要阅读与实际观看证据判定,门槛可按项目配置。`, '检测不到有效运镜、因果表达或装饰性动作,低静止率也不是质量通过。', '画面须继续做删字、静音、合看及同类样片对标;技术成功不替代真实视听验收。', 'overview/dense图片时间是请求采样时间,不代表源文件精确逐帧PTS;exact审计帧按真实解码帧号抽取,列出实际PTS及原请求秒点。'],
310
+ };
311
+ await json(path.join(out, 'frame-index.json'), { overview, dense, exact, exactCoverage, samplingNote: summary.limitations.at(-1),exactSamplingNote:'exact[] uses source decoded frame index and actual best-effort PTS; production fps/time is only the requested location. Requests beyond decoded PTS plus measured final-frame duration are rejected; the exact EOF boundary maps to the last displayed frame.' });
312
+ await json(path.join(out, 'summary.json'), summary);
313
+ await fs.writeFile(path.join(out, 'summary.txt'), [
314
+ '动态定位完成;未作质量通过判定。', `源文件:${source}`, `SHA256:${sourceHash}`,
315
+ `时长:${duration}s;帧率:${fps};${video.width}×${video.height};音轨:${summary.source.audioStreams}`,
316
+ `参数:minFreeze=${o['min-freeze']}s,threshold=${o['threshold-db']}dB,dense=${o['dense-fps']}fps`,
317
+ `近静止总计 ${nearStaticSeconds}s;最长 ${summary.totals.longestSeconds}s;>${o['rework-over']}s 默认返修疑点 ${summary.totals.defaultReworkCount}处`,
318
+ ...freezes.map(f => `${timestamp(f.start)}–${timestamp(f.end)} | ${f.duration}s | ${f.review}${f.closedAtEof ? ' | closed-at-video-EOF' : ''}`),
319
+ ...summary.limitations, '',
320
+ ].join('\n'), { encoding: 'utf8', flag: 'wx' });
321
+ const escape = value => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('"', '&quot;');
322
+ const html = frames => frames.map(f => `<figure><a href="${escape(f.path)}"><img src="${escape(f.path)}"></a><figcaption>#${f.frame} · ${f.timestamp}${f.sourcePtsSeconds!==undefined?`<br>源PTS ${f.sourcePtsSeconds}s;请求 ${escape(f.requestedTimes.join(', '))}s<br>${escape(f.objects.join(', '))} · ${escape(f.reasons.join(', '))}`:''}</figcaption></figure>`).join('\n');
323
+ await fs.writeFile(path.join(out, 'frames.html'), `<!doctype html><meta charset="utf-8"><title>动态定位帧证据</title><style>body{font:16px sans-serif;background:#eee}section{display:grid;grid-template-columns:repeat(4,minmax(0,1fr))}figure{margin:6px}img{width:100%}figcaption{padding:5px}</style><h1>帧证据:需结合原片审看</h1><p>${escape(summary.limitations.at(-1))}</p>${exact.length?`<h2>审计疑点:真实解码帧(从0计数)</h2><section>${html(exact)}</section>`:''}<h2>全片总览</h2><section>${html(overview)}</section>${dense.map(r => `<h2>${timestamp(r.start)}–${timestamp(r.end)},${o['dense-fps']}fps</h2><section>${html(r.frames)}</section>`).join('\n')}`, { encoding: 'utf8', flag: 'wx' });
324
+ await json(path.join(out, 'commands.json'), commands);
325
+ clearInterval(heartbeat);
326
+ await event('end', { result: 'analysis-complete', qualityAssessment: 'not-performed' });
327
+ return { status: summary.status, output: out, summary: path.join(out, 'summary.json'), totals: summary.totals, qualityAssessment: summary.qualityAssessment };
328
+ } catch (error) {
329
+ clearInterval(heartbeat);
330
+ await event('error', { message: error.message });
331
+ await json(path.join(out, 'error.json'), { error: error.message, stage, source, sourceHash, commands });
332
+ throw error;
333
+ }
334
+ }
335
+
336
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
337
+ try {
338
+ const o = options(process.argv.slice(2));
339
+ if (o.help) console.log(HELP);
340
+ else console.log(JSON.stringify(await motionCheck(o), null, 2));
341
+ } catch (error) {
342
+ console.error(JSON.stringify({ status: 'failed', error: error.message }));
343
+ process.exitCode = 1;
344
+ }
345
+ }