Live video streaming job
ffmpeg pulls a video from the internet and re-streams it as live HLS from a MicroVM. Anyone with the link can watch, and the run lasts until you cancel it.
What this tutorial proves
- A task reaches the internet only through an allow-list (
egress_allow). - A deployment gets its own public HTTPS address, and the task chooses which paths are public.
- A run can report live progress while it runs (
ctx.chunk). - A run can last until you stop it, and it stops cleanly on
run:cancel(SIGTERM). - System tools such as ffmpeg are installed into the image at build time.
What you build
A task that turns any https video into a live stream that anyone can watch in a browser.
- The task starts a small HTTP server on port 8080 and tells the platform it is ready.
- ffmpeg downloads the video (outbound) and re-encodes it to HLS at playback speed.
- Viewers open
/live/on the deployment's public address (inbound). - When the video ends, the task keeps serving it for replay until you cancel the run.
viewer ──HTTPS──▶ <route-id>--<tenant-id>.ignitify.app/live/ ──▶ VM :8080 (Node server + ffmpeg)
│
VM ──HTTPS (egress_allow only)──▶ raw.githubusercontent.com (the source video)The task's nature
In task.yaml you declare what the task is. The platform decides how to run it.
| Setting | Value | Why |
|---|---|---|
network.type | bidirectional | Outbound to fetch the video, inbound so viewers can connect. |
egress_allow | [raw.githubusercontent.com] | The only host the task may reach. A redirect to another host is blocked. |
inbound_port | 8080 | The port the task listens on. It must match PORT in index.ts. |
inbound_routes | /live/ | Only these paths are public. Everything else answers 404. |
interaction | continuous | Progress chunks reach run:get while the run is live. |
duration | long | The run lasts until you cancel it. Heartbeats keep it alive past timeout_sec, up to the platform's hard cap. |
preset | std.medium | 512 MiB. Live x264 runs out of memory on std.micro. |
Before you start
- A plan that allows inbound traffic and the
std.mediumpreset. This tutorial uses Pro. - The CLI, installed and signed in. See Install.
$ ignitify loginCreate the task
Register the name and get a task folder with starter files. You replace the starter files in the next step.
$ ignitify task:create streaming-jobtasks/streaming-job/
├── task.yaml the config: nature, network, build packages, run defaults
├── index.ts the shell: init(), run(), server, ffmpeg, signals
├── utils.ts the pure parts: payload, ffmpeg arguments, progress parser, routes
└── README.md how to run itThe code
index.ts wires the server, the ffmpeg process and the stop signal. utils.ts holds the pure functions, so they are easy to read and to test. The platform bundles both files into one, so a relative import works.
// Live video stream: ffmpeg reads a video from a URL and re-streams it as HLS that anyone can watch.
//
// Payload: { url: string (https), seconds?: number (default 60, max 300), height?: number (default 480),
// start_delay_sec?: number (default 0: stream at once; set it to wait before streaming),
// linger_sec?: number (default: none) }
// After the stream ends the task keeps serving, so viewers can replay the whole video. It stops only on
// SIGTERM (`ignitify run:cancel <run-id>`), or at the platform's hard cap. Set linger_sec to stop on its own instead.
//
// Outbound: ffmpeg downloads the source (egress_allow in task.yaml).
// Inbound: an HTTP server on inbound_port serves /live/ (inbound_routes in task.yaml):
// /live/ a player page (hls.js), for any browser
// /live/index.m3u8 the HLS playlist, for VLC, Safari or ffplay
// ctx.chunk(data) streams the viewer URL first, then progress (max 10 KiB each).
//
// This file is the shell: server, ffmpeg process, signals. The pure parts live in utils.ts.
import { spawn, execFile, type ChildProcessByStdio } from "node:child_process";
import { createServer, type Server, type ServerResponse } from "node:http";
import { promisify } from "node:util";
import { mkdir, readFile, rm } from "node:fs/promises";
import path from "node:path";
import type { Readable } from "node:stream";
import {
ROUTE, PROGRESS_START, ffmpegArgs, parseInput, parseProgress, resolveRoute, sleep, stopSignal, viewerUrl,
type ProgressReport, type Route, type StreamInput,
} from "./utils.js";
type Ctx = {
chunk(data: unknown): void;
metric(name: string, value: number): void;
ready(): Promise<void> | void;
callback?: { url: string };
};
type RunResult =
| { success: true; cancelled: true; stage: "before-stream" }
| { success: true; cancelled: boolean; watch: string | undefined; streamed_s: number; height: number; wall_ms: number };
type Ffmpeg = ChildProcessByStdio<null, Readable, Readable>;
const execFileP = promisify(execFile);
const PORT = 8080; // must equal execution.network.inbound_port
// The VM has no /tmp. The only writable disk is the scratch disk, mounted at /mnt/scratch (the task's HOME).
const HLS_DIR = path.join(process.env.HOME ?? "/mnt/scratch", "hls");
const CHUNK_EVERY_MS = 2000;
const STDERR_TAIL_CHARS = 2000;
export async function init(): Promise<void> {
const { stdout } = await execFileP("ffmpeg", ["-version"]);
console.log(stdout.split("\n")[0]);
}
function respond(route: Route, res: ServerResponse): void {
if (route.kind === "player") {
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(route.body);
return;
}
if (route.kind === "none") {
res.writeHead(404).end();
return;
}
readFile(route.file).then(
(body) => res.writeHead(200, { "content-type": route.type, "cache-control": "no-cache" }).end(body),
() => res.writeHead(404).end(),
);
}
async function startServer(): Promise<Server> {
const server = createServer((req, res) => respond(resolveRoute(new URL(req.url ?? "/", "http://x").pathname, HLS_DIR), res));
await new Promise<void>((resolve) => server.listen(PORT, resolve));
return server;
}
// Wait `ms`, or less if a stop comes first.
const sleepUnlessStopped = (ms: number, stopped: Promise<void>): Promise<void> => Promise.race([stopped, sleep(ms)]);
function startFfmpeg(input: StreamInput, stopped: Promise<void>): Ffmpeg {
const ff = spawn("ffmpeg", ffmpegArgs(input, path.join(HLS_DIR, "index.m3u8")), { stdio: ["ignore", "pipe", "pipe"] });
void stopped.then(() => ff.kill("SIGTERM"));
return ff;
}
// Keep only the last STDERR_TAIL_CHARS of stderr, for the error message.
function stderrTail(ff: Ffmpeg): () => string {
let tail = "";
ff.stderr.on("data", (b: Buffer) => { tail = (tail + String(b)).slice(-STDERR_TAIL_CHARS); });
return () => tail;
}
// One `streaming` chunk and metric per CHUNK_EVERY_MS, and always for the last report.
function reportProgress(ff: Ffmpeg, ctx: Ctx, seconds: number): void {
let state = PROGRESS_START;
let lastChunk = 0;
const emit = (r: ProgressReport): void => {
if (Date.now() - lastChunk < CHUNK_EVERY_MS && !r.end) return;
lastChunk = Date.now();
ctx.chunk({ status: "streaming", time_s: Number(r.doneSec.toFixed(1)), of_s: seconds, speed: r.speed });
ctx.metric("streamed_seconds", r.doneSec);
};
ff.stdout.on("data", (b: Buffer) => {
const parsed = parseProgress(state, String(b));
state = parsed.state;
parsed.reports.forEach(emit);
});
}
function exitCode(ff: Ffmpeg): Promise<number> {
return new Promise((resolve, reject) => {
ff.on("error", reject);
ff.on("close", (c) => resolve(c ?? -1));
});
}
export async function run(payload: Record<string, unknown>, ctx: Ctx): Promise<RunResult> {
const input = parseInput(payload);
const { stopped, isStopped } = stopSignal();
await rm(HLS_DIR, { recursive: true, force: true });
await mkdir(HLS_DIR, { recursive: true });
const server = await startServer();
await ctx.ready();
const watch = viewerUrl(ctx.callback?.url);
ctx.chunk({ status: "live", watch, playlist: watch && `${watch}index.m3u8` });
console.log(`serving ${ROUTE} on :${PORT}${watch ? `, public at ${watch}` : ""}`);
// Stay up before streaming, so the viewer can open the link first.
if (input.startDelaySec > 0) {
ctx.chunk({ status: "waiting", start_in_s: input.startDelaySec, watch });
console.log(`streaming starts in ${input.startDelaySec} s`);
await sleepUnlessStopped(input.startDelaySec * 1000, stopped);
}
if (isStopped()) {
server.close();
return { success: true, cancelled: true, stage: "before-stream" };
}
const ff = startFfmpeg(input, stopped);
const stderr = stderrTail(ff);
reportProgress(ff, ctx, input.seconds);
const started = Date.now();
const code = await exitCode(ff);
if (code !== 0 && !isStopped()) {
server.close();
throw new Error(`ffmpeg exited with ${code}: ${stderr().trim()}`);
}
if (!isStopped()) {
ctx.chunk({ status: "ended", replay_until: input.lingerSec ? `${input.lingerSec} s` : "run:cancel", watch });
console.log("stream ended, still serving the replay until the run is cancelled");
const lingerMs = (input.lingerSec ?? 0) * 1000;
await (lingerMs > 0 ? sleepUnlessStopped(lingerMs, stopped) : stopped);
}
server.close();
return { success: true, cancelled: isStopped(), watch, streamed_s: input.seconds, height: input.height, wall_ms: Date.now() - started };
}// Helpers for the live stream task. All pure (payload parsing, ffmpeg arguments, the -progress parser,
// route resolution, the player page), except sleep and stopSignal. index.ts wires the effects.
import path from "node:path";
export const ROUTE = "/live/"; // must equal the inbound_routes prefix
const MAX_SECONDS = 300;
export type StreamInput = {
readonly url: string;
readonly seconds: number;
readonly height: number;
readonly startDelaySec: number;
readonly lingerSec: number | undefined;
};
// One finished -progress report: the encoded time and ffmpeg's speed; `end` on the last one.
export type ProgressReport = {
readonly doneSec: number;
readonly speed: string;
readonly end: boolean;
};
// The parser's carry-over between stdout reads: a partial line, and the fields of the open report.
export type ProgressState = {
readonly buf: string;
readonly fields: Readonly<Record<string, string>>;
};
export type Route =
| { readonly kind: "player"; readonly body: string }
| { readonly kind: "file"; readonly file: string; readonly type: string }
| { readonly kind: "none" };
const TYPES: Readonly<Record<string, string>> = {
".m3u8": "application/vnd.apple.mpegurl",
".ts": "video/mp2t",
};
const PLAYER = `<!doctype html><meta charset="utf-8"><title>Live</title>
<body style="margin:0;background:#000">
<video id="v" controls autoplay muted playsinline style="width:100%;height:100vh"></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.17/dist/hls.min.js"></script>
<script>
const v = document.getElementById("v"), src = "index.m3u8";
// The playlist does not exist until the stream starts: poll until it does, then play.
const play = () => {
if (v.canPlayType("application/vnd.apple.mpegurl")) v.src = src;
else { const h = new Hls(); h.loadSource(src); h.attachMedia(v); }
};
const wait = () => fetch(src, { cache: "no-store" }).then((r) => (r.ok ? play() : setTimeout(wait, 2000)), () => setTimeout(wait, 2000));
wait();
</script></body>`;
const positiveOr = (v: unknown, d: number): number => (typeof v === "number" && v > 0 ? v : d);
// Throws on a missing or non-https url; every other field falls back to its default.
export function parseInput(payload: Readonly<Record<string, unknown>>): StreamInput {
const url = typeof payload.url === "string" ? new URL(payload.url) : undefined;
if (!url || url.protocol !== "https:") throw new Error("payload.url must be an https URL");
return {
url: url.toString(),
seconds: Math.min(positiveOr(payload.seconds, 60), MAX_SECONDS),
height: positiveOr(payload.height, 480),
startDelaySec: typeof payload.start_delay_sec === "number" ? Math.max(0, payload.start_delay_sec) : 0,
lingerSec: typeof payload.linger_sec === "number" && payload.linger_sec > 0 ? payload.linger_sec : undefined,
};
}
// -re reads at playback speed, so the stream is live, not a fast transcode.
// "event" playlist keeps every segment, so a late viewer can still seek to the start.
export function ffmpegArgs(input: StreamInput, playlist: string): readonly string[] {
return [
"-hide_banner", "-nostats", "-loglevel", "error", "-progress", "pipe:1",
"-re", "-i", input.url, "-t", String(input.seconds),
"-vf", `scale=-2:${input.height}`, "-c:v", "libx264", "-preset", "veryfast", "-g", "48", "-sc_threshold", "0",
"-c:a", "aac", "-b:a", "128k",
"-f", "hls", "-hls_time", "4", "-hls_list_size", "0", "-hls_playlist_type", "event",
playlist,
];
}
export const PROGRESS_START: ProgressState = { buf: "", fields: {} };
// -progress prints key=value lines; a "progress=" line ends one report.
// Text in, finished reports out; a partial last line waits in `buf` for the next read.
export function parseProgress(state: ProgressState, text: string): { state: ProgressState; reports: readonly ProgressReport[] } {
const lines = (state.buf + text).split("\n");
const buf = lines.pop() ?? "";
const none: readonly ProgressReport[] = [];
const start = { fields: state.fields, reports: none };
const { fields, reports } = lines.reduce((acc, line) => {
const [k, v] = line.split("=");
if (k === undefined || v === undefined) return acc;
const next = { ...acc.fields, [k]: v };
if (k !== "progress") return { ...acc, fields: next };
const report = { doneSec: Number(next.out_time_us ?? 0) / 1e6, speed: next.speed ?? "", end: v === "end" };
return { fields: {}, reports: [...acc.reports, report] };
}, start);
return { state: { buf, fields }, reports };
}
// Serve only .m3u8/.ts files inside `dir`, under ROUTE, plus the player page. Everything else is 404.
export function resolveRoute(urlPath: string, dir: string): Route {
if (urlPath === ROUTE || urlPath === ROUTE.slice(0, -1)) return { kind: "player", body: PLAYER };
const name = path.basename(urlPath);
const type = TYPES[path.extname(name)];
if (!urlPath.startsWith(ROUTE) || !type) return { kind: "none" };
return { kind: "file", file: path.join(dir, name), type };
}
// The public address: the deployment hostname, taken from this run's callback URL.
export function viewerUrl(callbackUrl: string | undefined): string | undefined {
return callbackUrl ? `${new URL(callbackUrl).origin}${ROUTE}` : undefined;
}
export const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
// A graceful `run:cancel` arrives as SIGTERM. Node's default would exit at once, leaving ffmpeg behind.
// `stopped` resolves on the first SIGTERM/SIGINT; `isStopped()` reads the same fact synchronously.
export function stopSignal(): { stopped: Promise<void>; isStopped: () => boolean } {
const stopped = new Promise<void>((resolve) => {
process.once("SIGTERM", resolve);
process.once("SIGINT", resolve);
});
let flag = false;
void stopped.then(() => { flag = true; });
return { stopped, isStopped: () => flag };
}schema_version: 1
slug: streaming-job # must match this directory's name
runtime: node
# Installed into the image at build time.
build:
system_packages: [ffmpeg]
execution:
duration: long # runs until you cancel it
interaction: continuous # ctx.chunk updates reach `run:get` while the run is live
network:
type: bidirectional # outbound to the video host, inbound from viewers
egress_allow: [raw.githubusercontent.com] # the only host the task may reach
inbound_port: 8080 # must equal PORT in index.ts
inbound_routes: # the only public paths ("/" is refused: it covers /__callback/)
- prefix: /live/
inbound_max_concurrent: 16 # requests in flight at one time, not viewers
run:
payload:
url: https://raw.githubusercontent.com/chthomos/video-media-samples/master/big-buck-bunny-1080p-30sec.mp4
seconds: 30
preset: std.medium # 512 MiB: live x264 runs out of memory on std.micro
timeout_sec: 21600 # silence budget; heartbeats extend it up to the hard cap. The task normally ends on run:cancel# streaming-job
ffmpeg downloads a video from an https URL and re-streams it as live HLS. Anyone with the link can watch. After the stream ends, the task keeps serving the whole video for replay until you cancel the run.
## Files
- `task.yaml`: slug, runtime, build packages, task nature and default run parameters.
- `index.ts`: the shell: `init()`, `run()`, the HTTP server, the ffmpeg process and signals.
- `utils.ts`: the pure parts: payload parsing, ffmpeg arguments, the progress parser, routes.
## Payload
| Field | Default | Meaning |
| :-- | :-- | :-- |
| `url` | none | https URL of the source video (required) |
| `seconds` | 60 | Seconds to stream (at most 300) |
| `height` | 480 | Output height in pixels |
| `start_delay_sec` | 0 | Wait this long before streaming starts |
| `linger_sec` | none | Stop on its own this long after the stream ends. Leave out to run until `run:cancel` |
## Lifecycle
```bash
ignitify login
ignitify task:create streaming-job
ignitify task:validate streaming-job --review-packages
ignitify task:deploy streaming-job
ignitify task:run streaming-job
ignitify run:get <run-id> --full # progress.watch is the viewer address
ignitify run:cancel <run-id> --yes # graceful stop (SIGTERM)
```
Watch it at `https://<route-id>--<tenant-id>.ignitify.app/live/` in a browser, or play the playlist:
```bash
ffplay https://<route-id>--<tenant-id>.ignitify.app/live/index.m3u8
```
Deploy again after every change to `index.ts`, `utils.ts` or `task.yaml`.Validate
Check task.yaml on your machine. Nothing is sent and nothing is built.
$ ignitify task:validate streaming-job✓ task config valid
Ask the platform's AI to review the system packages and estimate the build time. It is advice only and never changes the exit code. Only the package names and the runtime leave your machine.
$ ignitify task:validate streaming-job --review-packages✓ task config validPackage review AI advice only. A suggestion is not checked against Debian. Package Verdict Size Note Suggest ─────── ─────── ─────── ──── ─────── ffmpeg ok <size>No concerns found in 1 package.Build time Added about <range> (model estimate) Applies to the first deploy of this list. A later code-only redeploy reuses the drive.
List the files that a deploy would upload:
$ ignitify task:pack streaming-jobDeploy
Upload the source. The platform installs ffmpeg, bundles index.ts and utils.ts, and builds the image.
$ ignitify task:deploy streaming-job✓ Image built · <build time>✓ Deployment Createddeployment_id <deployment-id>
$ ignitify deployment:get <deployment-id>Deploy again after every change to index.ts, utils.ts or task.yaml. Each deployment gets its own public address.
Run and watch
Start a run. The default payload in task.yaml streams a 30 s Big Buck Bunny clip, so no flags are needed.
$ ignitify task:run streaming-jobTo stream another video, pass a payload. Add the video's host to egress_allow first, and redeploy.
$ ignitify task:run streaming-job --payload '{"url":"https://raw.githubusercontent.com/chthomos/video-media-samples/master/big-buck-bunny-1080p-30sec.mp4","seconds":30,"height":360}'Find the viewer address. progress holds the last chunk the task sent, and its watch field is the address. The plain run:get view does not show progress, so use --full.
$ ignitify run:get <run-id> --full{
"status": "RUNNING",
"progress": {
"status": "live",
"watch": "https://<route-id>--<tenant-id>.ignitify.app/live/",
"playlist": "https://<route-id>--<tenant-id>.ignitify.app/live/index.m3u8"
}
}Open the watch address in a browser, or play the playlist with ffplay or VLC:
$ ffplay https://<route-id>--<tenant-id>.ignitify.app/live/index.m3u8The task log shows the same address and any ffmpeg error:
$ ignitify run:logs <run-id>[task] INFO: serving /live/ on :8080, public at https://<route-id>--<tenant-id>.ignitify.app/live/
When the video ends, the last chunk becomes {"status":"ended","replay_until":"run:cancel"}. The run stays RUNNING, and viewers can replay the whole video.
Stop and clean up
A graceful cancel sends the task SIGTERM. The task stops ffmpeg, closes the server and returns {"cancelled": true}. It arrives with the next heartbeat, so it can take about 5 s.
$ ignitify run:cancel <run-id> --yes$ ignitify run:cancel <run-id> --yes --force$ ignitify run:get <run-id>Delete what you no longer need:
$ ignitify deployment:delete <deployment-id> --yes$ ignitify task:delete streaming-job --yesLoad test
How many viewers can one run serve? We ran simulated viewers against one run and added more in steps.
- Viewer: simulated HLS player: 12 s buffer, 3 retries (0.5 s, 1 s, 1.5 s), one connection each.
- Video: Big Buck Bunny 1080p, 30 s, re-encoded to 480p HLS: 8 segments, about 1–1.8 Mbit/s.
- Where: Ignitify test fleet (dev-class hosts), std.medium, Pro tier limits, 2026-10-20.
| Viewers | Refused requests | Throughput | p95 segment | Freezes |
|---|---|---|---|---|
| 8 | 0% | 11.1 Mbit/s | 0.1 s | 0 |
| 16 | 0% | 24.1 Mbit/s | 1.0 s | 0 |
| 24 | 0% | 30.5 Mbit/s | 0.3 s | 0 |
| 32 | 0.4% | 38.6 Mbit/s | 0.1 s | 0 |
| 48 | 9.1% | 56.7 Mbit/s | 0.3 s | 0 |
| 64 | 13.9% | 74.1 Mbit/s | 0.7 s | 0 |
| 80 | 14.4% | 94.4 Mbit/s | 1.0 s | 0 |
| 96 | 53.7% | 101.1 Mbit/s | 1.5 s | 4 (5.7 s) |
| 128 | 76.5% | 98.2 Mbit/s | 1.7 s | 15 (50 s) |
| 160 | 82.3% | 98.1 Mbit/s | 1.7 s | 41 (334 s) |
What the numbers mean
- The task never failed. No test step caused a crash or a connection error. The platform refused extra requests before they reached the VM.
- Refusals start at about 32 viewers, but nobody notices.
inbound_max_concurrent: 16counts requests at the same instant, not viewers. A viewer downloads a 4 s segment in a fraction of a second, then waits. When more than 16 downloads overlap, one is refused, and the player retries half a second later. Its 12 s buffer hides the wait. - Freezes start at 96 viewers, and the cause is bandwidth. Throughput stays flat at the plan's cap of about 100 Mbit/s. Downloads slow down, more of them overlap, retries fail, and a buffer runs empty.
- So one run serves about 80 viewers at 480p with no freezes. A lower
heightuses less bandwidth per viewer and raises that number.
Next steps
- The
streamintegration writes these settings and this plumbing for you. - Change
heightto 360 or 720 and compare the load-test numbers. - Stream from another host: add it to
egress_allowand redeploy. See Network access. - Learn how runs end and what each status means: Lifecycle and statuses.
- Read every
task.yamlkey: task.yaml reference.