@softure-ai/marketing-kit 0.3.1 → 0.5.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 (126) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +135 -14
  3. package/dist/cli/footage.d.ts.map +1 -1
  4. package/dist/cli/footage.js +15 -6
  5. package/dist/cli/footage.js.map +1 -1
  6. package/dist/config/actions-schema.d.ts +14 -14
  7. package/dist/config/config.d.ts.map +1 -1
  8. package/dist/config/config.js +5 -0
  9. package/dist/config/config.js.map +1 -1
  10. package/dist/config/schema.d.ts +92 -69
  11. package/dist/config/schema.d.ts.map +1 -1
  12. package/dist/config/schema.js +40 -4
  13. package/dist/config/schema.js.map +1 -1
  14. package/dist/config/shot-steps.d.ts +16 -16
  15. package/dist/footage/audio.d.ts +52 -0
  16. package/dist/footage/audio.d.ts.map +1 -0
  17. package/dist/footage/audio.js +100 -0
  18. package/dist/footage/audio.js.map +1 -0
  19. package/dist/footage/captions.d.ts +57 -0
  20. package/dist/footage/captions.d.ts.map +1 -0
  21. package/dist/footage/captions.js +112 -0
  22. package/dist/footage/captions.js.map +1 -0
  23. package/dist/footage/compose.d.ts +5 -5
  24. package/dist/footage/compose.d.ts.map +1 -1
  25. package/dist/footage/compose.js +31 -22
  26. package/dist/footage/compose.js.map +1 -1
  27. package/dist/footage/edl.d.ts +54 -16
  28. package/dist/footage/edl.d.ts.map +1 -1
  29. package/dist/footage/edl.js +204 -52
  30. package/dist/footage/edl.js.map +1 -1
  31. package/dist/footage/elevenlabs.d.ts +4 -1
  32. package/dist/footage/elevenlabs.d.ts.map +1 -1
  33. package/dist/footage/elevenlabs.js +18 -6
  34. package/dist/footage/elevenlabs.js.map +1 -1
  35. package/dist/footage/fake.d.ts +2 -0
  36. package/dist/footage/fake.d.ts.map +1 -1
  37. package/dist/footage/fake.js +2 -1
  38. package/dist/footage/fake.js.map +1 -1
  39. package/dist/footage/film.d.ts +35 -1
  40. package/dist/footage/film.d.ts.map +1 -1
  41. package/dist/footage/film.js +9 -1
  42. package/dist/footage/film.js.map +1 -1
  43. package/dist/footage/frames.d.ts +38 -0
  44. package/dist/footage/frames.d.ts.map +1 -0
  45. package/dist/footage/frames.js +40 -0
  46. package/dist/footage/frames.js.map +1 -0
  47. package/dist/footage/loudness.d.ts +49 -0
  48. package/dist/footage/loudness.d.ts.map +1 -0
  49. package/dist/footage/loudness.js +114 -0
  50. package/dist/footage/loudness.js.map +1 -0
  51. package/dist/footage/normalize.d.ts +6 -2
  52. package/dist/footage/normalize.d.ts.map +1 -1
  53. package/dist/footage/normalize.js +7 -9
  54. package/dist/footage/normalize.js.map +1 -1
  55. package/dist/footage/paid.d.ts +70 -0
  56. package/dist/footage/paid.d.ts.map +1 -0
  57. package/dist/footage/paid.js +172 -0
  58. package/dist/footage/paid.js.map +1 -0
  59. package/dist/footage/pipeline.d.ts +34 -10
  60. package/dist/footage/pipeline.d.ts.map +1 -1
  61. package/dist/footage/pipeline.js +294 -85
  62. package/dist/footage/pipeline.js.map +1 -1
  63. package/dist/footage/probe.d.ts +18 -4
  64. package/dist/footage/probe.d.ts.map +1 -1
  65. package/dist/footage/probe.js +18 -13
  66. package/dist/footage/probe.js.map +1 -1
  67. package/dist/footage/process.d.ts +45 -0
  68. package/dist/footage/process.d.ts.map +1 -0
  69. package/dist/footage/process.js +109 -0
  70. package/dist/footage/process.js.map +1 -0
  71. package/dist/footage/providers.d.ts +49 -5
  72. package/dist/footage/providers.d.ts.map +1 -1
  73. package/dist/footage/providers.js +4 -0
  74. package/dist/footage/providers.js.map +1 -1
  75. package/dist/footage/publish.d.ts +62 -0
  76. package/dist/footage/publish.d.ts.map +1 -0
  77. package/dist/footage/publish.js +164 -0
  78. package/dist/footage/publish.js.map +1 -0
  79. package/dist/footage/render.d.ts +5 -4
  80. package/dist/footage/render.d.ts.map +1 -1
  81. package/dist/footage/render.js +29 -17
  82. package/dist/footage/render.js.map +1 -1
  83. package/dist/footage/sentences.d.ts +44 -0
  84. package/dist/footage/sentences.d.ts.map +1 -0
  85. package/dist/footage/sentences.js +102 -0
  86. package/dist/footage/sentences.js.map +1 -0
  87. package/dist/footage/tools.d.ts +33 -0
  88. package/dist/footage/tools.d.ts.map +1 -0
  89. package/dist/footage/tools.js +108 -0
  90. package/dist/footage/tools.js.map +1 -0
  91. package/dist/footage/words.d.ts +6 -0
  92. package/dist/footage/words.d.ts.map +1 -0
  93. package/dist/footage/words.js +14 -0
  94. package/dist/footage/words.js.map +1 -0
  95. package/dist/index.d.ts +15 -6
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +15 -6
  98. package/dist/index.js.map +1 -1
  99. package/docker/footage-worker.Dockerfile +29 -0
  100. package/package.json +2 -1
  101. package/schema/edl.schema.json +115 -0
  102. package/schema/marketing.schema.json +112 -5
  103. package/src/cli/footage.ts +13 -5
  104. package/src/config/config.ts +5 -0
  105. package/src/config/schema.ts +40 -4
  106. package/src/footage/audio.ts +123 -0
  107. package/src/footage/captions.ts +146 -0
  108. package/src/footage/compose.ts +32 -24
  109. package/src/footage/edl.ts +225 -56
  110. package/src/footage/elevenlabs.ts +21 -8
  111. package/src/footage/fake.ts +4 -1
  112. package/src/footage/film.ts +43 -2
  113. package/src/footage/frames.ts +65 -0
  114. package/src/footage/loudness.ts +143 -0
  115. package/src/footage/normalize.ts +7 -9
  116. package/src/footage/paid.ts +213 -0
  117. package/src/footage/pipeline.ts +344 -89
  118. package/src/footage/probe.ts +20 -12
  119. package/src/footage/process.ts +135 -0
  120. package/src/footage/providers.ts +56 -6
  121. package/src/footage/publish.ts +180 -0
  122. package/src/footage/render.ts +29 -19
  123. package/src/footage/sentences.ts +137 -0
  124. package/src/footage/tools.ts +119 -0
  125. package/src/footage/words.ts +15 -0
  126. package/src/index.ts +84 -0
