vidspotai-shared 1.0.136 → 1.0.138

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 (106) hide show
  1. package/lib/globals/aiModels/enums.d.ts +2 -0
  2. package/lib/globals/aiModels/enums.d.ts.map +1 -1
  3. package/lib/globals/aiModels/enums.js +7 -0
  4. package/lib/globals/aiModels/index.d.ts.map +1 -1
  5. package/lib/globals/aiModels/index.js +2 -0
  6. package/lib/globals/film/filmCatalog.d.ts +88 -0
  7. package/lib/globals/film/filmCatalog.d.ts.map +1 -0
  8. package/lib/globals/film/filmCatalog.js +218 -0
  9. package/lib/globals/index.d.ts +2 -0
  10. package/lib/globals/index.d.ts.map +1 -1
  11. package/lib/globals/index.js +2 -0
  12. package/lib/globals/reelRemake.d.ts +116 -0
  13. package/lib/globals/reelRemake.d.ts.map +1 -0
  14. package/lib/globals/reelRemake.js +142 -0
  15. package/lib/globals/types.d.ts +15 -1
  16. package/lib/globals/types.d.ts.map +1 -1
  17. package/lib/globals/types.js +16 -0
  18. package/lib/libs/storage/cdnUrl.d.ts +1 -3
  19. package/lib/libs/storage/cdnUrl.d.ts.map +1 -1
  20. package/lib/libs/storage/cdnUrl.js +8 -6
  21. package/lib/models/filmProject.model.d.ts +424 -0
  22. package/lib/models/filmProject.model.d.ts.map +1 -0
  23. package/lib/models/filmProject.model.js +14 -0
  24. package/lib/models/image.model.d.ts +3 -0
  25. package/lib/models/image.model.d.ts.map +1 -1
  26. package/lib/models/index.d.ts +2 -0
  27. package/lib/models/index.d.ts.map +1 -1
  28. package/lib/models/index.js +2 -0
  29. package/lib/models/reelRemake.model.d.ts +222 -0
  30. package/lib/models/reelRemake.model.d.ts.map +1 -0
  31. package/lib/models/reelRemake.model.js +2 -0
  32. package/lib/models/video.model.d.ts +5 -0
  33. package/lib/models/video.model.d.ts.map +1 -1
  34. package/lib/schemas/film.schema.d.ts +500 -0
  35. package/lib/schemas/film.schema.d.ts.map +1 -0
  36. package/lib/schemas/film.schema.js +201 -0
  37. package/lib/schemas/index.d.ts +1 -0
  38. package/lib/schemas/index.d.ts.map +1 -1
  39. package/lib/schemas/index.js +1 -0
  40. package/lib/services/agent/providerFallback/chains.d.ts.map +1 -1
  41. package/lib/services/agent/providerFallback/chains.js +13 -0
  42. package/lib/services/agent/tools/generateVideo.tool.d.ts.map +1 -1
  43. package/lib/services/agent/tools/generateVideo.tool.js +2 -1
  44. package/lib/services/aiGen/aiGenFactory.service.d.ts.map +1 -1
  45. package/lib/services/aiGen/aiGenFactory.service.js +4 -0
  46. package/lib/services/aiGen/providers/bytedance/bytedance.service.d.ts.map +1 -1
  47. package/lib/services/aiGen/providers/bytedance/bytedance.service.js +17 -0
  48. package/lib/services/aiGen/providers/fal/index.d.ts +1 -0
  49. package/lib/services/aiGen/providers/fal/index.d.ts.map +1 -1
  50. package/lib/services/aiGen/providers/fal/index.js +1 -0
  51. package/lib/services/aiGen/providers/kling/klingRequests.d.ts.map +1 -1
  52. package/lib/services/aiGen/providers/kling/klingRequests.js +3 -0
  53. package/lib/services/aiGen/providers/types.d.ts +6 -0
  54. package/lib/services/aiGen/providers/types.d.ts.map +1 -1
  55. package/lib/services/film/compileShotPrompt.d.ts +16 -0
  56. package/lib/services/film/compileShotPrompt.d.ts.map +1 -0
  57. package/lib/services/film/compileShotPrompt.js +152 -0
  58. package/lib/services/film/filmAssets.d.ts +73 -0
  59. package/lib/services/film/filmAssets.d.ts.map +1 -0
  60. package/lib/services/film/filmAssets.js +341 -0
  61. package/lib/services/film/filmCut.d.ts +159 -0
  62. package/lib/services/film/filmCut.d.ts.map +1 -0
  63. package/lib/services/film/filmCut.js +616 -0
  64. package/lib/services/film/filmPublic.d.ts +9 -0
  65. package/lib/services/film/filmPublic.d.ts.map +1 -0
  66. package/lib/services/film/filmPublic.js +39 -0
  67. package/lib/services/film/filmTakes.d.ts +65 -0
  68. package/lib/services/film/filmTakes.d.ts.map +1 -0
  69. package/lib/services/film/filmTakes.js +168 -0
  70. package/lib/services/film/writersRoom.d.ts +276 -0
  71. package/lib/services/film/writersRoom.d.ts.map +1 -0
  72. package/lib/services/film/writersRoom.js +431 -0
  73. package/lib/services/firestore.service.d.ts +7 -0
  74. package/lib/services/firestore.service.d.ts.map +1 -1
  75. package/lib/services/firestore.service.js +15 -0
  76. package/lib/services/index.d.ts +12 -0
  77. package/lib/services/index.d.ts.map +1 -1
  78. package/lib/services/index.js +12 -0
  79. package/lib/services/providerHealth.service.d.ts +12 -0
  80. package/lib/services/providerHealth.service.d.ts.map +1 -0
  81. package/lib/services/providerHealth.service.js +75 -0
  82. package/lib/services/reelRemake/castDetection.d.ts +56 -0
  83. package/lib/services/reelRemake/castDetection.d.ts.map +1 -0
  84. package/lib/services/reelRemake/castDetection.js +146 -0
  85. package/lib/services/reelRemake/castSuggestion.d.ts +43 -0
  86. package/lib/services/reelRemake/castSuggestion.d.ts.map +1 -0
  87. package/lib/services/reelRemake/castSuggestion.js +99 -0
  88. package/lib/services/reelRemake/keyframeSwap.d.ts +44 -0
  89. package/lib/services/reelRemake/keyframeSwap.d.ts.map +1 -0
  90. package/lib/services/reelRemake/keyframeSwap.js +139 -0
  91. package/lib/services/reelRemake/shootPlan.d.ts +65 -0
  92. package/lib/services/reelRemake/shootPlan.d.ts.map +1 -0
  93. package/lib/services/reelRemake/shootPlan.js +193 -0
  94. package/lib/services/reelRemake/stopWork.d.ts +54 -0
  95. package/lib/services/reelRemake/stopWork.d.ts.map +1 -0
  96. package/lib/services/reelRemake/stopWork.js +91 -0
  97. package/lib/services/translation/translation.service.d.ts +10 -1
  98. package/lib/services/translation/translation.service.d.ts.map +1 -1
  99. package/lib/services/translation/translation.service.js +34 -1
  100. package/lib/utils/errors.d.ts +3 -0
  101. package/lib/utils/errors.d.ts.map +1 -1
  102. package/lib/utils/errors.js +6 -0
  103. package/lib/utils/helpers.d.ts +1 -1
  104. package/lib/utils/helpers.d.ts.map +1 -1
  105. package/lib/utils/helpers.js +2 -1
  106. package/package.json +1 -1
