Trame

h264

Screen frames to an H.264 stream with the encoders the system has, without ffmpeg: the GPU's when there is one, otherwise a software encoder. The packets are Annex B access units, ready for a muxer (MP4, MKV) or for a stream.

Formula
#import "trame:h264"

e, err := h264.open(width, height, fps = 60, o = {bitrate = 8_000_000})   // or {qp = 23}: a constant quantiser
if err != .None { /* .Unavailable: no encoder here */ }
defer h264.close(e)
for frame in frames {
	packets, _ := h264.encode(e, h264.Frame{pixels = frame.bgra, width = width, height = height, stride = frame.stride, format = .BGRA}, frame.time)
	for p in packets { mux(p.data, p.timestamp, p.keyframe) }   // valid until the next call on e
}
rest, _ := h264.flush(e)

Every call blocks: the GPU, the encoder's threads, the libraries' loading. Call them on a worker; one encoder belongs to one thread (on Windows, open joins that thread to COM's multithreaded apartment and close leaves it).

The backends

BackendSystemWhat it needs installed
.NvencLinux, WindowsNVIDIA's own driver, 520 or later (NVENC API 12.0), on a GPU with NVENC (Maxwell, GeForce 900, and later; some GT and MX models have none): libcuda.so.1 and libnvidia-encode.so.1 on Linux (also looked for in /run/opengl-driver/lib, NixOS), nvcuda.dll and nvEncodeAPI64.dll on Windows. Not nouveau: that one goes through .Vaapi.
.VaapiLinuxlibva.so.2 and libva-drm.so.2 (libva 2.x), and a driver that encodes H.264: intel-media-driver (iHD, Broadwell and later) or libva-intel-driver (i965, older Intel), Mesa's radeonsi for AMD, nouveau for older NVIDIA. The render node /dev/dri/renderD128 (or a later one) readable by the user.
.Openh264LinuxCisco's libopenh264.so.7 (openh264 2.4 or later of the 2.x line).
.Media_Foundation_HardwareWindowsThe GPU's H.264 encoder MFT, which its driver installs (Intel Quick Sync, NVIDIA NVENC, AMD AMF).
.Media_Foundation_SoftwareWindowsMicrosoft's H.264 encoder: Windows 7 and later, except the N and KN editions without the Media Feature Pack.

available() lists the backends the system has now; a settings page shows it. backend_of(e) says which one open took. Encoder_Options.backend takes .Auto (the GPU's, else software), .Hardware or .Software. open tries the backends in the order of the table, NVENC first; one that fails to open gives way to the next. The libraries are loaded at run time (dlopen, LoadLibrary): a program starts without them, and open answers .Unavailable.

NVENC runs on a CUDA context on both systems (on Windows, a D3D11 device would be the other way: CUDA is the same code and needs no device of its own). The frames go in through NVENC's own buffer in system memory. available opens a session to know: NVIDIA's consumer GPUs take a limited number of sessions at once, and an encoder holds one.

On Linux, nix shell nixpkgs#libva-utils -c vainfo lists what the driver encodes: look for VAProfileH264High : VAEntrypointEncSlice (or EncSliceLP).

The stream

  • Profile. High, then Main, then Constrained Baseline, as the GPU's encoder offers (NVENC: High); openh264 makes Constrained Baseline.
  • I and P pictures only, each picture the reference of the next: a packet comes out for each frame, with no reordering. NVENC, VA-API and openh264 give it before encode returns; a Media Foundation encoder can give it one or two frames later, and flush gives the rest.
  • Keyframes. One every keyframe_interval (2 s by default), counted in frames at fps. Every keyframe is an IDR picture that carries the SPS and the PPS, so the first packet always does. parameter_sets(packet.data) gives them to a muxer (avcC).
  • Rate. bitrate (bits a second) takes a variable rate when the encoder offers one, else a constant one; without it, qp (1 ..= 51, default 23) is a constant quantiser. An encoder that has no constant quantiser gets a rate of about 0.1 bit a pixel.
  • Colours. BT.709, limited range (16 ..= 235), as players assume for HD video; the SPS says so in its VUI. The conversion runs on the GPU when VA-API has video processing (VAProcPipeline), otherwise on the CPU (to_nv12, to_i420). NVENC takes NV12 made on the CPU: its own conversion of RGB uses the BT.601 matrix. Each chroma sample is the mean of its 2 x 2 pixels.
  • Odd sizes. 4:2:0 and H.264 cropping work in steps of 2 pixels: an odd side is padded by repeating the last column or row once. The stream's picture is stream_width x stream_height (even); width x height are the frames' size, which a muxer writes in its header.
  • Timestamps. Each packet carries the timestamp given with its frame; fps only guides the rate control.

The pure parts

They run on every system, and tests/h264 checks them with exact values:

  • Bit_Writer: write_bits (u(n)), write_ue and write_se (Exp-Golomb), write_trailing_bits.
  • write_sps, write_pps, write_slice_header for the one stream shape above; append_nal makes a NAL unit with its emulation prevention bytes. VA-API takes them as packed headers when the driver asks for them.
  • to_nv12, to_i420: BGRA or RGBA to 4:2:0.
  • next_nal, nal_type, has_nal_type, parameter_sets: Annex B.
  • level_for: the lowest level for a size, a frame rate and a bitrate.

Edit this page on GitHub