Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/camera_livekit_bridge/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ endif()

add_subdirectory(video_types)
add_subdirectory(ipc_client)
add_subdirectory(remap_table)
add_subdirectory(gpu_ops)
add_subdirectory(nvenc)
add_subdirectory(chrony_clock)
Expand Down
136 changes: 101 additions & 35 deletions examples/camera_livekit_bridge/GPU_PROCESSING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ SPDX-License-Identifier: Apache-2.0
# 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 and how to add a step, for example lens rectification.
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`).

Expand All @@ -29,30 +29,39 @@ camera_receiver (NVDEC) camera_livekit_bridge, one thread per stream
## Using steps

```bash
camera_livekit_bridge ... --stream head=sensing-head:2 \
--gpu-step sine-warp=14,90 --gpu-step another-step=ARGS
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 NAME[=ARGS]` adds a step to every stream. It is repeatable. Steps run in the order given.
- Steps run at the source 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 calibration for another size, a size NV12 cannot hold) stops the
bridge at start with the stream, the step and the reason.
- `--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 three things:
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)` | at prepare time | The size this step produces. Default: unchanged. Return a different size for a crop or scale. |
| `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()`:
Expand All @@ -63,8 +72,8 @@ Rules for `enqueue()`:
- 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 the video-range fill (luma 16,
chroma 128).
- 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.
Expand All @@ -73,7 +82,10 @@ input surface directly, so a step never allocates its own output.

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.
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
Expand All @@ -89,6 +101,8 @@ 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;
Expand All @@ -110,30 +124,82 @@ private:
};
```

## Writing lens rectification as a step
## 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 sine warp is the same operation with a made-up mapping.

- **The mapping.** For output pixel `(u, v)` build the ray of the ideal pinhole camera (the new camera matrix), distort
it with the lens model (fisheye or radial-tangential coefficients from the camera's intrinsics), and project it with
the real intrinsics. The result is the source position `(sx, sy)`. The sine warp uses
`sx = x + A*sin(2*pi*y/L + phase), sy = y` in its place.
- **Compute it once.** The mapping depends on the calibration and the picture size, never on the pixels. In
`prepare()`, compute `(sx, sy)` for every output pixel on the host, `cudaMalloc` a `float2` table of that size, and
upload it. Free it in the destructor. The per-frame kernel then reads the table entry and bilinear-samples the
source, which costs about the same as the sine warp.
- **Chroma.** The chroma plane is half size. Either keep a second half-size table, or evaluate the luma table at each
chroma sample's luma position (`(2*cx, 2*cy + 0.5)` with the usual siting) and halve the result.
- **Outside the image.** A source position outside the image gets the fill (luma 16, chroma 128). Test for it with a
positive predicate so a NaN also takes the fill path.
- **Size.** Rectification often crops or rescales the field of view. Return that from `output_size()`; the encoder is
created for the last step's output.
- **Calibration input.** Pass a calibration file path as the step's argument, parse it in `make_gpu_step()`, and
refuse in `prepare()` a picture size the calibration was not made for. If cameras differ, the per-stream pipelines
allow a different calibration per stream; the step spec would need a stream name or a per-stream argument.
- **Check it.** A known calibration of a synthetic grid with straight lines is the natural test: after the step the
lines are straight within a pixel.
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

Expand Down
Loading
Loading