-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathchunkEncoder.ts
More file actions
705 lines (656 loc) · 23.8 KB
/
chunkEncoder.ts
File metadata and controls
705 lines (656 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/**
* Chunk Encoder Service
*
* Encodes captured frames into video using FFmpeg.
* Supports CPU (libx264) and GPU encoding.
*/
import { spawn } from "child_process";
import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from "fs";
import { join, dirname } from "path";
import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
import {
type GpuEncoder,
getCachedGpuEncoder,
getGpuEncoderName,
mapPresetForGpuEncoder,
} from "../utils/gpuEncoder.js";
import { type HdrTransfer, getHdrEncoderColorParams } from "../utils/hdr.js";
import { formatFfmpegError, runFfmpeg } from "../utils/runFfmpeg.js";
import { fpsToFfmpegArg } from "@hyperframes/core";
import type { EncoderOptions, EncodeResult, MuxResult } from "./chunkEncoder.types.js";
export type { EncoderOptions, EncodeResult, MuxResult } from "./chunkEncoder.types.js";
export const ENCODER_PRESETS = {
draft: { preset: "ultrafast", quality: 28, codec: "h264" as const },
standard: { preset: "medium", quality: 18, codec: "h264" as const },
high: { preset: "slow", quality: 15, codec: "h264" as const },
};
export interface EncoderPreset {
preset: string;
quality: number;
codec: "h264" | "h265" | "vp9" | "prores";
pixelFormat: string;
hdr?: { transfer: HdrTransfer };
}
/**
* Get encoder preset for a given quality and output format.
* WebM uses VP9 with alpha-capable pixel format; MP4 uses h264 (or h265 for HDR);
* MOV uses ProRes 4444 with alpha for editor-compatible transparency.
*/
export function getEncoderPreset(
quality: "draft" | "standard" | "high",
format: "mp4" | "webm" | "mov" = "mp4",
hdr?: { transfer: HdrTransfer },
): EncoderPreset {
const base = ENCODER_PRESETS[quality];
if (format === "webm") {
return {
preset: base.preset === "ultrafast" ? "realtime" : "good",
quality: base.quality,
codec: "vp9",
pixelFormat: "yuva420p",
};
}
if (format === "mov") {
return {
preset: "4444",
quality: base.quality,
codec: "prores",
pixelFormat: "yuva444p10le",
};
}
if (hdr) {
return {
preset: base.preset === "ultrafast" ? "fast" : base.preset,
quality: base.quality,
codec: "h265",
pixelFormat: "yuv420p10le",
hdr,
};
}
return { ...base, pixelFormat: "yuv420p" };
}
// Re-export GPU utilities so existing consumers that import from chunkEncoder still work.
export { detectGpuEncoder, type GpuEncoder } from "../utils/gpuEncoder.js";
export function buildEncoderArgs(
options: EncoderOptions,
inputArgs: string[],
outputPath: string,
gpuEncoder: GpuEncoder = null,
): string[] {
const {
fps,
codec = "h264",
preset = "medium",
quality = 23,
bitrate,
pixelFormat = "yuv420p",
useGpu = false,
} = options;
// libx264 cannot encode HDR. If a caller passes hdr with codec=h264 we'd
// produce a "half-HDR" file (BT.2020 container tags but a BT.709 VUI block
// inside the bitstream) which confuses HDR-aware players. Strip hdr and
// log a warning so the caller picks h265 (the SDR-tagged output is honest).
if (options.hdr && codec === "h264") {
console.warn(
"[chunkEncoder] HDR is not supported with codec=h264 (libx264 has no HDR support). " +
"Stripping HDR metadata and tagging output as SDR/BT.709. Use codec=h265 for HDR output.",
);
options = { ...options, hdr: undefined };
}
const args: string[] = [...inputArgs, "-r", fpsToFfmpegArg(fps)];
const shouldUseGpu = useGpu && gpuEncoder !== null;
if (codec === "h264" || codec === "h265") {
if (shouldUseGpu) {
const encoderName = getGpuEncoderName(gpuEncoder, codec);
args.push("-c:v", encoderName);
switch (gpuEncoder) {
case "nvenc":
args.push("-preset", mapPresetForGpuEncoder("nvenc", preset));
if (bitrate) args.push("-b:v", bitrate);
else args.push("-cq", String(quality));
break;
case "videotoolbox":
if (bitrate) args.push("-b:v", bitrate);
else {
const vtQuality = Math.max(0, Math.min(100, 100 - quality * 2));
args.push("-q:v", String(vtQuality));
}
args.push("-allow_sw", "1");
break;
case "vaapi":
args.unshift("-vaapi_device", "/dev/dri/renderD128");
args.push("-vf", "format=nv12,hwupload");
if (bitrate) args.push("-b:v", bitrate);
else args.push("-qp", String(quality));
break;
case "qsv":
args.push("-preset", mapPresetForGpuEncoder("qsv", preset));
if (bitrate) args.push("-b:v", bitrate);
else args.push("-global_quality", String(quality));
break;
}
// Same B-frame story as the SW branch below — nvenc emits B-frames
// by default (qsv via b_strategy, vaapi too), and the negative-DTS
// freeze hits the same downstream players. The unconditional
// `-avoid_negative_ts make_zero` near the bottom of this function
// covers the mux level, but we belt-and-suspenders the encoder too
// so even tools that consume the chunk file directly (without going
// through our mux step) play correctly. videotoolbox doesn't accept
// `-bf` so it's skipped — videotoolbox h264 also doesn't emit
// negative DTS in practice on macOS Sonoma+.
if (
codec === "h264" &&
(gpuEncoder === "nvenc" || gpuEncoder === "qsv" || gpuEncoder === "vaapi")
) {
args.push("-bf", "0");
if (gpuEncoder === "qsv") {
args.push("-b_strategy", "0");
}
}
} else {
const encoderName = codec === "h264" ? "libx264" : "libx265";
args.push("-c:v", encoderName, "-preset", preset);
if (bitrate) args.push("-b:v", bitrate);
else args.push("-crf", String(quality));
// Closed-GOP / forced-keyframe args so an external orchestrator can
// ffmpeg-concat chunk files with `-c copy`. Without these, libx264 /
// libx265 emit open-GOP frames with mid-chunk scenecut keyframes; the
// first frame of each chunk isn't an independently-decodable IDR and
// concat-copy playback freezes at chunk seams on some decoders.
const lockGop = options.lockGopForChunkConcat === true;
let gop = 0;
if (lockGop) {
if (
typeof options.gopSize !== "number" ||
!Number.isFinite(options.gopSize) ||
options.gopSize <= 0
) {
throw new Error(
`[chunkEncoder] lockGopForChunkConcat=true requires a positive integer gopSize (received ${String(options.gopSize)})`,
);
}
gop = Math.floor(options.gopSize);
args.push(
"-g",
String(gop),
"-keyint_min",
String(gop),
"-sc_threshold",
"0",
"-force_key_frames",
`expr:eq(mod(n,${gop}),0)`,
);
}
// Disable B-frames. Standard h264 with B-frames produces negative DTS
// at the start of the stream (the first B-frame's decode order is
// "before" the first I-frame's presentation time). VS Code's video
// preview, several browser <video> pipelines, and some HW decoders
// freeze on the first frame when DTS is negative, so audio plays alone.
// -bf 0 makes PTS == DTS at every frame, eliminating the issue at the
// source. Quality cost is ~5–10% larger files at the same CRF — a
// worthwhile trade for "the file plays everywhere".
//
// Also emit `-bf 0` for h265 when closed-GOP is locked: chunked
// concat-copy of h265 with B-frames hits the same negative-DTS hazard
// at every chunk boundary, even though single-stream h265 normally
// tolerates B-frames fine.
if (codec === "h264" || (codec === "h265" && lockGop)) {
args.push("-bf", "0");
}
// Encoder-specific params: anti-banding + color space tagging.
// aq-mode=3 redistributes bits to dark flat areas (gradients).
// For HDR x265 paths we additionally embed BT.2020 + transfer + HDR static
// mastering metadata via x265-params; libx264 only carries BT.709 tags
// since HDR through H.264 is not supported by this encoder path.
//
// When closed-GOP is locked we additionally bake the keyint/scenecut
// controls into the codec param string so libx264's slice-type decisions
// and libx265's rate-control respect the IDR cadence end-to-end (without
// these, ffmpeg's `-force_key_frames` is honored but the underlying
// encoder may still insert mini-GOPs with open-GOP references that
// break concat-copy on some decoders). `repeat-headers=1` writes SPS/PPS
// at every keyframe so each chunk file is self-contained.
const xParamsFlag = codec === "h264" ? "-x264-params" : "-x265-params";
const colorParams =
codec === "h265" && options.hdr
? getHdrEncoderColorParams(options.hdr.transfer).x265ColorParams
: "colorprim=bt709:transfer=bt709:colormatrix=bt709";
let gopParams = "";
if (lockGop) {
const shared = "scenecut=0:open-gop=0:repeat-headers=1";
gopParams = codec === "h264" ? shared : `keyint=${gop}:min-keyint=${gop}:${shared}`;
}
const joinParams = (...parts: string[]): string =>
parts.filter((p) => p.length > 0).join(":");
if (preset === "ultrafast") {
args.push(xParamsFlag, joinParams("aq-mode=3", colorParams, gopParams));
} else {
args.push(
xParamsFlag,
joinParams("aq-mode=3", "aq-strength=0.8", "deblock=1,1", colorParams, gopParams),
);
}
}
// Apple devices require hvc1 tag for HEVC playback (default hev1 won't open in QuickTime)
if (codec === "h265") {
args.push("-tag:v", "hvc1");
}
} else if (codec === "vp9") {
args.push("-c:v", "libvpx-vp9", "-b:v", bitrate || "0", "-crf", String(quality));
args.push("-deadline", preset === "ultrafast" ? "realtime" : "good");
args.push("-row-mt", "1");
// Closed-GOP args for distributed chunk concat-copy. Mirrors the
// libx264/libx265 branch above: `lockGopForChunkConcat=true` lays a
// keyframe at every chunk boundary so `ffmpeg -f concat -c copy` can
// stitch sibling chunks losslessly.
//
// VP9-specific: `-auto-alt-ref 0` is mandatory. Alt-ref (a.k.a.
// "ARNR") frames are non-displayable references libvpx-vp9 inserts
// anywhere in the GOP for compression; they break concat-copy at
// chunk seams because the boundary frame is no longer the first
// displayable reference. The alpha branch below already disables
// alt-ref for an unrelated reason (alpha + alt-ref is unsupported);
// closed-GOP extends that to every pixel format.
//
// `-cpu-used 2` pins the libvpx-vp9 speed/quality tradeoff so chunks
// encoded on workers with different default cpu-used values still
// produce visually consistent output across seams. libvpx-vp9's
// default with `-deadline good` has drifted across versions
// historically — locking it makes the planHash round-trip
// deterministic.
const lockGopVp9 = options.lockGopForChunkConcat === true;
if (lockGopVp9) {
if (
typeof options.gopSize !== "number" ||
!Number.isFinite(options.gopSize) ||
options.gopSize <= 0
) {
throw new Error(
`[chunkEncoder] lockGopForChunkConcat=true requires a positive integer gopSize (received ${String(options.gopSize)})`,
);
}
const gop = Math.floor(options.gopSize);
args.push(
"-g",
String(gop),
"-keyint_min",
String(gop),
"-auto-alt-ref",
"0",
"-cpu-used",
"2",
);
}
if (pixelFormat === "yuva420p") {
// Alpha + alt-ref is unsupported by libvpx-vp9. The closed-GOP
// branch above already disables alt-ref; only push the flag for
// the non-locked alpha case to keep the args list clean (a second
// `-auto-alt-ref 0` is harmless but noisier in `ffmpeg -loglevel`
// diagnostics).
if (!lockGopVp9) {
args.push("-auto-alt-ref", "0");
}
args.push("-metadata:s:v:0", "alpha_mode=1");
}
} else if (codec === "prores") {
args.push("-c:v", "prores_ks", "-profile:v", preset, "-vendor", "apl0");
args.push("-pix_fmt", pixelFormat);
return [...args, "-y", outputPath];
}
// Color space metadata — tags the output so players interpret colors correctly.
//
// Default (no options.hdr): Chrome screenshots are sRGB/bt709 pixels and
// we tag them truthfully as bt709. Tagging as bt2020 when pixels are bt709
// causes browsers to apply the wrong color transform, producing visible
// orange/warm shifts.
//
// HDR (options.hdr provided): the caller asserts the input pixels are
// already in the BT.2020 color space (e.g. extracted HDR video frames or a
// pre-tagged source). We tag the output as BT.2020 + the corresponding
// transfer (smpte2084 for PQ, arib-std-b67 for HLG). HDR static mastering
// metadata (master-display, max-cll) is embedded only in the SW libx265
// path above; GPU H.265 + HDR carries the color tags but not the static
// metadata, which is acceptable for previews but not for HDR-aware delivery.
if (codec === "h264" || codec === "h265") {
if (options.hdr) {
const transferTag = options.hdr.transfer === "pq" ? "smpte2084" : "arib-std-b67";
args.push(
"-colorspace:v",
"bt2020nc",
"-color_primaries:v",
"bt2020",
"-color_trc:v",
transferTag,
"-color_range",
"tv",
);
} else {
args.push(
"-colorspace:v",
"bt709",
"-color_primaries:v",
"bt709",
"-color_trc:v",
"bt709",
"-color_range",
"tv",
);
}
// Range conversion: Chrome's full-range RGB → limited/TV range.
if (gpuEncoder === "vaapi") {
const vfIdx = args.indexOf("-vf");
if (vfIdx !== -1) {
args[vfIdx + 1] = `scale=in_range=pc:out_range=tv,${args[vfIdx + 1]}`;
}
} else if (!shouldUseGpu) {
// Range conversion: Chrome screenshots are full-range RGB.
// The scale filter handles both 8-bit and 10-bit correctly.
args.push("-vf", "scale=in_range=pc:out_range=tv");
}
// Fixed timescale for consistent A/V timing across platforms.
args.push("-video_track_timescale", "90000");
}
if (gpuEncoder !== "vaapi") {
args.push("-pix_fmt", pixelFormat);
}
args.push("-avoid_negative_ts", "make_zero");
args.push("-y", outputPath);
return args;
}
export async function encodeFramesFromDir(
framesDir: string,
framePattern: string,
outputPath: string,
options: EncoderOptions,
signal?: AbortSignal,
config?: Partial<Pick<EngineConfig, "ffmpegEncodeTimeout">>,
): Promise<EncodeResult> {
const startTime = Date.now();
const outputDir = dirname(outputPath);
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
const files = readdirSync(framesDir).filter((f) => f.match(/\.(jpg|jpeg|png)$/i));
const frameCount = files.length;
if (frameCount === 0) {
return {
success: false,
outputPath,
durationMs: Date.now() - startTime,
framesEncoded: 0,
fileSize: 0,
error: "[FFmpeg] No frame files found in directory",
};
}
let gpuEncoder: GpuEncoder = null;
if (options.useGpu) {
gpuEncoder = await getCachedGpuEncoder();
}
const inputPath = join(framesDir, framePattern);
const inputArgs = ["-framerate", fpsToFfmpegArg(options.fps), "-i", inputPath];
const args = buildEncoderArgs(options, inputArgs, outputPath, gpuEncoder);
return new Promise((resolve) => {
const ffmpeg = spawn("ffmpeg", args);
let stderr = "";
const onAbort = () => {
ffmpeg.kill("SIGTERM");
};
if (signal) {
if (signal.aborted) {
ffmpeg.kill("SIGTERM");
} else {
signal.addEventListener("abort", onAbort, { once: true });
}
}
const encodeTimeout = config?.ffmpegEncodeTimeout ?? DEFAULT_CONFIG.ffmpegEncodeTimeout;
const timer = setTimeout(() => {
ffmpeg.kill("SIGTERM");
}, encodeTimeout);
ffmpeg.stderr.on("data", (data) => {
stderr += data.toString();
});
ffmpeg.on("close", (code) => {
clearTimeout(timer);
if (signal) signal.removeEventListener("abort", onAbort);
const durationMs = Date.now() - startTime;
if (signal?.aborted) {
resolve({
success: false,
outputPath,
durationMs,
framesEncoded: 0,
fileSize: 0,
error: "FFmpeg encode cancelled",
});
return;
}
if (code !== 0) {
resolve({
success: false,
outputPath,
durationMs,
framesEncoded: 0,
fileSize: 0,
error: formatFfmpegError(code, stderr),
});
return;
}
const fileSize = existsSync(outputPath) ? statSync(outputPath).size : 0;
resolve({ success: true, outputPath, durationMs, framesEncoded: frameCount, fileSize });
});
ffmpeg.on("error", (err) => {
clearTimeout(timer);
if (signal) signal.removeEventListener("abort", onAbort);
resolve({
success: false,
outputPath,
durationMs: Date.now() - startTime,
framesEncoded: 0,
fileSize: 0,
error: `[FFmpeg] ${err.message}`,
});
});
});
}
export async function encodeFramesChunkedConcat(
framesDir: string,
framePattern: string,
outputPath: string,
options: EncoderOptions,
chunkSizeFrames: number,
signal?: AbortSignal,
): Promise<EncodeResult> {
const start = Date.now();
const files = readdirSync(framesDir)
.filter((f) => f.match(/\.(jpg|jpeg|png)$/i))
.sort();
if (files.length === 0) {
return {
success: false,
outputPath,
durationMs: Date.now() - start,
framesEncoded: 0,
fileSize: 0,
error: "[FFmpeg] No frame files found in directory",
};
}
const chunkSize = Math.max(30, Math.floor(chunkSizeFrames));
const chunkCount = Math.ceil(files.length / chunkSize);
const chunkDir = join(dirname(outputPath), "chunk-encode");
if (!existsSync(chunkDir)) mkdirSync(chunkDir, { recursive: true });
const chunkPaths: string[] = [];
for (let i = 0; i < chunkCount; i++) {
if (signal?.aborted) {
return {
success: false,
outputPath,
durationMs: Date.now() - start,
framesEncoded: 0,
fileSize: 0,
error: "Chunked encode cancelled",
};
}
const startNumber = i * chunkSize;
const framesInChunk = Math.min(chunkSize, files.length - startNumber);
const ext = outputPath.endsWith(".webm")
? ".webm"
: outputPath.endsWith(".mov")
? ".mov"
: ".mp4";
const chunkPath = join(chunkDir, `chunk_${String(i).padStart(4, "0")}${ext}`);
const inputPath = join(framesDir, framePattern);
const inputArgs = [
"-framerate",
fpsToFfmpegArg(options.fps),
"-start_number",
String(startNumber),
"-i",
inputPath,
"-frames:v",
String(framesInChunk),
];
let gpuEncoder: GpuEncoder = null;
if (options.useGpu) gpuEncoder = await getCachedGpuEncoder();
const args = buildEncoderArgs(options, inputArgs, chunkPath, gpuEncoder);
const chunkResult = await new Promise<{ success: boolean; error?: string }>((resolve) => {
const ffmpeg = spawn("ffmpeg", args);
let stderr = "";
ffmpeg.stderr.on("data", (d) => {
stderr += d.toString();
});
ffmpeg.on("close", (code) => {
if (code === 0) resolve({ success: true });
else resolve({ success: false, error: `Chunk ${i} encode failed: ${stderr.slice(-400)}` });
});
ffmpeg.on("error", (err) => {
resolve({ success: false, error: `Chunk ${i} encode error: ${err.message}` });
});
});
if (!chunkResult.success) {
return {
success: false,
outputPath,
durationMs: Date.now() - start,
framesEncoded: 0,
fileSize: 0,
error: chunkResult.error,
};
}
chunkPaths.push(chunkPath);
}
const concatListPath = join(chunkDir, "concat-list.txt");
const concatInput = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
writeFileSync(concatListPath, concatInput, "utf-8");
const concatArgs = [
"-f",
"concat",
"-safe",
"0",
"-i",
concatListPath,
"-c",
"copy",
"-y",
outputPath,
];
const concatResult = await new Promise<{ success: boolean; error?: string }>((resolve) => {
const ffmpeg = spawn("ffmpeg", concatArgs);
let stderr = "";
ffmpeg.stderr.on("data", (d) => {
stderr += d.toString();
});
ffmpeg.on("close", (code) => {
if (code === 0) resolve({ success: true });
else resolve({ success: false, error: `Chunk concat failed: ${stderr.slice(-400)}` });
});
ffmpeg.on("error", (err) => {
resolve({ success: false, error: `Chunk concat error: ${err.message}` });
});
});
if (!concatResult.success) {
return {
success: false,
outputPath,
durationMs: Date.now() - start,
framesEncoded: 0,
fileSize: 0,
error: concatResult.error,
};
}
const fileSize = existsSync(outputPath) ? statSync(outputPath).size : 0;
return {
success: true,
outputPath,
durationMs: Date.now() - start,
framesEncoded: files.length,
fileSize,
};
}
export async function muxVideoWithAudio(
videoPath: string,
audioPath: string,
outputPath: string,
signal?: AbortSignal,
config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
): Promise<MuxResult> {
const outputDir = dirname(outputPath);
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
const isWebm = outputPath.endsWith(".webm");
const isMov = outputPath.endsWith(".mov");
const args = ["-i", videoPath, "-i", audioPath, "-c:v", "copy"];
if (isWebm) {
args.push("-c:a", "libopus", "-b:a", "128k");
} else if (isMov) {
args.push("-c:a", "aac", "-b:a", "192k");
} else {
args.push("-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart");
}
// PTS bases can diverge during mux and reintroduce negative DTS. See
// buildEncoderArgs for the full reasoning on why that breaks playback.
args.push("-avoid_negative_ts", "make_zero");
args.push("-shortest", "-y", outputPath);
const processTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
const result = await runFfmpeg(args, { signal, timeout: processTimeout });
if (signal?.aborted) {
return {
success: false,
outputPath,
durationMs: result.durationMs,
error: "FFmpeg mux cancelled",
};
}
return {
success: result.success,
outputPath,
durationMs: result.durationMs,
error: !result.success ? formatFfmpegError(result.exitCode, result.stderr) : undefined,
};
}
export async function applyFaststart(
inputPath: string,
outputPath: string,
signal?: AbortSignal,
config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
): Promise<MuxResult> {
// faststart is MP4-only (moves moov atom to file start for streaming).
// WebM and MOV don't need it — skip the re-mux.
if (outputPath.endsWith(".webm") || outputPath.endsWith(".mov")) {
if (inputPath !== outputPath) copyFileSync(inputPath, outputPath);
return { success: true, outputPath, durationMs: 0 };
}
const args = ["-i", inputPath, "-c", "copy", "-movflags", "+faststart", "-y", outputPath];
const processTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
const result = await runFfmpeg(args, { signal, timeout: processTimeout });
if (signal?.aborted) {
return {
success: false,
outputPath,
durationMs: result.durationMs,
error: "FFmpeg faststart cancelled",
};
}
return {
success: result.success,
outputPath,
durationMs: result.durationMs,
error: !result.success ? formatFfmpegError(result.exitCode, result.stderr) : undefined,
};
}