# GPU processing in the camera bridge Every picture the bridge publishes can pass through a series of GPU steps on its way from the receiver to the encoder. This page describes how that works, the lens rectification step, and how to add a step. None of this runs by default. With no `--gpu-step` the picture is only copied (or shrunk, if the stream has `:DIV`). ## Where it sits ```text camera_receiver (NVDEC) camera_livekit_bridge, one thread per stream decoded NV12 in a GPU ring --CUDA IPC--> slot (GPU) --> [step 1] --> [step 2] --> ... --> NVENC input surface (slot notices on a socket) all on one CUDA stream, no host copy --> H.264 --> LiveKit ``` - The receiver decodes into a ring of GPU buffers and tells the bridge which slot holds the newest picture. The bridge maps the buffers once with CUDA IPC; pixels never cross the socket and never reach host memory. - The bridge owns the code between the slot and the encoder input surface. That code is a `GpuPipeline` (`gpu_ops/inc/gpu_ops/gpu_step.hpp`): an ordered list of `GpuStep`s. With no steps it is one plain copy. - Each stream has its own pipeline, so streams can have different steps and different calibrations. - The encoder is created for the size the last step produces, so a step may change the picture size. ## Using steps ```bash camera_livekit_bridge ... --stream head=sensing-head:2 --stream wrist1=sensing-wrist1 \ --gpu-step head:rectify=tables/head.icrmap --gpu-step wrist1:rectify=tables/wrist1.icrmap \ --gpu-step sine-warp=14,90 ``` - `--gpu-step [STREAM:]NAME[=ARGS]` adds a step. It is repeatable. With `STREAM:` the step is added to that stream only, where `STREAM` is the `NAME` of a `--stream NAME=TRACK[:DIV]`; without it, to every stream. Each stream runs its steps in the order they were given. - The value is cut at the first `=`, and the stream ends at the last `:` before it. Everything after that `=` is the step's own argument, so a path may contain colons, commas and equals signs. - A step for a stream that no `--stream` names stops the bridge at start with the flag and the stream. - The first step receives the source size and each later step the size the step before it produces. Of the known steps only `rectify` changes the size. The stream's own `:DIV` downscale is added last, so it shrinks the result of the steps. Run corrections such as rectification at full resolution and let the downscale come after. - A step that cannot run on a stream (an odd size, a missing or damaged table file, a table for another size, a size NV12 cannot hold) stops the bridge at start with the stream, its size, the step and the reason. Known steps: | Step | Arguments | Purpose | | --- | --- | --- | | `sine-warp` | `AMPLITUDE_PX,WAVELENGTH_PX,PHASE_RAD`, all optional | An example horizontal ripple. It shows the shape of a step; it is not calibrated rectification. | | `rectify` | `PATH`, required | Lens rectification as a table-driven remap. `PATH` is a remap table file for that camera and picture size; the step produces the table's output size. See "Lens rectification: the `rectify` step". | ## The step contract A step derives from `GpuStep` and implements these: | Method | Called | Does | | --- | --- | --- | | `set_full_range(full_range)` | before `prepare()` | Optional; ignored by default. Says whether the pictures are full range (0-255) rather than video range (16-235), from `--source-full-range`. A step that writes a fill keeps it. | | `prepare(input_size)` | once per picture size, before the first frame | Returns an empty string if the step can run on that size, otherwise the reason. Allocate and upload here: lookup tables, calibration, scratch. Remember the size; `enqueue()` receives planes only. | | `output_size(input_size)` | after a successful `prepare()` | The size this step produces. Default: unchanged. Return a different size for a crop or scale; a step may learn it in `prepare()`, as the rectify step does from its table. | | `enqueue(in, out, stream)` | every frame | Launch kernels on `stream` and return the CUDA status. | Rules for `enqueue()`: - Only queue work. Do not allocate, synchronise the device or the stream, or throw. The bridge waits for the stream once per frame, after the whole pipeline, and then checks the receiver's slot (see below). - `in` and `out` are different buffers. Work is not in place. - Pixels only. Frame number, timestamps and metadata travel with the frame; a step never touches them. - NV12 layout: a full-size luma plane and one interleaved chroma plane at half size in both directions. Planes are pitched; use the pitch, not the width, to step between rows. Sizes must stay even. - The output must be fully written, including positions the step cannot compute: use black in the picture's range (luma 16 for video range and 0 for full range, chroma 128 for both). The pipeline owns the buffers between steps (allocated in `GpuPipeline::prepare()`) and gives the last step the encoder input surface directly, so a step never allocates its own output. ## Adding a step 1. Add a class deriving from `GpuStep`. Put the kernels in a `.cu` file next to it in `gpu_ops/`, add the file to `gpu_ops/CMakeLists.txt`, and keep the public class in `gpu_ops/inc/gpu_ops/`. `sine_warp.hpp` and `sine_warp.cu` are a complete small example to copy, except for the fill: the sine warp writes video-range black whatever the range. A step whose fill follows the picture's range overrides `set_full_range()`, as `RectifyStep` does. `rectify.hpp`, `rectify_step.cpp` and `rectify.cu` are an example that uploads a table, changes the picture size and has a CPU reference. 2. Register it with one branch in `make_gpu_step()` in `gpu_ops/gpu_pipeline.cpp`, which maps `NAME[=ARGS]` to the step and parses its arguments (throw `std::invalid_argument` for bad ones). 3. Add a case to `tests/gpu_pipeline/test_gpu_pipeline.cpp`. A good first test is a case where the answer is known: an identity setting that must equal a plain copy, and one setting that visibly changes the picture. 4. Run it: `cmake --build build && ctest --test-dir build`, then a live run with `--gpu-step` and a saved frame. Skeleton: ```cpp class MyStep final : public GpuStep { public: explicit MyStep(Params params) : m_params(params) {} const char* name() const override { return "my-step"; } // A step that writes a fill also overrides set_full_range(bool) and keeps the range for it. std::string prepare(const ImageSize& input) override { m_size = input; if (input.width % 2 != 0 || input.height % 2 != 0) return "needs an even picture size"; // upload tables here return {}; } cudaError_t enqueue(const Nv12Planes& in, const Nv12PlanesOut& out, cudaStream_t stream) override { my_kernel_launch(in, out, m_size, m_params, stream); // luma and chroma return cudaGetLastError(); } private: Params m_params; ImageSize m_size; }; ``` ## Lens rectification: the `rectify` step Rectification is a remap: for each pixel of the corrected picture, find where it comes from in the camera image and sample there. The `rectify` step does the sampling. It does not do the finding. - **A separate tool plans the mapping.** It reads the camera calibration, computes for every output pixel the source position `(sx, sy)` (the ray of the ideal pinhole camera, distorted with the lens model and projected with the real intrinsics), folds any crop and resize into the same positions, and writes one remap table file per camera and picture size. The step does not interpret calibration files or lens models, so every planning rule stays in that tool. - **Use.** `--gpu-step STREAM:rectify=PATH`. Cameras differ, so name the stream. `PATH` is everything after the `=`; the file's name does not matter, only its contents. - **Size.** The picture the step receives must have the table's source size; that picture is the stream's when `rectify` is the first step. The step produces the table's output size. A `:DIV` downscale still comes after, and the encoder is created for the result. - **Start.** The file is read once, when the stream starts. A missing, unreadable or refused file, or a table made for another picture size, stops the bridge with the stream, its size, the step and one sentence that names the file by its base name. Both tables (below) are uploaded to the GPU once and freed with the step; nothing is allocated per frame. - **Luma.** For each output pixel the kernel reads `(sx, sy)`. When the position is inside the source, `0 <= sx <= width - 1` and `0 <= sy <= height - 1`, it samples the source luma there bilinearly, rounds half up and clamps to 0..255. Otherwise it writes the fill. The test is a positive predicate, so a NaN takes the fill. - **Chroma.** The chroma plane is half size, and chroma sample `(cx, cy)` sits at luma position `(2cx, 2cy + 0.5)`. When the table is loaded, a half-size chroma table is built on the host: each chroma sample takes the luma entries at `(2cx, 2cy)` and `(2cx, 2cy + 1)`. If either has no source pixel, neither has the chroma sample, and U and V take the fill. Otherwise their mean is the source luma position `(sx, sy)` of that sample, which is `(sx / 2, (sy - 0.5) / 2)` in source chroma coordinates. Halving `sy` alone is wrong by a quarter of a chroma row: with it an identity table would not reproduce the chroma plane. The source chroma plane, `0` to `chroma width - 1` by `0` to `chroma height - 1`, ends short of the luma plane's border: by one luma column (half a chroma sample) at the right and by half a luma row (a quarter of a chroma sample) at the top and bottom. A position in that margin is clamped into the chroma plane, which repeats the edge chroma sample as chroma upsampling does at a picture's border; a position already in the plane is not moved. U and V are sampled bilinearly at the result. So a chroma sample takes the fill only when one of its two luma entries does, and a view that reaches the source's border keeps its colour there. - **Fill.** Black in the picture's range: luma 16 and chroma 128 for video range, luma 0 and chroma 128 with `--source-full-range`. ### The remap table file Little-endian: a fixed header, then the payload. | Offset | Size | Field | | --- | --- | --- | | 0 | 8 | magic, the ASCII bytes `ICRMAP01` | | 8 | 4 | u32 header size in bytes: 48, where the payload starts | | 12 | 4 | u32 source width: luma pixels of the picture the step receives | | 16 | 4 | u32 source height | | 20 | 4 | u32 output width: luma pixels of the picture the step produces | | 24 | 4 | u32 output height | | 28 | 4 | u32 flags, 0 | | 32 | 8 | u64 FNV-1a 64-bit hash of the payload bytes | | 40 | 8 | u64 reserved, 0 | | 48 | 8 x output width x output height | payload: row-major, one entry per output luma pixel, each two float32 `(sx, sy)` | - `(sx, sy)` is the position in the source luma plane that output pixel `(u, v)` samples, in pixels, x to the right and y down, with integer coordinates at pixel centres. This is the convention of OpenCV's `initUndistortRectifyMap` with `CV_32FC1` and of `cv::remap`. - A position outside `[0, source width - 1] x [0, source height - 1]`, or one that is not finite, means "no source pixel": the output gets the fill. - All four sizes are even, not zero and at most 16777216, and the file is exactly 48 bytes plus the payload. Up to that size (2^24) a float32 holds every pixel position exactly. - The reader refuses a wrong magic, another header size, flags other than 0, an odd or zero size, a size above 16777216, a length that does not match the sizes, and a payload that does not match its hash. ### How it is built and tested - The table reader, the chroma table and the per-pixel sampling are in `remap_table/`, which includes no CUDA header. `remap_table/inc/remap_table/remap_pixel.hpp` holds the per-pixel functions and is compiled for both the host and the device; the kernels in `gpu_ops/rectify.cu` only turn a thread index into a sample position, bounds-check it and call them. `remap_nv12_reference()` runs the same functions on the CPU. - Each interpolation is one explicit fused multiply-add. Left to the compiler, some targets fuse `a + t * (b - a)` and others do not, and the device and the CPU reference would then round differently next to a half. - `tests/remap_table` needs no GPU: the file reader and its refusals, the chroma table and its clamp at the source's borders, and the CPU reference on identity, shifted, filled and resized tables with pitched pictures. - `tests/gpu_pipeline` needs a GPU: the kernels' output must equal the CPU reference byte for byte, row padding included, in both ranges. ## What the bridge does around the steps - The pipeline runs on one CUDA stream and the bridge waits for that stream once per frame. That wait is required: the receiver's ring slot can be overwritten, so the copy out of it must be finished before the slot may be trusted. - After the wait, the bridge checks for a newer notice for the same slot, or as many newer notices as the ring has other slots, and drops the picture instead of encoding it (the `slot overruns` count in the stats line). This is a best-effort check, not exclusive ownership of the slot; see `README.md`. - Steps add GPU time to every frame. Keep a step's kernels light and measure with the stats line (`encode` and the capture-to-ready latency) before and after. - The encoder surface is copied into by the last step, so a step that leaves part of its output unwritten publishes whatever that surface held before.