Node.js and Rust Image and Video Libraries

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Baseline date: 2026-10-07. The Node.js examples were run on Node.js 24 against sharp 0.35.5 (libvips 8.18.7), Jimp 1.6.1 and blurhash 2.0.5, with FFmpeg 9.0.2 from the linuxserver/ffmpeg Docker image. The Rust examples were compiled and run with Rust 1.99 against axum 0.8.9, image 0.25.10, blurhash 0.2.3 and tokio 1.54, and the Rust FFmpeg example against FFmpeg 7.1.5 from a Debian package. Check each project’s repository for newer releases.

Node.js

Library Licence Notes

sharp

Apache-2.0

libvips-based, fast and low in memory. Reads JPEG, PNG, WebP, AVIF, GIF, TIFF and SVG, and writes JPEG, PNG, WebP, AVIF, GIF and TIFF. The recommended default. Prebuilt binaries are installed with the package.

Jimp

MIT

Pure JavaScript, no native dependencies, so it installs anywhere. Much slower than sharp. WebP and AVIF are available through separate WASM plugins.

blurhash

MIT

The reference encoder and decoder, see the BlurHash page.

fluent-ffmpeg

MIT

Legacy. The repository was archived in May 2025 and the npm package is marked as no longer supported. Existing code keeps working with the FFmpeg it was written for, but new code should spawn ffmpeg directly.

sharp: variants, metadata and BlurHash

npm install sharp blurhash
import sharp from 'sharp';
import { encode } from 'blurhash';

export async function makeVariants(input, outDir) {
  const base = sharp(input).rotate();                    // apply EXIF orientation, then drop the tag
  // metadata() reports the input header, which ignores .rotate(); autoOrient (sharp 0.34+) gives the upright size.
  const { autoOrient: { width } } = await base.metadata();

  for (const w of [320, 640, 1280]) {
    const resized = base.clone().resize({ width: w, withoutEnlargement: true });
    await resized.clone().avif({ quality: 60, effort: 4 }).toFile(`${outDir}/w${w}.avif`);
    await resized.clone().webp({ quality: 78 }).toFile(`${outDir}/w${w}.webp`);
    await resized.clone().jpeg({ quality: 80, mozjpeg: true }).toFile(`${outDir}/w${w}.jpg`);
  }

  // A 2:3 cover with attention-based cropping.
  await base.clone().resize(640, 960, { fit: 'cover', position: 'attention' }).toFile(`${outDir}/cover.jpg`);

  // BlurHash from a 64 px raw RGBA buffer.
  const { data, info } = await base.clone()
    .resize(64, 64, { fit: 'inside' })
    .ensureAlpha()
    .raw()
    .toBuffer({ resolveWithObject: true });
  const blurhash = encode(new Uint8ClampedArray(data), info.width, info.height, 4, 3);

  return { width, blurhash };
}

sharp strips metadata by default, and withMetadata() (or keepMetadata() in recent versions) keeps it, so the default is what a public variant wants. Convert wide-gamut sources to sRGB with toColorspace() before output. Use sharp.concurrency() and sharp.cache() to control CPU and memory in a worker pod. References: sharp resize, sharp output and sharp input and metadata.

Jimp

import { Jimp } from 'jimp';

const image = await Jimp.read('original.jpg');
image.resize({ w: 320 });                                  // keeps the aspect ratio
await image.write('w320.jpg');
const buffer = await image.getBuffer('image/jpeg', { quality: 80 });

Use Jimp when you cannot install native code (some serverless runtimes, locked-down environments) and the images are small. Reference: Jimp documentation.

Video: spawn ffmpeg directly

import { spawn } from 'node:child_process';

export function transcode(src, dst, height = 720) {
  return new Promise((resolve, reject) => {
    const args = ['-y', '-i', src, '-vf', `scale=-2:${height}`, '-c:v', 'libx264', '-preset', 'slow', '-crf', '22',
      '-g', '48', '-keyint_min', '48', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', dst];
    const child = spawn('ffmpeg', args, { stdio: ['ignore', 'ignore', 'pipe'] });
    const timer = setTimeout(() => child.kill('SIGKILL'), 60 * 60 * 1000);   // hard time limit
    let stderr = '';
    child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-4000); });
    child.on('error', (error) => { clearTimeout(timer); reject(error); });
    child.on('close', (code) => {
      clearTimeout(timer);
      code === 0 ? resolve() : reject(new Error(`ffmpeg exited with ${code}: ${stderr}`));
    });
  });
}

