@effectnode/media 0.1.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 (133) hide show
  1. package/bin/effectnode-media +2 -0
  2. package/dist/backend/index.d.ts +8 -0
  3. package/dist/backend/index.js +13 -0
  4. package/dist/backend/movie-backend/agent/agent-backend.d.ts +16 -0
  5. package/dist/backend/movie-backend/agent/agent-backend.js +703 -0
  6. package/dist/backend/movie-backend/agent/storyprompt.d.ts +1 -0
  7. package/dist/backend/movie-backend/agent/storyprompt.js +90 -0
  8. package/dist/backend/movie-backend/agent/tools/edit-image.d.ts +3 -0
  9. package/dist/backend/movie-backend/agent/tools/edit-image.js +192 -0
  10. package/dist/backend/movie-backend/agent/tools/get-time.d.ts +3 -0
  11. package/dist/backend/movie-backend/agent/tools/get-time.js +7 -0
  12. package/dist/backend/movie-backend/agent/tools/grep-files.d.ts +3 -0
  13. package/dist/backend/movie-backend/agent/tools/grep-files.js +59 -0
  14. package/dist/backend/movie-backend/agent/tools/image-to-video-generation.d.ts +3 -0
  15. package/dist/backend/movie-backend/agent/tools/image-to-video-generation.js +160 -0
  16. package/dist/backend/movie-backend/agent/tools/index.d.ts +7 -0
  17. package/dist/backend/movie-backend/agent/tools/index.js +59 -0
  18. package/dist/backend/movie-backend/agent/tools/list-files.d.ts +3 -0
  19. package/dist/backend/movie-backend/agent/tools/list-files.js +17 -0
  20. package/dist/backend/movie-backend/agent/tools/read-file.d.ts +3 -0
  21. package/dist/backend/movie-backend/agent/tools/read-file.js +28 -0
  22. package/dist/backend/movie-backend/agent/tools/remove-file.d.ts +3 -0
  23. package/dist/backend/movie-backend/agent/tools/remove-file.js +22 -0
  24. package/dist/backend/movie-backend/agent/tools/rename-file.d.ts +3 -0
  25. package/dist/backend/movie-backend/agent/tools/rename-file.js +37 -0
  26. package/dist/backend/movie-backend/agent/tools/show-image.d.ts +3 -0
  27. package/dist/backend/movie-backend/agent/tools/show-image.js +28 -0
  28. package/dist/backend/movie-backend/agent/tools/stitch-videos.d.ts +3 -0
  29. package/dist/backend/movie-backend/agent/tools/stitch-videos.js +96 -0
  30. package/dist/backend/movie-backend/agent/tools/text-to-video-generation.d.ts +3 -0
  31. package/dist/backend/movie-backend/agent/tools/text-to-video-generation.js +125 -0
  32. package/dist/backend/movie-backend/agent/tools/types.d.ts +15 -0
  33. package/dist/backend/movie-backend/agent/tools/types.js +1 -0
  34. package/dist/backend/movie-backend/agent/tools/update-file.d.ts +3 -0
  35. package/dist/backend/movie-backend/agent/tools/update-file.js +27 -0
  36. package/dist/backend/movie-backend/agent/tools/write-file.d.ts +3 -0
  37. package/dist/backend/movie-backend/agent/tools/write-file.js +26 -0
  38. package/dist/backend/movie-backend/agent/workspace.d.ts +25 -0
  39. package/dist/backend/movie-backend/agent/workspace.js +124 -0
  40. package/dist/backend/movie-backend/core.d.ts +4 -0
  41. package/dist/backend/movie-backend/core.js +1167 -0
  42. package/dist/backend/movie-backend/generation-queue.d.ts +24 -0
  43. package/dist/backend/movie-backend/generation-queue.js +766 -0
  44. package/dist/backend/movie-backend/process.d.ts +21 -0
  45. package/dist/backend/movie-backend/process.js +98 -0
  46. package/dist/backend/movie-backend/render-media.d.ts +48 -0
  47. package/dist/backend/movie-backend/render-media.js +3311 -0
  48. package/dist/backend/routes/health.d.ts +1 -0
  49. package/dist/backend/routes/health.js +9 -0
  50. package/dist/backend/routes/index.d.ts +1 -0
  51. package/dist/backend/routes/index.js +11 -0
  52. package/dist/backend/routes/media.d.ts +1 -0
  53. package/dist/backend/routes/media.js +13 -0
  54. package/dist/backend/routes/projects.d.ts +8 -0
  55. package/dist/backend/routes/projects.js +68 -0
  56. package/dist/backend/routes/voice.d.ts +1 -0
  57. package/dist/backend/routes/voice.js +39 -0
  58. package/dist/backend/routes.d.ts +1 -0
  59. package/dist/backend/routes.js +20 -0
  60. package/dist/backend/server.d.ts +1 -0
  61. package/dist/backend/server.js +23 -0
  62. package/dist/backend/workspace.d.ts +5 -0
  63. package/dist/backend/workspace.js +27 -0
  64. package/dist/backend/ws/index.d.ts +3 -0
  65. package/dist/backend/ws/index.js +27 -0
  66. package/dist/backend/ws/messages.d.ts +8 -0
  67. package/dist/backend/ws/messages.js +21 -0
  68. package/dist/backend/ws.d.ts +3 -0
  69. package/dist/backend/ws.js +29 -0
  70. package/dist/index.d.ts +2 -0
  71. package/dist/index.js +80 -0
  72. package/frontend/index.html +22 -0
  73. package/frontend/public/ffmpeg/ffmpeg-core.js +16 -0
  74. package/frontend/public/ffmpeg/ffmpeg-core.wasm +0 -0
  75. package/frontend/src/index.css +46 -0
  76. package/frontend/src/main.tsx +13 -0
  77. package/frontend/src/movie-app/AppRouter.tsx +14 -0
  78. package/frontend/src/movie-app/MediaStudio.tsx +9 -0
  79. package/frontend/src/movie-app/SetupPage.tsx +293 -0
  80. package/frontend/src/movie-app/components/AgentWorkspace.tsx +574 -0
  81. package/frontend/src/movie-app/components/ChatUI/ChatUI.tsx +655 -0
  82. package/frontend/src/movie-app/components/ChatUI/MarkdownMessage.tsx +267 -0
  83. package/frontend/src/movie-app/components/EditorTabs/AgentTab.tsx +61 -0
  84. package/frontend/src/movie-app/components/EditorTabs/BatchImageToVideoTab.tsx +927 -0
  85. package/frontend/src/movie-app/components/EditorTabs/BatchVideoTab.tsx +777 -0
  86. package/frontend/src/movie-app/components/EditorTabs/BatchVoiceVideoTab.tsx +913 -0
  87. package/frontend/src/movie-app/components/EditorTabs/CharacterSheet.tsx +234 -0
  88. package/frontend/src/movie-app/components/EditorTabs/CharactersTab.tsx +664 -0
  89. package/frontend/src/movie-app/components/EditorTabs/CropTool.tsx +251 -0
  90. package/frontend/src/movie-app/components/EditorTabs/ExtendVideoTab.tsx +305 -0
  91. package/frontend/src/movie-app/components/EditorTabs/ExtractImageTab.tsx +249 -0
  92. package/frontend/src/movie-app/components/EditorTabs/FastImageEditTab.tsx +555 -0
  93. package/frontend/src/movie-app/components/EditorTabs/GenerateVideoTab.tsx +722 -0
  94. package/frontend/src/movie-app/components/EditorTabs/LlmServerTab.tsx +40 -0
  95. package/frontend/src/movie-app/components/EditorTabs/MlxVlmServerPanel.tsx +490 -0
  96. package/frontend/src/movie-app/components/EditorTabs/MovieStudioTab.tsx +938 -0
  97. package/frontend/src/movie-app/components/EditorTabs/ReferencesToVideoTab.tsx +881 -0
  98. package/frontend/src/movie-app/components/EditorTabs/SceneVisualTab.tsx +267 -0
  99. package/frontend/src/movie-app/components/EditorTabs/StoryWriterTab.tsx +51 -0
  100. package/frontend/src/movie-app/components/EditorTabs/TaskQueuePanel.tsx +246 -0
  101. package/frontend/src/movie-app/components/EditorTabs/TerminalLogPanel.tsx +49 -0
  102. package/frontend/src/movie-app/components/EditorTabs/TextToImageTab.tsx +574 -0
  103. package/frontend/src/movie-app/components/EditorTabs/VoiceChatPanel.tsx +320 -0
  104. package/frontend/src/movie-app/components/ProjectEditorPage.tsx +636 -0
  105. package/frontend/src/movie-app/components/ProjectManager.tsx +381 -0
  106. package/frontend/src/movie-app/index.css +46 -0
  107. package/frontend/src/movie-app/index.html +16 -0
  108. package/frontend/src/movie-app/lambobo.png +0 -0
  109. package/frontend/src/movie-app/lib/batchImageToVideoStorage.ts +69 -0
  110. package/frontend/src/movie-app/lib/batchVideoStorage.ts +68 -0
  111. package/frontend/src/movie-app/lib/batchVoiceStorage.ts +75 -0
  112. package/frontend/src/movie-app/lib/ffmpeg.ts +42 -0
  113. package/frontend/src/movie-app/lib/referencesToVideoStorage.ts +64 -0
  114. package/frontend/src/movie-app/lib/textToImageStorage.ts +61 -0
  115. package/frontend/src/movie-app/public/ffmpeg/ffmpeg-core.js +16 -0
  116. package/frontend/src/movie-app/public/ffmpeg/ffmpeg-core.wasm +0 -0
  117. package/frontend/src/movie-app/stores/batchImageToVideoStore.ts +736 -0
  118. package/frontend/src/movie-app/stores/batchVideoStore.ts +670 -0
  119. package/frontend/src/movie-app/stores/batchVoiceStore.ts +990 -0
  120. package/frontend/src/movie-app/stores/characterStore.ts +109 -0
  121. package/frontend/src/movie-app/stores/chatStore.ts +459 -0
  122. package/frontend/src/movie-app/stores/generationStore.ts +2140 -0
  123. package/frontend/src/movie-app/stores/logStore.ts +25 -0
  124. package/frontend/src/movie-app/stores/movieStudioStore.ts +709 -0
  125. package/frontend/src/movie-app/stores/projectStore.ts +124 -0
  126. package/frontend/src/movie-app/stores/queueStore.ts +214 -0
  127. package/frontend/src/movie-app/stores/referencesToVideoStore.ts +467 -0
  128. package/frontend/src/movie-app/stores/sceneVisualStore.ts +251 -0
  129. package/frontend/src/movie-app/stores/voiceChatStore.ts +170 -0
  130. package/frontend/src/movie-app/stores/workspaceStore.ts +158 -0
  131. package/frontend/src/vite-env.d.ts +1 -0
  132. package/frontend/tsconfig.json +19 -0
  133. package/package.json +65 -0