@@ -0,0 +1,616 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FILM_CUT_REAP_RENDER_MS = exports.sfxSecondsOf = exports.FILM_CUT_REFUNDS_COLLECTION = exports.FILM_SFX_MODEL = exports.FILM_SCORE_MODEL = exports.FILM_CUT_STALE_MS = void 0;
4
+ exports.isCutLive = isCutLive;
5
+ exports.planFilmCut = planFilmCut;
6
+ exports.voiceCreditsFor = voiceCreditsFor;
7
+ exports.sfxCreditsFor = sfxCreditsFor;
8
+ exports.estimateFilmCut = estimateFilmCut;
9
+ exports.filmScoreBrief = filmScoreBrief;
10
+ exports.buildFilmCutProject = buildFilmCutProject;
11
+ exports.markFilmStage = markFilmStage;
12
+ exports.patchEpisodeRender = patchEpisodeRender;
13
+ exports.applyFilmCutRender = applyFilmCutRender;
14
+ exports.applyFilmCutQa = applyFilmCutQa;
15
+ exports.filmCutVideoId = filmCutVideoId;
16
+ exports.claimFilmCutRefund = claimFilmCutRefund;
17
+ exports.failStaleFilmCut = failStaleFilmCut;
18
+ exports.isStaleCut = isStaleCut;
19
+ /**
20
+ * Film Studio cut (Stage 6): one episode's picked takes → a canonical Project
21
+ * → the existing Remotion render queue.
22
+ *
23
+ * The cut job (FILM_JOBS kind "cut") voices dialogue the takes don't carry
24
+ * themselves (Kling, or a shot shown as a still), generates the shots' sound
25
+ * effects where the picture is silent, picks or composes a score,
26
+ * then calls `buildFilmCutProject`. The Project is saved on a videoJobs doc
27
+ * (`filmCut` back-reference) so the editor opens it like any other video and
28
+ * the render invoker writes the MP4 back here via `applyFilmCutRender`.
29
+ *
30
+ * Shots with no take fall back to their storyboard frame as a slow push-in
31
+ * still (an animatic), so an episode can be cut before every shot is shot.
32
+ */
33
+ const filmCatalog_1 = require("../../globals/film/filmCatalog");
34
+ const aiModels_1 = require("../../globals/aiModels");
35
+ const enums_1 = require("../../globals/aiModels/enums");
36
+ const ttsModels_1 = require("../../globals/ttsModels");
37
+ const project_schema_1 = require("../../schemas/project.schema");
38
+ const helpers_1 = require("../../utils/helpers");
39
+ const aiGenFactory_service_1 = require("../aiGen/aiGenFactory.service");
40
+ const firestore_service_1 = require("../firestore.service");
41
+ /** A cut whose heartbeat is older than this no longer blocks a recut. */
42
+ exports.FILM_CUT_STALE_MS = 30 * 60000;
43
+ /** The "original score" model: Lyria 2, ~30s instrumental clips, looped under the episode. */
44
+ exports.FILM_SCORE_MODEL = enums_1.EMusicGenModels.GOOGLE_LYRIA_2;
45
+ /** Shot sound effects (`shot.sfx`), billed per second like /v1/sfx. Provider cap 0.5–30s. */
46
+ exports.FILM_SFX_MODEL = enums_1.ESfxGenModels.ELEVENLABS_SOUND_EFFECTS;
47
+ const SFX_MAX_SEC = 30;
48
+ /** Firestore ledger: one doc per cut job that has been refunded, so the worker and the reaper never both refund. */
49
+ exports.FILM_CUT_REFUNDS_COLLECTION = "filmCutRefunds";
50
+ const TITLE_CARD_MS = 3000;
51
+ const END_CARD_MS = 3000;
52
+ /** Breath before the first line of a shot, and between consecutive lines. */
53
+ const LINE_LEAD_MS = 250;
54
+ const LINE_GAP_MS = 200;
55
+ /** Overlap between looped copies of a short score, faded across. */
56
+ const SCORE_CROSSFADE_MS = 1500;
57
+ const MAX_SCORE_COPIES = 40;
58
+ const TRACK = {
59
+ visual: "track-visual",
60
+ cards: "track-text",
61
+ subtitles: "track-subtitles",
62
+ dialogue: "track-dialogue",
63
+ sfx: "track-sfx",
64
+ music: "track-music",
65
+ };
66
+ const FRAMES = {
67
+ "16:9": { width: 1920, height: 1080, aspect: "16:9" },
68
+ // The Project aspect enum has no 21:9; the size is what sets the frame.
69
+ "21:9": { width: 1920, height: 824, aspect: "16:9" },
70
+ "9:16": { width: 1080, height: 1920, aspect: "9:16" },
71
+ };
72
+ function isCutLive(render, now = Date.now()) {
73
+ return Boolean(render &&
74
+ (render.status === "queued" || render.status === "rendering") &&
75
+ render.heartbeatAt &&
76
+ now - render.heartbeatAt < exports.FILM_CUT_STALE_MS);
77
+ }
78
+ /** Which shots go in the cut and what has to be voiced. `shots` in episode order. */
79
+ function planFilmCut(project, shots) {
80
+ const cast = new Map(project.cast.map((c) => [c.id, c]));
81
+ const plan = {
82
+ shots: [],
83
+ missingShotIds: [],
84
+ stillShotIds: [],
85
+ voiceLines: [],
86
+ voiceChars: 0,
87
+ sfxCues: [],
88
+ durationMs: 0,
89
+ };
90
+ for (const shot of shots) {
91
+ const take = shot.take?.status === "succeeded" && shot.take.url ? shot.take : undefined;
92
+ const frameUrl = shot.keyframe?.status === "succeeded" ? shot.keyframe.url : undefined;
93
+ const url = take?.url ?? frameUrl;
94
+ if (!url) {
95
+ plan.missingShotIds.push(shot.id);
96
+ continue;
97
+ }
98
+ const lines = shot.dialogue
99
+ .filter((d) => d.line.trim())
100
+ .map((d, i) => {
101
+ const member = cast.get(d.castId);
102
+ return {
103
+ key: `${shot.id}:${i}`,
104
+ shotId: shot.id,
105
+ castId: d.castId,
106
+ speaker: member?.name ?? "",
107
+ text: d.line.trim(),
108
+ ...(d.delivery?.trim() ? { delivery: d.delivery.trim() } : {}),
109
+ ...(member?.voiceId ? { voiceId: member.voiceId } : {}),
110
+ };
111
+ });
112
+ const voiced = Boolean(take?.audio);
113
+ const durationMs = Math.round(Math.max(1, take?.durationSec ?? shot.durationSec) * 1000);
114
+ // A voiced take already has the model's own sound design; silent takes and stills get the cue.
115
+ const cue = shot.sfx?.trim();
116
+ const sfx = cue && !voiced
117
+ ? {
118
+ key: shot.id,
119
+ shotId: shot.id,
120
+ prompt: cue,
121
+ durationSec: Math.min(SFX_MAX_SEC, Math.max(1, Math.round(durationMs / 100) / 10)),
122
+ }
123
+ : undefined;
124
+ plan.shots.push({ shotId: shot.id, source: take ? "take" : "frame", url, durationMs, voiced, lines, ...(sfx ? { sfx } : {}) });
125
+ if (!take)
126
+ plan.stillShotIds.push(shot.id);
127
+ if (!voiced)
128
+ plan.voiceLines.push(...lines);
129
+ if (sfx)
130
+ plan.sfxCues.push(sfx);
131
+ plan.durationMs += durationMs;
132
+ }
133
+ plan.voiceChars = plan.voiceLines.reduce((n, l) => n + l.text.length, 0);
134
+ return plan;
135
+ }
136
+ /** Credits for one line set at the default TTS provider's per-character rate (same maths as /v1/tts). */
137
+ function voiceCreditsFor(chars) {
138
+ if (chars <= 0)
139
+ return 0;
140
+ return (0, helpers_1.getCreditsFromCost)((chars / 1000) * ttsModels_1.ttsProviderConfigs[ttsModels_1.DEFAULT_TTS_PROVIDER].costPer1KChars);
141
+ }
142
+ /** Credits for a set of sound effects totalling `seconds`, at the SFX model's per-second rate (one billed op, like the voices). */
143
+ function sfxCreditsFor(seconds) {
144
+ if (seconds <= 0)
145
+ return 0;
146
+ const perSecond = aiModels_1.aiModelConfigs[exports.FILM_SFX_MODEL].cost?.perSecond ?? 0;
147
+ return (0, helpers_1.getCreditsFromCost)(perSecond * seconds);
148
+ }
149
+ const sfxSecondsOf = (cues) => cues.reduce((n, c) => n + c.durationSec, 0);
150
+ exports.sfxSecondsOf = sfxSecondsOf;
151
+ /** Rendering is our own compute and free; voices, effects and an original score are billed like their tools. */
152
+ function estimateFilmCut(plan, options) {
153
+ const voiceCredits = voiceCreditsFor(plan.voiceChars);
154
+ const sfxCredits = options.sfx ? sfxCreditsFor((0, exports.sfxSecondsOf)(plan.sfxCues)) : 0;
155
+ const musicCredits = options.score === "original"
156
+ ? (0, aiGenFactory_service_1.getAiGenProviderService)(exports.FILM_SCORE_MODEL).getCreditUsed({ modelKey: exports.FILM_SCORE_MODEL })
157
+ : 0;
158
+ return { voiceCredits, sfxCredits, musicCredits, totalCredits: voiceCredits + sfxCredits + musicCredits };
159
+ }
160
+ const GENRE_MOOD = {
161
+ horror: "dark",
162
+ thriller: "dark",
163
+ noir: "dark",
164
+ mystery: "dark",
165
+ war: "dark",
166
+ action: "energetic",
167
+ comedy: "quirky",
168
+ animated: "quirky",
169
+ romance: "acoustic",
170
+ western: "acoustic",
171
+ };
172
+ const TEMPO_BPM = { calm: 80, measured: 96, dynamic: 120, frantic: 140 };
173
+ /** Score direction from the project look: a library mood/query and a text-to-music prompt. */
174
+ function filmScoreBrief(project) {
175
+ const genre = (0, filmCatalog_1.findFilmOption)(filmCatalog_1.FILM_GENRES, project.look.genre);
176
+ const tempo = (0, filmCatalog_1.findFilmOption)(filmCatalog_1.FILM_TEMPOS, project.look.tempo);
177
+ const mood = (genre && GENRE_MOOD[genre.key]) ?? "cinematic";
178
+ const bpmTarget = (tempo && TEMPO_BPM[tempo.key]) ?? 96;
179
+ const prompt = [
180
+ `Instrumental film score underscore for a ${genre?.prompt ?? "cinematic drama"}`,
181
+ tempo?.prompt,
182
+ "no vocals, sits quietly beneath dialogue, steady and loopable",
183
+ ]
184
+ .filter(Boolean)
185
+ .join(", ");
186
+ return { mood, query: `${genre?.label ?? "cinematic"} film score`, bpmTarget, prompt };
187
+ }
188
+ const IDENTITY = { x: 0, y: 0, scaleX: 1, scaleY: 1, rotation: 0, opacity: 1 };
189
+ function base(id, trackId, from, to, name) {
190
+ return {
191
+ id,
192
+ trackId,
193
+ display: { from, to },
194
+ name,
195
+ effects: [],
196
+ transform: { ...IDENTITY },
197
+ locked: false,
198
+ };
199
+ }
200
+ function textClip(id, trackId, from, to, text, style) {
201
+ return {
202
+ ...base(id, trackId, from, to, style.role),
203
+ type: "text",
204
+ text,
205
+ fontFamily: "Poppins",
206
+ fontSize: style.fontSize,
207
+ fontWeight: style.fontWeight,
208
+ color: "#ffffff",
209
+ align: "center",
210
+ ...(style.preset ? { preset: style.preset } : {}),
211
+ metadata: {
212
+ role: style.role,
213
+ position: style.position,
214
+ ...(style.bgStyle ? { bgStyle: style.bgStyle } : {}),
215
+ ...(style.preset ? { preset: style.preset } : {}),
216
+ },
217
+ };
218
+ }
219
+ function track(id, kind, index, name) {
220
+ return { id, kind, name, index, muted: false, hidden: false, locked: false, gainDb: 0 };
221
+ }
222
+ const wordsOf = (text) => Math.max(1, text.split(/\s+/).filter(Boolean).length);
223
+ /** The episode's timeline. Pure: every URL and duration is resolved by the caller. */
224
+ function buildFilmCutProject(input) {
225
+ const { project, episode, plan, options, voices, music } = input;
226
+ const frame = FRAMES[project.aspectRatio];
227
+ const unit = Math.min(frame.width, frame.height);
228
+ const clips = [];
229
+ const isSeries = project.format === "series";
230
+ let t = 0;
231
+ if (options.titleCard) {
232
+ clips.push(textClip("title-card", TRACK.cards, 0, TITLE_CARD_MS, project.title, {
233
+ fontSize: Math.round(unit * 0.09),
234
+ fontWeight: 800,
235
+ role: "headline",
236
+ position: "center",
237
+ preset: "fade-soft",
238
+ }));
239
+ if (isSeries) {
240
+ clips.push(textClip("title-card-episode", TRACK.cards, 0, TITLE_CARD_MS, `Episode ${episode.index} · ${episode.title}`, {
241
+ fontSize: Math.round(unit * 0.045),
242
+ fontWeight: 500,
243
+ role: "subheadline",
244
+ position: "lower-third",
245
+ preset: "fade-soft",
246
+ }));
247
+ }
248
+ t = TITLE_CARD_MS;
249
+ }
250
+ const contentStart = t;
251
+ const spans = [];
252
+ plan.shots.forEach((shot, i) => {
253
+ const from = t;
254
+ const to = t + shot.durationMs;
255
+ if (shot.source === "take") {
256
+ const clip = {
257
+ ...base(`shot-${shot.shotId}`, TRACK.visual, from, to, `Shot ${i + 1}`),
258
+ type: "video",
259
+ src: shot.url,
260
+ trim: { from: 0, to: shot.durationMs },
261
+ volume: 1,
262
+ playbackRate: 1,
263
+ metadata: { shotId: shot.shotId },
264
+ };
265
+ clips.push(clip);
266
+ }
267
+ else {
268
+ const clip = {
269
+ ...base(`shot-${shot.shotId}`, TRACK.visual, from, to, `Shot ${i + 1} (frame)`),
270
+ type: "image",
271
+ src: shot.url,
272
+ motion: { kind: i % 2 ? "kenBurnsOut" : "kenBurnsIn", intensity: 0.4 },
273
+ metadata: { shotId: shot.shotId, still: true },
274
+ };
275
+ clips.push(clip);
276
+ }
277
+ spans.push({ shot, from, to });
278
+ t = to;
279
+ });
280
+ const contentEnd = t;
281
+ let endCard = null;
282
+ if (options.endCard) {
283
+ endCard = isSeries && (!input.isLastEpisode || episode.cliffhanger?.trim()) ? "To be continued…" : "The End";
284
+ t += END_CARD_MS;
285
+ }
286
+ const total = Math.max(t, 1000);
287
+ // Dialogue: synthesized lines play in order, each starting no earlier than its
288
+ // shot, never overlapping the previous line. Subtitles follow the audio for
289
+ // voiced lines and share the shot's window by word count for takes that
290
+ // carry their own dialogue.
291
+ let cursor = contentStart;
292
+ let dialogueClips = 0;
293
+ for (const { shot, from, to } of spans) {
294
+ if (shot.voiced) {
295
+ if (!options.subtitles || !shot.lines.length)
296
+ continue;
297
+ const start = from + LINE_LEAD_MS;
298
+ const window = Math.max(0, to - 150 - start);
299
+ const totalWords = shot.lines.reduce((n, l) => n + wordsOf(l.text), 0);
300
+ let at = start;
301
+ for (const line of shot.lines) {
302
+ const len = Math.round((window * wordsOf(line.text)) / totalWords);
303
+ if (len > 300)
304
+ clips.push(subtitle(line, at, at + len, unit));
305
+ at += len;
306
+ }
307
+ continue;
308
+ }
309
+ for (const line of shot.lines) {
310
+ const voice = voices[line.key];
311
+ if (!voice)
312
+ continue;
313
+ const lineFrom = Math.max(from + LINE_LEAD_MS, cursor);
314
+ if (lineFrom >= total - 300)
315
+ break;
316
+ const lineTo = Math.min(lineFrom + Math.max(300, voice.durationMs), total);
317
+ const clip = {
318
+ ...base(`line-${line.key}`, TRACK.dialogue, lineFrom, lineTo, line.speaker || "Dialogue"),
319
+ type: "audio",
320
+ src: voice.url,
321
+ volume: 1,
322
+ fadeInMs: 0,
323
+ fadeOutMs: 0,
324
+ metadata: { shotId: line.shotId, castId: line.castId, line: line.text },
325
+ };
326
+ clips.push(clip);
327
+ dialogueClips++;
328
+ if (options.subtitles)
329
+ clips.push(subtitle(line, lineFrom, lineTo, unit));
330
+ cursor = lineTo + LINE_GAP_MS;
331
+ }
332
+ }
333
+ // Sound effects: one bed per shot, under the dialogue, fading at the cut.
334
+ if (options.sfx !== false) {
335
+ for (const { shot, from, to } of spans) {
336
+ const fx = shot.sfx && input.effects?.[shot.sfx.key];
337
+ if (!fx)
338
+ continue;
339
+ const fxTo = Math.min(to, from + Math.max(300, fx.durationMs));
340
+ const clip = {
341
+ ...base(`sfx-${shot.shotId}`, TRACK.sfx, from, fxTo, "Sound effects"),
342
+ type: "audio",
343
+ src: fx.url,
344
+ trim: { from: 0, to: fxTo - from },
345
+ volume: 0.55,
346
+ duckAgainstTrackId: TRACK.dialogue,
347
+ fadeInMs: 150,
348
+ fadeOutMs: 300,
349
+ metadata: { shotId: shot.shotId, sfx: shot.sfx.prompt },
350
+ };
351
+ clips.push(clip);
352
+ }
353
+ }
354
+ if (endCard) {
355
+ clips.push(textClip("end-card", TRACK.cards, contentEnd, total, endCard, {
356
+ fontSize: Math.round(unit * 0.07),
357
+ fontWeight: 700,
358
+ role: "headline",
359
+ position: "center",
360
+ preset: "fade-soft",
361
+ }));
362
+ }
363
+ if (music)
364
+ clips.push(...scoreClips(music, total, dialogueClips > 0 || plan.shots.some((s) => s.voiced)));
365
+ const used = new Set(clips.map((c) => c.trackId));
366
+ const tracks = [
367
+ track(TRACK.visual, "video", 0, "Shots"),
368
+ track(TRACK.cards, "text", 1, "Title cards"),
369
+ track(TRACK.subtitles, "text", 2, "Subtitles"),
370
+ track(TRACK.dialogue, "audio", 3, "Dialogue"),
371
+ track(TRACK.sfx, "audio", 4, "Sound effects"),
372
+ track(TRACK.music, "audio", 5, "Score"),
373
+ ].filter((tr) => tr.id === TRACK.visual || used.has(tr.id));
374
+ const now = input.now ?? new Date().toISOString();
375
+ return {
376
+ schemaVersion: project_schema_1.PROJECT_SCHEMA_VERSION,
377
+ id: input.cutId,
378
+ name: isSeries ? `${project.title} · Episode ${episode.index}: ${episode.title}` : project.title,
379
+ durationMs: total,
380
+ fps: 30,
381
+ size: { width: frame.width, height: frame.height },
382
+ aspect: frame.aspect,
383
+ background: { type: "color", value: "#000000" },
384
+ tracks,
385
+ clips,
386
+ transitions: [],
387
+ masterVolume: 1,
388
+ metadata: {
389
+ source: "film-studio",
390
+ filmProjectId: project.id,
391
+ filmEpisodeId: episode.id,
392
+ aspectRatio: project.aspectRatio,
393
+ ...(music?.attribution ? { musicAttribution: music.attribution } : {}),
394
+ },
395
+ createdAt: now,
396
+ updatedAt: now,
397
+ };
398
+ }
399
+ function subtitle(line, from, to, unit) {
400
+ return textClip(`sub-${line.key}`, TRACK.subtitles, from, to, line.text, {
401
+ fontSize: Math.round(unit * 0.045),
402
+ fontWeight: 600,
403
+ role: "body",
404
+ position: "bottom",
405
+ bgStyle: "shadow",
406
+ preset: "none",
407
+ });
408
+ }
409
+ /** The score across the whole episode, looped with crossfades when the track is shorter. */
410
+ function scoreClips(music, total, underDialogue) {
411
+ const volume = underDialogue ? 0.22 : 0.35;
412
+ const len = music.durationMs > SCORE_CROSSFADE_MS * 2 ? music.durationMs : total;
413
+ const clips = [];
414
+ let from = 0;
415
+ for (let k = 0; k < MAX_SCORE_COPIES && from < total; k++) {
416
+ const to = Math.min(from + len, total);
417
+ clips.push({
418
+ ...base(`score-${k}`, TRACK.music, from, to, "Score"),
419
+ type: "audio",
420
+ src: music.url,
421
+ trim: { from: 0, to: to - from },
422
+ volume,
423
+ duckAgainstTrackId: TRACK.dialogue,
424
+ fadeInMs: SCORE_CROSSFADE_MS,
425
+ fadeOutMs: to === total ? 2500 : SCORE_CROSSFADE_MS,
426
+ metadata: { source: music.source },
427
+ });
428
+ if (to === total)
429
+ break;
430
+ from = to - SCORE_CROSSFADE_MS;
431
+ }
432
+ return clips;
433
+ }
434
+ /** Drop keys set to undefined (Firestore rejects them), so a patch can clear a field. */
435
+ function compact(obj) {
436
+ const out = { ...obj };
437
+ for (const k of Object.keys(out))
438
+ if (out[k] === undefined)
439
+ delete out[k];
440
+ return out;
441
+ }
442
+ /**
443
+ * Stage timings: "start" closes whatever stage is still open and opens
444
+ * `stage`; "end" closes `stage` if it's open; "stop" closes every open stage
445
+ * (a failure). Pure; returns a new array.
446
+ */
447
+ function markFilmStage(timings, stage, at, now = Date.now()) {
448
+ const closes = (t) => t.ms === undefined && (at !== "end" || t.stage === stage);
449
+ const rows = (timings ?? []).map((t) => (closes(t) ? { ...t, ms: Math.max(0, now - t.startedAt) } : t));
450
+ return at === "start" ? [...rows, { stage, startedAt: now }] : rows;
451
+ }
452
+ /**
453
+ * Patch one episode's `render` in a transaction. With `lease`, only while that
454
+ * cut job still owns the episode (false when superseded or gone).
455
+ */
456
+ async function patchEpisodeRender(projectId, episodeId, patch, opts = {}) {
457
+ const ref = firestore_service_1.FirestoreService.filmProjectsCol.doc(projectId);
458
+ return ref.firestore.runTransaction(async (tx) => {
459
+ const project = (await tx.get(ref)).data();
460
+ const ep = project?.episodes.find((e) => e.id === episodeId);
461
+ if (!project || !ep)
462
+ return false;
463
+ // A lease holder only writes while its cut is current and not failed (the reaper may have failed it).
464
+ if (opts.lease && (ep.render?.cutJobId !== opts.lease || ep.render.status === "failed"))
465
+ return false;
466
+ const now = new Date().toISOString();
467
+ const merged = { status: "idle", ...ep.render, ...patch, updatedAt: now };
468
+ if (opts.timing)
469
+ merged.timings = markFilmStage(merged.timings, opts.timing.stage, opts.timing.at);
470
+ const render = compact(merged);
471
+ const episodes = project.episodes.map((e) => (e.id === episodeId ? { ...e, render } : e));
472
+ // "complete" once every episode has a cut; back to "ready" when the last live cut ends otherwise.
473
+ const done = episodes.every((e) => e.render?.status === "succeeded");
474
+ const live = episodes.some((e) => isCutLive(e.render));
475
+ const status = done
476
+ ? "complete"
477
+ : !live && (project.status === "cutting" || project.status === "complete")
478
+ ? "ready"
479
+ : undefined;
480
+ tx.update(ref, {
481
+ episodes,
482
+ ...(status ? { status } : {}),
483
+ updatedAt: now,
484
+ });
485
+ return true;
486
+ });
487
+ }
488
+ /**
489
+ * Render-invoker hook for a videoJobs doc carrying `filmCut`: mirror the
490
+ * render's progress onto the episode. A render finishing while a newer cut is
491
+ * still voicing/assembling (status "queued") only refreshes the playable URL.
492
+ */
493
+ async function applyFilmCutRender(target, outcome) {
494
+ const ref = firestore_service_1.FirestoreService.filmProjectsCol.doc(target.projectId);
495
+ const current = (await ref.get()).data()?.episodes.find((e) => e.id === target.episodeId)?.render;
496
+ const cutting = current?.status === "queued" && isCutLive(current);
497
+ if (cutting) {
498
+ if (outcome.status !== "succeeded")
499
+ return false;
500
+ return patchEpisodeRender(target.projectId, target.episodeId, {
501
+ url: outcome.url,
502
+ ...(outcome.posterUrl ? { posterUrl: outcome.posterUrl } : {}),
503
+ });
504
+ }
505
+ switch (outcome.status) {
506
+ case "rendering":
507
+ return patchEpisodeRender(target.projectId, target.episodeId, {
508
+ status: "rendering",
509
+ stage: "rendering",
510
+ renderJobId: outcome.renderJobId,
511
+ heartbeatAt: Date.now(),
512
+ error: undefined,
513
+ qa: undefined,
514
+ }, { timing: { stage: "rendering", at: "start" } });
515
+ case "succeeded":
516
+ return patchEpisodeRender(target.projectId, target.episodeId, {
517
+ status: "succeeded",
518
+ stage: undefined,
519
+ renderJobId: outcome.renderJobId,
520
+ url: outcome.url,
521
+ ...(outcome.posterUrl ? { posterUrl: outcome.posterUrl } : {}),
522
+ error: undefined,
523
+ qa: undefined,
524
+ }, { timing: { stage: "rendering", at: "end" } });
525
+ case "failed":
526
+ return patchEpisodeRender(target.projectId, target.episodeId, {
527
+ status: "failed",
528
+ stage: undefined,
529
+ renderJobId: outcome.renderJobId,
530
+ error: outcome.error,
531
+ }, { timing: { stage: "rendering", at: "stop" } });
532
+ }
533
+ }
534
+ /**
535
+ * Write the critic's review onto the episode, only while `qa.renderJobId` is
536
+ * still the episode's succeeded render (a newer render or cut drops it).
537
+ */
538
+ async function applyFilmCutQa(target, qa) {
539
+ const ref = firestore_service_1.FirestoreService.filmProjectsCol.doc(target.projectId);
540
+ return ref.firestore.runTransaction(async (tx) => {
541
+ const project = (await tx.get(ref)).data();
542
+ const ep = project?.episodes.find((e) => e.id === target.episodeId);
543
+ const render = ep?.render;
544
+ if (!project || !render || render.status !== "succeeded" || render.renderJobId !== qa.renderJobId)
545
+ return false;
546
+ const episodes = project.episodes.map((e) => e.id === target.episodeId ? { ...e, render: { ...render, qa: compact(qa) } } : e);
547
+ tx.update(ref, { episodes, updatedAt: new Date().toISOString() });
548
+ return true;
549
+ });
550
+ }
551
+ /** Stable videoJobs id for an episode's cut, so a recut replaces it in the library rather than adding another. */
552
+ function filmCutVideoId(projectId, episodeId) {
553
+ return `film-cut-${projectId}-${episodeId}`;
554
+ }
555
+ /**
556
+ * Claim the one refund a cut job may make. The worker (unused credits, or all
557
+ * of them on failure), the Function (enqueue failure) and the reaper (a cut
558
+ * whose worker died) all go through here, so a cut is never refunded twice.
559
+ */
560
+ async function claimFilmCutRefund(cutJobId, credits, by) {
561
+ const ref = firestore_service_1.FirestoreService.filmProjectsCol.firestore
562
+ .collection(exports.FILM_CUT_REFUNDS_COLLECTION)
563
+ .doc(cutJobId.replace(/[/:]/g, "_"));
564
+ try {
565
+ await ref.create({ cutJobId, credits, by, at: new Date().toISOString() });
566
+ return true;
567
+ }
568
+ catch (err) {
569
+ // ALREADY_EXISTS: someone else refunded this cut.
570
+ if (err.code === 6)
571
+ return false;
572
+ throw err;
573
+ }
574
+ }
575
+ /** Stale-cut reaper thresholds: a pre-render stage that stopped heartbeating, and a render that never reported back. */
576
+ exports.FILM_CUT_REAP_RENDER_MS = 3 * 60 * 60000;
577
+ /**
578
+ * Fail one stale cut under its lease. Returns the render as it was when
579
+ * failed (for the refund), or null when it's no longer stale or no longer this cut.
580
+ */
581
+ async function failStaleFilmCut(projectId, episodeId, now = Date.now()) {
582
+ const ref = firestore_service_1.FirestoreService.filmProjectsCol.doc(projectId);
583
+ return ref.firestore.runTransaction(async (tx) => {
584
+ const project = (await tx.get(ref)).data();
585
+ const ep = project?.episodes.find((e) => e.id === episodeId);
586
+ const render = ep?.render;
587
+ if (!project || !render || !isStaleCut(render, now))
588
+ return null;
589
+ const failed = compact({
590
+ ...render,
591
+ status: "failed",
592
+ stage: undefined,
593
+ error: render.status === "rendering"
594
+ ? "The render stopped responding. Retry the render or cut again."
595
+ : "The cut stopped responding. Your credits were refunded; cut again.",
596
+ updatedAt: new Date(now).toISOString(),
597
+ });
598
+ const episodes = project.episodes.map((e) => (e.id === episodeId ? { ...e, render: failed } : e));
599
+ const live = episodes.some((e) => isCutLive(e.render, now));
600
+ tx.update(ref, {
601
+ episodes,
602
+ ...(!live && project.status === "cutting" ? { status: "ready" } : {}),
603
+ updatedAt: new Date(now).toISOString(),
604
+ });
605
+ return render;
606
+ });
607
+ }
608
+ /** Pre-render stages past the heartbeat window, or a render that never came back. */
609
+ function isStaleCut(render, now = Date.now()) {
610
+ const beat = render.heartbeatAt ?? 0;
611
+ if (render.status === "queued")
612
+ return now - beat >= exports.FILM_CUT_STALE_MS;
613
+ if (render.status === "rendering")
614
+ return now - beat >= exports.FILM_CUT_REAP_RENDER_MS;
615
+ return false;
616
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Film Studio, Stage 7: what a film looks like outside the studio (share
3
+ * page, showcase). Only finished cuts are shown; nothing about how the film
4
+ * was made (cast sheets, prompts, jobs, credits) leaves the project.
5
+ */
6
+ import type { FilmPublicView, IFilmProjectModel } from "../../models/filmProject.model";
7
+ /** The public face of a project. `episodes` is empty until something has been cut. */
8
+ export declare function toFilmPublicView(project: IFilmProjectModel): FilmPublicView;
9
+ //# sourceMappingURL=filmPublic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filmPublic.d.ts","sourceRoot":"","sources":["../../../src/services/film/filmPublic.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAExF,sFAAsF;AACtF,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,CAiC3E"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toFilmPublicView = toFilmPublicView;
4
+ /** The public face of a project. `episodes` is empty until something has been cut. */
5
+ function toFilmPublicView(project) {
6
+ const episodes = [...project.episodes]
7
+ .sort((a, b) => a.index - b.index)
8
+ .flatMap((ep) => {
9
+ const r = ep.render;
10
+ if (r?.status !== "succeeded" || !r.url)
11
+ return [];
12
+ return [
13
+ {
14
+ id: ep.id,
15
+ index: ep.index,
16
+ title: ep.title,
17
+ ...(ep.synopsis ? { synopsis: ep.synopsis } : {}),
18
+ ...(r.durationSec ? { durationSec: r.durationSec } : {}),
19
+ url: r.url,
20
+ ...(r.posterUrl ? { posterUrl: r.posterUrl } : {}),
21
+ },
22
+ ];
23
+ });
24
+ return {
25
+ title: project.title,
26
+ ...(project.logline ? { logline: project.logline } : {}),
27
+ ...(project.synopsis ? { synopsis: project.synopsis } : {}),
28
+ format: project.format,
29
+ aspectRatio: project.aspectRatio,
30
+ ...(project.look.genre ? { genre: project.look.genre } : {}),
31
+ // Without a cover, the first episode's poster frame stands in.
32
+ ...(project.coverUrl
33
+ ? { coverUrl: project.coverUrl }
34
+ : episodes[0]?.posterUrl
35
+ ? { coverUrl: episodes[0].posterUrl }
36
+ : {}),
37
+ episodes,
38
+ };
39
+ }