export function cover(src, dst, seconds) {
  return new Promise((resolve, reject) => {
    const child = spawn('ffmpeg', ['-y', '-ss', String(seconds), '-i', src, '-frames:v', '1', '-q:v', '2', dst]);
    child.on('error', reject);
    child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`ffmpeg exited with ${code}`))));
  });
}

Both functions were run against the trailer (through the FFmpeg container) and behave as written: the transcode wrote a 1280 by 720 file, the cover a JPEG at 5 seconds, and a missing input rejects with the last stderr lines of FFmpeg. The Jimp snippet above also ran, and wrote a 320 by 180 JPEG of about 10 KB from the 1920 by 1080 frame. Passing arguments as an array keeps user-provided names from reaching a shell. Reference: Node.js child_process.spawn and the commands in video encoding fundamentals. If you inherit fluent-ffmpeg code, plan its replacement: it only builds the same argument list.

What sharp produced for a phone photo

The running example is the Bookshelf cover upload. A phone photo is the interesting input, because its pixels are landscape and an EXIF tag says to turn them. To reproduce one, the cover frame of the trailer (1920 by 1080) was written with EXIF orientation 6 (sharp(file).jpeg().withMetadata({ orientation: 6 })) and passed through makeVariants above. The header and the upright size differ, which is the reason the function reads autoOrient and not width:

header 1920 1080 orientation 6 autoOrient {"width":1080,"height":1920}
{ width: 1080, blurhash: 'LVKn#dkRk7%2|mr^oMk7XMk9jYni' }
Width AVIF (quality 60) WebP (quality 78) JPEG (mozjpeg, quality 80)

320 (320 by 569)

7.2 KB

8.2 KB

11.9 KB

640 (640 by 1138)

21.0 KB

21.7 KB

31.7 KB

1280 (1080 by 1920)

47.5 KB

46.7 KB

62.9 KB

Three details worth noticing. The 1280 variant is 1080 pixels wide, because withoutEnlargement refuses to upscale a 1080 pixel source, so the file is named after the requested width and the API must report the real one. The cover (resize(640, 960, { fit: 'cover', position: 'attention' })) came out at exactly 640 by 960. And no output file carries the orientation tag any more: rotate() applied it and wrote none, so a viewer does not turn the picture twice. The sizes are those of a test pattern, so read the ratios (AVIF and WebP at about two thirds of JPEG here) as an illustration and measure your own photos.

flowchart LR I["Upload"] --> R["rotate: apply the orientation tag"] R --> M["metadata: upright width and height"] R --> C1["clone: resize 320"] R --> C2["clone: resize 640"] R --> C3["clone: resize 1280, no enlargement"] R --> CV["clone: cover 640 by 960, attention crop"] R --> B["clone: 64 px raw RGBA, BlurHash"] C1 --> O1["AVIF, WebP, JPEG"] C2 --> O2["AVIF, WebP, JPEG"] C3 --> O3["AVIF, WebP, JPEG"]

A video worker: ladder, HLS and master playlist

The video side of the same upload is the Bookshelf trailer, encoded into three rungs and packaged as HLS, see encoding fundamentals and video streaming for the reasoning and the numbers. The module below is what the worker runs. It probes the file, drops the rungs that would upscale, encodes each rung without audio, encodes the audio once, packages every rendition with a stream copy (so the segments cut exactly at the keyframes that the encode created), measures the real peak and average bit rate from the segments, and writes the multivariant playlist itself:

