dsh-game-material-master 0.2.0 → 0.3.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.
package/lib/pipeline.js CHANGED
@@ -822,9 +822,294 @@ export async function pollVideosOnce(projectId) {
822
822
  }
823
823
  }
824
824
  // ── 阶段 3:抽帧 ─────────────────────────────────────────────────────────
825
+ /** 手动选帧的候选帧张数。和转圈轴用同一档范围:太少拖不动,太多抽帧变慢。 */
826
+ const WALK_CANDIDATE_DEFAULT = 32;
827
+ /**
828
+ * 把 `outputCount` 个输出帧均匀铺到 `candidateCount` 张候选帧上。
829
+ * 下标用「格心」(第 i 等份的中点),和转圈轴上圆圈的算法一致。
830
+ */
831
+ function evenSlotPicks(outputCount, candidateCount) {
832
+ const total = Math.max(1, candidateCount);
833
+ const count = Math.max(1, outputCount);
834
+ const picks = [];
835
+ for (let i = 0; i < count; i++) {
836
+ picks.push(Math.min(total - 1, Math.max(0, Math.round(((i + 0.5) * total) / count - 0.5))));
837
+ }
838
+ return picks;
839
+ }
840
+ /** 候选帧张数变了之后,按比例换算已经拖过的圆圈,避免下标对不上新条带。 */
841
+ function rescaleSlotPicks(picks, from, to) {
842
+ const ratio = from > 0 ? to / from : 1;
843
+ return picks.map((index) => clampInt(index * ratio, 0, Math.max(0, to - 1)));
844
+ }
845
+ /**
846
+ * 按候选帧缓存,把这个方向的序列帧切出来(绿幕 PNG + raw.bin),再走一遍抠像合成。
847
+ * 拖动圆圈只改下标,不必重新解码视频。
848
+ */
849
+ async function applyWalkPicks(projectId, key) {
850
+ const project = await readProject(projectId);
851
+ if (project === undefined)
852
+ throw new Error(`项目不存在:${projectId}`);
853
+ const candidates = project.frames[key]?.candidates;
854
+ if (candidates?.raw === undefined || (candidates.rawWidth ?? 0) <= 0 || (candidates.rawHeight ?? 0) <= 0) {
855
+ throw new Error("还没有候选帧,请先手动抽取");
856
+ }
857
+ const width = candidates.rawWidth;
858
+ const height = candidates.rawHeight ?? 0;
859
+ const raw = await readFile(assetPath(projectId, candidates.raw));
860
+ const frameBytes = width * height * 4;
861
+ const total = Math.max(0, Math.floor(raw.length / frameBytes));
862
+ if (total === 0)
863
+ throw new Error("候选帧缓存是空的,请重新抽取");
864
+ const outputCount = Math.max(1, project.settings.frameCount);
865
+ const picks = candidates.picks.length === outputCount
866
+ ? candidates.picks.map((index) => clampInt(index, 0, total - 1))
867
+ : evenSlotPicks(outputCount, total);
868
+ const slices = [];
869
+ const framePaths = [];
870
+ for (let slot = 0; slot < picks.length; slot++) {
871
+ const index = picks[slot];
872
+ slices.push(Buffer.from(raw.subarray(index * frameBytes, (index + 1) * frameBytes)));
873
+ framePaths.push(`frames/${key}/f${String(slot).padStart(2, "0")}.png`);
874
+ }
875
+ const rawRelative = `frames/${key}/raw.bin`;
876
+ await mkdir(dirname(assetPath(projectId, rawRelative)), { recursive: true });
877
+ await writeFile(assetPath(projectId, rawRelative), Buffer.concat(slices));
878
+ for (let slot = 0; slot < slices.length; slot++) {
879
+ await writeFile(assetPath(projectId, framePaths[slot]), encodePng(slices[slot], width, height));
880
+ }
881
+ await patchProject(projectId, (current) => {
882
+ const node = current.frames[key];
883
+ current.frames[key] = {
884
+ ...node,
885
+ status: "ready",
886
+ frames: framePaths,
887
+ keyed: [],
888
+ approved: false,
889
+ stale: false,
890
+ error: undefined,
891
+ raw: rawRelative,
892
+ rawWidth: width,
893
+ rawHeight: height,
894
+ rawFrameCount: picks.length,
895
+ duration: candidates.duration,
896
+ updatedAt: Date.now(),
897
+ candidates: node.candidates === undefined ? undefined : { ...node.candidates, picks, status: "ready", stale: false, error: undefined }
898
+ };
899
+ const label = directionOf(key)?.label ?? key;
900
+ log(current, "info", `「${label}」按手动选帧切出 ${picks.length} 帧`);
901
+ });
902
+ await renderSheet(projectId);
903
+ }
904
+ /**
905
+ * 从一个方向的行走视频里抽出候选帧,并按当前圆圈(没有就等分)切成序列帧。
906
+ * 只动这一个方向;其它方向的帧保持原样。
907
+ */
908
+ export async function startFramePick(projectId, key, count) {
909
+ if (directionOf(key) === undefined)
910
+ throw new Error(`未知方向:${key}`);
911
+ const project = await readProject(projectId);
912
+ if (project === undefined)
913
+ throw new Error(`项目不存在:${projectId}`);
914
+ if (project.videos[key]?.file === undefined)
915
+ throw new Error("还没有可抽帧的视频,请先在第 2 步生成视频");
916
+ const requested = clampInt(count ?? project.frames[key]?.candidates?.rawFrameCount ?? WALK_CANDIDATE_DEFAULT, TURN_FRAME_COUNT_MIN, TURN_FRAME_COUNT_MAX);
917
+ const label = directionOf(key)?.label ?? key;
918
+ const taskKey = `frames:pick:${key}`;
919
+ const started = kick(projectId, taskKey, `手动选帧·${label}`, async () => {
920
+ setJobTargets(projectId, taskKey, [key]);
921
+ const fresh = await readProject(projectId);
922
+ if (fresh === undefined)
923
+ throw new Error(`项目不存在:${projectId}`);
924
+ const video = fresh.videos[key];
925
+ if (video?.file === undefined)
926
+ throw new Error("还没有可抽帧的视频,请先在第 2 步生成视频");
927
+ const previous = fresh.frames[key]?.candidates;
928
+ await patchProject(projectId, (current) => {
929
+ const node = current.frames[key];
930
+ current.frames[key] = {
931
+ ...node,
932
+ status: "running",
933
+ error: undefined,
934
+ candidates: {
935
+ status: "running",
936
+ frames: previous?.frames ?? [],
937
+ times: previous?.times ?? [],
938
+ picks: previous?.picks ?? [],
939
+ raw: previous?.raw,
940
+ rawWidth: previous?.rawWidth,
941
+ rawHeight: previous?.rawHeight,
942
+ rawFrameCount: previous?.rawFrameCount,
943
+ duration: previous?.duration,
944
+ strip: previous?.strip,
945
+ error: undefined
946
+ }
947
+ };
948
+ log(current, "info", `开始抽取「${label}」的候选帧:${requested} 张`);
949
+ });
950
+ try {
951
+ const extracted = await extractFrames({
952
+ video: assetPath(projectId, video.file),
953
+ frameCount: requested,
954
+ longEdge: fresh.settings.workingLongEdge,
955
+ cropInset: fresh.settings.cropInset
956
+ });
957
+ const total = extracted.frames.length;
958
+ const outputCount = Math.max(1, fresh.settings.frameCount);
959
+ const picks = previous?.picks !== undefined && previous.picks.length === outputCount && (previous.rawFrameCount ?? 0) > 0
960
+ ? previous.rawFrameCount === total
961
+ ? previous.picks.map((index) => clampInt(index, 0, total - 1))
962
+ : rescaleSlotPicks(previous.picks, previous.rawFrameCount ?? total, total)
963
+ : evenSlotPicks(outputCount, total);
964
+ const rawRelative = `frames/${key}/candidates/raw.bin`;
965
+ await mkdir(dirname(assetPath(projectId, rawRelative)), { recursive: true });
966
+ await writeFile(assetPath(projectId, rawRelative), Buffer.concat(extracted.frames));
967
+ const files = [];
968
+ const times = [];
969
+ for (let i = 0; i < extracted.frames.length; i++) {
970
+ const relative = `frames/${key}/candidates/f${String(i).padStart(2, "0")}.png`;
971
+ await writeFile(assetPath(projectId, relative), encodePng(extracted.frames[i], extracted.width, extracted.height));
972
+ files.push(relative);
973
+ times.push((i * extracted.duration) / Math.max(1, extracted.frames.length));
974
+ }
975
+ const strip = composeSheet([{ key, frames: extracted.frames, width: extracted.width, height: extracted.height }], {
976
+ cellWidth: 96,
977
+ cellHeight: Math.max(24, Math.round((96 * extracted.height) / Math.max(1, extracted.width))),
978
+ frameCount: extracted.frames.length,
979
+ autoCrop: false,
980
+ fillRatio: 1,
981
+ pixelSize: 0,
982
+ fitMode: "stretch",
983
+ bottomMargin: 0
984
+ });
985
+ const stripRelative = `frames/${key}/candidates/strip.png`;
986
+ await writeFile(assetPath(projectId, stripRelative), encodePng(strip.rgba, strip.width, strip.height));
987
+ await patchProject(projectId, (current) => {
988
+ const node = current.frames[key];
989
+ current.frames[key] = {
990
+ ...node,
991
+ candidates: {
992
+ status: "ready",
993
+ frames: files,
994
+ times,
995
+ raw: rawRelative,
996
+ rawWidth: extracted.width,
997
+ rawHeight: extracted.height,
998
+ rawFrameCount: files.length,
999
+ duration: extracted.duration,
1000
+ strip: stripRelative,
1001
+ picks,
1002
+ stale: false,
1003
+ updatedAt: Date.now()
1004
+ }
1005
+ };
1006
+ log(current, "info", `「${label}」候选帧抽取完成:${files.length} 张 / 视频 ${extracted.duration.toFixed(2)} 秒`);
1007
+ });
1008
+ await applyWalkPicks(projectId, key);
1009
+ }
1010
+ catch (error) {
1011
+ const message = messageOf(error);
1012
+ await patchProject(projectId, (current) => {
1013
+ const node = current.frames[key];
1014
+ current.frames[key] = {
1015
+ ...node,
1016
+ status: node.raw === undefined ? "error" : node.status,
1017
+ error: message,
1018
+ candidates: node.candidates === undefined ? undefined : { ...node.candidates, status: "error", error: message }
1019
+ };
1020
+ log(current, "error", `「${label}」手动选帧失败:${message}`);
1021
+ });
1022
+ throw error;
1023
+ }
1024
+ finally {
1025
+ dropJobTarget(projectId, taskKey, key);
1026
+ }
1027
+ });
1028
+ return started ? { started: true } : { started: false, reason: "这个方向正在手动选帧" };
1029
+ }
1030
+ /** 改这个方向某一个输出帧落在哪张候选帧上(圆圈松手时调用)。 */
1031
+ export async function setFramePick(projectId, key, slot, index) {
1032
+ const project = await readProject(projectId);
1033
+ if (project === undefined)
1034
+ throw new Error(`项目不存在:${projectId}`);
1035
+ if (directionOf(key) === undefined)
1036
+ throw new Error(`未知方向:${key}`);
1037
+ const candidates = project.frames[key]?.candidates;
1038
+ const total = candidates?.frames?.length ?? 0;
1039
+ if (total === 0 || candidates?.raw === undefined)
1040
+ throw new Error("还没有候选帧,请先手动抽取");
1041
+ const outputCount = Math.max(1, project.settings.frameCount);
1042
+ const picks = candidates.picks.length === outputCount
1043
+ ? candidates.picks.map((value) => clampInt(value, 0, total - 1))
1044
+ : evenSlotPicks(outputCount, total);
1045
+ const nextSlot = clampInt(slot, 0, outputCount - 1);
1046
+ const nextIndex = clampInt(index, 0, total - 1);
1047
+ const unchanged = candidates.picks.length === outputCount &&
1048
+ candidates.picks[nextSlot] === nextIndex &&
1049
+ project.frames[key]?.status === "ready";
1050
+ picks[nextSlot] = nextIndex;
1051
+ await patchProject(projectId, (current) => {
1052
+ const node = current.frames[key];
1053
+ if (node.candidates !== undefined)
1054
+ node.candidates = { ...node.candidates, picks: [...picks] };
1055
+ });
1056
+ if (!unchanged)
1057
+ await applyWalkPicks(projectId, key);
1058
+ return { slot: nextSlot, index: nextIndex, changed: !unchanged, picks };
1059
+ }
1060
+ /** 一次写回这个方向的全部圆圈。长度必须等于「每段视频抽帧数」,整图才是整齐的格子。 */
1061
+ export async function setFramePicks(projectId, key, picks) {
1062
+ const project = await readProject(projectId);
1063
+ if (project === undefined)
1064
+ throw new Error(`项目不存在:${projectId}`);
1065
+ if (directionOf(key) === undefined)
1066
+ throw new Error(`未知方向:${key}`);
1067
+ const total = project.frames[key]?.candidates?.frames?.length ?? 0;
1068
+ if (total === 0)
1069
+ throw new Error("还没有候选帧,请先手动抽取");
1070
+ const outputCount = Math.max(1, project.settings.frameCount);
1071
+ if (picks.length !== outputCount) {
1072
+ throw new Error(`这一方向要选 ${outputCount} 帧(与「每段视频抽帧数」一致),收到 ${picks.length} 个位置`);
1073
+ }
1074
+ const next = picks.map((value) => {
1075
+ if (!Number.isFinite(Number(value)))
1076
+ throw new Error("截帧位置必须是数字");
1077
+ return clampInt(Number(value), 0, total - 1);
1078
+ });
1079
+ await patchProject(projectId, (current) => {
1080
+ const node = current.frames[key];
1081
+ if (node.candidates !== undefined)
1082
+ node.candidates = { ...node.candidates, picks: next };
1083
+ });
1084
+ await applyWalkPicks(projectId, key);
1085
+ return { picks: next };
1086
+ }
1087
+ /** 把这个方向的圆圈放回等分位置,并按新位置重切序列帧。 */
1088
+ export async function resetFramePicks(projectId, key) {
1089
+ const project = await readProject(projectId);
1090
+ if (project === undefined)
1091
+ throw new Error(`项目不存在:${projectId}`);
1092
+ if (directionOf(key) === undefined)
1093
+ throw new Error(`未知方向:${key}`);
1094
+ const total = project.frames[key]?.candidates?.frames?.length ?? 0;
1095
+ if (total === 0)
1096
+ throw new Error("还没有候选帧,请先手动抽取");
1097
+ const picks = evenSlotPicks(Math.max(1, project.settings.frameCount), total);
1098
+ await patchProject(projectId, (current) => {
1099
+ const node = current.frames[key];
1100
+ if (node.candidates !== undefined)
1101
+ node.candidates = { ...node.candidates, picks };
1102
+ const label = directionOf(key)?.label ?? key;
1103
+ log(current, "info", `「${label}」的选帧圆圈已回到等分位置`);
1104
+ });
1105
+ await applyWalkPicks(projectId, key);
1106
+ return { picks };
1107
+ }
825
1108
  /**
826
1109
  * 抽取序列帧。`keys` 是要抽的方向;省略则按「有视频的方向」全抽。
827
1110
  * 调用方(`runFrames`)已经把没有视频的方向滤掉了,这里再滤一次兜底。
1111
+ *
1112
+ * 这条路按时长等分,会清掉该方向上一次的手动选帧。要逐帧挑位置,走 `startFramePick`。
828
1113
  */
