Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(media): kill the whole ffmpeg process group on timeout

Yudhi Armyndharis125cecf8c726
diff --git a/src/modules/media/ffmpeg-run.spec.ts b/src/modules/media/ffmpeg-run.spec.ts
index a4d0bbf47..be426213d 100644
--- a/src/modules/media/ffmpeg-run.spec.ts
+++ b/src/modules/media/ffmpeg-run.spec.ts
@@ -1,5 +1,5 @@
import { spawn, type ChildProcess } from 'node:child_process';
-import { chmod, mkdtemp, readdir, writeFile } from 'node:fs/promises';
+import { chmod, mkdtemp, readdir, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { FfmpegConversionError, probeFfmpeg, runFfmpeg } from './ffmpeg';
@@ -46,6 +46,7 @@ done
case "$mode" in
fail) echo "Invalid data found when processing input" >&2; exit 1 ;;
hang) sleep 10 ;;
+ orphan) sleep 10 & echo $! > "$0.pid"; wait ;;
empty) : > "$out" ;;
big) head -c 4096 /dev/zero > "$out" ;;
argv) printf '%s ' "$@" > "$out" ;;
@@ -127,6 +128,31 @@ esac
expect(child.stderr?.destroyed).toBe(true);
}, 15_000);
+ // A wrapper that runs ffmpeg without `exec` leaves the real worker as a grandchild. Killing only the
+ // wrapper would free the concurrency slot while that worker keeps running.
+ it('kills the whole process group on timeout, not just the direct child', async () => {
+ const pidFile = `${stubPath}.pid`;
+ await expect(
+ runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('orphan'), options({ timeoutMs: 300 })),
+ ).rejects.toThrow(/timed out after 300ms/);
+
+ const grandchild = Number((await readFile(pidFile, 'utf8')).trim());
+ const alive = (): boolean => {
+ try {
+ process.kill(grandchild, 0);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ try {
+ for (let i = 0; i < 40 && alive(); i++) await new Promise(r => setTimeout(r, 50));
+ expect(alive()).toBe(false);
+ } finally {
+ if (alive()) process.kill(grandchild, 'SIGKILL');
+ }
+ }, 15_000);
+
// Transcoding can inflate as well as shrink, so the output needs a ceiling of its own.
it('refuses output above the cap, and says what it measured', async () => {
await expect(
diff --git a/src/modules/media/ffmpeg.ts b/src/modules/media/ffmpeg.ts
index 7f6c777e8..e6136415a 100644
--- a/src/modules/media/ffmpeg.ts
+++ b/src/modules/media/ffmpeg.ts
@@ -192,7 +192,9 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {
return new Promise((resolve, reject) => {
// An argument array, never a shell string: nothing here can be word-split or expanded, so a
// filename with a space or a quote is data rather than syntax.
- const child = spawn(options.ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] });
+ // `detached` puts the child at the head of its own process group, so the timeout can kill
+ // everything under it (see below).
+ const child = spawn(options.ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'], detached: true });
let stderr = '';
let timedOut = false;
@@ -204,8 +206,16 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {
const timer = setTimeout(() => {
timedOut = true;
// SIGKILL rather than SIGTERM: the case being defended against is a codec stuck in a loop,
- // which is exactly the case that would ignore a polite signal.
- child.kill('SIGKILL');
+ // which is exactly the case that would ignore a polite signal. The whole group, because a
+ // wrapper script that runs ffmpeg without `exec` leaves the real worker as a grandchild, and
+ // killing only the wrapper would free the concurrency slot while that worker keeps running.
+ try {
+ // A negative pid addresses the process group; no pid means the spawn failed and nothing runs.
+ if (child.pid !== undefined) process.kill(-child.pid, 'SIGKILL');
+ } catch {
+ // The group is already gone, or the platform has no process groups: fall back to the child.
+ child.kill('SIGKILL');
+ }
// Let go of our end of the stderr pipe too. A descendant of the killed process (ffmpeg under a
// wrapper script) can still hold the inherited stderr, and the open pipe would keep this
// process alive until that descendant exits.