// ladder.mjs: probe, encode the rungs, package HLS and write the multivariant playlist
import { spawn } from 'node:child_process';
import { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';

const RUNGS = [
  { name: '1080p', height: 1080, crf: 22, maxrate: 6000, bufsize: 12000 },
  { name: '720p', height: 720, crf: 22, maxrate: 3000, bufsize: 6000 },
  { name: '360p', height: 360, crf: 23, maxrate: 800, bufsize: 1600 },
];

function run(cmd, args, { onProgress, timeoutMs = 3_600_000 } = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
    const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);
    let stdout = '', stderr = '';
    child.stdout.on('data', (chunk) => {
      stdout += chunk;
      if (onProgress) {                                   // -progress pipe:1 prints key=value lines
        const match = String(chunk).match(/out_time_us=(\d+)/g);
        if (match) onProgress(Number(match.at(-1).split('=')[1]) / 1e6);
      }
    });
    child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-4000); });
    child.on('error', (error) => { clearTimeout(timer); reject(error); });
    child.on('close', (code) => {
      clearTimeout(timer);
      code === 0 ? resolve(stdout) : reject(new Error(`${cmd} exited with ${code}: ${stderr}`));
    });
  });
}

export async function probe(src) {
  const json = await run('ffprobe', ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', src]);
  const info = JSON.parse(json);
  const video = info.streams.find((s) => s.codec_type === 'video');
  const [num, den] = video.r_frame_rate.split('/').map(Number);
  return { width: video.width, height: video.height, fps: num / den, duration: Number(info.format.duration) };
}

async function encodeRung(src, dir, rung, fps, onProgress) {
  const gop = String(Math.round(fps * 2));                // a keyframe every 2 s, whatever the frame rate
  const out = path.join(dir, `${rung.name}.mp4`);
  await run('ffmpeg', ['-y', '-nostats', '-progress', 'pipe:1', '-i', src, '-an',
    '-vf', `scale=-2:${rung.height}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', String(rung.crf),
    '-maxrate', `${rung.maxrate}k`, '-bufsize', `${rung.bufsize}k`, '-g', gop, '-keyint_min', gop,
    '-sc_threshold', '0', '-pix_fmt', 'yuv420p', out], { onProgress });
  return out;
}

async function avcCodec(file) {                              // avc1.PPCCLL from the real encoder output
  const json = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-print_format', 'json', '-show_streams', file]);
  const { profile, level } = JSON.parse(json).streams[0];
  const code = { Baseline: '42', 'Constrained Baseline': '42', Main: '4d', High: '64' }[profile];
  return `avc1.${code}00${level.toString(16).padStart(2, '0')}`;
}

async function packageHls(input, dir, name, extra = []) {
  await mkdir(path.join(dir, name), { recursive: true });
  await run('ffmpeg', ['-y', '-i', input, ...extra, '-c', 'copy', '-f', 'hls', '-hls_time', '6', '-hls_playlist_type', 'vod',
    '-hls_segment_type', 'fmp4', '-hls_fmp4_init_filename', 'init.mp4',
    '-hls_segment_filename', path.join(dir, name, 'seg_%03d.m4s'), path.join(dir, name, 'index.m3u8')]);
}

async function bandwidth(dir, name) {                       // peak and average bit rate from the real segments
  const playlist = await readFile(path.join(dir, name, 'index.m3u8'), 'utf8');
  const lines = playlist.split('\n');
  let total = 0, seconds = 0, peak = 0;
  for (let i = 0; i < lines.length; i++) {
    const m = lines[i].match(/^#EXTINF:([\d.]+),/);
    if (!m) continue;
    const size = (await stat(path.join(dir, name, lines[i + 1]))).size;
    total += size; seconds += Number(m[1]);
    peak = Math.max(peak, (size * 8) / Number(m[1]));
  }
  return { average: Math.round((total * 8) / seconds), peak: Math.round(peak) };
}

export async function buildLadder(src, dir, log = console.log) {
  const info = await probe(src);
  const rungs = RUNGS.filter((r) => r.height <= info.height);   // never upscale
  await mkdir(dir, { recursive: true });
  const tmp = path.join(dir, '_tmp');
  await mkdir(tmp, { recursive: true });

  const lines = ['#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-INDEPENDENT-SEGMENTS'];
  const audio = path.join(tmp, 'audio.m4a');
  await run('ffmpeg', ['-y', '-i', src, '-vn', '-c:a', 'aac', '-b:a', '128k', audio]);
  await packageHls(audio, dir, 'audio');
  const a = await bandwidth(dir, 'audio');
  lines.push('#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="main",DEFAULT=YES,AUTOSELECT=YES,URI="audio/index.m3u8"');

  for (const rung of rungs) {
    const file = await encodeRung(src, tmp, rung, info.fps, (t) => log(`${rung.name} ${Math.round((t / info.duration) * 100)}%`));
    await packageHls(file, dir, rung.name);
    const b = await bandwidth(dir, rung.name);
    const codec = await avcCodec(file);
    const width = Math.round((info.width * rung.height) / info.height / 2) * 2;
    lines.push(`#EXT-X-STREAM-INF:BANDWIDTH=${b.peak + a.peak},AVERAGE-BANDWIDTH=${b.average + a.average},` +
      `RESOLUTION=${width}x${rung.height},FRAME-RATE=${info.fps.toFixed(3)},CODECS="${codec},mp4a.40.2",AUDIO="aud"`, `${rung.name}/index.m3u8`);
  }
  await rm(tmp, { recursive: true });                          // intermediates are not published
  await writeFile(path.join(dir, 'master.m3u8'), lines.join('\n') + '\n');
  return { info, rungs: rungs.map((r) => r.name), files: (await readdir(dir)).sort() };
}
sequenceDiagram participant W as Worker participant P as ffprobe participant F as ffmpeg participant D as Output directory W->>P: probe: size, frame rate, duration P-->>W: 1920x1080, 24 fps, 20 s W->>F: audio to AAC, then package as HLS loop for each rung that fits the source W->>F: encode video only, capped CRF, GOP of 2 s F-->>W: out_time_us lines on stdout, as progress W->>F: package with stream copy, 6 s fMP4 segments W->>D: read the playlist and the segment sizes end W->>D: write master.m3u8 with measured bandwidth

Running buildLadder('trailer.mp4', 'site/trailer') on the trailer printed the progress of each rung and returned { rungs: ['1080p', '720p', '360p'], files: ['1080p', '360p', '720p', 'audio', 'master.m3u8'] }, with a multivariant playlist whose numbers come from the segments and not from the encoder settings:

#EXTM3U
#EXT-X-VERSION:7
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="main",DEFAULT=YES,AUTOSELECT=YES,URI="audio/index.m3u8"
#EXT-X-STREAM-INF:BANDWIDTH=6751859,AVERAGE-BANDWIDTH=5736237,RESOLUTION=1920x1080,FRAME-RATE=24.000,CODECS="avc1.640028,mp4a.40.2",AUDIO="aud"
1080p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3061522,AVERAGE-BANDWIDTH=2183310,RESOLUTION=1280x720,FRAME-RATE=24.000,CODECS="avc1.64001f,mp4a.40.2",AUDIO="aud"
720p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=650798,AVERAGE-BANDWIDTH=486351,RESOLUTION=640x360,FRAME-RATE=24.000,CODECS="avc1.64001e,mp4a.40.2",AUDIO="aud"
360p/index.m3u8

Points that the run made concrete:

  • -progress pipe:1 prints key=value blocks on stdout, and out_time_us is the encoded time in microseconds, so progress is that value over the duration read by ffprobe. Combine -nostats with it to keep stderr for errors.

  • The CODECS string comes from ffprobe (profile and level of each encode), because the level changes with the size: avc1.640028 for 1080p, avc1.64001f for 720p and avc1.64001e for 360p. A hard-coded string is wrong for at least one rung, and players use the declared codecs to decide whether they can decode a variant at all.

  • Each of the three rungs and the audio were packaged into four segments of 6, 6, 6 and 2 seconds, the same for every rung.

  • FFmpeg’s own decoder was happy with each media playlist (ffmpeg -v error -i 720p/index.m3u8 -f null - prints nothing), but pointing it at master.m3u8 printed H.264 "Invalid NAL unit size" messages, also for a playlist written by FFmpeg itself. Validate rungs one by one and test the multivariant playlist with a real player, see video playback on the web.

  • The rungs run one after the other. FFmpeg’s encoders are already multi-threaded, so running all three in parallel mostly competes for the same cores. Add parallelism between jobs (the BullMQ concurrency option below), not inside one.

NestJS with BullMQ

The upload side of NestJS is covered in file upload and streaming, and queues in events, scheduling and queues. The pattern for media is a controller that hands out a pre-signed URL and enqueues a job, and a processor that does the work:

npm install @nestjs/bullmq bullmq
// media.module.ts
@Module({
  imports: [
    BullModule.forRoot({ connection: { host: process.env.REDIS_HOST, port: 6379 } }),
    BullModule.registerQueue({
      name: 'media',
      defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 5000 }, removeOnComplete: 1000 },
    }),
  ],
  providers: [MediaService, MediaProcessor],
  controllers: [MediaController],
})
export class MediaModule {}