829
1114
  export function startExtract(projectId, keys) {
830
1115
  const started = kick(projectId, "frames:extract", "抽取序列帧", async () => {
package/lib/store.js CHANGED
@@ -246,7 +246,8 @@ function normalizeProject(raw) {
246
246
  frames: Array.isArray(node.frames) ? node.frames.map(String) : [],
247
247
  keyed: Array.isArray(node.keyed) ? node.keyed.map(String) : [],
248
248
  approved: node.approved === true,
249
- stale: node.stale === true
249
+ stale: node.stale === true,
250
+ candidates: normalizeFrameCandidates(node.candidates)
250
251
  };
251
252
  }
252
253
  }
@@ -303,6 +304,25 @@ function num(value, fallback) {
303
304
  const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
304
305
  return Number.isFinite(n) ? n : fallback;
305
306
  }
307
+ function normalizeFrameCandidates(raw) {
308
+ if (raw === null || typeof raw !== "object")
309
+ return undefined;
310
+ return {
311
+ status: raw.status ?? "empty",
312
+ frames: Array.isArray(raw.frames) ? raw.frames.map(String) : [],
313
+ times: Array.isArray(raw.times) ? raw.times.map((value) => num(value, 0)) : [],
314
+ raw: typeof raw.raw === "string" ? raw.raw : undefined,
315
+ rawWidth: typeof raw.rawWidth === "number" ? raw.rawWidth : undefined,
316
+ rawHeight: typeof raw.rawHeight === "number" ? raw.rawHeight : undefined,
317
+ rawFrameCount: typeof raw.rawFrameCount === "number" ? raw.rawFrameCount : undefined,
318
+ duration: typeof raw.duration === "number" ? raw.duration : undefined,
319
+ strip: typeof raw.strip === "string" ? raw.strip : undefined,
320
+ picks: Array.isArray(raw.picks) ? raw.picks.map((value) => Math.max(0, Math.round(num(value, 0)))) : [],
321
+ error: typeof raw.error === "string" ? raw.error : undefined,
322
+ stale: raw.stale === true,
323
+ updatedAt: typeof raw.updatedAt === "number" ? raw.updatedAt : undefined
324
+ };
325
+ }
306
326
  function clampIntSetting(value, fallback, min, max) {
307
327
  return Math.min(max, Math.max(min, Math.round(num(value, fallback))));
308
328
  }