Capcodec encoder implementation and benchmarking
Capcodec is the H.264 video encoder used for screen content when the media server selects it. It turns raw YUV video into a standards-based H.264 stream, packages that stream for file or streaming use, and provides a benchmark system that compares quality, speed, memory use, and decode safety with x264. See Capcodec media codec for the wider codec role and Media server and web cluster for the surrounding service.
System boundary
The encoder sits between decoded video frames and the media server's video output. It does not choose the source video or deliver audio. The media server supplies frames and later combines the encoded video with the rest of the media output.
The same encoder also serves as a stand-alone tool for benchmark runs. This keeps production behavior and measured behavior close while still allowing the benchmark system to test many quality and speed settings.
Encoding pipeline
The encoding flow has three stages: prepare frames, encode H.264, and package the result. A frame may include side information that marks changed regions, cursor movement, or scrolling. This information helps the encoder spend work where screen content changed, while a pixel comparison remains available when side information is absent.
flowchart LR
A[Input video] --> B[Frame preparation]
S[Optional screen side information] --> B
B --> C[Capcodec H.264 encoder]
C --> D[Annex B bitstream]
D --> E[Progressive MP4]
D --> F[Fragmented MP4]
D --> G[HLS init and media segments]
Frame preparation
Frame preparation gives the encoder even dimensions, an exact frame-rate fraction, and the YUV420P pixel format expected by the H.264 path. In the media server, FFmpeg decodes and scales the source before it pipes raw frames to Capcodec. The conversion uses limited-range BT.709 labels so the input and encoded output agree on color meaning.
References: apps/…/capcodec-encoder.ts• L129-207 apps/…/capcodec-encoder.ts• L286-345 capcodec/…/corpus.py• L92-139
H.264 bitstream generation
The encoder produces H.264 pictures with keyframes and predictive frames. Presets trade analysis work for speed. Rate control can follow constant quality or a capped bitrate target. Lookahead, changed-area hints, and optional B-frames support the different needs of screen recordings, live output, and low-delay output.
The encoder can write per-frame statistics and a reconstructed YUV stream. These outputs support performance analysis and frame-by-frame checks without changing the main video contract.
References: capcodec/…/encoder.tov• L32-50 capcodec/…/encoder.tov• L902-949 capcodec/…/main.tov• L499-525 capcodec/…/main.tov• L781-810
Container generation
The bitstream uses Annex B NAL units as its internal boundary. The MP4 muxer collects those units into samples and records timing, keyframe flags, reference status, and frame order. It can then produce a progressive MP4 or a fragmented MP4. Reordered frames receive composition timing so playback order stays correct.
HLS uses the fragmented MP4 form. It writes an initialization segment, media segments, and playlists that describe the segment durations and video format. The media server uses fragmented MP4 because it can flush output at GOP boundaries while audio is handled by the surrounding FFmpeg flow.
References: capcodec/…/mp4.tov• L3-29 capcodec/…/mp4.tov• L43-129 capcodec/…/mp4.tov• L281-391 capcodec/…/mp4.tov• L393-479 capcodec/…/hls.tov• L1-37
Command-line surface
The command-line surface is centered on capcodec encode. It accepts raw YUV input from a file or standard input and writes Annex B, MP4, fragmented MP4, or HLS output. The output suffix can select the container when no explicit format is given.
The main controls fall into a small set of user goals:
- Quality and rate:
--crf,--qp,--bitrate,--maxrate, and--bufsize. - Speed and delay:
--preset,--threads,--lookahead,--bframes, and--zerolatency. - Screen-content guidance:
--sideinfo,--noise, and analysis controls. - Output and inspection:
--recon,--stats,--frames, and the output format.
The media server maps its job quality and preset to this surface. Its ultrafast, superfast, veryfast, and faster names map to Capcodec fast; slower x264-style names map to slow. Environment values override the job only when they pass the allowed range checks.
References: capcodec/…/main.tov• L72-101 capcodec/…/main.tov• L111-269 apps/…/capcodec-encoder.ts• L34-104
Media-server integration
The media server treats Capcodec as an optional external encoder. The published image includes FFmpeg but not the Capcodec binary, so an operator must mount a matching executable and set CAP_MEDIA_VIDEO_ENCODER=capcodec. The server checks that the binary is executable before it starts work.
The integration runs two linked processes. FFmpeg decodes and prepares raw frames. Capcodec reads those frames from standard input and writes the requested video output. Progress comes from the decode process, while errors include the recent messages from either process. Cancellation stops both processes and the output must be non-empty before the job succeeds.
| Setting | Purpose |
|---|---|
CAPCODEC_BIN | Selects the mounted Capcodec executable. |
CAPCODEC_CRF | Overrides the job quality value from 0 through 51. |
CAPCODEC_PRESET | Overrides the job speed preset. |
CAPCODEC_KEYINT | Sets the keyframe interval. |
CAPCODEC_NOISE | Sets the change threshold used without side information. |
References: apps/…/capcodec.md• L1-16 apps/…/capcodec-encoder.ts• L78-117 apps/…/capcodec-encoder.ts• L286-375
Benchmark corpus
The corpus represents the content mix that matters for a screen encoder. Most clips are lossless captures of scripted, app-like Chrome pages. One clip is full-screen natural video. Each source has a fixed frame count, frame rate, dimensions, content tags, text regions, and optional side information.
The standard set contains twelve clips:
| Content group | Clips |
|---|---|
| Text and code | slow_typing, code_editor, dark_mode, code_4k |
| UI and motion | busy_ui, busy_ui_60fps, dashboard, slides, webcam_overlay |
| Static and scroll | idle, text_scroll |
| Natural video | full_motion |
The capture process checks frame timing and lossless source integrity. The full_motion clip also checks that Chrome presents the source frames in order. These checks make a benchmark failure easier to separate from a bad source capture.
References: capcodec/…/README.md• L3-13 capcodec/…/README.md• L54-76 capcodec/…/README.md• L78-126 capcodec/…/manifest.json• L3-19 capcodec/…/manifest.json• L908-1121
Evaluation harness
The harness turns each source clip into a set of encoder runs. It prepares a common YUV420P source, runs the reference and test encoders over quality points, decodes every result, and measures the result with the selected metric set. Cached identities include the encoder, binary, settings, source, machine, and metric configuration so old results do not silently stand in for a different run.
The main tiers expose different costs:
| Tier | Main use |
|---|---|
smoke | Small quality and decode gate on a few clips. |
standard | Full quality comparison with speed and matched-quality runs. |
ocr | Text readability checks on selected clips. |
full | Full corpus, all metrics, OCR, playback checks, and broad speed coverage. |
Quality and validity measurements
Quality runs compare bitrate against PSNR-YUV, VMAF, and SSIM curves. The reference is x264-veryfast at CRF 23. The harness reports BD-rate over the shared quality range. A negative value means the test encoder needs fewer bits for similar measured quality.
Decoded output is part of the result, not a separate manual step. FFmpeg checks frame count and bitstream health. When available, the JM decoder provides a second H.264 check. Reconstruction hashes can also compare the encoder's own reconstructed frames with decoded output. OCR and saved crops focus the report on text, which is a key screen-content requirement.
References: capcodec/…/runner.py• L20-63 capcodec/…/runner.py• L323-399 capcodec/…/metrics.py• L23-41 capcodec/…/metrics.py• L268-411 capcodec/…/bdrate.py• L7-44
Speed and performance reporting
Speed runs measure wall time, CPU time, peak memory, and encoder stage time. The harness can compare speed at matched quality, while speedcmp.py separately matches Capcodec to x264's VMAF and times shuffled rounds with other user processes paused. This avoids treating a faster run at lower quality as a real speed win.
Reports are written as CSV, JSON, HTML, and Markdown scoreboard data. They show rate-distortion curves, per-clip BD-rate, speed ratios, memory use, stage cost, decode failures, and errors. The current published comparison covers all twelve clips. It reports Capcodec faster than x264 veryfast on every measured clip in the listed live, medium, and zero-latency speed runs, while the quality result varies by content and metric.
The benchmark output is evidence for decisions, not a permanent property of every binary. Reports record the source commit, machine, FFmpeg version, clip set, and elapsed time. Published tables must therefore be read with their build and measurement notes.
References: capcodec/…/speedcmp.py• L228-259 capcodec/…/speedcmp.py• L262-377 capcodec/…/runner.py• L147-203 capcodec/…/report.py• L180-205 capcodec/…/scoreboard.py• L45-95 apps/…/capcodec-benchmarks.md• L1-26
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the media-server argument builder aligned with the CLI names and with the input color and frame-rate contract.
- Keep MP4 and HLS timing rules aligned with frame reordering, keyframes, and fragment boundaries.
- Keep benchmark adapter output types aligned with metric input handling for Annex B, MP4, fragmented MP4, and HLS.
- Rebuild or invalidate benchmark results when the encoder binary, source conversion rule, metric version, or corpus manifest changes.
- Keep the published comparison notes tied to the exact measured commits and benchmark mode.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Capcodec is selected without a mounted executable | The media job fails before encoding starts. | assertCapcodecBinary checks executable access and gives the mount guidance. |
| Odd or invalid frame dimensions reach the encoder | Raw frame layout or H.264 input contract is invalid. | The media path fits output to a positive even size. |
| Reordered frames are packaged without matching composition timing | Playback order or presentation time is wrong. | The muxer records decode order and composition offsets for reordered output. |
| A benchmark source has dropped, repeated, or missing frames | Quality and speed results no longer describe the intended clip. | Corpus capture checks, manifest metadata, decode frame counts, and playback checks expose the issue. |
| Quality curves have too little shared range | BD-rate is missing or misleading. | The rate comparison requires enough monotonic points and a non-trivial overlap. |
| A run fails to decode or match reconstruction | A performance result may hide a broken bitstream. | The harness counts FFmpeg, JM, and reconstruction failures in the report and gate. |
Key files
| File | Why to read it |
|---|---|
capcodec/src/encoder.tov | Defines the encoder's public frame and option model and the output statistics used by reports. |
capcodec/cli/main.tov | Defines the stand-alone encode command and connects input, encoder, muxer, stats, and output completion. |
capcodec/src/mux/mp4.tov | Defines progressive and fragmented MP4 output and timing for reordered frames. |
capcodec/src/mux/hls.tov | Defines HLS segment names and playlist output. |
| apps/…/capcodec-encoder.ts | Defines the media-server boundary, option precedence, raw-frame pipe, progress, and cancellation behavior. |
| capcodec/…/README.md | Explains the corpus goals, capture checks, clip classes, and side information. |
| capcodec/…/corpus.py | Defines how manifest clips become normalized benchmark sources. |
| capcodec/…/runner.py | Coordinates tiers, encoder runs, cache use, metric checks, and benchmark gates. |
| capcodec/…/metrics.py | Defines decode checks, quality metrics, OCR checks, and frame mapping. |
| capcodec/…/speedcmp.py | Defines matched-quality speed measurement and controlled timing runs. |
| capcodec/…/report.py | Defines the HTML and CSV performance views. |
| apps/…/capcodec-benchmarks.md | Gives the current published comparison and its measurement limits. |