// media.service.ts
@Injectable()
export class MediaService {
  constructor(@InjectQueue('media') private readonly queue: Queue) {}

  async complete(id: string) {
    // jobId makes the enqueue idempotent: the same media id is never queued twice
    await this.queue.add('process', { id }, { jobId: `media-${id}` });
  }
}

// media.processor.ts
@Processor('media', { concurrency: 2 })
export class MediaProcessor extends WorkerHost {
  async process(job: Job<{ id: string }>) {
    const { width, blurhash } = await makeVariants(await this.storage.download(job.data.id), this.workDir);
    await this.repository.markReady(job.data.id, { width, blurhash });
  }
}

BullMQ retries a failed job with the configured backoff, and keeps failed jobs for inspection, which plays the role of a dead-letter queue. Run the processor in a separate process or deployment, so a CPU-heavy job does not block request handling. References: BullMQ documentation and NestJS queues.

Rust with axum

For the language and the framework themselves, see the Rust Reference and the Axum section (uploads are covered in File Uploads and background work in Background Jobs and Tasks). This example focuses on the media side. It uses axum ( docs.rs/axum ) for HTTP and multipart, the image crate for decoding, resizing and encoding, the blurhash crate for the hash, and tokio::process for FFmpeg.

[dependencies]
axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] }
image = "0.25"
blurhash = "0.2"
serde = { version = "1", features = ["derive"] }
uuid = { version = "1", features = ["v4"] }
use axum::{
    extract::{DefaultBodyLimit, Multipart, Path, State},
    http::StatusCode,
    routing::{get, post},
    Json, Router,
};
use image::{imageops::FilterType, ImageFormat, ImageReader};
use serde::Serialize;
use std::{collections::HashMap, io::Cursor, sync::Arc};
use tokio::{process::Command, sync::RwLock};