@@ -0,0 +1,670 @@
1
+ import { create } from "zustand";
2
+ import type {
3
+ AspectRatio,
4
+ Resolution,
5
+ VideoMode,
6
+ ProjectImage,
7
+ } from "./generationStore";
8
+ import { loadFFmpeg } from "../lib/ffmpeg";
9
+ import {
10
+ clearBatchVideoState,
11
+ loadBatchVideoState,
12
+ saveBatchVideoState,
13
+ type PersistedBatchVideoState,
14
+ } from "../lib/batchVideoStorage";
15
+
16
+ const API_BASE = `http://localhost:${(window as any).PORT}`;
17
+
18
+ export type BatchRowStatus =
19
+ | "idle"
20
+ | "uploading"
21
+ | "generating"
22
+ | "done"
23
+ | "error";
24
+
25
+ export interface BatchVideoRow {
26
+ id: string;
27
+ prompt: string;
28
+ imagePath: string | null;
29
+ imageUrl: string | null;
30
+ imageFilename: string | null;
31
+ status: BatchRowStatus;
32
+ result: string | null;
33
+ error: string | null;
34
+ logs: string[];
35
+ }
36
+
37
+ interface BatchVideoStore {
38
+ // Rows
39
+ rows: BatchVideoRow[];
40
+
41
+ // Shared generation settings
42
+ duration: number;
43
+ aspectRatio: AspectRatio;
44
+ resolution: Resolution;
45
+ mode: VideoMode;
46
+
47
+ // Batch generation state
48
+ running: boolean;
49
+ progress: { current: number; total: number } | null;
50
+ cancelRequested: boolean;
51
+ logs: string[];
52
+
53
+ // Stitching state
54
+ stitching: boolean;
55
+ stitchLogs: string[];
56
+ stitchResult: string | null;
57
+ stitchError: string | null;
58
+
59
+ // Persistence
60
+ projectId: string | null;
61
+ hydrated: boolean;
62
+ hydrate: (projectId: string) => Promise<void>;
63
+ clear: () => void;
64
+
65
+ addRow: () => void;
66
+ removeRow: (id: string) => void;
67
+ updatePrompt: (id: string, prompt: string) => void;
68
+ clearRowResult: (id: string) => void;
69
+ uploadRowImage: (
70
+ id: string,
71
+ base64: string,
72
+ filename: string | undefined,
73
+ projectId: string,
74
+ ) => Promise<string | null>;
75
+ setRowImage: (id: string, image: ProjectImage) => void;
76
+
77
+ setDuration: (v: number) => void;
78
+ setAspectRatio: (v: AspectRatio) => void;
79
+ setResolution: (v: Resolution) => void;
80
+ setMode: (v: VideoMode) => void;
81
+
82
+ generateRows: (projectId: string, ids: string[]) => Promise<void>;
83
+ generateRow: (projectId: string, id: string) => Promise<void>;
84
+ generateAll: (projectId: string) => Promise<void>;
85
+ cancel: () => void;
86
+
87
+ stitchVideos: () => Promise<void>;
88
+
89
+ reset: () => void;
90
+ }
91
+
92
+ let batchAbortController: AbortController | null = null;
93
+
94
+ function getDimensions(
95
+ aspect: AspectRatio,
96
+ resolution: Resolution,
97
+ ): { width: number; height: number } {
98
+ const size = parseInt(resolution);
99
+ switch (aspect) {
100
+ case "1:1":
101
+ return { width: size, height: size };
102
+ case "16:9":
103
+ return { width: Math.round((size * 16) / 9), height: size };
104
+ case "9:16":
105
+ return { width: size, height: Math.round((size * 16) / 9) };
106
+ case "4:3":
107
+ return { width: Math.round((size * 4) / 3), height: size };
108
+ case "3:4":
109
+ return { width: size, height: Math.round((size * 4) / 3) };
110
+ }
111
+ }
112
+
113
+ // The image-to-video backend only accepts a bare filename, so normalise any
114
+ // uploaded path / file URL / api-files URL down to just the basename.
115
+ function normalizeImagePath(path: string): string {
116
+ let p = path;
117
+ if (p.includes("/api/files?path=")) {
118
+ try {
119
+ const url = new URL(p);
120
+ p = url.searchParams.get("path") || p;
121
+ } catch {
122
+ // not a valid URL, use as-is
123
+ }
124
+ }
125
+ if (p.startsWith("file://")) {
126
+ p = p.slice(7);
127
+ }
128
+ return p.split("/").pop() || p;
129
+ }
130
+
131
+ async function readSSEStream(
132
+ response: Response,
133
+ onEvent: (event: string, data: any) => void,
134
+ ): Promise<void> {
135
+ const reader = response.body?.getReader();
136
+ if (!reader) return;
137
+
138
+ const decoder = new TextDecoder();
139
+ let buffer = "";
140
+
141
+ try {
142
+ while (true) {
143
+ const { done, value } = await reader.read();
144
+ if (done) break;
145
+
146
+ buffer += decoder.decode(value, { stream: true });
147
+ const lines = buffer.split("\n");
148
+ buffer = lines.pop() || "";
149
+
150
+ let eventType = "message";
151
+ for (const line of lines) {
152
+ if (line.startsWith("event: ")) {
153
+ eventType = line.slice(7).trim();
154
+ } else if (line.startsWith("data: ")) {
155
+ try {
156
+ onEvent(eventType, JSON.parse(line.slice(6)));
157
+ } catch {
158
+ // skip malformed lines
159
+ }
160
+ eventType = "message";
161
+ }
162
+ }
163
+ }
164
+ } finally {
165
+ reader.releaseLock();
166
+ }
167
+ }
168
+
169
+ function playBeep() {
170
+ try {
171
+ const ctx = new (
172
+ window.AudioContext || (window as any).webkitAudioContext
173
+ )();
174
+ const osc = ctx.createOscillator();
175
+ const gain = ctx.createGain();
176
+ osc.connect(gain);
177
+ gain.connect(ctx.destination);
178
+ osc.type = "sine";
179
+ osc.frequency.setValueAtTime(880, ctx.currentTime);
180
+ gain.gain.setValueAtTime(0.3, ctx.currentTime);
181
+ gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.4);
182
+ osc.start(ctx.currentTime);
183
+ osc.stop(ctx.currentTime + 0.4);
184
+ } catch {
185
+ // silently ignore if audio not available
186
+ }
187
+ }
188
+
189
+ function makeRow(): BatchVideoRow {
190
+ return {
191
+ id: `row-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
192
+ prompt: "",
193
+ imagePath: null,
194
+ imageUrl: null,
195
+ imageFilename: null,
196
+ status: "idle",
197
+ result: null,
198
+ error: null,
199
+ logs: [],
200
+ };
201
+ }
202
+
203
+ function toPersistedState(
204
+ s: Pick<
205
+ BatchVideoStore,
206
+ "rows" | "duration" | "aspectRatio" | "resolution" | "mode"
207
+ >,
208
+ ): PersistedBatchVideoState {
209
+ return {
210
+ rows: s.rows.map((r) => ({
211
+ id: r.id,
212
+ prompt: r.prompt,
213
+ imagePath: r.imagePath,
214
+ imageUrl: r.imageUrl,
215
+ imageFilename: r.imageFilename,
216
+ })),
217
+ duration: s.duration,
218
+ aspectRatio: s.aspectRatio,
219
+ resolution: s.resolution,
220
+ mode: s.mode,
221
+ };
222
+ }
223
+
224
+ // Fire-and-forget save of the current editable UI state.
225
+ function persistBatchState() {
226
+ const { projectId } = useBatchVideoStore.getState();
227
+ if (!projectId) return;
228
+ void saveBatchVideoState(projectId, toPersistedState(useBatchVideoStore.getState()));
229
+ }
230
+
231
+ export const useBatchVideoStore = create<BatchVideoStore>((set, get) => ({
232
+ rows: [makeRow()],
233
+
234
+ duration: 5,
235
+ aspectRatio: "1:1",
236
+ resolution: "480p",
237
+ mode: "distilled",
238
+
239
+ running: false,
240
+ progress: null,
241
+ cancelRequested: false,
242
+ logs: [],
243
+
244
+ stitching: false,
245
+ stitchLogs: [],
246
+ stitchResult: null,
247
+ stitchError: null,
248
+
249
+ projectId: null,
250
+ hydrated: false,
251
+
252
+ hydrate: async (projectId) => {
253
+ // No-op if we've already hydrated for this project.
254
+ if (get().hydrated && get().projectId === projectId) return;
255
+
256
+ // Switching to a different project: reset to defaults so rows and
257
+ // settings from the previous project don't leak through.
258
+ const previous = get().projectId;
259
+ if (previous !== null && previous !== projectId) {
260
+ get().reset();
261
+ }
262
+ set({ hydrated: true, projectId });
263
+
264
+ const stored = await loadBatchVideoState(projectId);
265
+ if (!stored) return;
266
+
267
+ set((s) => {
268
+ const rows: BatchVideoRow[] = (stored.rows ?? []).map((r) => ({
269
+ id: r.id,
270
+ prompt: r.prompt,
271
+ imagePath: r.imagePath,
272
+ imageUrl: r.imageUrl,
273
+ imageFilename: r.imageFilename,
274
+ status: "idle",
275
+ result: null,
276
+ error: null,
277
+ logs: [],
278
+ }));
279
+
280
+ return {
281
+ rows: rows.length > 0 ? rows : [makeRow()],
282
+ duration: stored.duration ?? s.duration,
283
+ aspectRatio: stored.aspectRatio ?? s.aspectRatio,
284
+ resolution: stored.resolution ?? s.resolution,
285
+ mode: stored.mode ?? s.mode,
286
+ };
287
+ });
288
+ },
289
+
290
+ clear: () => {
291
+ const { projectId } = get();
292
+ get().reset();
293
+ if (projectId) void clearBatchVideoState(projectId);
294
+ },
295
+
296
+ addRow: () => {
297
+ set((s) => ({ rows: [...s.rows, makeRow()] }));
298
+ persistBatchState();
299
+ },
300
+
301
+ removeRow: (id) => {
302
+ set((s) => ({ rows: s.rows.filter((r) => r.id !== id) }));
303
+ persistBatchState();
304
+ },
305
+
306
+ updatePrompt: (id, prompt) => {
307
+ set((s) => ({
308
+ rows: s.rows.map((r) => (r.id === id ? { ...r, prompt } : r)),
309
+ }));
310
+ persistBatchState();
311
+ },
312
+
313
+ clearRowResult: (id) =>
314
+ set((s) => ({
315
+ rows: s.rows.map((r) =>
316
+ r.id === id ? { ...r, result: null, error: null, status: "idle" } : r,
317
+ ),
318
+ })),
319
+
320
+ uploadRowImage: async (id, base64, filename, projectId) => {
321
+ set((s) => ({
322
+ rows: s.rows.map((r) =>
323
+ r.id === id ? { ...r, status: "uploading" } : r,
324
+ ),
325
+ }));
326
+
327
+ try {
328
+ const res = await fetch(`${API_BASE}/api/upload/image`, {
329
+ method: "POST",
330
+ headers: { "Content-Type": "application/json" },
331
+ body: JSON.stringify({
332
+ image: base64,
333
+ filename: filename || `upload-${Date.now()}.png`,
334
+ projectId,
335
+ }),
336
+ });
337
+
338
+ if (!res.ok) {
339
+ const err = await res.text();
340
+ set((s) => ({
341
+ rows: s.rows.map((r) =>
342
+ r.id === id ? { ...r, status: "error", error: err } : r,
343
+ ),
344
+ }));
345
+ return null;
346
+ }
347
+
348
+ const data = await res.json();
349
+ const url = `http://localhost:${(window as any).PORT}/api/files?path=${encodeURIComponent(data.path)}`;
350
+ set((s) => ({
351
+ rows: s.rows.map((r) =>
352
+ r.id === id
353
+ ? {
354
+ ...r,
355
+ status: "idle",
356
+ imagePath: data.path,
357
+ imageUrl: url,
358
+ imageFilename: data.filename,
359
+ }
360
+ : r,
361
+ ),
362
+ }));
363
+ persistBatchState();
364
+ return data.path as string;
365
+ } catch (e) {
366
+ set((s) => ({
367
+ rows: s.rows.map((r) =>
368
+ r.id === id ? { ...r, status: "error", error: String(e) } : r,
369
+ ),
370
+ }));
371
+ return null;
372
+ }
373
+ },
374
+
375
+ setRowImage: (id, image) => {
376
+ set((s) => ({
377
+ rows: s.rows.map((r) =>
378
+ r.id === id
379
+ ? {
380
+ ...r,
381
+ imagePath: image.url,
382
+ imageUrl: image.url,
383
+ imageFilename: image.filename,
384
+ status: "idle",
385
+ error: null,
386
+ }
387
+ : r,
388
+ ),
389
+ }));
390
+ persistBatchState();
391
+ },
392
+
393
+ setDuration: (duration) => {
394
+ set({ duration });
395
+ persistBatchState();
396
+ },
397
+ setAspectRatio: (aspectRatio) => {
398
+ set({ aspectRatio });
399
+ persistBatchState();
400
+ },
401
+ setResolution: (resolution) => {
402
+ set({ resolution });
403
+ persistBatchState();
404
+ },
405
+ setMode: (mode) => {
406
+ set({ mode });
407
+ persistBatchState();
408
+ },
409
+
410
+ generateRows: async (projectId, ids) => {
411
+ if (get().running) return;
412
+
413
+ const rows = get().rows;
414
+ const targets = ids
415
+ .map((id) => rows.find((r) => r.id === id))
416
+ .filter((r): r is BatchVideoRow => !!r)
417
+ .filter((r) => r.prompt.trim() && r.imagePath);
418
+
419
+ if (targets.length === 0) return;
420
+
421
+ const { duration, aspectRatio, resolution, mode } = get();
422
+ const { width, height } = getDimensions(aspectRatio, resolution);
423
+
424
+ batchAbortController = new AbortController();
425
+ const signal = batchAbortController.signal;
426
+
427
+ set({
428
+ running: true,
429
+ progress: { current: 0, total: targets.length },
430
+ cancelRequested: false,
431
+ logs: [],
432
+ });
433
+
434
+ let cancelled = false;
435
+
436
+ for (let i = 0; i < targets.length; i++) {
437
+ if (get().cancelRequested) {
438
+ cancelled = true;
439
+ break;
440
+ }
441
+
442
+ const row = targets[i];
443
+ const imagePath = normalizeImagePath(row.imagePath!);
444
+
445
+ set((s) => ({
446
+ progress: { current: i + 1, total: targets.length },
447
+ rows: s.rows.map((r) =>
448
+ r.id === row.id
449
+ ? { ...r, status: "generating", error: null, logs: [] }
450
+ : r,
451
+ ),
452
+ logs: [
453
+ ...s.logs,
454
+ `[${i + 1}/${targets.length}] Generating: ${row.prompt.trim().slice(0, 80)}`,
455
+ ],
456
+ }));
457
+
458
+ try {
459
+ const res = await fetch(`${API_BASE}/api/render/image-to-video`, {
460
+ method: "POST",
461
+ headers: { "Content-Type": "application/json" },
462
+ body: JSON.stringify({
463
+ prompt: row.prompt.trim(),
464
+ imagePath,
465
+ projectId,
466
+ width,
467
+ height,
468
+ frames: duration * 24 + 1,
469
+ frameRate: 24,
470
+ mode,
471
+ }),
472
+ signal,
473
+ });
474
+
475
+ if (!res.ok) {
476
+ const err = await res.text();
477
+ set((s) => ({
478
+ rows: s.rows.map((r) =>
479
+ r.id === row.id ? { ...r, status: "error", error: err } : r,
480
+ ),
481
+ }));
482
+ continue;
483
+ }
484
+
485
+ await readSSEStream(res, (event, data) => {
486
+ switch (event) {
487
+ case "log":
488
+ set((s) => ({
489
+ rows: s.rows.map((r) =>
490
+ r.id === row.id
491
+ ? { ...r, logs: [...r.logs, data.text as string] }
492
+ : r,
493
+ ),
494
+ logs: [...s.logs, data.text as string],
495
+ }));
496
+ break;
497
+ case "complete":
498
+ set((s) => ({
499
+ rows: s.rows.map((r) =>
500
+ r.id === row.id
501
+ ? {
502
+ ...r,
503
+ status: "done",
504
+ result: `http://localhost:${(window as any).PORT}/api/files?path=${encodeURIComponent(data.path)}`,
505
+ }
506
+ : r,
507
+ ),
508
+ }));
509
+ break;
510
+ case "error":
511
+ set((s) => ({
512
+ rows: s.rows.map((r) =>
513
+ r.id === row.id
514
+ ? {
515
+ ...r,
516
+ status: "error",
517
+ error: data.error || "Video generation failed",
518
+ }
519
+ : r,
520
+ ),
521
+ }));
522
+ break;
523
+ }
524
+ });
525
+ } catch (e: any) {
526
+ if (e?.name === "AbortError") {
527
+ cancelled = true;
528
+ break;
529
+ }
530
+ set((s) => ({
531
+ rows: s.rows.map((r) =>
532
+ r.id === row.id
533
+ ? { ...r, status: "error", error: String(e) }
534
+ : r,
535
+ ),
536
+ }));
537
+ }
538
+ }
539
+
540
+ batchAbortController = null;
541
+ set({ running: false, progress: null, cancelRequested: false });
542
+
543
+ if (!cancelled) {
544
+ playBeep();
545
+ }
546
+ },
547
+
548
+ generateRow: (projectId, id) => get().generateRows(projectId, [id]),
549
+
550
+ generateAll: (projectId) => {
551
+ const ids = get()
552
+ .rows.filter((r) => r.prompt.trim() && r.imagePath)
553
+ .map((r) => r.id);
554
+ return get().generateRows(projectId, ids);
555
+ },
556
+
557
+ cancel: () => {
558
+ set({ cancelRequested: true });
559
+ if (batchAbortController) {
560
+ batchAbortController.abort();
561
+ }
562
+ set({
563
+ running: false,
564
+ progress: null,
565
+ cancelRequested: false,
566
+ rows: get().rows.map((r) =>
567
+ r.status === "generating" ? { ...r, status: "idle" } : r,
568
+ ),
569
+ });
570
+ fetch(`${API_BASE}/api/render/cancel`, { method: "POST" }).catch(() => {});
571
+ },
572
+
573
+ stitchVideos: async () => {
574
+ if (get().stitching) return;
575
+
576
+ const results = get()
577
+ .rows.filter((r) => r.result)
578
+ .map((r) => r.result as string);
579
+
580
+ if (results.length < 2) {
581
+ set({
582
+ stitchError: "Need at least 2 generated videos to stitch.",
583
+ stitchResult: null,
584
+ });
585
+ return;
586
+ }
587
+
588
+ set({
589
+ stitching: true,
590
+ stitchLogs: [],
591
+ stitchResult: null,
592
+ stitchError: null,
593
+ });
594
+
595
+ try {
596
+ const ffmpeg = await loadFFmpeg();
597
+
598
+ // Write each generated video into the in-memory FS in order.
599
+ const list: string[] = [];
600
+ for (let i = 0; i < results.length; i++) {
601
+ const blob = await fetch(results[i]).then((r) => {
602
+ if (!r.ok) throw new Error(`Failed to fetch video ${i + 1}`);
603
+ return r.blob();
604
+ });
605
+ const data = new Uint8Array(await blob.arrayBuffer());
606
+ const name = `in${i}.mp4`;
607
+ await ffmpeg.writeFile(name, data);
608
+ list.push(`file '${name}'`);
609
+ set((s) => ({
610
+ stitchLogs: [...s.stitchLogs, `Added video ${i + 1}/${results.length}`],
611
+ }));
612
+ }
613
+
614
+ await ffmpeg.writeFile("list.txt", list.join("\n"));
615
+ set((s) => ({
616
+ stitchLogs: [...s.stitchLogs, "Concatenating videos..."],
617
+ }));
618
+
619
+ const ret = await ffmpeg.exec([
620
+ "-f",
621
+ "concat",
622
+ "-safe",
623
+ "0",
624
+ "-i",
625
+ "list.txt",
626
+ "-c",
627
+ "copy",
628
+ "output.mp4",
629
+ ]);
630
+
631
+ if (ret !== 0) {
632
+ throw new Error(`ffmpeg exited with code ${ret}`);
633
+ }
634
+
635
+ const out = (await ffmpeg.readFile("output.mp4")) as Uint8Array;
636
+ const bytes = new Uint8Array(out);
637
+ const url = URL.createObjectURL(
638
+ new Blob([bytes.buffer], { type: "video/mp4" }),
639
+ );
640
+
641
+ set({
642
+ stitching: false,
643
+ stitchResult: url,
644
+ stitchLogs: [...get().stitchLogs, "Done"],
645
+ });
646
+ } catch (e) {
647
+ set({
648
+ stitching: false,
649
+ stitchError: String(e),
650
+ });
651
+ }
652
+ },
653
+
654
+ reset: () =>
655
+ set({
656
+ rows: [makeRow()],
657
+ duration: 5,
658
+ aspectRatio: "1:1",
659
+ resolution: "480p",
660
+ mode: "distilled",
661
+ running: false,
662
+ progress: null,
663
+ cancelRequested: false,
664
+ logs: [],
665
+ stitching: false,
666
+ stitchLogs: [],
667
+ stitchResult: null,
668
+ stitchError: null,
669
+ }),
670
+ }));