---
name: ffmpeg-pipeline-broadcast
description: Build broadcast-grade FFmpeg pipelines from Node — concatenation, scaling, color grading, audio normalization (loudnorm to -16 LUFS), silence trimming, hardware-accelerated encoding (NVENC, VideoToolbox, QSV). Use for any video processing task that touches more than one clip or requires consistent output specs.
category: video-editing
version: 0.1.0
tags: [ffmpeg, video, encoding, audio, broadcast]
recommended_npm: ["fluent-ffmpeg", "ffmpeg-static", "ffprobe-static", "execa"]
license: MIT
author: claude-code-skills
---

FFmpeg from Node is best invoked through `fluent-ffmpeg` for readable pipelines, or directly via `execa` for single-shot commands you want to log verbatim.

## Setup

```ts
import ffmpeg from "fluent-ffmpeg";
import ffmpegPath from "ffmpeg-static";
import ffprobePath from "ffprobe-static";

ffmpeg.setFfmpegPath(ffmpegPath!);
ffmpeg.setFfprobePath(ffprobePath.path);
```

## Probe before you process

```ts
import { execa } from "execa";
const { stdout } = await execa("ffprobe", [
  "-v", "error", "-show_format", "-show_streams", "-of", "json", input,
]);
const meta = JSON.parse(stdout);
const v = meta.streams.find((s: any) => s.codec_type === "video");
const a = meta.streams.find((s: any) => s.codec_type === "audio");
```

Always check: width/height, fps, sample_rate, sample_aspect_ratio, color_primaries. Output drift starts here.

## The 90% pipeline: normalize loudness + scale + encode

```ts
await new Promise<void>((resolve, reject) => {
  ffmpeg(input)
    .audioFilters([
      "loudnorm=I=-16:LRA=11:TP=-1.5",   // EBU R128 streaming target
    ])
    .videoFilters([
      "scale=w=1920:h=1080:force_original_aspect_ratio=decrease",
      "pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black",
      "fps=30",
    ])
    .outputOptions([
      "-c:v libx264",
      "-preset slow",
      "-crf 18",                          // visually lossless-ish
      "-pix_fmt yuv420p",
      "-c:a aac",
      "-b:a 192k",
      "-movflags +faststart",            // moov atom up front for streaming
    ])
    .on("progress", (p) => process.stderr.write(`\r${Math.round(p.percent ?? 0)}%`))
    .on("end", () => resolve())
    .on("error", reject)
    .save(output);
});
```

## Concatenation done right

Two methods, pick by content:

- **Concat demuxer** (fastest, requires same codec + params):
  ```bash
  printf "file '%s'\n" *.mp4 > list.txt
  ffmpeg -f concat -safe 0 -i list.txt -c copy out.mp4
  ```
- **Filter graph** (different sources): use `concat` filter:
  ```
  -filter_complex "[0:v][0:a][1:v][1:a]concat=n=2:v=1:a=1[v][a]"
  ```

## Silence trimming (for talking-head or podcast)

```bash
ffmpeg -i in.mp4 -af "silenceremove=start_periods=1:start_duration=0:start_threshold=-40dB:detection=peak,aformat=dblp,areverse,silenceremove=start_periods=1:start_duration=0:start_threshold=-40dB:detection=peak,aformat=dblp,areverse" -c:v copy out.mp4
```

For aggressive trimming (gaps inside the clip), use `silenceremove` with `stop_periods=-1` or pre-detect with `silencedetect` and stitch with the concat filter.

## Hardware acceleration

| Platform | Encoder | When |
| --- | --- | --- |
| NVIDIA GPU | `h264_nvenc`, `hevc_nvenc` | batch encoding, not for archival |
| macOS | `h264_videotoolbox`, `hevc_videotoolbox` | best speed/quality on Apple silicon |
| Intel iGPU | `h264_qsv` | server-side batch |

Hardware encoders trade quality for speed. For final masters, stay on `libx264` CRF 18 or `libx265` CRF 22.

## Anti-patterns

- ❌ `-vf "scale=1920:1080"` without preserving aspect ratio — content stretches.
- ❌ Encoding with `-preset ultrafast` for anything you'll keep — file size doubles for the same quality.
- ❌ Skipping `-pix_fmt yuv420p` — output won't play in QuickTime / Safari.
- ❌ Concatenating clips with different `time_base` via `-c copy` — you get audio drift.
- ❌ Calling FFmpeg from a request handler synchronously — push to a job queue (see `bullmq-background-jobs`).
- ❌ Ignoring stderr — most useful diagnostics come from there, not stdout.

## Quality gates

- Final asset passes `ffprobe`: `pix_fmt=yuv420p`, audio at -16 LUFS ± 1, no negative `start_time`.
- File plays in Safari without re-encoding (faststart confirmed: `mp4info` shows moov before mdat).
- Subjective: A/B against the source — no compression banding in dark areas, no aliasing on fine text.