@@ -0,0 +1,143 @@
1
+ import { copyFileSync } from "node:fs";
2
+
3
+ import { z } from "zod";
4
+
5
+ import { FOOTAGE_SAMPLE_RATE } from "./normalize.js";
6
+ import { runFfmpeg, runProcess } from "./process.js";
7
+
8
+ /**
9
+ * The speech track's loudness, measured and normalized in two passes of ffmpeg's `loudnorm` (EBU R128): the first
10
+ * pass measures, the second applies one linear gain from that measurement, so a quiet phone clip is not left quiet
11
+ * and a loud one does not clip. It runs before the music is mixed under the speech.
12
+ */
13
+
14
+ export interface LoudnessTarget {
15
+ /** Integrated loudness in LUFS. */
16
+ target: number;
17
+ /** The highest true peak in dBTP. */
18
+ truePeak: number;
19
+ }
20
+
21
+ /** What the platforms play short videos at. */
22
+ export const DEFAULT_LOUDNESS: LoudnessTarget = { target: -14, truePeak: -1 };
23
+
24
+ /** Loudness range target in LU (ffmpeg's default); the gain stays linear, so the speech keeps its dynamics. */
25
+ const LOUDNESS_RANGE = 11;
26
+
27
+ /** Below this the track is silence: there is nothing to normalize. */
28
+ const SILENCE_LUFS = -70;
29
+
30
+ /** The first pass's measurement, as `loudnorm` prints it with `print_format=json`. */
31
+ export interface LoudnessMeasurement {
32
+ inputI: number;
33
+ inputTp: number;
34
+ inputLra: number;
35
+ inputThresh: number;
36
+ targetOffset: number;
37
+ }
38
+
39
+ const measurementSchema = z.looseObject({
40
+ input_i: z.string(),
41
+ input_tp: z.string(),
42
+ input_lra: z.string(),
43
+ input_thresh: z.string(),
44
+ target_offset: z.string(),
45
+ });
46
+
47
+ function getLoudnormFilter(target: LoudnessTarget): string {
48
+ return `loudnorm=I=${target.target}:TP=${target.truePeak}:LRA=${LOUDNESS_RANGE}`;
49
+ }
50
+
51
+ /** The first pass: decodes the track, prints the measurement on stderr, writes nothing. */
52
+ export function buildLoudnessMeasureArgs(input: string, target: LoudnessTarget): string[] {
53
+ return ["-hide_banner", "-nostats", "-i", input, "-af", `${getLoudnormFilter(target)}:print_format=json`, "-f", "null", "-"];
54
+ }
55
+
56
+ /** The measurement from the first pass's stderr (its last JSON block); null when there is none or it is incomplete. */
57
+ export function readLoudnessMeasurement(stderr: string): LoudnessMeasurement | null {
58
+ // The block around the last `"input_i"`, found by position (a regex over ffmpeg's whole stderr could backtrack).
59
+ const key = stderr.lastIndexOf('"input_i"');
60
+ const open = key === -1 ? -1 : stderr.lastIndexOf("{", key);
61
+ const close = key === -1 ? -1 : stderr.indexOf("}", key);
62
+ if (open === -1 || close === -1) return null;
63
+ const block = stderr.slice(open, close + 1);
64
+ let json: unknown;
65
+ try {
66
+ json = JSON.parse(block);
67
+ } catch {
68
+ return null;
69
+ }
70
+ const parsed = measurementSchema.safeParse(json);
71
+ if (!parsed.success) return null;
72
+ const value = parsed.data;
73
+ // `-inf` (silence) reads as -Infinity, which `isSilent` tells apart.
74
+ const read = (text: string): number => (text.trim() === "-inf" ? -Infinity : Number(text));
75
+ const measurement = {
76
+ inputI: read(value.input_i),
77
+ inputTp: read(value.input_tp),
78
+ inputLra: read(value.input_lra),
79
+ inputThresh: read(value.input_thresh),
80
+ targetOffset: read(value.target_offset),
81
+ };
82
+ return Object.values(measurement).some((number) => Number.isNaN(number)) ? null : measurement;
83
+ }
84
+
85
+ /** True when the measured track is silence, which no gain can bring to the target. */
86
+ export function isSilent(measurement: LoudnessMeasurement): boolean {
87
+ return !Number.isFinite(measurement.inputI) || measurement.inputI < SILENCE_LUFS || !Number.isFinite(measurement.inputThresh);
88
+ }
89
+
90
+ /** The second pass: one linear gain from the measurement, resampled back to the film's rate (`loudnorm` runs at 192 kHz). */
91
+ export function buildLoudnessArgs(options: { input: string; measurement: LoudnessMeasurement; target: LoudnessTarget; output: string }): string[] {
92
+ const { measurement } = options;
93
+ const filter = [
94
+ getLoudnormFilter(options.target),
95
+ `measured_I=${measurement.inputI}`,
96
+ `measured_TP=${measurement.inputTp}`,
97
+ `measured_LRA=${measurement.inputLra}`,
98
+ `measured_thresh=${measurement.inputThresh}`,
99
+ `offset=${measurement.targetOffset}`,
100
+ "linear=true",
101
+ ].join(":");
102
+ return [
103
+ "-v",
104
+ "error",
105
+ "-y",
106
+ "-i",
107
+ options.input,
108
+ "-af",
109
+ `${filter},aresample=${FOOTAGE_SAMPLE_RATE}`,
110
+ "-ar",
111
+ String(FOOTAGE_SAMPLE_RATE),
112
+ "-c:a",
113
+ "libmp3lame",
114
+ "-q:a",
115
+ "2",
116
+ options.output,
117
+ ];
118
+ }
119
+
120
+ export type LoudnessOutcome = { kind: "normalized"; measured: number } | { kind: "silent" };
121
+
122
+ /**
123
+ * Measures `input` and writes it normalized to `output`; a silent track is copied as it is. Throws naming the step
124
+ * when ffmpeg fails, rejects with the signal's reason on abort.
125
+ */
126
+ export async function normalizeLoudness(input: string, output: string, target: LoudnessTarget, options: { signal?: AbortSignal; onSeconds?: (seconds: number) => void } = {}): Promise<LoudnessOutcome> {
127
+ const signal = options.signal === undefined ? {} : { signal: options.signal };
128
+ const measured = await runProcess({ command: "ffmpeg", args: buildLoudnessMeasureArgs(input, target), ...signal });
129
+ if (measured.kind === "not-started") throw new Error(`Measuring the speech track's loudness: ffmpeg did not start (${measured.error}).`);
130
+ if (measured.code !== 0) throw new Error(`Measuring the speech track's loudness: ffmpeg ended with code ${String(measured.code)}: ${measured.stderr.trim().split("\n").slice(-3).join(" | ")}.`);
131
+ const measurement = readLoudnessMeasurement(measured.stderr);
132
+ if (measurement === null) throw new Error(`Measuring the speech track's loudness: ffmpeg printed no loudnorm measurement for ${input}.`);
133
+ if (isSilent(measurement)) {
134
+ copyFileSync(input, output);
135
+ return { kind: "silent" };
136
+ }
137
+ await runFfmpeg("Normalizing the speech track's loudness", buildLoudnessArgs({ input, measurement, target, output }), {
138
+ ...signal,
139
+ output,
140
+ ...(options.onSeconds === undefined ? {} : { onSeconds: options.onSeconds }),
141
+ });
142
+ return { kind: "normalized", measured: measurement.inputI };
143
+ }
@@ -1,7 +1,6 @@
1
- import { spawnSync } from "node:child_process";
2
-
3
1
  import type { ClipFit, FootageClip } from "./film.js";
