@softure-ai/marketing-kit 0.9.2 → 0.11.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/CHANGELOG.md +26 -0
- package/README.md +39 -0
- package/dist/config/actions-schema.d.ts +14 -14
- package/dist/config/schema.d.ts +68 -68
- package/dist/config/shot-steps.d.ts +16 -16
- package/dist/footage/draft.d.ts +1 -1
- package/dist/footage/draft.d.ts.map +1 -1
- package/dist/footage/draft.js +7 -3
- package/dist/footage/draft.js.map +1 -1
- package/dist/footage/ffmpeg-command.d.ts +31 -0
- package/dist/footage/ffmpeg-command.d.ts.map +1 -0
- package/dist/footage/ffmpeg-command.js +60 -0
- package/dist/footage/ffmpeg-command.js.map +1 -0
- package/dist/footage/ffmpeg-failure.d.ts +36 -0
- package/dist/footage/ffmpeg-failure.d.ts.map +1 -0
- package/dist/footage/ffmpeg-failure.js +75 -0
- package/dist/footage/ffmpeg-failure.js.map +1 -0
- package/dist/footage/pipeline.d.ts +21 -3
- package/dist/footage/pipeline.d.ts.map +1 -1
- package/dist/footage/pipeline.js +49 -11
- package/dist/footage/pipeline.js.map +1 -1
- package/dist/footage/process.d.ts +19 -1
- package/dist/footage/process.d.ts.map +1 -1
- package/dist/footage/process.js +57 -6
- package/dist/footage/process.js.map +1 -1
- package/dist/footage/publish.d.ts +16 -1
- package/dist/footage/publish.d.ts.map +1 -1
- package/dist/footage/publish.js +35 -5
- package/dist/footage/publish.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/footage/draft.ts +9 -4
- package/src/footage/ffmpeg-command.ts +78 -0
- package/src/footage/ffmpeg-failure.ts +89 -0
- package/src/footage/pipeline.ts +69 -11
- package/src/footage/process.ts +66 -6
- package/src/footage/publish.ts +49 -6
- package/src/index.ts +15 -1
package/src/footage/pipeline.ts
CHANGED
|
@@ -36,19 +36,21 @@ import {
|
|
|
36
36
|
isUrl,
|
|
37
37
|
type CacheEntry,
|
|
38
38
|
} from "./paid.js";
|
|
39
|
-
import { runFfmpeg, runProcess } from "./process.js";
|
|
39
|
+
import { runFfmpeg, runProcess, withFfmpegFailureReporting, type FfmpegFailureHook, type FfmpegFailureReporting } from "./process.js";
|
|
40
40
|
import { splitFilmSentences, type Sentence } from "./sentences.js";
|
|
41
41
|
import {
|
|
42
42
|
buildCoverArgs,
|
|
43
43
|
buildFinishArgs,
|
|
44
44
|
clampCoverSeconds,
|
|
45
45
|
findFinishProblems,
|
|
46
|
+
findFinishVideoProblems,
|
|
46
47
|
getCoverPath,
|
|
47
48
|
getDefaultCoverSeconds,
|
|
48
49
|
isPublishableAudio,
|
|
49
50
|
isPublishableVideo,
|
|
50
51
|
probeFilmFacts,
|
|
51
52
|
readTopLevelBoxes,
|
|
53
|
+
type FinishVideo,
|
|
52
54
|
} from "./publish.js";
|
|
53
55
|
import { describePaidSteps, toPaidAudio, type FootageCharge, type FootageProgress, type FootageProviders, type FootageStage, type PaidAudio, type PaidStep } from "./providers.js";
|
|
54
56
|
import { buildAudioArgs, buildCutPreviewArgs, buildLastFrameArgs, buildMusicArgs, buildSpeechArgs, getSpeechCutOptions } from "./render.js";
|
|
@@ -110,6 +112,12 @@ export interface FootageRunOptions {
|
|
|
110
112
|
* the normalize stamp, so changing it does not normalize clips already made again.
|
|
111
113
|
*/
|
|
112
114
|
normalize?: NormalizeEncoder;
|
|
115
|
+
/**
|
|
116
|
+
* Called when an ffmpeg step fails, before the run throws, with exactly what ran: the arguments, the folder, the
|
|
117
|
+
* whole stderr and the inputs (`FfmpegFailure`). A promise is awaited, so `writeFfmpegFailure` can keep it for a
|
|
118
|
+
* person to run again. Every failure also gets one `log` line with the step and its full command.
|
|
119
|
+
*/
|
|
120
|
+
onFfmpegFailure?: FfmpegFailureHook;
|
|
113
121
|
}
|
|
114
122
|
|
|
115
123
|
export interface PreparedClip {
|
|
@@ -155,6 +163,11 @@ function createStageProgress(
|
|
|
155
163
|
};
|
|
156
164
|
}
|
|
157
165
|
|
|
166
|
+
/** The ffmpeg failure reporting of a footage entry point: its `log` and its `onFfmpegFailure`. */
|
|
167
|
+
export function getFfmpegReporting(options: Pick<FootageRunOptions, "log" | "onFfmpegFailure">): FfmpegFailureReporting {
|
|
168
|
+
return { log: options.log, ...(options.onFfmpegFailure === undefined ? {} : { onFailure: options.onFfmpegFailure }) };
|
|
169
|
+
}
|
|
170
|
+
|
|
158
171
|
/** Rejects with the signal's reason once the run was aborted (before a paid call, which the provider may not stop). */
|
|
159
172
|
function throwIfAborted(signal: AbortSignal | undefined): void {
|
|
160
173
|
signal?.throwIfAborted();
|
|
@@ -186,7 +199,12 @@ function getNormalizeStamp(clip: FootageClip, source: string, frame: Frame): str
|
|
|
186
199
|
}
|
|
187
200
|
|
|
188
201
|
/** Downloads URL clips, probes every clip (all problems at once) and a local music file, normalizes each clip that changed. */
|
|
189
|
-
export
|
|
202
|
+
export function prepareFootage(film: FootageFilm, options: Pick<FootageRunOptions, "buildDir" | "log" | "fetch" | "signal" | "onProgress" | "normalize" | "onFfmpegFailure">): Promise<FootageResult<PreparedClip[]>> {
|
|
203
|
+
return withFfmpegFailureReporting(getFfmpegReporting(options), () => runPrepareFootage(film, options));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The body of `prepareFootage`, inside its ffmpeg failure reporting. */
|
|
207
|
+
async function runPrepareFootage(
|
|
190
208
|
film: FootageFilm,
|
|
191
209
|
options: Pick<FootageRunOptions, "buildDir" | "log" | "fetch" | "signal" | "onProgress" | "normalize">,
|
|
192
210
|
): Promise<FootageResult<PreparedClip[]>> {
|
|
@@ -275,7 +293,12 @@ export function getMusicPaidStep(film: FootageFilm, options: Pick<FootageRunOpti
|
|
|
275
293
|
* voice cleaned first when the film isolates it. Without `isCommit`, a cache miss returns the dry run: every paid
|
|
276
294
|
* call the film still needs, music included, with its length.
|
|
277
295
|
*/
|
|
278
|
-
export
|
|
296
|
+
export function transcribeFootage(film: FootageFilm, clips: PreparedClip[], options: FootageRunOptions): Promise<FootageResult<TranscribeOutcome>> {
|
|
297
|
+
return withFfmpegFailureReporting(getFfmpegReporting(options), () => runTranscribeFootage(film, clips, options));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The body of `transcribeFootage`, inside its ffmpeg failure reporting. */
|
|
301
|
+
async function runTranscribeFootage(film: FootageFilm, clips: PreparedClip[], options: FootageRunOptions): Promise<FootageResult<TranscribeOutcome>> {
|
|
279
302
|
const { buildDir, providers, log, signal } = options;
|
|
280
303
|
if (options.isPlaceholder) return ok(transcribePlaceholder(film, clips, buildDir));
|
|
281
304
|
const keyTerms = getFilmKeyTerms(film);
|
|
@@ -402,6 +425,8 @@ export interface CutFootageFilmOptions {
|
|
|
402
425
|
/** The sentence ids to keep; absent keeps all. */
|
|
403
426
|
keepSentences?: readonly string[];
|
|
404
427
|
signal?: AbortSignal;
|
|
428
|
+
/** Called when a cut frame's ffmpeg step fails, before the cut throws (`FootageRunOptions.onFfmpegFailure`). */
|
|
429
|
+
onFfmpegFailure?: FfmpegFailureHook;
|
|
405
430
|
}
|
|
406
431
|
|
|
407
432
|
/** The file next to the EDL that records what the auto transitions measured. */
|
|
@@ -412,7 +437,12 @@ export const CUTS_FILE = "cuts.json";
|
|
|
412
437
|
* (`chooseCutTransitions`): each jump cut gets `zoom` or `fade`, and what it measured is answered and written to
|
|
413
438
|
* `cuts.json` next to the EDL, so an app or an agent sees why. Otherwise the same as `cutFootage`, and `cuts` is empty.
|
|
414
439
|
*/
|
|
415
|
-
export
|
|
440
|
+
export function cutFootageFilm(film: FootageFilm, clips: PreparedClip[], words: Record<string, TimedWord[]>, edlPath: string, options: CutFootageFilmOptions = {}): Promise<{ edl: Edl; cuts: CutMeasure[] }> {
|
|
441
|
+
return withFfmpegFailureReporting(options.onFfmpegFailure === undefined ? {} : { onFailure: options.onFfmpegFailure }, () => runCutFootageFilm(film, clips, words, edlPath, options));
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The body of `cutFootageFilm`, inside its ffmpeg failure reporting. */
|
|
445
|
+
async function runCutFootageFilm(
|
|
416
446
|
film: FootageFilm,
|
|
417
447
|
clips: PreparedClip[],
|
|
418
448
|
words: Record<string, TimedWord[]>,
|
|
@@ -592,6 +622,12 @@ export interface RenderFootageOptions extends FootageRunOptions {
|
|
|
592
622
|
* `slow`). `quality: "draft"` with `crf: 18` encodes fast at the published quality. By default the tier's CRF.
|
|
593
623
|
*/
|
|
594
624
|
crf?: number;
|
|
625
|
+
/**
|
|
626
|
+
* Re-encode the picture in the final pass instead of copying it: H.264 High, yuv420p, at this x264 preset and CRF,
|
|
627
|
+
* optionally capped at `maxBitrate` (issue #1068). `quality: "draft", crf: 18` plus `{ preset: "veryfast", crf: 20 }`
|
|
628
|
+
* publishes High at a controlled size. By default the picture is copied when publishable.
|
|
629
|
+
*/
|
|
630
|
+
finishVideo?: FinishVideo;
|
|
595
631
|
}
|
|
596
632
|
|
|
597
633
|
export type RenderedFootage = { kind: "dry-run"; steps: PaidStep[] } | ({ kind: "rendered"; output: string; seconds: number; edlPath: string } & FinishedFootage);
|
|
@@ -601,7 +637,12 @@ export type RenderedFootage = { kind: "dry-run"; steps: PaidStep[] } | ({ kind:
|
|
|
601
637
|
* hyperframes, final pass, cover. First of all it checks that hyperframes' temp folder and the build folder have the
|
|
602
638
|
* 1 GiB free hyperframes requires, so a full disk ends the run with a sentence before anything is bought or built.
|
|
603
639
|
*/
|
|
604
|
-
export
|
|
640
|
+
export function renderFootage(film: FootageFilm, clips: PreparedClip[], transcript: Extract<TranscribeOutcome, { kind: "ready" }>, edl: Edl, options: RenderFootageOptions): Promise<FootageResult<RenderedFootage>> {
|
|
641
|
+
return withFfmpegFailureReporting(getFfmpegReporting(options), () => runRenderFootage(film, clips, transcript, edl, options));
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** The body of `renderFootage`, inside its ffmpeg failure reporting. */
|
|
645
|
+
async function runRenderFootage(
|
|
605
646
|
film: FootageFilm,
|
|
606
647
|
clips: PreparedClip[],
|
|
607
648
|
transcript: Extract<TranscribeOutcome, { kind: "ready" }>,
|
|
@@ -609,6 +650,8 @@ export async function renderFootage(
|
|
|
609
650
|
options: RenderFootageOptions,
|
|
610
651
|
): Promise<FootageResult<RenderedFootage>> {
|
|
611
652
|
const { buildDir, log, signal } = options;
|
|
653
|
+
const finishVideoProblems = options.finishVideo === undefined ? [] : findFinishVideoProblems(options.finishVideo);
|
|
654
|
+
if (finishVideoProblems.length > 0) return err(finishVideoProblems.join(" "));
|
|
612
655
|
const lowDisk = findLowDiskProblems({ temp: getRenderTempDir(process.env, options.tempDir), build: buildDir }, options.readFreeBytes ?? getFreeBytes);
|
|
613
656
|
if (lowDisk.length > 0) return err(`not enough disk space to render: ${lowDisk.join(" ")}`);
|
|
614
657
|
const seconds = getFootageFilmSeconds(film, edl);
|
|
@@ -739,12 +782,12 @@ export interface FinishedFootage {
|
|
|
739
782
|
/**
|
|
740
783
|
* The final pass over hyperframes' render: the mix normalized to `film.mixLoudness` (measured on the render, one
|
|
741
784
|
* linear gain; the picture still copied), publishable codecs and fast start (stream copy where the render already
|
|
742
|
-
* matches), checked with ffprobe, then the cover and the file's facts. Exported for tests only.
|
|
785
|
+
* matches; `finishVideo` re-encodes the picture to H.264 High at its preset and CRF), checked with ffprobe, then the cover and the file's facts. Exported for tests only.
|
|
743
786
|
*/
|
|
744
787
|
export async function finishFootage(
|
|
745
788
|
film: Pick<FootageFilm, "mixLoudness" | "cover">,
|
|
746
789
|
input: { renderFile: string; seconds: number; coverAt: number },
|
|
747
|
-
options: Pick<RenderFootageOptions, "log" | "signal" | "output" | "onProgress">,
|
|
790
|
+
options: Pick<RenderFootageOptions, "log" | "signal" | "output" | "onProgress" | "finishVideo">,
|
|
748
791
|
): Promise<FootageResult<FinishedFootage>> {
|
|
749
792
|
const { log, signal, output } = options;
|
|
750
793
|
const aborting = signal === undefined ? {} : { signal };
|
|
@@ -763,9 +806,10 @@ export async function finishFootage(
|
|
|
763
806
|
log(`loudness: the film's mix measured ${measured.measurement.inputI.toFixed(1)} LUFS, normalized to ${mixLoudness.target} LUFS (true peak ${mixLoudness.truePeak} dBTP).`);
|
|
764
807
|
}
|
|
765
808
|
}
|
|
766
|
-
const
|
|
809
|
+
const { finishVideo } = options;
|
|
810
|
+
const isVideoCopied = finishVideo === undefined && isPublishableVideo(rendered.facts.video);
|
|
767
811
|
const isAudioCopied = audioFilter === undefined && (rendered.facts.audio === null || isPublishableAudio(rendered.facts.audio));
|
|
768
|
-
const finishArgs = buildFinishArgs(input.renderFile, rendered.facts, output, audioFilter === undefined ? {} : { audioFilter });
|
|
812
|
+
const finishArgs = buildFinishArgs(input.renderFile, rendered.facts, output, { ...(audioFilter === undefined ? {} : { audioFilter }), ...(finishVideo === undefined ? {} : { video: finishVideo }) });
|
|
769
813
|
await runFfmpeg("The film's final pass", finishArgs, { ...aborting, output, onSeconds: (done) => progress(0, done) });
|
|
770
814
|
rmSync(input.renderFile, { force: true });
|
|
771
815
|
const finished = await probeFilmFacts(output, aborting);
|
|
@@ -774,7 +818,7 @@ export async function finishFootage(
|
|
|
774
818
|
if (problems.length > 0) return err(`the finished film ${output} is not publishable: ${problems.join("; ")}.`);
|
|
775
819
|
progress(0, input.seconds);
|
|
776
820
|
const { bytes, width, height, durationSeconds } = finished.facts;
|
|
777
|
-
const streams = isVideoCopied
|
|
821
|
+
const streams = describeFinishStreams({ isVideoCopied, isAudioCopied, hasAudio: rendered.facts.audio !== null, ...(finishVideo === undefined ? {} : { finishVideo }) });
|
|
778
822
|
log(`finish: ${streams} to H.264 ${finished.facts.video.profile ?? ""}, AAC 48 kHz stereo, fast start; ${width}×${height}, ${durationSeconds.toFixed(2)} s, ${bytes} bytes.`);
|
|
779
823
|
let cover: string | null = null;
|
|
780
824
|
if (film.cover !== null) {
|
|
@@ -787,6 +831,15 @@ export async function finishFootage(
|
|
|
787
831
|
return ok({ bytes, width, height, durationSeconds, cover });
|
|
788
832
|
}
|
|
789
833
|
|
|
834
|
+
/** What the final pass did to each stream, for its log line. */
|
|
835
|
+
function describeFinishStreams(pass: { isVideoCopied: boolean; isAudioCopied: boolean; hasAudio: boolean; finishVideo?: FinishVideo }): string {
|
|
836
|
+
if (pass.finishVideo === undefined) return pass.isVideoCopied && pass.isAudioCopied ? "streams copied" : pass.isVideoCopied ? "picture copied, sound re-encoded" : "re-encoded";
|
|
837
|
+
const { preset, crf, maxBitrate } = pass.finishVideo;
|
|
838
|
+
const picture = `picture re-encoded (${preset} CRF ${crf}${maxBitrate === undefined ? "" : `, max ${maxBitrate}`})`;
|
|
839
|
+
if (!pass.hasAudio) return picture;
|
|
840
|
+
return `${picture}, sound ${pass.isAudioCopied ? "copied" : "re-encoded"}`;
|
|
841
|
+
}
|
|
842
|
+
|
|
790
843
|
/** hyperframes' progress lines carry a percentage (`… 42%`); the last one on a line counts. */
|
|
791
844
|
export function readRenderPercent(line: string): number | null {
|
|
792
845
|
const matches = [...line.matchAll(/(\d{1,3}(?:\.\d+)?)\s?%/g)];
|
|
@@ -902,7 +955,12 @@ export interface RenderFootageFilmOptions extends RenderFootageOptions {
|
|
|
902
955
|
* The whole footage film from a `FootageFilm` object, no `marketing.json` needed: prepare, transcribe (or the dry
|
|
903
956
|
* run), cut (reusing an EDL already in the build folder unless `isRecut`), render.
|
|
904
957
|
*/
|
|
905
|
-
export
|
|
958
|
+
export function renderFootageFilm(film: FootageFilm, options: RenderFootageFilmOptions): Promise<FootageResult<RenderedFootage>> {
|
|
959
|
+
return withFfmpegFailureReporting(getFfmpegReporting(options), () => runRenderFootageFilm(film, options));
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/** The body of `renderFootageFilm`, inside its ffmpeg failure reporting. */
|
|
963
|
+
async function runRenderFootageFilm(film: FootageFilm, options: RenderFootageFilmOptions): Promise<FootageResult<RenderedFootage>> {
|
|
906
964
|
const clips = await prepareFootage(film, options);
|
|
907
965
|
if (!clips.ok) return clips;
|
|
908
966
|
const transcript = await transcribeFootage(film, clips.value, options);
|
package/src/footage/process.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import { spawn } from "node:child_process";
|
|
2
3
|
import { rmSync } from "node:fs";
|
|
3
4
|
|
|
5
|
+
import { FFMPEG_FAILURE_STDERR_LINES, findFfmpegInputs, formatFfmpegCommand, type FfmpegFailure } from "./ffmpeg-command.js";
|
|
6
|
+
|
|
4
7
|
/**
|
|
5
8
|
* Child processes of the footage blocks (ffmpeg, ffprobe, hyperframes), run without blocking the event loop, so a jobs
|
|
6
9
|
* worker keeps its lease heartbeat during a long normalize or render. An abort kills the child, removes the partial
|
|
@@ -103,6 +106,28 @@ export function readFfmpegProgressSeconds(line: string): number | null {
|
|
|
103
106
|
return match === null ? null : Number(match[1]) / 1_000_000;
|
|
104
107
|
}
|
|
105
108
|
|
|
109
|
+
/** Called with a failed ffmpeg step before it throws; a promise is awaited, so the app can write the failure out. */
|
|
110
|
+
export type FfmpegFailureHook = (failure: FfmpegFailure) => void | Promise<void>;
|
|
111
|
+
|
|
112
|
+
export interface FfmpegFailureReporting {
|
|
113
|
+
onFailure?: FfmpegFailureHook;
|
|
114
|
+
/** Gets one line naming the failed step and its full command. */
|
|
115
|
+
log?: (line: string) => void;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const failureReporting = new AsyncLocalStorage<FfmpegFailureReporting>();
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Runs `run` with `onFailure` and `log` set for every ffmpeg step inside it, however deep (the footage entry points
|
|
122
|
+
* wrap their body in it). A value it does not set keeps the one of an enclosing call.
|
|
123
|
+
*/
|
|
124
|
+
export function withFfmpegFailureReporting<T>(reporting: FfmpegFailureReporting, run: () => Promise<T>): Promise<T> {
|
|
125
|
+
const outer = failureReporting.getStore();
|
|
126
|
+
const onFailure = reporting.onFailure ?? outer?.onFailure;
|
|
127
|
+
const log = reporting.log ?? outer?.log;
|
|
128
|
+
return failureReporting.run({ ...(onFailure === undefined ? {} : { onFailure }), ...(log === undefined ? {} : { log }) }, run);
|
|
129
|
+
}
|
|
130
|
+
|
|
106
131
|
export interface FfmpegRunOptions {
|
|
107
132
|
signal?: AbortSignal;
|
|
108
133
|
/** The file the run writes, removed on abort. */
|
|
@@ -111,14 +136,38 @@ export interface FfmpegRunOptions {
|
|
|
111
136
|
onSeconds?: (seconds: number) => void;
|
|
112
137
|
/** The folder ffmpeg runs in, so relative names in the arguments and the filter graph resolve there. */
|
|
113
138
|
cwd?: string;
|
|
139
|
+
/** Called when the run fails, before it throws; by default the one `withFfmpegFailureReporting` set. */
|
|
140
|
+
onFailure?: FfmpegFailureHook;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Logs the failure and hands it to the hook; an error of the hook itself is logged, never thrown over ffmpeg's. */
|
|
144
|
+
async function reportFfmpegFailure(failure: FfmpegFailure, onFailure: FfmpegFailureHook | undefined): Promise<void> {
|
|
145
|
+
const reporting = failureReporting.getStore();
|
|
146
|
+
const log = reporting?.log;
|
|
147
|
+
log?.(`ffmpeg failed: ${failure.step}, in ${failure.cwd}: ${formatFfmpegCommand(failure.args)}`);
|
|
148
|
+
const hook = onFailure ?? reporting?.onFailure;
|
|
149
|
+
if (hook === undefined) return;
|
|
150
|
+
try {
|
|
151
|
+
await hook(failure);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
const message = `ffmpeg failed: the failure hook of "${failure.step}" threw: ${error instanceof Error ? error.message : String(error)}`;
|
|
154
|
+
if (log === undefined) console.error(message);
|
|
155
|
+
else log(message);
|
|
156
|
+
}
|
|
114
157
|
}
|
|
115
158
|
|
|
116
|
-
/**
|
|
159
|
+
/**
|
|
160
|
+
* Runs ffmpeg with its progress on stdout; throws naming the step when it fails (a broken input or machine), after
|
|
161
|
+
* handing the whole failure (`FfmpegFailure`) to `onFailure` and one line with the command to the reporting `log`.
|
|
162
|
+
*/
|
|
117
163
|
export async function runFfmpeg(step: string, args: string[], options: FfmpegRunOptions = {}): Promise<void> {
|
|
118
164
|
const errors: string[] = [];
|
|
165
|
+
const stderr: string[] = [];
|
|
166
|
+
const spawned = ["-progress", "pipe:1", "-nostats", ...args];
|
|
167
|
+
const cwd = options.cwd ?? process.cwd();
|
|
119
168
|
const outcome = await runProcess({
|
|
120
169
|
command: "ffmpeg",
|
|
121
|
-
args:
|
|
170
|
+
args: spawned,
|
|
122
171
|
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
123
172
|
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
124
173
|
removeOnAbort: options.output === undefined ? [] : [options.output],
|
|
@@ -127,12 +176,23 @@ export async function runFfmpeg(step: string, args: string[], options: FfmpegRun
|
|
|
127
176
|
if (seconds !== null) options.onSeconds?.(seconds);
|
|
128
177
|
},
|
|
129
178
|
onStderrLine: (line) => {
|
|
179
|
+
stderr.push(line);
|
|
180
|
+
if (stderr.length > FFMPEG_FAILURE_STDERR_LINES) stderr.shift();
|
|
130
181
|
if (line.trim().length > 0) errors.push(line);
|
|
131
182
|
},
|
|
132
183
|
});
|
|
184
|
+
if (outcome.kind === "exited" && outcome.code === 0) return;
|
|
185
|
+
const failure: FfmpegFailure = {
|
|
186
|
+
step,
|
|
187
|
+
args: spawned,
|
|
188
|
+
cwd,
|
|
189
|
+
code: outcome.kind === "exited" ? outcome.code : null,
|
|
190
|
+
signal: outcome.kind === "exited" ? outcome.signal : null,
|
|
191
|
+
stderr: outcome.kind === "exited" ? stderr : [outcome.error],
|
|
192
|
+
inputs: findFfmpegInputs(spawned, cwd),
|
|
193
|
+
};
|
|
194
|
+
await reportFfmpegFailure(failure, options.onFailure);
|
|
133
195
|
if (outcome.kind === "not-started") throw new Error(`${step}: ffmpeg did not start (${outcome.error}).`);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
throw new Error(`${step}: ffmpeg ended with code ${String(outcome.code)} (signal ${outcome.signal ?? "-"})${detail.length > 0 ? `: ${detail}` : ""}.`);
|
|
137
|
-
}
|
|
196
|
+
const detail = errors.slice(-5).join(" | ");
|
|
197
|
+
throw new Error(`${step}: ffmpeg ended with code ${String(outcome.code)} (signal ${outcome.signal ?? "-"})${detail.length > 0 ? `: ${detail}` : ""}.`);
|
|
138
198
|
}
|
package/src/footage/publish.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { z } from "zod";
|
|
|
5
5
|
|
|
6
6
|
import { getSegmentStarts, type Edl } from "./edl.js";
|
|
7
7
|
import type { ClipRole } from "./film.js";
|
|
8
|
-
import { FOOTAGE_SAMPLE_RATE } from "./normalize.js";
|
|
8
|
+
import { FOOTAGE_SAMPLE_RATE, X264_PRESETS, type X264Preset } from "./normalize.js";
|
|
9
9
|
import { runProcess } from "./process.js";
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -103,15 +103,58 @@ export function isPublishableAudio(audio: NonNullable<FilmFacts["audio"]>): bool
|
|
|
103
103
|
return audio.codec === "aac" && audio.sampleRate === FOOTAGE_SAMPLE_RATE && audio.channels === 2;
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
/**
|
|
107
|
+
* How the final pass encodes the picture when an app asks for it (issue #1068): H.264 High, yuv420p, at this x264
|
|
108
|
+
* `preset` and `crf` (a whole number from 0 to 51), optionally capped at `maxBitrate` (an ffmpeg rate such as `"12M"`
|
|
109
|
+
* or `"12000k"`; the encoder's buffer is twice the cap). A `quality: "draft"` render plus `{ preset: "veryfast",
|
|
110
|
+
* crf: 20 }` publishes High at a controlled size for about a quarter of what hyperframes' `standard` tier costs.
|
|
111
|
+
*/
|
|
112
|
+
export interface FinishVideo {
|
|
113
|
+
preset: X264Preset;
|
|
114
|
+
crf: number;
|
|
115
|
+
maxBitrate?: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A rate ffmpeg reads: a positive number with an optional `k` or `M` suffix. */
|
|
119
|
+
const BITRATE_PATTERN = /^(\d+(?:\.\d+)?)([kM]?)$/;
|
|
120
|
+
|
|
121
|
+
/** What makes a `FinishVideo` unusable, one sentence per value; empty when nothing does. */
|
|
122
|
+
export function findFinishVideoProblems(video: FinishVideo): string[] {
|
|
123
|
+
const problems: string[] = [];
|
|
124
|
+
if (!(X264_PRESETS as readonly string[]).includes(video.preset)) problems.push(`finishVideo.preset must be one of ${X264_PRESETS.join(", ")}, got ${String(video.preset)}.`);
|
|
125
|
+
if (!Number.isInteger(video.crf) || video.crf < 0 || video.crf > 51) problems.push(`finishVideo.crf must be a whole number from 0 to 51, got ${String(video.crf)}.`);
|
|
126
|
+
if (video.maxBitrate !== undefined) {
|
|
127
|
+
const match = BITRATE_PATTERN.exec(video.maxBitrate);
|
|
128
|
+
if (match === null || Number(match[1]) <= 0) problems.push(`finishVideo.maxBitrate must be a positive rate such as "12M" or "12000k", got "${video.maxBitrate}".`);
|
|
129
|
+
}
|
|
130
|
+
return problems;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The encoder's buffer for a rate cap: twice the cap, in the cap's unit. */
|
|
134
|
+
function getBufferSize(maxBitrate: string): string {
|
|
135
|
+
const match = BITRATE_PATTERN.exec(maxBitrate);
|
|
136
|
+
if (match === null) throw new Error(`finishVideo.maxBitrate "${maxBitrate}" is not a rate; check it with findFinishVideoProblems first.`);
|
|
137
|
+
return `${String(Number(match[1]) * 2)}${match[2] ?? ""}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The picture's encoder arguments: H.264 High yuv420p at the given preset and CRF, capped when asked. */
|
|
141
|
+
function getVideoEncodeArgs(video: FinishVideo): string[] {
|
|
142
|
+
const cap = video.maxBitrate === undefined ? [] : ["-maxrate", video.maxBitrate, "-bufsize", getBufferSize(video.maxBitrate)];
|
|
143
|
+
return ["-c:v", "libx264", "-profile:v", "high", "-pix_fmt", "yuv420p", "-preset", video.preset, "-crf", String(video.crf), ...cap];
|
|
144
|
+
}
|
|
145
|
+
|
|
106
146
|
/**
|
|
107
147
|
* The final pass: each stream that is already publishable is copied, the other re-encoded (the picture to H.264 High),
|
|
108
148
|
* and the `moov` box moved to the front. A film without sound keeps none. `audioFilter` (the mix's loudness pass)
|
|
109
|
-
* re-encodes the sound through it.
|
|
149
|
+
* re-encodes the sound through it. `video` re-encodes the picture whatever it is, at its preset and CRF (issue #1068).
|
|
110
150
|
*/
|
|
111
|
-
export function buildFinishArgs(input: string, facts: Pick<FilmFacts, "video" | "audio">, output: string, options: { audioFilter?: string } = {}): string[] {
|
|
112
|
-
const video =
|
|
113
|
-
|
|
114
|
-
|
|
151
|
+
export function buildFinishArgs(input: string, facts: Pick<FilmFacts, "video" | "audio">, output: string, options: { audioFilter?: string; video?: FinishVideo } = {}): string[] {
|
|
152
|
+
const video =
|
|
153
|
+
options.video !== undefined
|
|
154
|
+
? getVideoEncodeArgs(options.video)
|
|
155
|
+
: isPublishableVideo(facts.video)
|
|
156
|
+
? ["-c:v", "copy"]
|
|
157
|
+
: getVideoEncodeArgs({ preset: "medium", crf: VIDEO_CRF });
|
|
115
158
|
const encodeAudio = ["-c:a", "aac", "-b:a", AUDIO_BITRATE, "-ar", String(FOOTAGE_SAMPLE_RATE), "-ac", "2"];
|
|
116
159
|
const audio =
|
|
117
160
|
facts.audio === null
|
package/src/index.ts
CHANGED
|
@@ -386,6 +386,7 @@ export {
|
|
|
386
386
|
buildFinishArgs,
|
|
387
387
|
clampCoverSeconds,
|
|
388
388
|
findFinishProblems,
|
|
389
|
+
findFinishVideoProblems,
|
|
389
390
|
getCoverPath,
|
|
390
391
|
getDefaultCoverSeconds,
|
|
391
392
|
isFastStart,
|
|
@@ -396,8 +397,21 @@ export {
|
|
|
396
397
|
readFilmFacts,
|
|
397
398
|
readTopLevelBoxes,
|
|
398
399
|
type FilmFacts,
|
|
400
|
+
type FinishVideo,
|
|
399
401
|
} from "./footage/publish.js";
|
|
400
|
-
export {
|
|
402
|
+
export {
|
|
403
|
+
readFfmpegProgressSeconds,
|
|
404
|
+
runFfmpeg,
|
|
405
|
+
runProcess,
|
|
406
|
+
withFfmpegFailureReporting,
|
|
407
|
+
type FfmpegFailureHook,
|
|
408
|
+
type FfmpegFailureReporting,
|
|
409
|
+
type FfmpegRunOptions,
|
|
410
|
+
type ProcessOptions,
|
|
411
|
+
type ProcessOutcome,
|
|
412
|
+
} from "./footage/process.js";
|
|
413
|
+
export { FFMPEG_FAILURE_STDERR_LINES, formatFfmpegCommand, splitFilterGraph, type FfmpegFailure } from "./footage/ffmpeg-command.js";
|
|
414
|
+
export { buildFfmpegFailureScript, FFMPEG_FAILURE_FILES, writeFfmpegFailure, type FfmpegFailureInput } from "./footage/ffmpeg-failure.js";
|
|
401
415
|
export {
|
|
402
416
|
estimateFootageFilm,
|
|
403
417
|
findCachedStep,
|