From 4f9748705936d61206a6285dda8ecf034f24ebd1 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Wed, 25 Nov 2026 22:21:18 -0800 Subject: [PATCH] examples/camera_livekit_bridge: add a table-driven lens rectification GPU step Add a `rectify` GPU step that remaps each NV12 picture through a table file. A separate planning tool writes the table from the camera calibration and folds undistortion, crop and resize into it, so the bridge interprets no calibration file or lens model. - `remap_table/`: the table file reader (fixed header, payload hash, size checks) and the per-pixel sampling, with no CUDA dependency so both are tested on the host. Luma is sampled bilinearly; chroma positions are derived from the luma table and clamped into the chroma plane, so a view that reaches the source's border keeps its colour. Positions with no source pixel take the fill for the picture's range. - `gpu_ops/`: `RectifyStep` uploads the table in `prepare()`, runs the same sampling in a CUDA kernel and may change the picture size. - `--gpu-step [STREAM:]NAME[=ARGS]` adds a step to one stream, since each camera needs its own table. A table that is missing, damaged or made for another picture size stops the bridge at start. - Tests: `tests/remap_table` and `tests/gpu_step_spec` run without a GPU; `tests/gpu_pipeline` compares the device output with the host reference byte for byte. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/camera_livekit_bridge/CMakeLists.txt | 1 + .../camera_livekit_bridge/GPU_PROCESSING.md | 136 ++- examples/camera_livekit_bridge/README.md | 35 +- .../camera_livekit_bridge/bridge/main.cpp | 32 +- .../bridge/stream_worker.cpp | 4 +- .../bridge/stream_worker.hpp | 11 +- .../gpu_ops/CMakeLists.txt | 9 +- .../gpu_ops/gpu_pipeline.cpp | 15 +- .../gpu_ops/inc/gpu_ops/gpu_step.hpp | 27 +- .../gpu_ops/inc/gpu_ops/gpu_step_spec.hpp | 68 ++ .../gpu_ops/inc/gpu_ops/rectify.hpp | 70 ++ .../gpu_ops/inc/gpu_ops/sine_warp.hpp | 30 +- .../camera_livekit_bridge/gpu_ops/rectify.cu | 63 ++ .../gpu_ops/rectify_step.cpp | 68 ++ .../remap_table/CMakeLists.txt | 15 + .../inc/remap_table/remap_pixel.hpp | 112 +++ .../inc/remap_table/remap_table.hpp | 123 +++ .../remap_table/remap_table.cpp | 328 +++++++ .../tests/gpu_pipeline/CMakeLists.txt | 7 +- .../tests/gpu_pipeline/test_gpu_pipeline.cpp | 245 ++++- .../tests/gpu_step_spec/CMakeLists.txt | 14 + .../gpu_step_spec/test_gpu_step_spec.cpp | 117 +++ .../tests/remap_table/CMakeLists.txt | 14 + .../tests/remap_table/test_remap_table.cpp | 850 ++++++++++++++++++ 24 files changed, 2306 insertions(+), 88 deletions(-) create mode 100644 examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step_spec.hpp create mode 100644 examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/rectify.hpp create mode 100644 examples/camera_livekit_bridge/gpu_ops/rectify.cu create mode 100644 examples/camera_livekit_bridge/gpu_ops/rectify_step.cpp create mode 100644 examples/camera_livekit_bridge/remap_table/CMakeLists.txt create mode 100644 examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_pixel.hpp create mode 100644 examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_table.hpp create mode 100644 examples/camera_livekit_bridge/remap_table/remap_table.cpp create mode 100644 examples/camera_livekit_bridge/tests/gpu_step_spec/CMakeLists.txt create mode 100644 examples/camera_livekit_bridge/tests/gpu_step_spec/test_gpu_step_spec.cpp create mode 100644 examples/camera_livekit_bridge/tests/remap_table/CMakeLists.txt create mode 100644 examples/camera_livekit_bridge/tests/remap_table/test_remap_table.cpp diff --git a/examples/camera_livekit_bridge/CMakeLists.txt b/examples/camera_livekit_bridge/CMakeLists.txt index 8669783950..b5ae07ac3d 100644 --- a/examples/camera_livekit_bridge/CMakeLists.txt +++ b/examples/camera_livekit_bridge/CMakeLists.txt @@ -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) diff --git a/examples/camera_livekit_bridge/GPU_PROCESSING.md b/examples/camera_livekit_bridge/GPU_PROCESSING.md index f25985c4ae..d8594d4eab 100644 --- a/examples/camera_livekit_bridge/GPU_PROCESSING.md +++ b/examples/camera_livekit_bridge/GPU_PROCESSING.md @@ -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`). @@ -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()`: @@ -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. @@ -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 @@ -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; @@ -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 diff --git a/examples/camera_livekit_bridge/README.md b/examples/camera_livekit_bridge/README.md index 98315e1950..7114355e96 100644 --- a/examples/camera_livekit_bridge/README.md +++ b/examples/camera_livekit_bridge/README.md @@ -49,7 +49,8 @@ temporary wiring. The processing path keeps input and output on the GPU. The bri completion; the receiver's input slot is read without a lease (see the slot-overwrite limitation described in this README), so reading it safely depends on an ownership contract on the receiver side. When processing moves behind the camera reader interface it must keep GPU-resident buffers and completion-based lifetime. The sine-warp step demonstrates kernel -integration; it is not a calibrated rectification implementation. +integration; it is not a calibrated rectification implementation. The rectify step remaps each picture through a table +that a separate planning tool writes from the camera calibration; the bridge reads no calibration itself. The `chrony_clock/` adapter connects the reusable timing library to the current video publication path and is intended to converge on the receiver backend's clock-mapping contract. With `capture_monotonic_us`, a mapping that cannot be @@ -59,20 +60,34 @@ precision target keeps its timestamp. `monotonic_us` is a separate, declared bas ## GPU steps (per-frame image operations) Between the receiver's IPC buffer and the encoder the picture can pass through a series of GPU steps, with no host -copy. None run by default. `--gpu-step NAME[=ARGS]` adds one, repeatable; steps run in the order given, at the source -size, and a stream's own `:DIV` downscale shrinks the result afterwards. +copy. None run by default. `--gpu-step [STREAM:]NAME[=ARGS]` adds one, repeatable; steps run in the order given, each +on the picture the one before it produces, and a stream's own `:DIV` downscale shrinks the result afterwards. With +`STREAM:` (the `NAME` of a `--stream`) the step is added to that stream only; without it, to every stream. A step for +a stream that no `--stream` names is an error at start. | Step | Arguments | Purpose | | --- | --- | --- | | `sine-warp` | `AMPLITUDE_PX,WAVELENGTH_PX,PHASE_RAD` (all optional) | An EXAMPLE horizontal ripple. It is not calibrated rectification; it exists to show the shape of a step. | +| `rectify` | `PATH` (required) | Lens rectification as a table-driven remap. `PATH` is a remap table file for that camera and picture size, and may contain colons, commas and equals signs. The step produces the table's output size, which a stream's `:DIV` then divides. | -The system and how to add a step (with a walk-through of writing lens rectification) are described in +A remap table is written by a separate planning tool, which folds undistortion, crop and resize into it. The bridge +does not interpret calibration files or lens models. Cameras differ, so give each stream its own table: + +```bash +camera_livekit_bridge ... --stream head=sensing-head --stream wrist1=sensing-wrist1 \ + --gpu-step head:rectify=tables/head.icrmap --gpu-step wrist1:rectify=tables/wrist1.icrmap +``` + +A table that is missing, damaged or made for another picture size stops the bridge at start with the stream and the +reason. Where a table names no source pixel the step writes black for the picture's range (see `--source-full-range`). + +The system, the rectify step with its table file format, and how to add a step are described in [`GPU_PROCESSING.md`](GPU_PROCESSING.md). A step is a class deriving from `GpuStep` (`gpu_ops/inc/gpu_ops/gpu_step.hpp`) with `prepare()` (once per picture size: allocate and upload) and `enqueue()` (per frame: launch kernels on the given stream). To add one, write the class and add a line to `make_gpu_step()` in `gpu_ops/gpu_pipeline.cpp`. `SineWarpStep` (`gpu_ops/inc/gpu_ops/sine_warp.hpp`) is -the template, and its comment explains how lens rectification would be written the same way: a remap table computed -once from the camera calibration and uploaded in `prepare()`, and a per-frame kernel that samples the source through it -(luma and chroma), with the fill for positions outside the image. +the template for a step that computes its mapping per pixel. `RectifyStep` (`gpu_ops/inc/gpu_ops/rectify.hpp`) is the +one to copy for a step that uploads a table in `prepare()` and changes the picture size; its per-pixel sampling lives +in `remap_table/`, which needs no CUDA and is tested on the host. ## Build @@ -102,7 +117,8 @@ build/bridge/camera_livekit_bridge \ `--stream NAME=TRACK[:DIV]` publishes the receiver's stream `NAME` as the LiveKit track `TRACK`, shrunk by the integer `DIV` on the GPU (the size must divide to even dimensions). Track names, the join token's identity and the -published sizes must match the streams file egocap is given. The token needs +published sizes must match the streams file egocap is given; with a `rectify` +step the published size is the table's output size, divided by `DIV`. The token needs publish permission. Every 5 s it prints each track's frame rate, keyframes, skipped, rejected and slot-overrun frames and mean encode time. @@ -160,7 +176,8 @@ then signals full range, so players and recordings keep the black and white leve limited range (16-235). The receiver's IPC catalog does not carry the range, so it is set here and must match the source: a full-range picture published as limited range has crushed blacks and clipped whites, and the reverse looks washed out. The encoder copies levels as they are and does no range conversion. The stream signals no colour -primaries, transfer or matrix, so a player assumes its default (BT.709 for HD). +primaries, transfer or matrix, so a player assumes its default (BT.709 for HD). GPU steps are told the range too: the +`rectify` step fills what its table leaves without a source pixel with luma 0 for full range and 16 otherwise. `--bitrate-mbps` is the maximum. The encoder starts at 2 Mbps and follows the target bitrate that LiveKit's congestion control reports for each track (90% of the target, never above the maximum or below 0.5 Mbps), so a diff --git a/examples/camera_livekit_bridge/bridge/main.cpp b/examples/camera_livekit_bridge/bridge/main.cpp index cf24b949b3..bb808b8d8a 100644 --- a/examples/camera_livekit_bridge/bridge/main.cpp +++ b/examples/camera_livekit_bridge/bridge/main.cpp @@ -5,6 +5,7 @@ #include "stream_worker.hpp" +#include #include #include @@ -36,12 +37,16 @@ void usage() { std::cerr << "usage: camera_livekit_bridge --livekit-url URL --livekit-token-file FILE --stream NAME=TRACK[:DIV] [--stream ...]\n" - " [--socket PATH] [--fps N] [--bitrate-mbps N] [--idr-period N] [--max-notice-age-ms N] [--gpu N] [--source-full-range]\n [--gpu-step NAME[=ARGS] ...] [--timestamp-basis monotonic_us|capture_monotonic_us]\n" + " [--socket PATH] [--fps N] [--bitrate-mbps N] [--idr-period N] [--max-notice-age-ms N] [--gpu N] [--source-full-range]\n [--gpu-step [STREAM:]NAME[=ARGS] ...] [--timestamp-basis monotonic_us|capture_monotonic_us]\n" " capture_monotonic_us: --chrony-sender HOST[:PORT] --chrony-sender-refid HEX [--chrony-pc-port PORT]\n" " [--chronyc PATH]\n" " NAME is a stream in camera_receiver's IPC catalog; TRACK is the LiveKit track name egocap expects;\n DIV shrinks the picture on the GPU by that integer factor before encoding.\n" " --gpu-step adds a per-frame GPU image operation, repeatable, run in the order given before the downscale;\n" - " none run by default. Known: sine-warp[=AMPLITUDE_PX,WAVELENGTH_PX,PHASE_RAD] (an example, not rectification).\n"; + " none run by default. With STREAM: (a --stream NAME) the step is added to that stream only, otherwise to\n" + " every stream. Known steps:\n" + " sine-warp[=AMPLITUDE_PX,WAVELENGTH_PX,PHASE_RAD] an example ripple, not rectification\n" + " rectify=PATH remap through the table file PATH, written by a separate planning tool for that camera\n" + " and picture size; the step produces the table's output size, which a :DIV then divides\n"; } std::string read_token(const std::string& path) @@ -72,6 +77,7 @@ int main(int argc, char** argv) uint32_t scale_div = 1; }; std::vector streams; + std::vector gpu_steps; WorkerConfig defaults; int gpu = 0; ChronyCaptureClockConfig chrony_config; @@ -151,7 +157,16 @@ int main(int argc, char** argv) else if (arg == "--chronyc") chrony_config.chronyc_path = next(); else if (arg == "--gpu-step") - defaults.gpu_steps.push_back(next()); + { + const std::string text = next(); + const auto option = parse_gpu_step_option(text); + if (!option) + { + std::cerr << "--gpu-step needs [STREAM:]NAME[=ARGS], got '" << text << "'\n"; + return 2; + } + gpu_steps.push_back(*option); + } else if (arg == "--gpu") gpu = std::atoi(next().c_str()); else if (arg == "--stream") @@ -186,6 +201,16 @@ int main(int argc, char** argv) return 2; } + std::vector stream_names; + for (const auto& spec : streams) + stream_names.push_back(spec.name); + if (const GpuStepOption* stray = gpu_step_for_unknown_stream(gpu_steps, stream_names)) + { + std::cerr << "--gpu-step '" << stray->stream << ":" << stray->spec << "' is for stream '" << stray->stream + << "', and no --stream has that NAME\n"; + return 2; + } + if (defaults.timestamp_basis == TimestampBasis::CaptureMonotonicUs && !use_chrony) { std::cerr @@ -223,6 +248,7 @@ int main(int argc, char** argv) config.track = spec.track; config.scale_div = spec.scale_div; config.socket_path = socket_path; + config.gpu_steps = gpu_steps_for_stream(gpu_steps, spec.name); workers.push_back(std::make_unique(config, context, *session)); } for (auto& worker : workers) diff --git a/examples/camera_livekit_bridge/bridge/stream_worker.cpp b/examples/camera_livekit_bridge/bridge/stream_worker.cpp index 76ed674308..ee195cd980 100644 --- a/examples/camera_livekit_bridge/bridge/stream_worker.cpp +++ b/examples/camera_livekit_bridge/bridge/stream_worker.cpp @@ -147,11 +147,13 @@ struct StreamWorker::Impl layout = read_layout(stream); check_plane_extents(stream, layout); source = { static_cast(stream.width), static_cast(stream.height) }; - // The steps asked for run in order at the source size, then the stream's own downscale shrinks the result. + // The steps asked for run in order, each on the size the one before it produces, then the stream's own + // downscale shrinks the result. for (const auto& step_spec : cfg.gpu_steps) pipeline.add(make_gpu_step(step_spec)); if (cfg.scale_div > 1) pipeline.add(make_box_downscale_step(cfg.scale_div)); + pipeline.set_full_range(cfg.source_full_range); const std::string unusable = pipeline.prepare({ source.width, source.height }); if (!unusable.empty()) throw std::runtime_error("stream '" + cfg.stream + "' (" + std::to_string(source.width) + "x" + diff --git a/examples/camera_livekit_bridge/bridge/stream_worker.hpp b/examples/camera_livekit_bridge/bridge/stream_worker.hpp index 567d37f035..8d7377733b 100644 --- a/examples/camera_livekit_bridge/bridge/stream_worker.hpp +++ b/examples/camera_livekit_bridge/bridge/stream_worker.hpp @@ -31,13 +31,14 @@ struct WorkerConfig /// A read that finishes later than this after its slot's notice is treated as possibly overwritten and dropped. /// Zero derives it from the ring: the time the publisher needs to wrap it at `fps`. uint32_t max_notice_age_ms = 0; - /// Integer factor the picture is shrunk by on the GPU before encoding (1 keeps the source size). + /// Integer factor the picture is shrunk by on the GPU before encoding (1 does not shrink it). uint32_t scale_div = 1; - /// The IPC pictures are full-range (0-255) rather than limited-range (16-235); the encoded stream signals it. The - /// receiver's IPC catalog does not carry the range, so the operator says it here. + /// The IPC pictures are full-range (0-255) rather than limited-range (16-235); the encoded stream signals it and + /// the GPU steps are told, for their fill. The receiver's IPC catalog does not carry the range, so the operator + /// says it here. bool source_full_range = false; - /// GPU steps run, in order, on every picture before the downscale (see gpu_ops/gpu_step.hpp). Empty by default: - /// the picture is only copied or shrunk. + /// GPU steps run, in order, on every picture of this stream before the downscale (see gpu_ops/gpu_step.hpp), each + /// as `NAME[=ARGS]`. Empty by default: the picture is only copied or shrunk. std::vector gpu_steps; /// What each frame's user_timestamp means; the consumer's streams file must name the same basis. TimestampBasis timestamp_basis = TimestampBasis::MonotonicUs; diff --git a/examples/camera_livekit_bridge/gpu_ops/CMakeLists.txt b/examples/camera_livekit_bridge/gpu_ops/CMakeLists.txt index f2a995fef2..b5a97b30cc 100644 --- a/examples/camera_livekit_bridge/gpu_ops/CMakeLists.txt +++ b/examples/camera_livekit_bridge/gpu_ops/CMakeLists.txt @@ -2,7 +2,13 @@ # SPDX-License-Identifier: Apache-2.0 # GPU operations on NV12 pictures, run between the IPC slot and the encoder input. -add_library(gpu_ops STATIC box_downscale.cu sine_warp.cu gpu_pipeline.cpp) +add_library(gpu_ops STATIC + box_downscale.cu + sine_warp.cu + rectify.cu + rectify_step.cpp + gpu_pipeline.cpp +) target_include_directories(gpu_ops INTERFACE @@ -11,6 +17,7 @@ target_include_directories(gpu_ops target_link_libraries(gpu_ops PUBLIC + camera_livekit_bridge::remap_table CUDA::cudart ) diff --git a/examples/camera_livekit_bridge/gpu_ops/gpu_pipeline.cpp b/examples/camera_livekit_bridge/gpu_ops/gpu_pipeline.cpp index 4553c8746c..68e2bb76c6 100644 --- a/examples/camera_livekit_bridge/gpu_ops/gpu_pipeline.cpp +++ b/examples/camera_livekit_bridge/gpu_ops/gpu_pipeline.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 #include "inc/gpu_ops/gpu_step.hpp" +#include "inc/gpu_ops/rectify.hpp" #include "inc/gpu_ops/sine_warp.hpp" #include @@ -102,6 +103,7 @@ std::string GpuPipeline::prepare(const ImageSize& source) for (const auto& step : m_steps) { m_inputs.push_back(size); + step->set_full_range(m_full_range); const std::string reason = step->prepare(size); if (!reason.empty()) return std::string(step->name()) + ": " + reason; @@ -174,9 +176,16 @@ std::unique_ptr make_gpu_step(const std::string& spec) params.phase_rad = values[2]; return std::make_unique(params); } - // Add steps here, for example: - // if (name == "rectify") return std::make_unique(load_calibration(args)); - throw std::invalid_argument("unknown GPU step '" + name + "' (known: sine-warp)"); + if (name == "rectify") + { + // rectify=PATH: everything after the first `=` is the remap table's path, whatever characters it holds. The + // step reads the file in prepare(), where a refusal is reported with the stream. + if (args.empty()) + throw std::invalid_argument("rectify needs a remap table file: rectify=PATH"); + return std::make_unique(args); + } + // Add steps here. + throw std::invalid_argument("unknown GPU step '" + name + "' (known: sine-warp, rectify)"); } } // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step.hpp b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step.hpp index a26b35b099..db808d923d 100644 --- a/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step.hpp +++ b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step.hpp @@ -32,9 +32,11 @@ struct ImageSize * a color change, an overlay. * * To add a step: - * 1. Write a class deriving from GpuStep (see SineWarpStep in sine_warp.hpp for a complete, small example). + * 1. Write a class deriving from GpuStep (see SineWarpStep in sine_warp.hpp for a complete, small example, and + * RectifyStep in rectify.hpp for one that uploads a table and changes the size). * 2. Add one line to make_gpu_step() in gpu_pipeline.cpp so `--gpu-step NAME[=ARGS]` can create it. - * 3. Pass `--gpu-step NAME=ARGS` once per step, in the order they should run. Nothing runs unless asked for. + * 3. Pass `--gpu-step [STREAM:]NAME=ARGS` once per step, in the order they should run. Nothing runs unless asked + * for. * * Contract: * - prepare() runs once per input size, before the first frame. Allocate and upload here (lookup tables, @@ -51,7 +53,14 @@ class GpuStep virtual const char* name() const = 0; - /// The size of the picture this step produces from one of `input` size. Default: unchanged. + /// Called before prepare(): whether the pictures are full range (0-255) rather than video range (16-235). It + /// matters to a step that writes a fill, where black is luma 0 rather than 16. Default: ignored. + virtual void set_full_range(bool /*full_range*/) + { + } + + /// The size of the picture this step produces from one of `input` size. Default: unchanged. The pipeline asks + /// after a successful prepare(), so a step may learn its output size there. virtual ImageSize output_size(const ImageSize& input) const { return input; @@ -76,6 +85,12 @@ class GpuPipeline void add(std::unique_ptr step); + /// Whether the source pictures are full range; prepare() passes it to every step. Video range unless set. + void set_full_range(bool full_range) + { + m_full_range = full_range; + } + /// Prepares every step for a picture of `source` size and allocates the intermediate buffers. Returns an empty /// string on success, otherwise which step cannot run and why. std::string prepare(const ImageSize& source); @@ -103,11 +118,13 @@ class GpuPipeline std::vector m_scratch; // the output of every step except the last ImageSize m_source; ImageSize m_output; + bool m_full_range = false; }; /** - * @brief Creates a step from a command-line spec `NAME` or `NAME=ARG[,ARG...]`; throws std::invalid_argument for an - * unknown name or bad arguments. The single place that maps names to steps: add new steps here. + * @brief Creates a step from a command-line spec `NAME` or `NAME=ARGS`; throws std::invalid_argument for an unknown + * name or bad arguments. ARGS is everything after the first `=`, read the step's own way (a number list, a path). + * The single place that maps names to steps: add new steps here. */ std::unique_ptr make_gpu_step(const std::string& spec); diff --git a/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step_spec.hpp b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step_spec.hpp new file mode 100644 index 0000000000..005c7e6966 --- /dev/null +++ b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/gpu_step_spec.hpp @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include +#include + +namespace camera_bridge +{ + +/// One `--gpu-step [STREAM:]NAME[=ARGS]` value. This header includes no CUDA header, so it is tested on the host. +struct GpuStepOption +{ + /// The `--stream` NAME the step is for; empty when it is for every stream. + std::string stream; + /// `NAME[=ARGS]`, what make_gpu_step() takes. + std::string spec; +}; + +/// Splits a `--gpu-step` value. The stream ends at the last `:` before the first `=`, so ARGS may hold any character +/// (a path with colons and equals signs). Empty when the stream or the step name would be empty. +inline std::optional parse_gpu_step_option(const std::string& text) +{ + const std::string head = text.substr(0, text.find('=')); + const auto colon = head.rfind(':'); + GpuStepOption option; + if (colon == std::string::npos) + { + if (head.empty()) + return std::nullopt; + option.spec = text; + return option; + } + if (colon == 0 || colon + 1 == head.size()) + return std::nullopt; + option.stream = text.substr(0, colon); + option.spec = text.substr(colon + 1); + return option; +} + +/// The specs that run on `stream`, in the order given: those for every stream and those that name it. +inline std::vector gpu_steps_for_stream(const std::vector& options, const std::string& stream) +{ + std::vector specs; + for (const auto& option : options) + { + if (option.stream.empty() || option.stream == stream) + specs.push_back(option.spec); + } + return specs; +} + +/// The first option that names a stream missing from `streams`, or nullptr when every option has a stream to run on. +inline const GpuStepOption* gpu_step_for_unknown_stream(const std::vector& options, + const std::vector& streams) +{ + for (const auto& option : options) + { + if (!option.stream.empty() && std::find(streams.begin(), streams.end(), option.stream) == streams.end()) + return &option; + } + return nullptr; +} + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/rectify.hpp b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/rectify.hpp new file mode 100644 index 0000000000..181f3163d8 --- /dev/null +++ b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/rectify.hpp @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "gpu_step.hpp" + +#include + +namespace camera_bridge +{ + +/** + * @brief Queues the remap of one NV12 picture through a table held in device memory. + * + * `source` has the table's source size and `destination` its output size. Every output byte is written: the sample + * the table names, bilinear, or black in the picture's range where it names none. Returns the CUDA status of the + * launches, or cudaErrorInvalidValue without a table. + */ +cudaError_t rectify_nv12(const Nv12Planes& source, + const Nv12PlanesOut& destination, + const RemapTableView& tables, + bool full_range, + cudaStream_t stream); + +/** + * @brief Lens rectification as a table-driven remap, created by `--gpu-step rectify=PATH`. + * + * PATH is a remap table file that a separate planning tool writes with undistortion, crop and resize folded in; the + * step interprets no lens model or calibration file. The file is read in prepare(), so a missing or refused file, or + * a table made for another picture size, is reported with the stream it is for. output_size() is the table's output + * size and is empty until prepare() has succeeded, which is the order the pipeline calls them in. + */ +class RectifyStep final : public GpuStep +{ +public: + explicit RectifyStep(std::string table_path); + ~RectifyStep() override; + RectifyStep(const RectifyStep&) = delete; + RectifyStep& operator=(const RectifyStep&) = delete; + + const char* name() const override + { + return "rectify"; + } + + void set_full_range(bool full_range) override + { + m_full_range = full_range; + } + + ImageSize output_size(const ImageSize& input) const override; + + std::string prepare(const ImageSize& input) override; + + cudaError_t enqueue(const Nv12Planes& in, const Nv12PlanesOut& out, cudaStream_t stream) override; + +private: + void release(); + + std::string m_path; + bool m_full_range = false; + // Device copies of the table, uploaded by prepare() and freed by the destructor. + RemapEntry* m_luma = nullptr; + RemapEntry* m_chroma = nullptr; + RemapSize m_source; + RemapSize m_output; +}; + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/sine_warp.hpp b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/sine_warp.hpp index 928be18e4a..f7c7754eea 100644 --- a/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/sine_warp.hpp +++ b/examples/camera_livekit_bridge/gpu_ops/inc/gpu_ops/sine_warp.hpp @@ -37,31 +37,13 @@ cudaError_t sine_warp_nv12(const Nv12Planes& source, cudaStream_t stream); /** - * @brief The sine warp as a GpuStep: the template to copy for a real step. + * @brief The sine warp as a GpuStep: the template to copy for a step that computes its mapping per pixel. * - * HOW LENS RECTIFICATION WOULD BE WRITTEN AS A STEP (this class is the same shape, with a different mapping): - * - * - Every pixel of the output picture asks "where in the distorted camera image does this pixel come from?". For - * rectification that answer comes from the camera calibration: for the output pixel (u, v) build the ray of the - * ideal pinhole camera (the new camera matrix), distort it with the lens model (for example the fisheye or - * Brown-Conrady coefficients stored with the camera's intrinsics), project it with the real intrinsics, and you - * have the source position (sx, sy). The sine warp replaces exactly this mapping with - * `sx = x + A*sin(2*pi*y/L + phase), sy = y`. - * - The mapping depends only on the calibration and the picture size, never on the pixels, so do it ONCE: - * in prepare(), compute (sx, sy) for every output pixel on the host, cudaMalloc a float2 table of that size - * and upload it. Keep the table as a member and free it in the destructor. The per-frame kernel is then only - * "read the table entry, bilinear-sample the source" and costs about the same as the sine warp. - * - Chroma: the NV12 chroma plane is half size. Either keep a second half-size table, or evaluate the table of - * the luma position of each chroma sample ((2*cx, 2*cy + 0.5) here) and halve the result. Samples whose source - * position falls outside the image get the fill: video-range black (luma 16, chroma 128). - * - Calibration is per camera and per resolution. Give the step its calibration as arguments (a file path, via - * make_gpu_step), refuse in prepare() a picture size the calibration was not made for, and remember that a - * stream shrunk by `--stream NAME=TRACK:DIV` is shrunk AFTER the steps, so a step always sees the source size. - * Rectify at full resolution, then let the downscale shrink the result. - * - Rectification usually crops or scales the field of view: that is output_size() (a different size than the - * input is allowed; the encoder is created for the last step's output size). - * - Several cameras: one pipeline exists per stream, so each stream can get its own calibration; pass the stream - * name or a per-stream argument if the steps differ. + * A step whose mapping comes from a table is RectifyStep in rectify.hpp, which does lens rectification: it uploads + * the table in prepare(), frees it in its destructor and changes the picture size. Either way a stream shrunk by + * `--stream NAME=TRACK:DIV` is shrunk after the steps, so a step never sees the shrunk size. This step's fill is + * video-range black whatever the range; a step whose fill follows the range overrides set_full_range(), as + * RectifyStep does. */ class SineWarpStep final : public GpuStep { diff --git a/examples/camera_livekit_bridge/gpu_ops/rectify.cu b/examples/camera_livekit_bridge/gpu_ops/rectify.cu new file mode 100644 index 0000000000..33da24b011 --- /dev/null +++ b/examples/camera_livekit_bridge/gpu_ops/rectify.cu @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/gpu_ops/rectify.hpp" + +#include + +namespace camera_bridge +{ + +namespace +{ + +constexpr unsigned kBlockX = 32; +constexpr unsigned kBlockY = 8; + +// The kernels only find their sample and bounds-check it. The per-pixel work is in remap_pixel.hpp, which the CPU +// reference runs too, so keep it there. +__global__ void rectify_luma(RemapPlaneJob job) +{ + const int x = blockIdx.x * blockDim.x + threadIdx.x; + const int y = blockIdx.y * blockDim.y + threadIdx.y; + if (x >= job.dst_width || y >= job.dst_height) + return; + remap_luma_pixel(job, x, y); +} + +__global__ void rectify_chroma(RemapPlaneJob job) +{ + const int cx = blockIdx.x * blockDim.x + threadIdx.x; + const int cy = blockIdx.y * blockDim.y + threadIdx.y; + if (cx >= job.dst_width || cy >= job.dst_height) + return; + remap_chroma_pixel(job, cx, cy); +} + +dim3 grid_for(const RemapPlaneJob& job) +{ + return dim3((job.dst_width + kBlockX - 1) / kBlockX, (job.dst_height + kBlockY - 1) / kBlockY); +} + +} // namespace + +cudaError_t rectify_nv12(const Nv12Planes& source, + const Nv12PlanesOut& destination, + const RemapTableView& tables, + bool full_range, + cudaStream_t stream) +{ + if (tables.luma == nullptr || tables.chroma == nullptr) + return cudaErrorInvalidValue; + const RemapJobs jobs = + remap_nv12_jobs(tables, { source.y, source.uv, source.y_pitch, source.uv_pitch }, + { destination.y, destination.uv, destination.y_pitch, destination.uv_pitch }, full_range); + const dim3 block(kBlockX, kBlockY); + rectify_luma<<>>(jobs.luma); + if (const cudaError_t status = cudaGetLastError(); status != cudaSuccess) + return status; + rectify_chroma<<>>(jobs.chroma); + return cudaGetLastError(); +} + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/gpu_ops/rectify_step.cpp b/examples/camera_livekit_bridge/gpu_ops/rectify_step.cpp new file mode 100644 index 0000000000..264f79ef43 --- /dev/null +++ b/examples/camera_livekit_bridge/gpu_ops/rectify_step.cpp @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/gpu_ops/rectify.hpp" + +#include + +namespace camera_bridge +{ + +RectifyStep::RectifyStep(std::string table_path) : m_path(std::move(table_path)) +{ +} + +RectifyStep::~RectifyStep() +{ + release(); +} + +void RectifyStep::release() +{ + cudaFree(m_luma); + cudaFree(m_chroma); + m_luma = nullptr; + m_chroma = nullptr; + m_source = {}; + m_output = {}; +} + +ImageSize RectifyStep::output_size(const ImageSize& /*input*/) const +{ + return { m_output.width, m_output.height }; +} + +std::string RectifyStep::prepare(const ImageSize& input) +{ + release(); + RemapTable table; + const std::string refused = load_remap_table(m_path, table); + if (!refused.empty()) + return refused; + const std::string file = "remap table '" + remap_table_name(m_path) + "'"; + // Both sizes: after a step that changes the size, the one this step receives is not the stream's. + if (!(table.source == RemapSize{ input.width, input.height })) + return file + " was made for a " + std::to_string(table.source.width) + "x" + + std::to_string(table.source.height) + " picture, not the " + std::to_string(input.width) + "x" + + std::to_string(input.height) + " one this step receives"; + const size_t luma_bytes = table.luma.size() * sizeof(RemapEntry); + const size_t chroma_bytes = table.chroma.size() * sizeof(RemapEntry); + if (cudaMalloc(reinterpret_cast(&m_luma), luma_bytes) != cudaSuccess || + cudaMalloc(reinterpret_cast(&m_chroma), chroma_bytes) != cudaSuccess || + cudaMemcpy(m_luma, table.luma.data(), luma_bytes, cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(m_chroma, table.chroma.data(), chroma_bytes, cudaMemcpyHostToDevice) != cudaSuccess) + { + release(); + return "cannot put " + file + " on the GPU"; + } + m_source = table.source; + m_output = table.output; + return {}; +} + +cudaError_t RectifyStep::enqueue(const Nv12Planes& in, const Nv12PlanesOut& out, cudaStream_t stream) +{ + return rectify_nv12(in, out, { m_luma, m_chroma, m_source, m_output }, m_full_range, stream); +} + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/remap_table/CMakeLists.txt b/examples/camera_livekit_bridge/remap_table/CMakeLists.txt new file mode 100644 index 0000000000..abbbde6379 --- /dev/null +++ b/examples/camera_livekit_bridge/remap_table/CMakeLists.txt @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# The remap table file, and the per-pixel sampling the rectify kernels share with their CPU reference. Nothing here +# includes a CUDA header, so it builds and is tested without a device. +add_library(remap_table STATIC remap_table.cpp) + +target_include_directories(remap_table + INTERFACE + $ +) + +target_compile_options(remap_table PRIVATE -Wall -Wextra) + +add_library(camera_livekit_bridge::remap_table ALIAS remap_table) diff --git a/examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_pixel.hpp b/examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_pixel.hpp new file mode 100644 index 0000000000..a701988dbb --- /dev/null +++ b/examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_pixel.hpp @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include + +// The per-pixel work of a table-driven remap. This header includes no CUDA header and is compiled for the host and, +// under a CUDA compiler, for the device as well, so the kernels and their CPU reference run the same code. +#if defined(__CUDACC__) +# define CAMERA_BRIDGE_REMAP_FN __host__ __device__ __forceinline__ +#else +# define CAMERA_BRIDGE_REMAP_FN inline +#endif + +namespace camera_bridge +{ + +/// Where one output sample reads the source plane: a position in samples, x to the right and y down, with integer +/// coordinates at sample centres. A position outside the plane, or not finite, names no source sample. +struct RemapEntry +{ + float sx; + float sy; +}; + +/// One plane of a remap: the table, the plane read and the plane written. Sizes count samples of that plane, so for +/// chroma they are half the luma sizes and each sample is an interleaved U,V pair. +struct RemapPlaneJob +{ + const RemapEntry* table; // dst_width x dst_height entries, row-major + const uint8_t* src; + size_t src_pitch; + int src_width; + int src_height; + uint8_t* dst; + size_t dst_pitch; + int dst_width; + int dst_height; + uint8_t fill; // written where the table names no source sample +}; + +/// True when (sx, sy) is a position in a width x height plane. A positive predicate, so NaN is outside. Exact while +/// neither size is above 2^24, where a float still holds `width - 1`; the table reader refuses larger ones. +CAMERA_BRIDGE_REMAP_FN bool remap_inside(float sx, float sy, int width, int height) +{ + return sx >= 0.0F && sx <= static_cast(width - 1) && sy >= 0.0F && sy <= static_cast(height - 1); +} + +// One explicit fused multiply-add per interpolation. A compiler left to choose fuses `a + t * (b - a)` on some +// targets and not on others, and the host and the device would then round differently next to a half. +CAMERA_BRIDGE_REMAP_FN float remap_lerp(float a, float b, float t) +{ + return fmaf(t, b - a, a); +} + +/// Bilinear sample of one byte channel at a position remap_inside() accepted. `stride` is the byte distance between +/// neighbouring samples of the channel: 1 for luma, 2 for interleaved chroma. +CAMERA_BRIDGE_REMAP_FN float remap_bilinear( + const uint8_t* plane, size_t pitch, int stride, int width, int height, float sx, float sy) +{ + const int x0 = static_cast(floorf(sx)); + const int y0 = static_cast(floorf(sy)); + const int x1 = x0 + 1 < width ? x0 + 1 : width - 1; + const int y1 = y0 + 1 < height ? y0 + 1 : height - 1; + const float fx = sx - static_cast(x0); + const float fy = sy - static_cast(y0); + const uint8_t* r0 = plane + static_cast(y0) * pitch; + const uint8_t* r1 = plane + static_cast(y1) * pitch; + const float top = remap_lerp(static_cast(r0[x0 * stride]), static_cast(r0[x1 * stride]), fx); + const float bottom = remap_lerp(static_cast(r1[x0 * stride]), static_cast(r1[x1 * stride]), fx); + return remap_lerp(top, bottom, fy); +} + +/// Rounds half up and clamps to a byte. +CAMERA_BRIDGE_REMAP_FN uint8_t remap_to_byte(float value) +{ + return static_cast(fminf(fmaxf(value + 0.5F, 0.0F), 255.0F)); +} + +/// Writes output luma sample (x, y). +CAMERA_BRIDGE_REMAP_FN void remap_luma_pixel(const RemapPlaneJob& job, int x, int y) +{ + const size_t column = static_cast(x); + const RemapEntry entry = job.table[static_cast(y) * static_cast(job.dst_width) + column]; + const bool inside = remap_inside(entry.sx, entry.sy, job.src_width, job.src_height); + job.dst[static_cast(y) * job.dst_pitch + column] = + inside ? + remap_to_byte(remap_bilinear(job.src, job.src_pitch, 1, job.src_width, job.src_height, entry.sx, entry.sy)) : + job.fill; +} + +/// Writes output chroma sample (cx, cy), both of its bytes. +CAMERA_BRIDGE_REMAP_FN void remap_chroma_pixel(const RemapPlaneJob& job, int cx, int cy) +{ + const size_t column = static_cast(cx); + const RemapEntry entry = job.table[static_cast(cy) * static_cast(job.dst_width) + column]; + uint8_t* out = job.dst + static_cast(cy) * job.dst_pitch + 2 * column; + if (!remap_inside(entry.sx, entry.sy, job.src_width, job.src_height)) + { + out[0] = job.fill; + out[1] = job.fill; + return; + } + out[0] = remap_to_byte(remap_bilinear(job.src, job.src_pitch, 2, job.src_width, job.src_height, entry.sx, entry.sy)); + out[1] = + remap_to_byte(remap_bilinear(job.src + 1, job.src_pitch, 2, job.src_width, job.src_height, entry.sx, entry.sy)); +} + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_table.hpp b/examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_table.hpp new file mode 100644 index 0000000000..bb6571cd15 --- /dev/null +++ b/examples/camera_livekit_bridge/remap_table/inc/remap_table/remap_table.hpp @@ -0,0 +1,123 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "remap_pixel.hpp" + +#include +#include +#include +#include + +namespace camera_bridge +{ + +/// A picture size in luma pixels. +struct RemapSize +{ + uint32_t width = 0; + uint32_t height = 0; + bool operator==(const RemapSize& other) const + { + return width == other.width && height == other.height; + } +}; + +/** + * @brief A remap table: for every pixel of the output picture, where in the source picture it is sampled. + * + * A separate planning tool writes the file and folds undistortion, crop and resize into it; nothing here interprets + * a lens model or a calibration file. GPU_PROCESSING.md describes the file format. + */ +struct RemapTable +{ + RemapSize source; ///< the picture the table samples + RemapSize output; ///< the picture it produces + /// One entry per output luma pixel, row-major, in source luma coordinates. This is the file's payload. + std::vector luma; + /// One entry per output chroma sample, row-major, in source chroma coordinates. Derived from `luma`. + std::vector chroma; +}; + +/// What a refusal calls the file at `path`: its base name, never its directory. +std::string remap_table_name(const std::string& path); + +/// FNV-1a 64-bit, the hash a table file carries of its payload. +uint64_t remap_table_hash(const uint8_t* bytes, size_t size); + +/// The bytes of a table file. It checks nothing, so a test can write a file the reader must refuse. +std::vector encode_remap_table(const RemapSize& source, + const RemapSize& output, + const std::vector& luma); + +/// Reads the bytes of a table file into `table`, chroma table included. Returns an empty string, or one sentence +/// that says why the bytes are refused and calls the file `name`; `table` is then unchanged. +std::string decode_remap_table(const uint8_t* bytes, size_t size, const std::string& name, RemapTable& table); + +/// Reads the table file at `path`. Returns an empty string, or one sentence that names the file by its base name: +/// it cannot be read, or decode_remap_table() refuses it. +std::string load_remap_table(const std::string& path, RemapTable& table); + +/** + * @brief Where an output chroma sample reads the source chroma plane, from the two luma entries it sits between. + * + * Chroma sample (cx, cy) sits at luma position (2cx, 2cy + 0.5): `upper` is the luma entry at (2cx, 2cy) and `lower` + * the one at (2cx, 2cy + 1). When either names no pixel of `source`, the result names no chroma sample. Otherwise + * their mean (sx, sy) is (sx / 2, (sy - 0.5) / 2) in chroma coordinates, clamped into the source chroma plane: that + * plane ends short of the luma plane's border, and a position in between repeats the edge chroma sample. + */ +RemapEntry derive_chroma_entry(const RemapSize& source, const RemapEntry& upper, const RemapEntry& lower); + +/// The chroma table of a luma table: derive_chroma_entry() for every output chroma sample. Empty when `luma` does +/// not hold output.width x output.height entries. +std::vector derive_chroma_table(const RemapSize& source, + const RemapSize& output, + const std::vector& luma); + +/// The two planes of an NV12 picture to read, in host or device memory. Pitches are in bytes. +struct RemapPlanes +{ + const uint8_t* y = nullptr; + const uint8_t* uv = nullptr; + size_t y_pitch = 0; + size_t uv_pitch = 0; +}; + +struct RemapPlanesOut +{ + uint8_t* y = nullptr; + uint8_t* uv = nullptr; + size_t y_pitch = 0; + size_t uv_pitch = 0; +}; + +/// A table's entries wherever they are stored: host memory for the CPU reference, device memory for the kernels. +struct RemapTableView +{ + const RemapEntry* luma = nullptr; + const RemapEntry* chroma = nullptr; + RemapSize source; + RemapSize output; +}; + +struct RemapJobs +{ + RemapPlaneJob luma; + RemapPlaneJob chroma; +}; + +/// The luma and chroma jobs of one picture. The fill is black in the picture's range: luma 16 for video range and 0 +/// for full range, chroma 128 for both. +RemapJobs remap_nv12_jobs(const RemapTableView& table, + const RemapPlanes& source, + const RemapPlanesOut& destination, + bool full_range); + +/// The CPU reference of the rectify step: every output sample, through the per-pixel functions its kernels call. +void remap_nv12_reference(const RemapTable& table, + const RemapPlanes& source, + const RemapPlanesOut& destination, + bool full_range); + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/remap_table/remap_table.cpp b/examples/camera_livekit_bridge/remap_table/remap_table.cpp new file mode 100644 index 0000000000..9e2409270d --- /dev/null +++ b/examples/camera_livekit_bridge/remap_table/remap_table.cpp @@ -0,0 +1,328 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/remap_table/remap_table.hpp" + +#include +#include +#include +#include +#include +#include + +namespace camera_bridge +{ + +namespace +{ + +// The file layout, little-endian. GPU_PROCESSING.md describes it. +constexpr char kMagic[] = "ICRMAP01"; +constexpr size_t kMagicBytes = sizeof(kMagic) - 1; +constexpr size_t kHeaderSizeAt = 8; +constexpr size_t kSourceWidthAt = 12; +constexpr size_t kSourceHeightAt = 16; +constexpr size_t kOutputWidthAt = 20; +constexpr size_t kOutputHeightAt = 24; +constexpr size_t kFlagsAt = 28; +constexpr size_t kHashAt = 32; +constexpr uint32_t kHeaderBytes = 48; +constexpr size_t kEntryBytes = 8; +// The largest width or height a table may name. Up to here a float holds every sample position exactly, which the +// inside test of the per-pixel functions needs, and a size fits the int they count in. +constexpr uint32_t kMaxSize = 1U << 24; +// The byte count of the largest table fits 64 bits, so it is computed unchecked. +static_assert(uint64_t{ kMaxSize } * kMaxSize <= (UINT64_MAX - kHeaderBytes) / kEntryBytes, "kMaxSize is too large"); + +constexpr uint8_t kVideoRangeBlack = 16; +constexpr uint8_t kFullRangeBlack = 0; +constexpr uint8_t kNeutralChroma = 128; + +uint32_t read_u32(const uint8_t* p) +{ + return static_cast(p[0]) | static_cast(p[1]) << 8 | static_cast(p[2]) << 16 | + static_cast(p[3]) << 24; +} + +uint64_t read_u64(const uint8_t* p) +{ + return static_cast(read_u32(p)) | static_cast(read_u32(p + 4)) << 32; +} + +float read_f32(const uint8_t* p) +{ + const uint32_t bits = read_u32(p); + float value = 0.0F; + std::memcpy(&value, &bits, sizeof(value)); + return value; +} + +void write_u32(uint8_t* p, uint32_t value) +{ + for (int i = 0; i < 4; ++i) + p[i] = static_cast(value >> (8 * i)); +} + +void write_u64(uint8_t* p, uint64_t value) +{ + write_u32(p, static_cast(value)); + write_u32(p + 4, static_cast(value >> 32)); +} + +void write_f32(uint8_t* p, float value) +{ + uint32_t bits = 0; + std::memcpy(&bits, &value, sizeof(bits)); + write_u32(p, bits); +} + +std::string dimensions(const RemapSize& size) +{ + return std::to_string(size.width) + "x" + std::to_string(size.height); +} + +bool even_and_positive(const RemapSize& size) +{ + return size.width != 0 && size.height != 0 && size.width % 2 == 0 && size.height % 2 == 0; +} + +bool within_limit(const RemapSize& size) +{ + return size.width <= kMaxSize && size.height <= kMaxSize; +} + +struct Header +{ + RemapSize source; + RemapSize output; + uint64_t hash = 0; +}; + +// The payload of a header read_header() accepted, in bytes. +uint64_t payload_size(const Header& header) +{ + return static_cast(header.output.width) * header.output.height * kEntryBytes; +} + +// The checks that need only the header. `size` is how much of the file is at hand, the whole of it or its start. +std::string read_header(const uint8_t* bytes, size_t size, const std::string& name, Header& header) +{ + if (size < kMagicBytes || std::memcmp(bytes, kMagic, kMagicBytes) != 0) + return "'" + name + "' is not a remap table: it does not start with " + kMagic; + const std::string file = "remap table '" + name + "'"; + if (size < kHeaderBytes) + return file + " ends inside its header"; + const uint32_t header_bytes = read_u32(bytes + kHeaderSizeAt); + if (header_bytes != kHeaderBytes) + return file + " has a header of " + std::to_string(header_bytes) + " bytes, and this reader knows the " + + std::to_string(kHeaderBytes) + "-byte one"; + if (read_u32(bytes + kFlagsAt) != 0) + return file + " has flags this reader does not know"; + header.source = { read_u32(bytes + kSourceWidthAt), read_u32(bytes + kSourceHeightAt) }; + header.output = { read_u32(bytes + kOutputWidthAt), read_u32(bytes + kOutputHeightAt) }; + if (!even_and_positive(header.source) || !even_and_positive(header.output)) + return file + " has a zero or odd size (source " + dimensions(header.source) + ", output " + + dimensions(header.output) + ")"; + if (!within_limit(header.source) || !within_limit(header.output)) + return file + " has a size above " + std::to_string(kMaxSize) + " (source " + dimensions(header.source) + + ", output " + dimensions(header.output) + ")"; + header.hash = read_u64(bytes + kHashAt); + return {}; +} + +// The chroma plane of an NV12 picture: half its size each way. The chroma table is clamped to this plane and the +// sampler tests against it, so both take it from here. +RemapSize chroma_plane(const RemapSize& picture) +{ + return { picture.width / 2, picture.height / 2 }; +} + +// `position` moved onto an axis of `samples` sample positions, 0 to samples - 1. Comparisons and no arithmetic, so a +// position already on the axis comes back bit for bit. +float clamped_to_axis(float position, uint32_t samples) +{ + const float last = static_cast(samples) - 1.0F; + if (position < 0.0F) + return 0.0F; + return position > last ? last : position; +} + +} // namespace + +std::string remap_table_name(const std::string& path) +{ + // The last component, also of a path that ends in slashes. + const auto last = path.find_last_not_of('/'); + if (last == std::string::npos) + return path; + const auto slash = path.find_last_of('/', last); + const auto first = slash == std::string::npos ? 0 : slash + 1; + return path.substr(first, last - first + 1); +} + +uint64_t remap_table_hash(const uint8_t* bytes, size_t size) +{ + uint64_t hash = 0xcbf29ce484222325ULL; + for (size_t i = 0; i < size; ++i) + { + hash ^= bytes[i]; + hash *= 0x100000001b3ULL; + } + return hash; +} + +std::vector encode_remap_table(const RemapSize& source, + const RemapSize& output, + const std::vector& luma) +{ + std::vector bytes(kHeaderBytes + luma.size() * kEntryBytes, 0); + std::memcpy(bytes.data(), kMagic, kMagicBytes); + write_u32(bytes.data() + kHeaderSizeAt, kHeaderBytes); + write_u32(bytes.data() + kSourceWidthAt, source.width); + write_u32(bytes.data() + kSourceHeightAt, source.height); + write_u32(bytes.data() + kOutputWidthAt, output.width); + write_u32(bytes.data() + kOutputHeightAt, output.height); + uint8_t* payload = bytes.data() + kHeaderBytes; + for (size_t i = 0; i < luma.size(); ++i) + { + write_f32(payload + i * kEntryBytes, luma[i].sx); + write_f32(payload + i * kEntryBytes + 4, luma[i].sy); + } + write_u64(bytes.data() + kHashAt, remap_table_hash(payload, luma.size() * kEntryBytes)); + return bytes; +} + +std::string decode_remap_table(const uint8_t* bytes, size_t size, const std::string& name, RemapTable& table) +{ + Header header; + const std::string refused = read_header(bytes, size, name, header); + if (!refused.empty()) + return refused; + const std::string file = "remap table '" + name + "'"; + const size_t payload_bytes = size - kHeaderBytes; + if (payload_bytes != payload_size(header)) + return file + " is " + std::to_string(size) + " bytes, which is not the length of a " + + dimensions(header.output) + " table"; + const uint8_t* payload = bytes + kHeaderBytes; + if (remap_table_hash(payload, payload_bytes) != header.hash) + return file + " is damaged: its payload does not match its hash"; + + std::vector luma(payload_bytes / kEntryBytes); + for (size_t i = 0; i < luma.size(); ++i) + luma[i] = { read_f32(payload + i * kEntryBytes), read_f32(payload + i * kEntryBytes + 4) }; + table.source = header.source; + table.output = header.output; + table.chroma = derive_chroma_table(header.source, header.output, luma); + table.luma = std::move(luma); + return {}; +} + +std::string load_remap_table(const std::string& path, RemapTable& table) +{ + const std::string name = remap_table_name(path); + std::ifstream file(path, std::ios::binary); + if (!file) + return "cannot open remap table '" + name + "'"; + const std::string unreadable = "cannot read remap table '" + name + "'"; + // The header first, then no further than one piece past the length it gives: a wrong file, a device or a + // directory is refused without being read whole, and no size a file merely claims is allocated. + std::vector bytes(kHeaderBytes); + file.read(reinterpret_cast(bytes.data()), kHeaderBytes); + bytes.resize(static_cast(file.gcount())); + Header header; + const std::string refused = read_header(bytes.data(), bytes.size(), name, header); + if (!refused.empty()) + return file.bad() ? unreadable : refused; + const uint64_t expected = kHeaderBytes + payload_size(header); + std::array piece{}; + while (file && bytes.size() <= expected) + { + file.read(piece.data(), static_cast(piece.size())); + bytes.insert(bytes.end(), piece.data(), piece.data() + file.gcount()); + } + if (file.bad()) + return unreadable; + if (file) + return "remap table '" + name + "' is longer than a " + dimensions(header.output) + " table"; + return decode_remap_table(bytes.data(), bytes.size(), name, table); +} + +RemapEntry derive_chroma_entry(const RemapSize& source, const RemapEntry& upper, const RemapEntry& lower) +{ + const int width = static_cast(source.width); + const int height = static_cast(source.height); + if (!remap_inside(upper.sx, upper.sy, width, height) || !remap_inside(lower.sx, lower.sy, width, height)) + { + const float none = std::numeric_limits::quiet_NaN(); + return { none, none }; + } + const float sx = 0.5F * (upper.sx + lower.sx); + const float sy = 0.5F * (upper.sy + lower.sy); + const RemapSize plane = chroma_plane(source); + // Halving sy alone is a quarter of a chroma row off: chroma row j sits at luma row 2j + 0.5. + return { clamped_to_axis(0.5F * sx, plane.width), clamped_to_axis(0.5F * (sy - 0.5F), plane.height) }; +} + +std::vector derive_chroma_table(const RemapSize& source, + const RemapSize& output, + const std::vector& luma) +{ + const size_t width = output.width; + const size_t chroma_width = chroma_plane(output).width; + const size_t chroma_height = chroma_plane(output).height; + if (luma.size() != width * output.height) + return {}; + std::vector chroma(chroma_width * chroma_height); + for (size_t cy = 0; cy < chroma_height; ++cy) + for (size_t cx = 0; cx < chroma_width; ++cx) + chroma[cy * chroma_width + cx] = + derive_chroma_entry(source, luma[2 * cy * width + 2 * cx], luma[(2 * cy + 1) * width + 2 * cx]); + return chroma; +} + +RemapJobs remap_nv12_jobs(const RemapTableView& table, + const RemapPlanes& source, + const RemapPlanesOut& destination, + bool full_range) +{ + RemapJobs jobs; + jobs.luma.table = table.luma; + jobs.luma.src = source.y; + jobs.luma.src_pitch = source.y_pitch; + jobs.luma.src_width = static_cast(table.source.width); + jobs.luma.src_height = static_cast(table.source.height); + jobs.luma.dst = destination.y; + jobs.luma.dst_pitch = destination.y_pitch; + jobs.luma.dst_width = static_cast(table.output.width); + jobs.luma.dst_height = static_cast(table.output.height); + jobs.luma.fill = full_range ? kFullRangeBlack : kVideoRangeBlack; + + jobs.chroma.table = table.chroma; + jobs.chroma.src = source.uv; + jobs.chroma.src_pitch = source.uv_pitch; + jobs.chroma.src_width = static_cast(chroma_plane(table.source).width); + jobs.chroma.src_height = static_cast(chroma_plane(table.source).height); + jobs.chroma.dst = destination.uv; + jobs.chroma.dst_pitch = destination.uv_pitch; + jobs.chroma.dst_width = static_cast(chroma_plane(table.output).width); + jobs.chroma.dst_height = static_cast(chroma_plane(table.output).height); + jobs.chroma.fill = kNeutralChroma; + return jobs; +} + +void remap_nv12_reference(const RemapTable& table, + const RemapPlanes& source, + const RemapPlanesOut& destination, + bool full_range) +{ + const RemapJobs jobs = remap_nv12_jobs( + { table.luma.data(), table.chroma.data(), table.source, table.output }, source, destination, full_range); + for (int y = 0; y < jobs.luma.dst_height; ++y) + for (int x = 0; x < jobs.luma.dst_width; ++x) + remap_luma_pixel(jobs.luma, x, y); + for (int cy = 0; cy < jobs.chroma.dst_height; ++cy) + for (int cx = 0; cx < jobs.chroma.dst_width; ++cx) + remap_chroma_pixel(jobs.chroma, cx, cy); +} + +} // namespace camera_bridge diff --git a/examples/camera_livekit_bridge/tests/gpu_pipeline/CMakeLists.txt b/examples/camera_livekit_bridge/tests/gpu_pipeline/CMakeLists.txt index 56d9d4540b..966b14c9d7 100644 --- a/examples/camera_livekit_bridge/tests/gpu_pipeline/CMakeLists.txt +++ b/examples/camera_livekit_bridge/tests/gpu_pipeline/CMakeLists.txt @@ -3,6 +3,11 @@ # Needs a CUDA device; the test exits 77 (skipped) without one. add_executable(test_gpu_pipeline test_gpu_pipeline.cpp) -target_link_libraries(test_gpu_pipeline PRIVATE camera_livekit_bridge::gpu_ops CUDA::cudart) +target_link_libraries(test_gpu_pipeline + PRIVATE + camera_livekit_bridge::gpu_ops + camera_livekit_bridge::remap_table + CUDA::cudart +) add_test(NAME gpu_pipeline COMMAND test_gpu_pipeline) set_tests_properties(gpu_pipeline PROPERTIES SKIP_RETURN_CODE 77) diff --git a/examples/camera_livekit_bridge/tests/gpu_pipeline/test_gpu_pipeline.cpp b/examples/camera_livekit_bridge/tests/gpu_pipeline/test_gpu_pipeline.cpp index c744dbb194..a99eb34e72 100644 --- a/examples/camera_livekit_bridge/tests/gpu_pipeline/test_gpu_pipeline.cpp +++ b/examples/camera_livekit_bridge/tests/gpu_pipeline/test_gpu_pipeline.cpp @@ -2,16 +2,24 @@ // SPDX-License-Identifier: Apache-2.0 // The GPU step pipeline: no steps copies, steps run in series in the order given, the sine warp is an identity at -// zero amplitude and a horizontal ripple otherwise, and bad specs are refused. +// zero amplitude and a horizontal ripple otherwise, the rectify step equals its CPU reference, and bad specs are +// refused. #include +#include +#include +#include #include +#include #include #include +#include #include +#include #include #include +#include #include namespace @@ -21,6 +29,8 @@ using camera_bridge::GpuPipeline; using camera_bridge::ImageSize; using camera_bridge::Nv12Planes; using camera_bridge::Nv12PlanesOut; +using camera_bridge::RemapEntry; +using camera_bridge::RemapSize; int g_failures = 0; @@ -118,6 +128,237 @@ std::vector run(const std::vector& steps, const ImageSize& return destination.download(); } +constexpr uint8_t kPad = 0xEE; + +// The bytes of a pitched NV12 picture, row padding included. +struct PitchedBytes +{ + std::vector y; + std::vector uv; +}; + +// A device NV12 picture whose rows are longer than the picture. +struct PitchedImage +{ + ImageSize size; + uint8_t* y = nullptr; + uint8_t* uv = nullptr; + size_t y_pitch = 0; + size_t uv_pitch = 0; + explicit PitchedImage(const ImageSize& s) : size(s) + { + // Wider rows than the picture, so the pitch exceeds the width whatever alignment the allocator picks. + cudaMallocPitch(reinterpret_cast(&y), &y_pitch, s.width + 64, s.height); + cudaMallocPitch(reinterpret_cast(&uv), &uv_pitch, s.width + 64, s.height / 2); + } + ~PitchedImage() + { + cudaFree(y); + cudaFree(uv); + } + PitchedImage(const PitchedImage&) = delete; + PitchedImage& operator=(const PitchedImage&) = delete; + Nv12Planes in() const + { + return { y, uv, y_pitch, uv_pitch }; + } + Nv12PlanesOut out() + { + return { y, uv, y_pitch, uv_pitch }; + } + // Every byte kPad, which neither the textured picture nor a fill uses. + PitchedBytes blank() const + { + return { std::vector(y_pitch * size.height, kPad), + std::vector(uv_pitch * (size.height / 2), kPad) }; + } + // Structure in both planes; the padding stays kPad. + PitchedBytes textured() const + { + PitchedBytes host = blank(); + for (uint32_t row = 0; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + host.y[row * y_pitch + x] = static_cast(20 + (x * 7 + row * 13 + (x * row) % 5) % 200); + for (uint32_t row = 0; row < size.height / 2; ++row) + for (uint32_t x = 0; x < size.width; ++x) + host.uv[row * uv_pitch + x] = + static_cast(x % 2 == 0 ? 30 + (x * 3 + row * 5) % 190 : 40 + (x * 9 + row * 11) % 170); + return host; + } + void upload(const PitchedBytes& host) + { + cudaMemcpy(y, host.y.data(), host.y.size(), cudaMemcpyHostToDevice); + cudaMemcpy(uv, host.uv.data(), host.uv.size(), cudaMemcpyHostToDevice); + } + PitchedBytes download() const + { + PitchedBytes host = blank(); + cudaMemcpy(host.y.data(), y, host.y.size(), cudaMemcpyDeviceToHost); + cudaMemcpy(host.uv.data(), uv, host.uv.size(), cudaMemcpyDeviceToHost); + return host; + } +}; + +std::vector identity_entries(const ImageSize& size) +{ + std::vector entries; + for (uint32_t y = 0; y < size.height; ++y) + for (uint32_t x = 0; x < size.width; ++x) + entries.push_back({ static_cast(x), static_cast(y) }); + return entries; +} + +// A rotation and zoom about the source centre, so positions are fractional and the output's corners fall outside the +// source; a block of entries is NaN. +std::vector rotated_entries(const ImageSize& source, const ImageSize& output) +{ + std::vector entries; + const float cosine = std::cos(0.35F); + const float sine = std::sin(0.35F); + for (uint32_t y = 0; y < output.height; ++y) + for (uint32_t x = 0; x < output.width; ++x) + { + const float u = 1.7F * (static_cast(x) - 0.5F * static_cast(output.width)); + const float v = 1.7F * (static_cast(y) - 0.5F * static_cast(output.height)); + RemapEntry entry{ 0.5F * static_cast(source.width) + cosine * u - sine * v, + 0.5F * static_cast(source.height) + sine * u + cosine * v }; + if (x >= 40 && x < 44 && y >= 20 && y < 24) + entry = { std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN() }; + entries.push_back(entry); + } + return entries; +} + +std::string write_table(const std::string& path, + const ImageSize& source, + const ImageSize& output, + const std::vector& entries) +{ + const std::vector bytes = camera_bridge::encode_remap_table( + RemapSize{ source.width, source.height }, RemapSize{ output.width, output.height }, entries); + std::ofstream(path, std::ios::binary).write(reinterpret_cast(bytes.data()), bytes.size()); + return path; +} + +// The rectify step: its kernels against the CPU reference on pitched pictures, the fill of each range, the output +// size a table sets, and the refusals. +void test_rectify() +{ + const char* base = std::getenv("TMPDIR"); + std::string directory = std::string(base != nullptr && *base != '\0' ? base : "/tmp") + "/gpu_pipeline_XXXXXX"; + if (mkdtemp(directory.data()) == nullptr) + { + check(false, "cannot make a scratch directory for remap tables"); + return; + } + const ImageSize source_size{ 128, 96 }; + // Not a multiple of the kernels' block size in either plane, so a grid that rounds down leaves bytes unwritten. + const ImageSize output_size{ 100, 68 }; + // The file name holds the characters a step argument must carry whole. + const std::string rotated_path = write_table( + directory + "/rotated,zoom=1.7:a.icrmap", source_size, output_size, rotated_entries(source_size, output_size)); + const std::string identity_path = + write_table(directory + "/identity.icrmap", source_size, source_size, identity_entries(source_size)); + + camera_bridge::RemapTable table; + check(camera_bridge::load_remap_table(rotated_path, table).empty(), "the rotated table is read on the host"); + for (const bool full_range : { false, true }) + { + const std::string range = full_range ? "full range: " : "video range: "; + GpuPipeline pipeline; + pipeline.add(camera_bridge::make_gpu_step("rectify=" + rotated_path)); + pipeline.set_full_range(full_range); + const std::string reason = pipeline.prepare(source_size); + check(reason.empty(), range + "rectify prepare: " + reason); + check(pipeline.output_size() == output_size, range + "the table's output size is the pipeline's"); + + PitchedImage source(source_size); + PitchedImage destination(output_size); + check(source.y_pitch > source_size.width && destination.y_pitch > output_size.width, "the pictures are pitched"); + const PitchedBytes pixels = source.textured(); + source.upload(pixels); + destination.upload(destination.blank()); + check(pipeline.enqueue(source.in(), destination.out(), nullptr) == cudaSuccess, range + "rectify enqueue"); + cudaDeviceSynchronize(); + const PitchedBytes got = destination.download(); + + PitchedBytes expected = destination.blank(); + camera_bridge::remap_nv12_reference( + table, { pixels.y.data(), pixels.uv.data(), source.y_pitch, source.uv_pitch }, + { expected.y.data(), expected.uv.data(), destination.y_pitch, destination.uv_pitch }, full_range); + check(got.y == expected.y, range + "rectified luma equals the CPU reference byte for byte, padding included"); + check(got.uv == expected.uv, range + "rectified chroma equals the CPU reference byte for byte, padding included"); + // The output's first pixel is outside the rotated source. + check(got.y[0] == (full_range ? 0 : 16) && got.uv[0] == 128 && got.uv[1] == 128, range + "the fill is black"); + } + + // An identity table is a plain copy. + ImageSize out; + check(run({ "rectify=" + identity_path }, source_size, out) == gradient(source_size) && out == source_size, + "rectify with an identity table copies the picture"); + + // A later step sees the size the table produces. + GpuPipeline chain; + chain.add(camera_bridge::make_gpu_step("rectify=" + rotated_path)); + chain.add(camera_bridge::make_box_downscale_step(2)); + check(chain.prepare(source_size).empty() && chain.output_size() == ImageSize{ 50, 34 }, + "rectify then downscale output size"); + // So a second table made for the source size is refused, and the refusal names the size that step received. + GpuPipeline twice; + twice.add(camera_bridge::make_gpu_step("rectify=" + rotated_path)); + twice.add(camera_bridge::make_gpu_step("rectify=" + identity_path)); + const std::string second = twice.prepare(source_size); + check(second.find("'identity.icrmap' was made for a 128x96 picture") != std::string::npos && + second.find("100x68") != std::string::npos, + "a table after a size-changing step is refused with the size it received: " + second); + + // Refusals come from prepare(), not from the factory, so the bridge reports them with the stream. + GpuPipeline other_size; + other_size.add(camera_bridge::make_gpu_step("rectify=" + rotated_path)); + const std::string wrong_size = other_size.prepare({ 130, 96 }); + check(wrong_size.find("rectify: ") == 0 && wrong_size.find("128x96") != std::string::npos && + wrong_size.find("130x96") != std::string::npos, + "a table for another source size is refused at prepare with both sizes: " + wrong_size); + check(wrong_size.find(directory) == std::string::npos, "the refusal does not name the table's directory"); + + GpuPipeline missing; + missing.add(camera_bridge::make_gpu_step("rectify=" + directory + "/absent.icrmap")); + const std::string no_file = missing.prepare(source_size); + check(no_file.find("absent.icrmap") != std::string::npos, "a missing table is refused at prepare: " + no_file); + + std::vector bytes = + camera_bridge::encode_remap_table({ 128, 96 }, { 128, 96 }, identity_entries(source_size)); + bytes[48] ^= 0x01; + const std::string damaged_path = directory + "/damaged.icrmap"; + std::ofstream(damaged_path, std::ios::binary).write(reinterpret_cast(bytes.data()), bytes.size()); + GpuPipeline damaged; + damaged.add(camera_bridge::make_gpu_step("rectify=" + damaged_path)); + const std::string bad_file = damaged.prepare(source_size); + check(bad_file.find("hash") != std::string::npos, "a damaged table is refused at prepare: " + bad_file); + + bool threw = false; + try + { + camera_bridge::make_gpu_step("rectify"); + } + catch (const std::invalid_argument&) + { + threw = true; + } + check(threw, "rectify without a table path is refused"); + + // A step that was never prepared has no table to launch with and no output size. + camera_bridge::RectifyStep unprepared(rotated_path); + Image tight(source_size); + check(unprepared.enqueue(tight.in(), tight.out(), nullptr) == cudaErrorInvalidValue, + "rectify enqueue without a prepared table is an invalid value"); + check(unprepared.output_size(source_size) == ImageSize{ 0, 0 }, "rectify has no output size before prepare"); + + for (const std::string& path : { rotated_path, identity_path, damaged_path }) + std::remove(path.c_str()); + rmdir(directory.c_str()); +} + } // namespace int main() @@ -192,6 +433,8 @@ int main() odd.add(camera_bridge::make_gpu_step("sine-warp")); check(!odd.prepare({ 127, 96 }).empty(), "an odd picture size is refused at prepare"); + test_rectify(); + if (g_failures != 0) { std::cerr << g_failures << " check(s) failed\n"; diff --git a/examples/camera_livekit_bridge/tests/gpu_step_spec/CMakeLists.txt b/examples/camera_livekit_bridge/tests/gpu_step_spec/CMakeLists.txt new file mode 100644 index 0000000000..3ba9250ac1 --- /dev/null +++ b/examples/camera_livekit_bridge/tests/gpu_step_spec/CMakeLists.txt @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Needs no CUDA device: the header under test includes no CUDA header. The target is linked for its include path. +add_executable(test_gpu_step_spec test_gpu_step_spec.cpp) + +target_link_libraries(test_gpu_step_spec + PRIVATE + camera_livekit_bridge::gpu_ops +) + +target_compile_options(test_gpu_step_spec PRIVATE -Wall -Wextra) + +add_test(NAME gpu_step_spec COMMAND test_gpu_step_spec) diff --git a/examples/camera_livekit_bridge/tests/gpu_step_spec/test_gpu_step_spec.cpp b/examples/camera_livekit_bridge/tests/gpu_step_spec/test_gpu_step_spec.cpp new file mode 100644 index 0000000000..ed43504dbf --- /dev/null +++ b/examples/camera_livekit_bridge/tests/gpu_step_spec/test_gpu_step_spec.cpp @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// `--gpu-step [STREAM:]NAME[=ARGS]`: how a value is split and which steps each stream gets. + +#include + +#include +#include +#include + +namespace +{ + +using camera_bridge::GpuStepOption; +using camera_bridge::parse_gpu_step_option; + +int g_failures = 0; + +void check(bool condition, const std::string& what) +{ + if (!condition) + { + std::cerr << "FAILED: " << what << "\n"; + ++g_failures; + } +} + +// True when `text` splits into this stream (empty: every stream) and this step spec. +bool splits(const std::string& text, const std::string& stream, const std::string& spec) +{ + const auto option = parse_gpu_step_option(text); + return option.has_value() && option->stream == stream && option->spec == spec; +} + +GpuStepOption option(const std::string& text) +{ + return parse_gpu_step_option(text).value_or(GpuStepOption{}); +} + +} // namespace + +int main() +{ + // Without a stream the value is the step spec, for every stream. + check(splits("sine-warp", "", "sine-warp"), "a bare name"); + check(splits("sine-warp=14,90", "", "sine-warp=14,90"), "a name with arguments"); + check(splits("rectify=/data/head.icrmap", "", "rectify=/data/head.icrmap"), "a path argument"); + + // With a stream. + check(splits("head:sine-warp", "head", "sine-warp"), "a stream and a bare name"); + check(splits("head:rectify=/data/head.icrmap", "head", "rectify=/data/head.icrmap"), "a stream and a path"); + check(splits("wrist1:sine-warp=4,32,0.5", "wrist1", "sine-warp=4,32,0.5"), "a stream and a number list"); + + // Only a colon before the first `=` separates a stream: everything after that `=` belongs to the step. + check(splits("rectify=/mnt/a:b/head.icrmap", "", "rectify=/mnt/a:b/head.icrmap"), "a path with a colon"); + check(splits("rectify=/mnt/a=b,c:d/head.icrmap", "", "rectify=/mnt/a=b,c:d/head.icrmap"), + "a path with equals signs, commas and colons"); + check(splits("head:rectify=/mnt/a:b/x=1,y=2.icrmap", "head", "rectify=/mnt/a:b/x=1,y=2.icrmap"), + "a stream and a path with colons, equals signs and commas"); + check(splits("rectify=head:left.icrmap", "", "rectify=head:left.icrmap"), "a colon only after the equals sign"); + check(splits("rectify=", "", "rectify="), "an empty argument is the step's to refuse"); + + // A stream name may hold a colon: the last one before the `=` separates. + check(splits("rig:head:rectify=/t.icrmap", "rig:head", "rectify=/t.icrmap"), "a stream name with a colon"); + + // No stream or no step name. + check(!parse_gpu_step_option("").has_value(), "an empty value is refused"); + check(!parse_gpu_step_option("=14,90").has_value(), "arguments without a name are refused"); + check(!parse_gpu_step_option(":rectify=/t.icrmap").has_value(), "an empty stream is refused"); + check(!parse_gpu_step_option("head:").has_value(), "a stream without a step is refused"); + check(!parse_gpu_step_option("head:=/t.icrmap").has_value(), "a stream and arguments without a name are refused"); + + // Each stream gets the steps for every stream and its own, in the order given. + const std::vector options = { + option("head:rectify=/t/head.icrmap"), + option("sine-warp=2"), + option("wrist1:rectify=/t/w1.icrmap"), + option("head:sine-warp=4"), + option("wrist1:sine-warp"), + option("sine-warp=8"), + }; + using Specs = std::vector; + check(camera_bridge::gpu_steps_for_stream(options, "head") == + Specs{ "rectify=/t/head.icrmap", "sine-warp=2", "sine-warp=4", "sine-warp=8" }, + "head gets its steps and the shared ones in order"); + check(camera_bridge::gpu_steps_for_stream(options, "wrist1") == + Specs{ "sine-warp=2", "rectify=/t/w1.icrmap", "sine-warp", "sine-warp=8" }, + "wrist1 gets its steps and the shared ones in order"); + check(camera_bridge::gpu_steps_for_stream(options, "wrist2") == Specs{ "sine-warp=2", "sine-warp=8" }, + "a stream with no step of its own gets the shared ones"); + check(camera_bridge::gpu_steps_for_stream({}, "head").empty(), "no options, no steps"); + + // A step for a stream that is not published is found; the first such one is reported. + const Specs published = { "head", "wrist1" }; + check(camera_bridge::gpu_step_for_unknown_stream(options, published) == nullptr, "every named stream is published"); + check(camera_bridge::gpu_step_for_unknown_stream({ option("sine-warp") }, {}) == nullptr, + "a step for every stream names none"); + const std::vector stray = { option("head:sine-warp"), option("wrist2:rectify=/t/w2.icrmap"), + option("chest:sine-warp") }; + const GpuStepOption* unknown = camera_bridge::gpu_step_for_unknown_stream(stray, published); + check(unknown != nullptr && unknown->stream == "wrist2" && unknown->spec == "rectify=/t/w2.icrmap", + "a step for an unpublished stream is found"); + // Stream names are compared whole and case matters. + check(camera_bridge::gpu_step_for_unknown_stream({ option("Head:sine-warp") }, published) != nullptr, + "a stream name differing in case is unknown"); + check(camera_bridge::gpu_step_for_unknown_stream({ option("hea:sine-warp") }, published) != nullptr, + "a prefix of a stream name is unknown"); + + if (g_failures != 0) + { + std::cerr << g_failures << " check(s) failed\n"; + return 1; + } + std::cout << "gpu_step_spec: all checks passed\n"; + return 0; +} diff --git a/examples/camera_livekit_bridge/tests/remap_table/CMakeLists.txt b/examples/camera_livekit_bridge/tests/remap_table/CMakeLists.txt new file mode 100644 index 0000000000..4c18a3cf0f --- /dev/null +++ b/examples/camera_livekit_bridge/tests/remap_table/CMakeLists.txt @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Needs no CUDA device: the table file and the CPU reference of the rectify step. +add_executable(test_remap_table test_remap_table.cpp) + +target_link_libraries(test_remap_table + PRIVATE + camera_livekit_bridge::remap_table +) + +target_compile_options(test_remap_table PRIVATE -Wall -Wextra) + +add_test(NAME remap_table COMMAND test_remap_table) diff --git a/examples/camera_livekit_bridge/tests/remap_table/test_remap_table.cpp b/examples/camera_livekit_bridge/tests/remap_table/test_remap_table.cpp new file mode 100644 index 0000000000..0560b6b60f --- /dev/null +++ b/examples/camera_livekit_bridge/tests/remap_table/test_remap_table.cpp @@ -0,0 +1,850 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The remap table file and the CPU reference of the rectify step. No CUDA device is needed: the reference runs the +// per-pixel functions the kernels call. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using camera_bridge::RemapEntry; +using camera_bridge::RemapSize; +using camera_bridge::RemapTable; + +int g_failures = 0; + +void check(bool condition, const std::string& what) +{ + if (!condition) + { + std::cerr << "FAILED: " << what << "\n"; + ++g_failures; + } +} + +constexpr uint8_t kPad = 0xEE; +constexpr float kNaN = std::numeric_limits::quiet_NaN(); +constexpr float kInf = std::numeric_limits::infinity(); + +// A host NV12 picture whose rows are longer than the picture. Every byte starts as kPad, which no test picture or +// fill uses, so an unwritten byte and a touched padding byte both show. +struct Picture +{ + RemapSize size; + size_t pitch; + std::vector y; + std::vector uv; + + Picture(const RemapSize& s, size_t padding) + : size(s), pitch(s.width + padding), y(pitch * s.height, kPad), uv(pitch * (s.height / 2), kPad) + { + } + camera_bridge::RemapPlanes in() const + { + return { y.data(), uv.data(), pitch, pitch }; + } + camera_bridge::RemapPlanesOut out() + { + return { y.data(), uv.data(), pitch, pitch }; + } + uint8_t& luma(uint32_t x, uint32_t row) + { + return y[row * pitch + x]; + } + uint8_t& u(uint32_t cx, uint32_t cy) + { + return uv[cy * pitch + 2 * cx]; + } + uint8_t& v(uint32_t cx, uint32_t cy) + { + return uv[cy * pitch + 2 * cx + 1]; + } + bool padding_intact() const + { + for (uint32_t row = 0; row < size.height; ++row) + for (size_t x = size.width; x < pitch; ++x) + if (y[row * pitch + x] != kPad) + return false; + for (uint32_t row = 0; row < size.height / 2; ++row) + for (size_t x = size.width; x < pitch; ++x) + if (uv[row * pitch + x] != kPad) + return false; + return true; + } + bool fully_written() const + { + for (uint32_t row = 0; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + if (y[row * pitch + x] == kPad) + return false; + for (uint32_t row = 0; row < size.height / 2; ++row) + for (uint32_t x = 0; x < size.width; ++x) + if (uv[row * pitch + x] == kPad) + return false; + return true; + } +}; + +// Structure in both planes, every value below kPad. +Picture pattern(const RemapSize& size, size_t padding) +{ + Picture picture(size, padding); + for (uint32_t row = 0; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + picture.luma(x, row) = static_cast((x * 7 + row * 13 + 3) % 200); + for (uint32_t cy = 0; cy < size.height / 2; ++cy) + for (uint32_t cx = 0; cx < size.width / 2; ++cx) + { + picture.u(cx, cy) = static_cast(20 + (cx * 5 + cy * 3) % 180); + picture.v(cx, cy) = static_cast(30 + (cx * 11 + cy * 17) % 170); + } + return picture; +} + +using Mapping = std::function; + +std::vector entries(const RemapSize& output, const Mapping& mapping) +{ + std::vector luma; + for (uint32_t row = 0; row < output.height; ++row) + for (uint32_t x = 0; x < output.width; ++x) + luma.push_back(mapping(x, row)); + return luma; +} + +// Every table a test samples through has been written and read back, so the reader is on the path. +RemapTable table_of(const RemapSize& source, const RemapSize& output, const Mapping& mapping) +{ + const std::vector bytes = camera_bridge::encode_remap_table(source, output, entries(output, mapping)); + RemapTable table; + const std::string refused = camera_bridge::decode_remap_table(bytes.data(), bytes.size(), "test.icrmap", table); + check(refused.empty(), "a written table is read back: " + refused); + return table; +} + +RemapEntry identity(uint32_t x, uint32_t row) +{ + return { static_cast(x), static_cast(row) }; +} + +bool same(const RemapEntry& entry, float sx, float sy) +{ + return entry.sx == sx && entry.sy == sy; +} + +uint64_t hash_of(const std::string& text) +{ + return camera_bridge::remap_table_hash(reinterpret_cast(text.data()), text.size()); +} + +// A 2x2 table for a 4x4 source, byte by byte as the format lays it out: entries (0, 0), (1.5, 0), (0, 2.25), (3, 3). +const std::vector kLiteralFile = { + 'I', 'C', 'R', 'M', 'A', 'P', '0', '1', // magic + 0x30, 0x00, 0x00, 0x00, // header size 48 + 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, // source 4x4 + 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, // output 2x2 + 0x00, 0x00, 0x00, 0x00, // flags + 0xE8, 0x92, 0x47, 0x21, 0xCB, 0x51, 0xA0, 0xC8, // FNV-1a 64 of the payload, 0xC8A051CB214792E8 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // (0, 0) + 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00, // (1.5, 0) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40, // (0, 2.25) + 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x40, 0x40, // (3, 3) +}; + +void test_hash() +{ + // Published FNV-1a 64-bit test vectors. + check(hash_of("") == 0xcbf29ce484222325ULL, "the hash of nothing is the offset basis"); + check(hash_of("a") == 0xaf63dc4c8601ec8cULL, "the hash of 'a'"); + check(hash_of("foobar") == 0x85944171f73967e8ULL, "the hash of 'foobar'"); +} + +void test_literal_file() +{ + RemapTable table; + const std::string refused = + camera_bridge::decode_remap_table(kLiteralFile.data(), kLiteralFile.size(), "literal.icrmap", table); + check(refused.empty(), "the literal file is read: " + refused); + check(table.source == RemapSize{ 4, 4 } && table.output == RemapSize{ 2, 2 }, "the literal file's sizes"); + check(table.luma.size() == 4 && same(table.luma[0], 0.0F, 0.0F) && same(table.luma[1], 1.5F, 0.0F) && + same(table.luma[2], 0.0F, 2.25F) && same(table.luma[3], 3.0F, 3.0F), + "the literal file's entries"); + // The one chroma sample: the mean of (0, 0) and (0, 2.25) is luma (0, 1.125), chroma (0, (1.125 - 0.5) / 2). + check(table.chroma.size() == 1 && same(table.chroma[0], 0.0F, 0.3125F), "the literal file's chroma entry"); + check(camera_bridge::encode_remap_table(table.source, table.output, table.luma) == kLiteralFile, + "the writer produces the literal file"); +} + +// The refusal for `bytes`, checked to be one sentence that names the file and to leave the table alone. +std::string refusal(const std::vector& bytes, const std::string& expected_word) +{ + RemapTable table; + table.source = { 2, 2 }; + const std::string reason = camera_bridge::decode_remap_table(bytes.data(), bytes.size(), "cam.icrmap", table); + check(!reason.empty(), "refused: " + expected_word); + check(reason.find("'cam.icrmap'") != std::string::npos, "the refusal names the file: " + reason); + check(reason.find(expected_word) != std::string::npos, "the refusal says '" + expected_word + "': " + reason); + check(reason.find('\n') == std::string::npos && reason.size() < 140, "the refusal is one short sentence: " + reason); + check(table.source == RemapSize{ 2, 2 } && table.luma.empty(), "a refusal leaves the table unchanged"); + return reason; +} + +void put_u32(std::vector& bytes, size_t at, uint32_t value) +{ + for (int i = 0; i < 4; ++i) + bytes[at + i] = static_cast(value >> (8 * i)); +} + +// The largest width or height a table may name. +constexpr uint32_t kLimit = 1U << 24; + +void test_refusals() +{ + const RemapSize source{ 8, 6 }; + const RemapSize output{ 4, 2 }; + const std::vector good = camera_bridge::encode_remap_table(source, output, entries(output, identity)); + RemapTable table; + check(camera_bridge::decode_remap_table(good.data(), good.size(), "cam.icrmap", table).empty(), "a good file"); + + refusal({}, "not a remap table"); + refusal({ 'I', 'C', 'R' }, "not a remap table"); + std::vector bad = good; + bad[7] = '2'; + refusal(bad, "not a remap table"); + refusal(std::vector(good.begin(), good.begin() + 20), "header"); + + bad = good; + bad[8] = 56; + refusal(bad, "header of 56 bytes"); + bad = good; + bad[28] = 1; + refusal(bad, "flags"); + + // Offsets of the four sizes: each refused when zero, when odd and when above the limit. + for (const size_t at : { 12, 16, 20, 24 }) + { + bad = good; + bad[at] = 0; + refusal(bad, "zero or odd"); + bad = good; + bad[at] = static_cast(good[at] + 1); + refusal(bad, "zero or odd"); + // The first even size above the limit, the first an int cannot hold, and the largest even one. + for (const uint32_t above : { kLimit + 2, 1U << 31, 0xFFFFFFFEU }) + { + bad = good; + put_u32(bad, at, above); + refusal(bad, "above 16777216"); + } + } + // The limit itself is a size: a source that large is read, and an identity's chroma entries come out as they + // do for any source. + bad = good; + put_u32(bad, 12, kLimit); + put_u32(bad, 16, kLimit); + RemapTable largest; + const std::string at_limit = camera_bridge::decode_remap_table(bad.data(), bad.size(), "cam.icrmap", largest); + check(at_limit.empty() && largest.source == RemapSize{ kLimit, kLimit }, + "a source at the limit is read: " + at_limit); + check(largest.chroma.size() == 2 && same(largest.chroma[0], 0.0F, 0.0F) && same(largest.chroma[1], 1.0F, 0.0F), + "a source at the limit gives the identity's chroma entries"); + // At the limit a float still holds every position, so the last sample is inside and the next one is not. + const int limit = static_cast(kLimit); + const float last = static_cast(kLimit - 1); + const float past = static_cast(kLimit); + check(camera_bridge::remap_inside(last, last, limit, limit), "the last sample of a plane at the limit is inside"); + check(!camera_bridge::remap_inside(past, 0.0F, limit, limit) && !camera_bridge::remap_inside(0.0F, past, limit, limit), + "one past the last sample of a plane at the limit is outside"); + + bad = good; + bad.pop_back(); + refusal(bad, "length"); + bad = good; + bad.push_back(0); + refusal(bad, "length"); + bad = good; + bad.resize(good.size() + 8, 0); + refusal(bad, "length"); + // An output size the payload does not hold, with every size still even. + refusal(camera_bridge::encode_remap_table(source, { 4, 4 }, entries(output, identity)), "length"); + // The largest output a header may name, over this payload. + bad = good; + put_u32(bad, 20, kLimit); + put_u32(bad, 24, kLimit); + refusal(bad, "length"); + + bad = good; + bad[48 + 5] ^= 0x01; + refusal(bad, "hash"); + bad = good; + bad[32] ^= 0x80; + refusal(bad, "hash"); +} + +void test_files() +{ + const char* base = std::getenv("TMPDIR"); + std::string directory = std::string(base != nullptr && *base != '\0' ? base : "/tmp") + "/remap_table_XXXXXX"; + if (mkdtemp(directory.data()) == nullptr) + { + check(false, "cannot make a scratch directory"); + return; + } + const std::string name = "camera,left=1:a.icrmap"; + const std::string path = directory + "/" + name; + const RemapSize source{ 8, 6 }; + const RemapSize output{ 4, 2 }; + const std::vector bytes = camera_bridge::encode_remap_table(source, output, entries(output, identity)); + std::ofstream(path, std::ios::binary).write(reinterpret_cast(bytes.data()), bytes.size()); + + RemapTable table; + const std::string refused = camera_bridge::load_remap_table(path, table); + check(refused.empty(), "a file is loaded: " + refused); + check(table.source == source && table.output == output && table.luma.size() == 8 && table.chroma.size() == 2, + "the loaded table's sizes"); + check(same(table.luma[5], 1.0F, 1.0F), "the loaded table's entries"); + check(camera_bridge::remap_table_name(path) == name && camera_bridge::remap_table_name(name) == name, + "a refusal's name for a file is its base name"); + check(camera_bridge::remap_table_name("/tables/head/") == "head" && camera_bridge::remap_table_name("/") == "/" && + camera_bridge::remap_table_name("").empty(), + "a path that ends in a slash is named by its last component"); + + // A refused file leaves the table as it was, and the sentence names the base name without the directory. + const auto refused_file = [&](const std::vector& content, const std::string& expected_word) + { + std::ofstream(path, std::ios::binary).write(reinterpret_cast(content.data()), content.size()); + const std::string reason = camera_bridge::load_remap_table(path, table); + check(reason.find(expected_word) != std::string::npos, "a file refused for its " + expected_word + ": " + reason); + check(reason.find("'" + name + "'") != std::string::npos && reason.find(directory) == std::string::npos, + "the refusal names the base name and not the directory: " + reason); + check(table.output == output && table.luma.size() == 8, "a refused file leaves the table unchanged"); + }; + std::vector changed = bytes; + changed[48] ^= 0x01; + refused_file(changed, "hash"); + changed = bytes; + changed.resize(bytes.size() - 16); + refused_file(changed, "length"); + changed = bytes; + changed.resize(bytes.size() + 8, 0); + refused_file(changed, "length"); + // Far more bytes than the sizes account for. + changed = bytes; + changed.resize(bytes.size() + 300000, 0); + refused_file(changed, "longer than a 4x2 table"); + changed.assign(300000, 0x55); + refused_file(changed, "not a remap table"); + changed.assign(bytes.begin(), bytes.begin() + 30); + refused_file(changed, "header"); + // A source size an int cannot hold. + changed = bytes; + put_u32(changed, 12, 1U << 31); + refused_file(changed, "above 16777216"); + // The largest output a header may name, in a file that ends after this payload. + changed = bytes; + put_u32(changed, 20, kLimit); + put_u32(changed, 24, kLimit); + refused_file(changed, "length"); + + // A table several times the size the loader reads at once. + const RemapSize large{ 256, 128 }; + const std::vector long_file = camera_bridge::encode_remap_table(large, large, entries(large, identity)); + std::ofstream(path, std::ios::binary).write(reinterpret_cast(long_file.data()), long_file.size()); + const std::string large_refused = camera_bridge::load_remap_table(path, table); + check(large_refused.empty() && table.output == large && table.luma.size() == 256 * 128 && + same(table.luma.back(), 255.0F, 127.0F) && same(table.chroma.back(), 127.0F, 63.0F), + "a large file is loaded whole: " + large_refused); + + std::remove(path.c_str()); + const std::string missing = camera_bridge::load_remap_table(path, table); + check(missing == "cannot open remap table '" + name + "'", "a missing file is refused: " + missing); + for (const std::string& not_a_file : { directory, directory + "/" }) + { + const std::string reason = camera_bridge::load_remap_table(not_a_file, table); + check(!reason.empty() && reason.find('/') == std::string::npos, "a directory is refused by its name: " + reason); + } + rmdir(directory.c_str()); +} + +void test_chroma_derivation() +{ + const RemapSize source{ 16, 16 }; + const RemapSize output{ 8, 6 }; + const auto unchanged = camera_bridge::derive_chroma_table(output, output, entries(output, identity)); + bool exact = unchanged.size() == 12; + for (uint32_t cy = 0; exact && cy < 3; ++cy) + for (uint32_t cx = 0; cx < 4; ++cx) + exact = exact && same(unchanged[cy * 4 + cx], static_cast(cx), static_cast(cy)); + check(exact, "an identity luma table gives an identity chroma table, with no quarter-row offset"); + + // Luma (x/2 + 3, y/2 + 2): chroma sample (cx, cy) averages (cx + 3, cy + 2) and (cx + 3, cy + 2.5), which is + // luma (cx + 3, cy + 2.25) and chroma ((cx + 3) / 2, (cy + 1.75) / 2). + const auto scaled = + camera_bridge::derive_chroma_table(source, output, + entries(output, + [](uint32_t x, uint32_t row) { + return RemapEntry{ 0.5F * x + 3.0F, 0.5F * row + 2.0F }; + })); + exact = scaled.size() == 12; + for (uint32_t cy = 0; exact && cy < 3; ++cy) + for (uint32_t cx = 0; cx < 4; ++cx) + exact = exact && same(scaled[cy * 4 + cx], 0.5F * cx + 1.5F, 0.5F * cy + 0.875F); + check(exact, "the chroma entry is the mean of its two luma entries in chroma coordinates"); + + // Either luma entry of a pair naming no source pixel makes the chroma entry name none. + const auto mapping = [](uint32_t x, uint32_t row) + { + if (x == 0 && row == 0) + return RemapEntry{ -0.5F, 0.0F }; // the upper entry of chroma (0, 0) + if (x == 2 && row == 1) + return RemapEntry{ 2.0F, kNaN }; // the lower entry of chroma (1, 0) + if (x == 4 && row == 1) + return RemapEntry{ 16.0F, 1.0F }; // one past the last source column + if (x == 1 || x == 3) + return RemapEntry{ kNaN, kNaN }; // odd columns take no part in chroma + return identity(x, row); + }; + const auto holes = camera_bridge::derive_chroma_table(source, output, entries(output, mapping)); + check(std::isnan(holes[0].sx) && std::isnan(holes[0].sy), "an outside upper entry gives no chroma source"); + check(std::isnan(holes[1].sx) && std::isnan(holes[1].sy), "a NaN lower entry gives no chroma source"); + check(std::isnan(holes[2].sx) && std::isnan(holes[2].sy), "an entry past the last column gives no chroma source"); + check(same(holes[3], 3.0F, 0.0F) && same(holes[4], 0.0F, 1.0F), "the other chroma entries are kept"); + + check(camera_bridge::derive_chroma_table(source, output, std::vector(5)).empty(), + "a luma table of the wrong length gives no chroma table"); +} + +bool names_none(const RemapEntry& entry) +{ + return std::isnan(entry.sx) && std::isnan(entry.sy); +} + +// The chroma entry at the source's borders. The source chroma plane spans luma columns 0 to width - 2 and luma rows +// 0.5 to height - 1.5, so a luma position on the right, top or bottom border lies past the plane's last sample. +void test_chroma_entry() +{ + const RemapSize source{ 16, 12 }; + const float last_column = 7.0F; + const float last_row = 5.0F; + // Both luma entries at (sx, sy), which is chroma (sx / 2, (sy - 0.5) / 2) before the clamp. + const auto at = [&source](float sx, float sy) { + return camera_bridge::derive_chroma_entry(source, { sx, sy }, { sx, sy }); + }; + check(same(at(0.0F, 6.5F), 0.0F, 3.0F), "the left border is the first chroma column"); + check(same(at(15.0F, 6.5F), last_column, 3.0F), "the right border, half a sample past the last column, reads it"); + check(same(at(8.0F, 0.0F), 4.0F, 0.0F), "the top border, a quarter of a sample above the first row, reads it"); + check(same(at(8.0F, 11.0F), 4.0F, last_row), "the bottom border, a quarter of a sample below the last row, reads it"); + check(same(at(0.0F, 0.0F), 0.0F, 0.0F) && same(at(15.0F, 0.0F), last_column, 0.0F) && + same(at(0.0F, 11.0F), 0.0F, last_row) && same(at(15.0F, 11.0F), last_column, last_row), + "the corners of the source read the corners of the chroma plane"); + check(same(at(14.0F, 0.5F), last_column, 0.0F) && same(at(14.0F, 10.5F), last_column, last_row) && + same(at(13.5F, 1.0F), 6.75F, 0.25F) && same(at(13.5F, 10.0F), 6.75F, 4.75F), + "positions on and next to the plane's last samples are kept"); + + const RemapEntry inside{ 8.0F, 6.0F }; + bool none = true; + for (const RemapEntry& outside : { RemapEntry{ -0.25F, 6.0F }, RemapEntry{ 15.25F, 6.0F }, RemapEntry{ 8.0F, -0.25F }, + RemapEntry{ 8.0F, 11.25F }, RemapEntry{ kNaN, 6.0F }, RemapEntry{ 8.0F, kInf } }) + none = none && names_none(camera_bridge::derive_chroma_entry(source, outside, inside)) && + names_none(camera_bridge::derive_chroma_entry(source, inside, outside)) && + names_none(camera_bridge::derive_chroma_entry(source, outside, outside)); + check(none, "a luma entry past any border, or not finite, leaves the chroma sample without a source"); + + // Quarter-pixel luma positions over the whole source, each paired with a second entry up to a pixel away. The + // position before the clamp is written out here; the sizes are those the sampler tests an entry against. + const camera_bridge::RemapJobs jobs = + camera_bridge::remap_nv12_jobs({ nullptr, nullptr, source, source }, {}, {}, false); + int kept = 0; + int moved = 0; + bool kept_exactly = true; + bool moved_to_nearest = true; + bool accepted = true; + for (int row = 0; row <= 44; ++row) + for (int column = 0; column <= 60; ++column) + for (const RemapEntry& step : + { RemapEntry{ 0.0F, 0.0F }, RemapEntry{ 0.25F, 0.5F }, RemapEntry{ -0.5F, 1.0F } }) + { + const RemapEntry upper{ 0.25F * static_cast(column), 0.25F * static_cast(row) }; + const RemapEntry lower{ upper.sx + step.sx, upper.sy + step.sy }; + if (!camera_bridge::remap_inside(lower.sx, lower.sy, 16, 12)) + continue; + const RemapEntry entry = camera_bridge::derive_chroma_entry(source, upper, lower); + const float x = 0.5F * (0.5F * (upper.sx + lower.sx)); + const float y = 0.5F * (0.5F * (upper.sy + lower.sy) - 0.5F); + accepted = accepted && camera_bridge::remap_inside( + entry.sx, entry.sy, jobs.chroma.src_width, jobs.chroma.src_height); + if (x >= 0.0F && x <= last_column && y >= 0.0F && y <= last_row) + { + ++kept; + kept_exactly = kept_exactly && same(entry, x, y); + continue; + } + ++moved; + moved_to_nearest = + moved_to_nearest && + same(entry, std::min(std::max(x, 0.0F), last_column), std::min(std::max(y, 0.0F), last_row)) && + std::abs(entry.sx - x) <= 0.5F && std::abs(entry.sy - y) <= 0.25F; + } + check(kept > 0 && kept_exactly, "a position already in the chroma plane is not moved"); + check(moved > 0 && moved_to_nearest, + "a position past the chroma plane moves to the nearest sample, at most half a sample across and a quarter down"); + check(accepted, "the sampler's own test accepts every entry derived from two luma entries inside the source"); +} + +// What the step writes at the source's borders: the edge chroma sample, repeated, wherever both luma entries of a +// chroma sample are picture. +void test_chroma_edges() +{ + const RemapSize source_size{ 16, 16 }; + Picture source(source_size, 3); + std::fill(source.y.begin(), source.y.end(), 77); + // U tells the chroma column and V the chroma row; neither is ever the fill's 128, nor is a blend used below. + const auto u_of = [](uint32_t cx) { return static_cast(40 + 10 * cx); }; + const auto v_of = [](uint32_t cy) { return static_cast(50 + 20 * cy); }; + for (uint32_t cy = 0; cy < 8; ++cy) + for (uint32_t cx = 0; cx < 8; ++cx) + { + source.u(cx, cy) = u_of(cx); + source.v(cx, cy) = v_of(cy); + } + // A 2x2 output, so one chroma sample: its upper luma entries read `upper` and its lower ones `lower`. The bytes + // are the two luma rows, then U and V. + const auto bytes_of = [&](const RemapEntry& upper, const RemapEntry& lower) + { + Picture result({ 2, 2 }, 1); + const auto mapping = [&](uint32_t, uint32_t row) { return row == 0 ? upper : lower; }; + camera_bridge::remap_nv12_reference(table_of(source_size, { 2, 2 }, mapping), source.in(), result.out(), false); + return std::vector{ result.luma(0, 0), result.luma(0, 1), result.u(0, 0), result.v(0, 0) }; + }; + const auto bytes_at = [&](float sx, float sy) { return bytes_of({ sx, sy }, { sx, sy }); }; + const auto picture = [](uint8_t u, uint8_t v) { return std::vector{ 77, 77, u, v }; }; + // V where luma row 8 falls, chroma row 3.75: a quarter of row 3's 110 and three quarters of row 4's 130. + const uint8_t v_middle = 125; + + check(bytes_at(8.0F, 0.0F) == picture(u_of(4), v_of(0)) && bytes_at(8.0F, 0.25F) == picture(u_of(4), v_of(0)), + "top border: chroma repeats the first chroma row"); + check(bytes_at(8.0F, 15.0F) == picture(u_of(4), v_of(7)) && bytes_at(8.0F, 14.75F) == picture(u_of(4), v_of(7)), + "bottom border: chroma repeats the last chroma row"); + check(bytes_at(15.0F, 8.0F) == picture(u_of(7), v_middle) && bytes_at(14.5F, 8.0F) == picture(u_of(7), v_middle), + "right border: chroma repeats the last chroma column"); + check(bytes_at(0.0F, 8.0F) == picture(u_of(0), v_middle), "left border: chroma is the first chroma column"); + check(bytes_at(0.0F, 0.0F) == picture(u_of(0), v_of(0)) && bytes_at(15.0F, 0.0F) == picture(u_of(7), v_of(0)) && + bytes_at(0.0F, 15.0F) == picture(u_of(0), v_of(7)) && bytes_at(15.0F, 15.0F) == picture(u_of(7), v_of(7)), + "corners: chroma repeats the corner chroma sample"); + + const std::vector fill{ 16, 16, 128, 128 }; + check(bytes_at(-0.25F, 8.0F) == fill && bytes_at(15.25F, 8.0F) == fill && bytes_at(8.0F, -0.25F) == fill && + bytes_at(8.0F, 15.25F) == fill, + "past any border both planes take the fill"); + check(bytes_of({ 8.0F, 15.0F }, { 8.0F, 15.5F }) == std::vector{ 77, 16, 128, 128 } && + bytes_of({ 15.5F, 8.0F }, { 15.0F, 8.0F }) == std::vector{ 16, 77, 128, 128 }, + "one luma entry past the border: its partner is sampled and their chroma sample takes the fill"); +} + +// A view that reaches every border of the source and names a source pixel everywhere, as a rectification without +// borders does: no sample of either plane takes the fill. +void test_view_to_the_borders() +{ + const RemapSize source_size{ 16, 12 }; + const RemapSize output{ 32, 24 }; + Picture source(source_size, 5); + std::fill(source.y.begin(), source.y.end(), 120); + for (uint32_t cy = 0; cy < source_size.height / 2; ++cy) + for (uint32_t cx = 0; cx < source_size.width / 2; ++cx) + { + source.u(cx, cy) = 60; + source.v(cx, cy) = 200; + } + // Output column 31 reads source column 15 and output row 23 source row 11, exactly. + const auto stretched = [](uint32_t x, uint32_t row) { + return RemapEntry{ static_cast(x * 15) / 31.0F, static_cast(row * 11) / 23.0F }; + }; + const RemapTable table = table_of(source_size, output, stretched); + check(same(table.luma.front(), 0.0F, 0.0F) && same(table.luma.back(), 15.0F, 11.0F), "the view spans the source"); + check(std::none_of(table.chroma.begin(), table.chroma.end(), names_none), "every chroma entry names a source sample"); + for (const bool full_range : { false, true }) + { + Picture result(output, 3); + camera_bridge::remap_nv12_reference(table, source.in(), result.out(), full_range); + bool one_colour = true; + for (uint32_t row = 0; row < output.height; ++row) + for (uint32_t x = 0; x < output.width; ++x) + one_colour = one_colour && result.luma(x, row) == 120; + for (uint32_t cy = 0; cy < output.height / 2; ++cy) + for (uint32_t cx = 0; cx < output.width / 2; ++cx) + one_colour = one_colour && result.u(cx, cy) == 60 && result.v(cx, cy) == 200; + check(one_colour, "a one-colour source seen to its borders gives a one-colour picture, with no fill"); + check(result.padding_intact(), "a view to the borders leaves the row padding alone"); + } +} + +void test_identity() +{ + const RemapSize size{ 16, 12 }; + const Picture source = pattern(size, 7); + Picture result(size, 3); + camera_bridge::remap_nv12_reference(table_of(size, size, identity), source.in(), result.out(), false); + bool luma_equal = true; + bool chroma_equal = true; + for (uint32_t row = 0; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + luma_equal = luma_equal && result.y[row * result.pitch + x] == source.y[row * source.pitch + x]; + for (uint32_t row = 0; row < size.height / 2; ++row) + for (uint32_t x = 0; x < size.width; ++x) + chroma_equal = chroma_equal && result.uv[row * result.pitch + x] == source.uv[row * source.pitch + x]; + check(luma_equal, "an identity table reproduces the luma plane byte for byte"); + check(chroma_equal, "an identity table reproduces the chroma plane byte for byte"); + check(result.padding_intact(), "an identity remap leaves the row padding alone"); +} + +void test_whole_pixel_shift() +{ + // Output (x, y) reads source (x + 2, y - 2): a whole chroma sample each way, so chroma shifts exactly too. + const RemapSize size{ 16, 12 }; + Picture source = pattern(size, 5); + Picture result(size, 9); + const auto shifted = [](uint32_t x, uint32_t row) { + return RemapEntry{ static_cast(x) + 2.0F, static_cast(row) - 2.0F }; + }; + camera_bridge::remap_nv12_reference(table_of(size, size, shifted), source.in(), result.out(), false); + bool luma_ok = true; + bool chroma_ok = true; + for (uint32_t row = 0; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + { + const bool inside = x + 2 < size.width && row >= 2; + luma_ok = luma_ok && result.luma(x, row) == (inside ? source.luma(x + 2, row - 2) : 16); + } + for (uint32_t cy = 0; cy < size.height / 2; ++cy) + for (uint32_t cx = 0; cx < size.width / 2; ++cx) + { + const bool inside = cx + 1 < size.width / 2 && cy >= 1; + chroma_ok = chroma_ok && result.u(cx, cy) == (inside ? source.u(cx + 1, cy - 1) : 128) && + result.v(cx, cy) == (inside ? source.v(cx + 1, cy - 1) : 128); + } + check(luma_ok, "a whole-pixel shift moves luma and fills what it uncovers"); + check(chroma_ok, "a whole-pixel shift moves chroma by half as many samples and fills what it uncovers"); + check(result.fully_written() && result.padding_intact(), "the shifted picture is written, its padding is not"); +} + +// A 4x4 source for the hand-computed cases. +Picture small_source() +{ + Picture picture({ 4, 4 }, 3); + const uint8_t luma[4][4] = { { 10, 13, 20, 21 }, { 30, 40, 50, 61 }, { 70, 75, 80, 90 }, { 100, 110, 120, 135 } }; + for (uint32_t row = 0; row < 4; ++row) + for (uint32_t x = 0; x < 4; ++x) + picture.luma(x, row) = luma[row][x]; + picture.u(0, 0) = 100; + picture.u(1, 0) = 110; + picture.u(0, 1) = 120; + picture.u(1, 1) = 140; + picture.v(0, 0) = 50; + picture.v(1, 0) = 53; + picture.v(0, 1) = 60; + picture.v(1, 1) = 71; + return picture; +} + +Picture remap_small(float dx, float dy) +{ + const Picture source = small_source(); + Picture result({ 4, 4 }, 5); + const auto mapping = [dx, dy](uint32_t x, uint32_t row) { + return RemapEntry{ static_cast(x) + dx, static_cast(row) + dy }; + }; + camera_bridge::remap_nv12_reference(table_of({ 4, 4 }, { 4, 4 }, mapping), source.in(), result.out(), false); + check(result.fully_written() && result.padding_intact(), "the small picture is written, its padding is not"); + return result; +} + +bool luma_is(Picture& picture, const uint8_t expected[4][4]) +{ + for (uint32_t row = 0; row < 4; ++row) + for (uint32_t x = 0; x < 4; ++x) + if (picture.luma(x, row) != expected[row][x]) + return false; + return true; +} + +bool chroma_is(Picture& picture, const uint8_t expected[2][4]) +{ + for (uint32_t cy = 0; cy < 2; ++cy) + for (uint32_t i = 0; i < 4; ++i) + if (picture.uv[cy * picture.pitch + i] != expected[cy][i]) + return false; + return true; +} + +void test_half_pixel_shift() +{ + // Half a pixel right: the mean of horizontal neighbours, a half rounding up; the last column has no neighbour. + Picture right = remap_small(0.5F, 0.0F); + const uint8_t right_luma[4][4] = { { 12, 17, 21, 16 }, { 35, 45, 56, 16 }, { 73, 78, 85, 16 }, { 105, 115, 128, 16 } }; + check(luma_is(right, right_luma), "half a pixel right: luma"); + // Chroma (cx, cy) reads chroma (cx + 0.25, cy): 102.5 and 50.75 round up, 125 is exact, 62.75 rounds up. The + // second column is the last, so a quarter past it repeats it. + const uint8_t right_chroma[2][4] = { { 103, 51, 110, 53 }, { 125, 63, 140, 71 } }; + check(chroma_is(right, right_chroma), "half a pixel right: chroma moves a quarter of a sample"); + + // Half a pixel down: the mean of vertical neighbours; the last row has none. + Picture down = remap_small(0.0F, 0.5F); + const uint8_t down_luma[4][4] = { { 20, 27, 35, 41 }, { 50, 58, 65, 76 }, { 85, 93, 100, 113 }, { 16, 16, 16, 16 } }; + check(luma_is(down, down_luma), "half a pixel down: luma"); + // Chroma row 0 reads chroma row 0.25: 105, 52.5, 117.5 and 57.5. Row 1 pairs with the last luma row, which has + // no source. + const uint8_t down_chroma[2][4] = { { 105, 53, 118, 58 }, { 128, 128, 128, 128 } }; + check(chroma_is(down, down_chroma), "half a pixel down: chroma moves a quarter of a sample"); + + // Half a pixel both ways: the mean of four, 23.25, 30.75, 38 and 106.25 among them. + Picture diagonal = remap_small(0.5F, 0.5F); + check(diagonal.luma(0, 0) == 23 && diagonal.luma(1, 0) == 31 && diagonal.luma(2, 0) == 38 && + diagonal.luma(2, 2) == 106 && diagonal.luma(3, 0) == 16 && diagonal.luma(0, 3) == 16, + "half a pixel both ways: luma"); + + // A quarter right: 10.75, 14.75 and 20.25. + Picture quarter = remap_small(0.25F, 0.0F); + check(quarter.luma(0, 0) == 11 && quarter.luma(1, 0) == 15 && quarter.luma(2, 0) == 20, "a quarter pixel right"); +} + +void test_fill() +{ + const RemapSize size{ 8, 4 }; + Picture source = pattern(size, 4); + // Row 0 holds entries that name no source pixel and one that names the last; the other rows are kept. + const std::vector row0 = { { -0.25F, 0.0F }, { kNaN, 1.0F }, { 1.0F, kNaN }, { kInf, 0.0F }, + { -kInf, 0.0F }, { 8.0F, 0.0F }, { 7.0F, 3.0F }, { 0.0F, 3.5F } }; + const auto mapping = [&row0](uint32_t x, uint32_t row) { return row == 0 ? row0[x] : identity(x, row); }; + for (const bool full_range : { false, true }) + { + const std::string range = full_range ? "full range: " : "video range: "; + const uint8_t black = full_range ? 0 : 16; + Picture result(size, 6); + camera_bridge::remap_nv12_reference(table_of(size, size, mapping), source.in(), result.out(), full_range); + bool filled = true; + for (const uint32_t x : { 0U, 1U, 2U, 3U, 4U, 5U, 7U }) + filled = filled && result.luma(x, 0) == black; + check(filled, range + "outside, NaN and infinite entries take the luma fill"); + check(result.luma(6, 0) == source.luma(7, 3), range + "the last source pixel is still sampled"); + bool kept = true; + for (uint32_t row = 1; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + kept = kept && result.luma(x, row) == source.luma(x, row); + check(kept, range + "the other rows are unchanged"); + // Chroma row 0 pairs luma rows 0 and 1 at even columns, and three pairs miss an entry. Chroma row 1 pairs two + // kept rows. + bool chroma_ok = true; + for (uint32_t cx = 0; cx < size.width / 2; ++cx) + chroma_ok = chroma_ok && (cx == 3 || (result.u(cx, 0) == 128 && result.v(cx, 0) == 128)) && + result.u(cx, 1) == source.u(cx, 1) && result.v(cx, 1) == source.v(cx, 1); + check(chroma_ok, range + "chroma takes its fill without a source and is unchanged with one"); + // The fourth pair, (7, 3) and (6, 1), averages to chroma (3.25, 0.75): past the last column, so that column + // at a quarter of row 0 and three quarters of row 1, a half rounding up. + const auto mix = [](uint32_t a, uint32_t b) { return static_cast((a + 3 * b + 2) / 4); }; + check(result.u(3, 0) == mix(source.u(3, 0), source.u(3, 1)) && + result.v(3, 0) == mix(source.v(3, 0), source.v(3, 1)), + range + "a pair of source pixels that averages past the last chroma column is sampled at it"); + check(result.fully_written() && result.padding_intact(), range + "written, padding left alone"); + + Picture nothing(size, 2); + const auto nowhere = [](uint32_t, uint32_t) { return RemapEntry{ kNaN, kNaN }; }; + camera_bridge::remap_nv12_reference(table_of(size, size, nowhere), source.in(), nothing.out(), full_range); + bool all_black = true; + for (uint32_t row = 0; row < size.height; ++row) + for (uint32_t x = 0; x < size.width; ++x) + all_black = all_black && nothing.luma(x, row) == black; + for (uint32_t row = 0; row < size.height / 2; ++row) + for (uint32_t x = 0; x < size.width; ++x) + all_black = all_black && nothing.uv[row * nothing.pitch + x] == 128; + check(all_black, range + "a table that names no source pixel gives a black picture"); + check(nothing.padding_intact(), range + "a black picture leaves the padding alone"); + } +} + +void test_size_change() +{ + // Half size: output (x, y) reads source (2x, 2y). Chroma (cx, cy) then reads chroma (2cx, 2cy + 0.25). + const RemapSize source_size{ 16, 12 }; + const RemapSize half{ 8, 6 }; + Picture source = pattern(source_size, 7); + Picture smaller(half, 5); + const auto subsample = [](uint32_t x, uint32_t row) { + return RemapEntry{ 2.0F * static_cast(x), 2.0F * static_cast(row) }; + }; + const RemapTable table = table_of(source_size, half, subsample); + check(table.output == half && table.luma.size() == 48 && table.chroma.size() == 12, "a half-size table's sizes"); + camera_bridge::remap_nv12_reference(table, source.in(), smaller.out(), false); + bool luma_ok = true; + bool chroma_ok = true; + for (uint32_t row = 0; row < half.height; ++row) + for (uint32_t x = 0; x < half.width; ++x) + luma_ok = luma_ok && smaller.luma(x, row) == source.luma(2 * x, 2 * row); + for (uint32_t cy = 0; cy < half.height / 2; ++cy) + for (uint32_t cx = 0; cx < half.width / 2; ++cx) + { + // Three quarters of one row and a quarter of the next, a half rounding up. + const auto mix = [](uint32_t a, uint32_t b) { return static_cast((3 * a + b + 2) / 4); }; + chroma_ok = chroma_ok && smaller.u(cx, cy) == mix(source.u(2 * cx, 2 * cy), source.u(2 * cx, 2 * cy + 1)) && + smaller.v(cx, cy) == mix(source.v(2 * cx, 2 * cy), source.v(2 * cx, 2 * cy + 1)); + } + check(luma_ok, "a smaller output samples the luma the table names"); + check(chroma_ok, "a smaller output samples chroma at the table's chroma positions"); + check(smaller.fully_written() && smaller.padding_intact(), "the smaller picture is written, its padding is not"); + + // Double size: every output byte is written and the even samples are the source's. + const RemapSize twice{ 32, 24 }; + Picture larger(twice, 3); + const auto stretch = [](uint32_t x, uint32_t row) { + return RemapEntry{ 0.5F * static_cast(x), 0.5F * static_cast(row) }; + }; + camera_bridge::remap_nv12_reference(table_of(source_size, twice, stretch), source.in(), larger.out(), false); + bool even_ok = true; + for (uint32_t row = 0; row < source_size.height; ++row) + for (uint32_t x = 0; x < source_size.width; ++x) + even_ok = even_ok && larger.luma(2 * x, 2 * row) == source.luma(x, row); + check(even_ok, "a larger output keeps the source at the positions that land on a pixel"); + check(larger.fully_written() && larger.padding_intact(), "the larger picture is written, its padding is not"); +} + +} // namespace + +int main() +{ + test_hash(); + test_literal_file(); + test_refusals(); + test_files(); + test_chroma_derivation(); + test_chroma_entry(); + test_chroma_edges(); + test_view_to_the_borders(); + test_identity(); + test_whole_pixel_shift(); + test_half_pixel_shift(); + test_fill(); + test_size_change(); + + if (g_failures != 0) + { + std::cerr << g_failures << " check(s) failed\n"; + return 1; + } + std::cout << "remap_table: all checks passed\n"; + return 0; +}