#[derive(Clone, Serialize)]
struct Media {
    id: String,
    status: &'static str,
    blurhash: Option<String>,
}

type Db = Arc<RwLock<HashMap<String, Media>>>;
const MAX_BYTES: usize = 10 * 1024 * 1024;

/// CPU-bound work: decode, resize, encode variants and compute the BlurHash.
fn process_image(bytes: Vec<u8>) -> Result<String, String> {
    let img = ImageReader::new(Cursor::new(bytes))
        .with_guessed_format()
        .map_err(|e| e.to_string())?
        .decode()
        .map_err(|e| e.to_string())?;

    for width in [320u32, 640, 1280] {
        if width >= img.width() {
            continue; // never upscale
        }
        let height = (img.height() as f64 * width as f64 / img.width() as f64).round() as u32;
        let resized = img.resize_exact(width, height, FilterType::Lanczos3);
        let mut out = Cursor::new(Vec::new());
        resized.write_to(&mut out, ImageFormat::Jpeg).map_err(|e| e.to_string())?;
        // upload out.into_inner() to object storage here
    }

    let small = img.resize(64, 64, FilterType::Triangle).to_rgba8();
    blurhash::encode(4, 3, small.width(), small.height(), small.as_raw()).map_err(|e| e.to_string())
}

async fn upload(
    State(db): State<Db>,
    mut multipart: Multipart,
) -> Result<(StatusCode, Json<Media>), StatusCode> {
    let field = multipart.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)?.ok_or(StatusCode::BAD_REQUEST)?;
    let bytes = field.bytes().await.map_err(|_| StatusCode::PAYLOAD_TOO_LARGE)?;
    if bytes.len() > MAX_BYTES {
        return Err(StatusCode::PAYLOAD_TOO_LARGE);
    }
    let id = uuid::Uuid::new_v4().to_string();
    let media = Media { id: id.clone(), status: "processing", blurhash: None };
    db.write().await.insert(id.clone(), media.clone());

    let db2 = db.clone();
    tokio::spawn(async move {
        // spawn_blocking keeps CPU-bound work off the async worker threads
        let result = tokio::task::spawn_blocking(move || process_image(bytes.to_vec())).await;
        if let Some(entry) = db2.write().await.get_mut(&id) {
            match result {
                Ok(Ok(hash)) => { entry.status = "ready"; entry.blurhash = Some(hash); }
                _ => entry.status = "failed",
            }
        }
    });
    Ok((StatusCode::ACCEPTED, Json(media)))
}