4
2
  import { getTrimmedDuration, type FootageProbe, type HdrKind } from "./probe.js";
3
+ import { runFfmpeg, type FfmpegRunOptions } from "./process.js";
5
4
 
6
5
  /**
7
6
  * One intermediate format for every clip, so the composition can cut between them freely: the film's frame at
@@ -123,11 +122,10 @@ export function buildNormalizeArgs(input: NormalizeInput): string[] {
123
122
  ];
124
123
  }
125
124
 
126
- /** Runs ffmpeg for one clip; throws with the clip's id when it fails (a broken file is not an expected outcome here). */
127
- export function normalizeFootage(input: NormalizeInput): void {
128
- const result = spawnSync("ffmpeg", buildNormalizeArgs(input), { stdio: ["ignore", "inherit", "inherit"] });
129
- if (result.error !== undefined) throw new Error(`Normalizing clip ${input.clip.id}: ffmpeg did not start (${result.error.message}).`);
130
- if (result.status !== 0) {
131
- throw new Error(`Normalizing clip ${input.clip.id} (${input.file}): ffmpeg ended with code ${String(result.status)} (signal ${result.signal ?? "-"}).`);
132
- }
125
+ /**
126
+ * Runs ffmpeg for one clip without blocking; throws with the clip's id when it fails (a broken file is not an expected
127
+ * outcome here). An abort removes the partial output and rejects with the signal's reason.
128
+ */
129
+ export async function normalizeFootage(input: NormalizeInput, options: Omit<FfmpegRunOptions, "output"> = {}): Promise<void> {
130
+ await runFfmpeg(`Normalizing clip ${input.clip.id} (${input.file})`, buildNormalizeArgs(input), { ...options, output: input.output });
133
131
  }
@@ -0,0 +1,213 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { extname, join } from "node:path";
4
+
5
+ import { err, ok, type TtsResult } from "../voice/provider.js";
6
+ import { footageCacheKey, getFootageCachePath, hashFile } from "./cache.js";
7
+ import { END_CARD_SECONDS, getFootageFilmSeconds } from "./compose.js";
8
+ import { readEdl, type Edl } from "./edl.js";
9
+ import type { FootageClip, FootageFilm } from "./film.js";
10
+ import { getTrimmedDuration, probeFootage } from "./probe.js";
11
+ import type { FootageProviders, FootageRates, PaidStepKind } from "./providers.js";
12
+
13
+ /**
14
+ * Where each paid result of a footage film is cached, shared by the pipeline and by the questions an app asks before
15
+ * a run: is this step cached (`findCachedStep`), and what will the film cost (`estimateFootageFilm`). Neither question
16
+ * normalizes a clip or calls a provider.
17
+ */
18
+
19
+ export interface FootageCacheOptions {
20
+ /** The paid cache's root; files are in `<cacheDir>/<film id>/`. */
21
+ cacheDir: string;
22
+ providers: FootageProviders;
23
+ /** The film's build folder: downloaded URL clips (`sources/`) and the cut (`edl.json`) are looked up there. */
24
+ buildDir?: string;
25
+ /** The cut, when the caller holds it; otherwise `<buildDir>/edl.json` is read. Video-scored music depends on it. */
26
+ edl?: Edl;
27
+ }
28
+
29
+ export interface CacheEntry {
30
+ key: string;
31
+ path: string;
32
+ }
33
+
34
+ export const isUrl = (source: string): boolean => /^https?:\/\//i.test(source);
35
+
36
+ export function getEdlPath(buildDir: string, isPlaceholder: boolean): string {
37
+ return join(buildDir, isPlaceholder ? "edl.placeholder.json" : "edl.json");
38
+ }
39
+
40
+ /** Where a URL clip is downloaded to inside `dir` (`<buildDir>/sources`). */
41
+ export function getDownloadPath(url: string, dir: string): string {
42
+ const name = createHash("sha256").update(url).digest("hex").slice(0, 16);
43
+ const extension = extname(new URL(url).pathname).toLowerCase() || ".mp4";
44
+ return join(dir, `${name}${extension}`);
45
+ }
46
+
47
+ /** The clip's local file: the file itself, or a URL's downloaded copy in the build folder; null when there is none yet. */
48
+ export function findLocalSource(clip: Pick<FootageClip, "source">, buildDir: string | undefined): string | null {
49
+ if (!isUrl(clip.source)) return existsSync(clip.source) ? clip.source : null;
50
+ if (buildDir === undefined) return null;
51
+ const file = getDownloadPath(clip.source, join(buildDir, "sources"));
52
+ return existsSync(file) ? file : null;
53
+ }
54
+
55
+ /** The cache identity of a clip's source part: its bytes and its trim. */
56
+ export async function getClipCacheKey(source: string, clip: Pick<FootageClip, "trim">): Promise<string> {
57
+ return footageCacheKey("transcript", { source: await hashFile(source), trim: clip.trim });
58
+ }
59
+
60
+ /** The cleaned voice of a clip; null when the film does not isolate the voice. */
61
+ export function getIsolatedCache(film: FootageFilm, clipKey: string, options: Pick<FootageCacheOptions, "cacheDir" | "providers">): CacheEntry | null {
62
+ if (!film.isolateVoice) return null;
63
+ const key = footageCacheKey("isolated", { clip: clipKey, provider: options.providers.isolation.id });
64
+ return { key, path: getFootageCachePath(options.cacheDir, film.id, "isolated", key) };
65
+ }
66
+
67
+ export function getTranscriptCache(film: FootageFilm, clipKey: string, options: Pick<FootageCacheOptions, "cacheDir" | "providers">): CacheEntry {
68
+ const { stt } = options.providers;
69
+ const key = footageCacheKey("transcript", { clip: clipKey, isolated: film.isolateVoice, provider: stt.id, model: stt.model, language: film.language });
70
+ return { key, path: getFootageCachePath(options.cacheDir, film.id, "transcript", key) };
71
+ }
72
+
73
+ /** Music generated from the film's prompt: keyed by the prompt, so a re-cut never pays again. */
74
+ export function getPromptMusicCache(film: FootageFilm, options: Pick<FootageCacheOptions, "cacheDir" | "providers">): CacheEntry {
75
+ const source = film.music.source;
76
+ const prompt = source.kind === "prompt" ? source.prompt : "";
77
+ const { music } = options.providers;
78
+ const key = footageCacheKey("music", { prompt, provider: music.id, model: music.model });
79
+ return { key, path: getFootageCachePath(options.cacheDir, film.id, "music", key) };
80
+ }
81
+
82
+ /** Music scored to the cut: keyed by the cut and the clips' bytes. `clipKeys` maps every clip id to its cache key. */
83
+ export function getVideoMusicCache(film: FootageFilm, edl: Edl, clipKeys: Record<string, string>, options: Pick<FootageCacheOptions, "cacheDir" | "providers">): CacheEntry {
84
+ const source = film.music.source;
85
+ const { music } = options.providers;
86
+ const description = source.kind === "video" ? source.description : "";
87
+ const tags = source.kind === "video" ? source.tags : [];
88
+ // The music is scored to the picture alone: ids and sound spans stay out, so an EDL from before ids keeps its key.
89
+ const segments = edl.segments.map(({ clip, start, end, transition, motion }) => ({ clip, start, end, transition, motion }));
90
+ const key = footageCacheKey("music", { segments, clips: clipKeys, description, tags, provider: music.id, model: music.model });
91
+ return { key, path: getFootageCachePath(options.cacheDir, film.id, "music", key) };
92
+ }
93
+
94
+ /** The cut the caller passed, or the one in the build folder; null when there is none (or it does not read). */
95
+ function findEdl(options: FootageCacheOptions): Edl | null {
96
+ if (options.edl !== undefined) return options.edl;
97
+ if (options.buildDir === undefined) return null;
98
+ const path = getEdlPath(options.buildDir, false);
99
+ if (!existsSync(path)) return null;
100
+ try {
101
+ const read = readEdl(JSON.parse(readFileSync(path, "utf8")) as unknown);
102
+ return read.ok ? read.edl : null;
103
+ } catch {
104
+ // A broken EDL file is reported by the run that reads it; here it only means the cut is unknown.
105
+ return null;
106
+ }
107
+ }
108
+
109
+ /** Every clip's cache key; null when a clip has no local file yet. */
110
+ async function getClipKeys(film: FootageFilm, buildDir: string | undefined): Promise<Record<string, string> | null> {
111
+ const keys: Record<string, string> = {};
112
+ for (const clip of film.clips) {
113
+ const source = findLocalSource(clip, buildDir);
114
+ if (source === null) return null;
115
+ keys[clip.id] = await getClipCacheKey(source, clip);
116
+ }
117
+ return keys;
118
+ }
119
+
120
+ /** Whether the film's music is already paid for; free music (none, a file) needs nothing, so it counts as cached. */
121
+ async function isMusicCached(film: FootageFilm, options: FootageCacheOptions): Promise<boolean> {
122
+ const source = film.music.source;
123
+ if (source.kind === "none" || source.kind === "file") return true;
124
+ if (source.kind === "prompt") return existsSync(getPromptMusicCache(film, options).path);
125
+ const edl = findEdl(options);
126
+ if (edl === null) return false;
127
+ const clipKeys = await getClipKeys(film, options.buildDir);
128
+ return clipKeys !== null && existsSync(getVideoMusicCache(film, edl, clipKeys, options).path);
129
+ }
130
+
131
+ /**
132
+ * Whether a paid step costs nothing now because its result is in the cache, without network or ffmpeg. `item` is a
133
+ * clip id (`transcribe`, `isolate`) or `film` (`music`). An unknown clip, a step the film does not take (isolation
134
+ * when it keeps the raw voice), a URL clip not downloaded yet and video-scored music without a cut answer false.
135
+ */
136
+ export async function findCachedStep(film: FootageFilm, step: PaidStepKind, item: string, options: FootageCacheOptions): Promise<boolean> {
137
+ if (step === "music") return isMusicCached(film, options);
138
+ const clip = film.clips.find((entry) => entry.id === item);
139
+ if (clip === undefined || clip.role !== "talk") return false;
140
+ const source = findLocalSource(clip, options.buildDir);
141
+ if (source === null) return false;
142
+ const clipKey = await getClipCacheKey(source, clip);
143
+ const entry = step === "isolate" ? getIsolatedCache(film, clipKey, options) : getTranscriptCache(film, clipKey, options);
144
+ return entry !== null && existsSync(entry.path);
145
+ }
146
+
147
+ export interface FootageEstimateItem {
148
+ step: PaidStepKind;
149
+ /** A clip id, or `film` for the music. */
150
+ item: string;
151
+ provider: string;
152
+ units: number;
153
+ unit: "seconds";
154
+ /** `units` × the step's rate; 0 when cached. */
155
+ credits: number;
156
+ cached: boolean;
157
+ }
158
+
159
+ export interface FootageEstimate {
160
+ items: FootageEstimateItem[];
161
+ totalCredits: number;
162
+ }
163
+
164
+ export interface EstimateFootageOptions extends FootageCacheOptions {
165
+ rates: FootageRates;
166
+ signal?: AbortSignal;
167
+ }
168
+
169
+ const round = (value: number, digits: number): number => {
170
+ const scale = 10 ** digits;
171
+ return Math.round(value * scale) / scale || 0;
172
+ };
173
+
174
+ /**
175
+ * What a footage film will cost in the caller's credits, before anything runs: every clip probed (a URL clip not yet
176
+ * downloaded is probed at its URL), nothing normalized, no provider called. Talking clips need speech to text (and
177
+ * isolation when the film cleans the voice); generated music lasts the cut's length when the cut is known, else the
178
+ * clips' length plus the end card. A cached step costs 0.
179
+ */
180
+ export async function estimateFootageFilm(film: FootageFilm, options: EstimateFootageOptions): Promise<TtsResult<FootageEstimate>> {
181
+ if (film.clips.length === 0) return err(`footage film ${film.id} has no clips.`);
182
+ const files: Record<string, string> = {};
183
+ for (const clip of film.clips) {
184
+ const local = findLocalSource(clip, options.buildDir);
185
+ if (local === null && !isUrl(clip.source)) return err(`clip "${clip.id}": no file at ${clip.source}`);
186
+ files[clip.id] = local ?? clip.source;
187
+ }
188
+ const probed = await probeFootage(film.clips, files, options.signal === undefined ? {} : { signal: options.signal });
189
+ if (!probed.ok) return err(probed.errors.join("\n"));
190
+ const items: FootageEstimateItem[] = [];
191
+ const add = (step: PaidStepKind, item: string, provider: string, units: number, cached: boolean): void => {
192
+ items.push({ step, item, provider, units: round(units, 3), unit: "seconds", credits: cached ? 0 : round(units * options.rates[step], 2), cached });
193
+ };
194
+ let clipSeconds = 0;
195
+ for (const { clip, probe } of probed.clips) {
196
+ const seconds = getTrimmedDuration(clip, probe);
197
+ clipSeconds += seconds;
198
+ if (clip.role !== "talk") continue;
199
+ const source = findLocalSource(clip, options.buildDir);
200
+ const clipKey = source === null ? null : await getClipCacheKey(source, clip);
201
+ const isolated = clipKey === null ? null : getIsolatedCache(film, clipKey, options);
202
+ if (film.isolateVoice) add("isolate", clip.id, options.providers.isolation.id, seconds, isolated !== null && existsSync(isolated.path));
203
+ const transcript = clipKey === null ? null : getTranscriptCache(film, clipKey, options);
204
+ add("transcribe", clip.id, options.providers.stt.id, seconds, transcript !== null && existsSync(transcript.path));
205
+ }
206
+ const music = film.music.source;
207
+ if (music.kind === "prompt" || music.kind === "video") {
208
+ const edl = findEdl(options);
209
+ const seconds = edl === null ? clipSeconds + (film.endCard === null ? 0 : END_CARD_SECONDS) : getFootageFilmSeconds(film, edl);
210
+ add("music", "film", options.providers.music.id, seconds, await isMusicCached(film, options));
211
+ }
212
+ return ok({ items, totalCredits: round(items.reduce((sum, item) => sum + item.credits, 0), 2) });
213
+ }