Sub topic 6
Building the transcoding pipeline
This chapter assumes you know what a codec, a container and a bitrate are, and that you have used a message queue and object storage. It also assumes you can read short Python and shell snippets. The bitrate ladder and HLS/DASH packaging have their own chapters. Here we build the machinery that turns an uploaded file into a set of encoded outputs.
What the pipeline must do
A transcoding pipeline takes one source file and produces many encoded outputs. Uploads are untrusted, vary widely in format, and are expensive to process. The pipeline therefore needs to:
- Check that the source is a usable video before spending compute on it.
- Encode it into every rendition the ladder requires.
- Finish quickly enough that creators see their video soon after upload.
- Survive worker crashes, retries and duplicate messages without producing corrupt or duplicated output.
- Scale up for bursts and down to near zero cost when idle.
Transcoding is CPU-bound, often runs for minutes per video, and is safe to repeat. These properties suggest an asynchronous job system: a queue, a pool of stateless workers, and a small state store.
Pipeline stages
1. Probe and validate
The first worker runs ffprobe on the stored source. It reads the container, streams, codecs, resolution, frame rate and duration. Reject early when:
- There is no video stream.
- The duration is zero or implausibly long.
- The resolution is below your minimum or above your maximum.
- The file is corrupt (ffprobe exits non-zero).
Probe results also drive planning. A 480p source should not be upscaled to 1080p, so the planner drops renditions taller than the source.
import json
import subprocess
def probe(path):
"""Return basic facts about the first video stream, or raise on bad input."""
result = subprocess.run(
["ffprobe", "-v", "error", "-print_format", "json",
"-show_streams", "-show_format", path],
check=True, capture_output=True, text=True,
)
info = json.loads(result.stdout)
video = next(
(s for s in info["streams"] if s["codec_type"] == "video"), None
)
if video is None:
raise ValueError("no video stream")
num, den = video["r_frame_rate"].split("/")
return {
"width": video["width"],
"height": video["height"],
"fps": int(num) / int(den),
"duration": float(info["format"]["duration"]),
"has_audio": any(s["codec_type"] == "audio" for s in info["streams"]),
}
if __name__ == "__main__":
print(probe("input.mp4"))2. Plan the job
The planner turns probe output into a list of tasks, for example "encode rendition 720p, chunk 3". Storing the plan in the job record makes retries and progress reporting simple, because each task has an identity.
3. Encode
Each encode task runs FFmpeg. The following command from the packaging stage produces a 720p H.264 rendition cut into 4-second HLS segments:
ffmpeg -i input.mp4 \
-vf scale=-2:720 \
-c:v libx264 -preset medium -b:v 2800k -maxrate 3000k -bufsize 6000k \
-g 48 -keyint_min 48 -sc_threshold 0 \
-c:a aac -b:a 128k \
-f hls -hls_time 4 -hls_playlist_type vod \
-hls_segment_filename "720p/seg_%04d.ts" \
720p/index.m3u8The flags that matter for pipeline design:
-g 48 -keyint_min 48 -sc_threshold 0forces a keyframe every 48 frames and disables scene-cut keyframes. Fixed keyframe spacing means segment boundaries line up across renditions, which adaptive playback needs.-maxrateand-bufsizecap bitrate spikes so the output stays predictable for the network.-preset mediumtrades encoding time for compression efficiency. Slower presets give smaller files at the same quality but cost more CPU.
4. Merge, verify and publish
After all tasks finish, a final step checks the outputs. It confirms that every rendition exists, that durations match the source within a small tolerance, and that playlists reference segments that are actually present. Only then does the job move to ready. A video should never be visible while some renditions are missing.
Speeding up with chunked parallel encoding
Encoding a two-hour film as one task can take longer than the film. The fix is to split the timeline into chunks, encode them in parallel, and concatenate the results.
The chunk boundaries must fall on keyframes, and each chunk must start with one, so the pieces join without visual glitches. Choose chunk length as a multiple of the keyframe interval. With segments of 4 seconds, chunks of 60 to 120 seconds work well, because 60 seconds is exactly 15 segments.
| Approach | Wall-clock time | Compression efficiency | Complexity |
|---|---|---|---|
| One task per video | Longest | Best | Lowest |
| One task per rendition | Bounded by the slowest rendition | Best | Low |
| One task per chunk per rendition | Shortest | Slightly worse at chunk edges | Highest |
Most systems start with one task per rendition and add chunking only for long videos. Short clips gain little from it, and chunking adds merge steps that can fail.
Orchestration, state and idempotency
Workers pull tasks from a queue. Queues deliver at least once, so the same task may run twice, and a worker may die halfway through. Design every task so that running it again is harmless.
Practical rules:
- Deterministic output keys. Write to a path derived from the video ID, rendition and chunk, such as
videos/{id}/720p/seg_0003.ts. A repeated run overwrites the same object with equivalent bytes. - Write to a temporary location, then commit. Upload to a staging prefix and promote it only when the task finishes. Readers never see half-written output.
- Track state in a store, not in the queue. A job record holds a status (
queued,running,failed,ready) and a per-task status. The next stage starts when all tasks of the previous stage are complete. - Use visibility timeouts and heartbeats. If a worker stops extending its lease, the queue makes the task visible again. Set the timeout above the longest expected task time, or the task runs twice at once.
- Limit retries and use a dead-letter queue. A source that crashes the encoder on every attempt should stop after a few tries and be flagged for inspection. Otherwise it blocks capacity forever.
Scaling the worker pool
Encoding is compute-heavy and bursty. Common choices:
- Autoscale on queue depth, not on CPU. Queue depth divided by average task time estimates how many workers you need to drain the backlog within your target delay.
- Use spot or preemptible instances. Because tasks are idempotent and retried, losing a worker only costs the work done on its current task. Chunking limits that loss.
- Separate queues by priority. A short creator-facing upload should not wait behind a catalog re-encode of ten thousand titles.
- Consider hardware encoders. GPU and dedicated encoders are much faster per video but typically give lower compression efficiency than software x264 or x265 at the same quality. Use them where latency matters more than bytes.
Common mistakes
- Trusting the file extension. Always probe; a
.mp4can contain anything. - Variable frame rate sources. Phone recordings often have variable frame rate, which breaks fixed keyframe math and can desync audio. Normalise with the
-rorfpsfilter in the encode step. - Mismatched audio across renditions. If renditions have different audio sample rates or channel layouts, switching renditions can cause audible glitches. Encode one audio spec and reuse it.
- No output verification. An encoder can exit with status 0 and still write a truncated file if the disk fills. Check durations and file sizes.
- Forgetting cleanup. Staging objects and local scratch space grow without bound. Set lifecycle rules and clean scratch directories at task end.
Exercise
A worker is encoding rendition 1080p of video v42 when its spot instance is reclaimed. The queue redelivers the task to a new worker. Name two design properties that make this safe, and one failure that could still occur if the visibility timeout is shorter than the encode time.
Show answer
The task is safe to redeliver because (1) output keys are deterministic, such as videos/v42/1080p/..., so a second run overwrites the same objects, and (2) the worker writes to a staging location and promotes only on success, so partial output from the dead worker is never served. If the visibility timeout is shorter than the encode time, the queue redelivers the task while the first worker is still running. Two workers then encode the same rendition at once, which wastes compute and can race when promoting the output. The fix is a timeout longer than the longest expected task, or heartbeats that extend the lease.
Exercise
Your source video is 30 fps and you reuse -g 48 -hls_time 4. Why is this a problem, and what value of -g would align keyframes with 4-second segments?
Show answer
At 30 fps, 48 frames is 1.6 seconds, so keyframes fall at 1.6, 3.2, 4.8 seconds and so on. A 4-second segment boundary does not land on a keyframe, so segments cannot start cleanly on one and segment lengths drift or vary. Use a keyframe interval that divides 4 seconds evenly, such as -g 120 (4 seconds) or -g 60 (2 seconds), with -keyint_min set to the same value.