async fn status(State(db): State<Db>, Path(id): Path<String>) -> Result<Json<Media>, StatusCode> {
    db.read().await.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
}

/// FFmpeg as a child process. Arguments are a list, never a shell string.
async fn transcode(src: &str, dst: &str) -> std::io::Result<bool> {
    let status = Command::new("ffmpeg")
        .args(["-y", "-i", src, "-vf", "scale=-2:720", "-c:v", "libx264", "-crf", "22"])
        .args(["-c:a", "aac", "-movflags", "+faststart", dst])
        .kill_on_drop(true)
        .status()
        .await?;
    Ok(status.success())
}

#[tokio::main]
async fn main() {
    let db: Db = Arc::default();
    let app = Router::new()
        .route("/images", post(upload))
        .route("/images/{id}", get(status))
        .layer(DefaultBodyLimit::max(MAX_BYTES + 1024))
        .with_state(db);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Notes on the example:

  • axum 0.8 uses the {id} path syntax. Older versions used :id.

  • The image crate encodes JPEG, PNG and WebP (lossless) in pure Rust, and has an AVIF encoder (ravif) behind a feature flag. For AVIF at scale, HEIC and JPEG XL, use libvips through a binding or the vips command line.

  • The in-memory map stands in for a database, and tokio::spawn for a queue. In production the upload handler writes to object storage and a worker consumes a queue, see upload pipelines.

  • DefaultBodyLimit guards the request size, and with_guessed_format reads the magic bytes rather than trusting the file name. The image crate has decoding limits that can be set with Limits, which protects against huge images.

  • kill_on_drop(true) stops FFmpeg if the task is cancelled. Add tokio::time::timeout around long jobs.

Running the example

The server above compiled with axum 0.8.9, image 0.25.10 and blurhash 0.2.3, and the compiler reported a single warning: transcode is never used, because the example only defines it. Wire it into the worker, as the job for video, before using it. The requests below were sent with curl to the running binary:

Request Response

POST /images with a 1080 by 1920 JPEG

202 and {"id":"...","status":"processing","blurhash":null}

GET /images/{id} one second later

{"id":"...","status":"ready","blurhash":"L~Kn#d,ibX*Zs;bDaznmj=j[jZja"}

POST /images with 5 KB of random bytes

202, and one second later GET returns "status":"failed"

GET /images/nope

404

POST /images with an 11 MB body

413

The garbage upload is accepted and fails in the background, because the handler checks size and not content. That is the right split for an upload endpoint, since decoding is the expensive step, and the status endpoint reports the outcome. A production handler would also write the reason next to failed.

A video worker with tokio

The video counterpart uses tokio::process::Command with a progress pipe, a time limit and a semaphore that limits how many FFmpeg processes run at once. This is a second binary of the same crate (src/bin/ladder.rs), and it encodes the three rungs of the trailer as HLS with fMP4 segments:

use std::{path::Path, process::Stdio, sync::Arc, time::Duration};
use tokio::{
    io::{AsyncBufReadExt, BufReader},
    process::Command,
    sync::Semaphore,
};

struct Rung {
    name: &'static str,
    height: u32,
    crf: u32,
    maxrate_k: u32,
}

const RUNGS: [Rung; 3] = [
    Rung { name: "1080p", height: 1080, crf: 22, maxrate_k: 6000 },
    Rung { name: "720p", height: 720, crf: 22, maxrate_k: 3000 },
    Rung { name: "360p", height: 360, crf: 23, maxrate_k: 800 },
];

/// One rung as HLS with fMP4 segments. Progress comes from `-progress pipe:1`, the time limit from tokio.
async fn encode_rung(src: &str, out: &Path, rung: &Rung, gop: u32, duration: f64) -> Result<(), String> {
    let dir = out.join(rung.name);
    tokio::fs::create_dir_all(&dir).await.map_err(|e| e.to_string())?;
    let mut child = Command::new("ffmpeg")
        .args(["-y", "-nostats", "-progress", "pipe:1", "-i", src, "-an"])
        .args(["-vf", &format!("scale=-2:{}", rung.height)])
        .args(["-c:v", "libx264", "-preset", "veryfast", "-crf", &rung.crf.to_string()])
        .args(["-maxrate", &format!("{}k", rung.maxrate_k), "-bufsize", &format!("{}k", rung.maxrate_k * 2)])
        .args(["-g", &gop.to_string(), "-keyint_min", &gop.to_string(), "-sc_threshold", "0", "-pix_fmt", "yuv420p"])
        .args(["-f", "hls", "-hls_time", "6", "-hls_playlist_type", "vod", "-hls_segment_type", "fmp4"])
        .args(["-hls_fmp4_init_filename", "init.mp4"])
        .arg("-hls_segment_filename")
        .arg(dir.join("seg_%03d.m4s"))
        .arg(dir.join("index.m3u8"))
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .kill_on_drop(true) // the child dies with the task
        .spawn()
        .map_err(|e| e.to_string())?;

    let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
    let work = async {
        while let Ok(Some(line)) = lines.next_line().await {
            if let Some(us) = line.strip_prefix("out_time_us=") {
                if let Ok(us) = us.parse::<f64>() {
                    let pct = (us / 1e6 / duration * 100.0).clamp(0.0, 100.0);
                    if pct >= 99.0 { println!("{} {:.0}%", rung.name, pct); }
                }
            }
        }
        child.wait().await
    };
    match tokio::time::timeout(Duration::from_secs(3600), work).await {
        Ok(Ok(status)) if status.success() => Ok(()),
        Ok(Ok(status)) => Err(format!("ffmpeg exited with {status}")),
        Ok(Err(e)) => Err(e.to_string()),
        Err(_) => Err("ffmpeg timed out".into()), // dropping the future kills the child
    }
}

#[tokio::main]
async fn main() -> Result<(), String> {
    let src = std::env::args().nth(1).expect("source file");
    let out = std::path::PathBuf::from(std::env::args().nth(2).expect("output dir"));
    let gop = 48; // 2 s at 24 fps
    let limit = Arc::new(Semaphore::new(2)); // at most two FFmpeg processes at once
    let mut tasks = Vec::new();
    for rung in RUNGS.iter() {
        let (permit, src, out) = (limit.clone().acquire_owned().await.unwrap(), src.clone(), out.clone());
        tasks.push(tokio::spawn(async move {
            let _permit = permit; // released when the task ends
            encode_rung(&src, &out, rung, gop, 20.0).await
        }));
    }
    for task in tasks {
        task.await.map_err(|e| e.to_string())??;
    }
    println!("all rungs done");
    Ok(())
}
flowchart TD M["main: probe done, three rungs to encode"] --> A1["acquire permit 1"] A1 --> T1["task 1080p: ffmpeg child, kill_on_drop"] M --> A2["acquire permit 2"] A2 --> T2["task 720p: ffmpeg child"] M --> A3["acquire permit 3: waits until a task ends"] T1 -- "ends, permit released" --> A3 A3 --> T3["task 360p: ffmpeg child"] T1 --> J["join all tasks"] T2 --> J T3 --> J J --> OK["all rungs done"]

Running it on the trailer wrote index.m3u8, init.mp4 and four seg_NNN.m4s files for each of the three rungs, with the media playlist #EXTINF values 6, 6, 6 and 2 seconds, as in the Node.js version, and printed all rungs done. Details that matter:

  • The permit is acquired before tokio::spawn, so the loop in main blocks while two encodes run and a third starts only when one finishes. Acquiring inside the task would spawn all of them at once and apply the limit too late.

  • The future that reads stdout and waits for the child is wrapped in tokio::time::timeout. When the timeout fires, the future is dropped, the Child is dropped with it, and kill_on_drop(true) makes tokio kill the process. Without that option a dropped Child keeps running.

  • Stdout is piped and read line by line, because a pipe nobody reads fills up and blocks FFmpeg. Stderr goes to Stdio::null() here, which is acceptable only because the exit status is checked. Keep the tail of stderr, as the Node.js version does, when you need the reason for a failure.

  • The two tasks are I/O waits plus an external process, so they do not need spawn_blocking. Decoding and encoding images with the image crate inside the process does, as in upload above.