Lab 1: V4L2 Capture Node Filter, BT.601 YUYV-to-RGB888 & Stride-Safe QImage Bridge
Cross-compile headless OpenCV 4 with ARMv7-A NEON/VFPv4 SIMD and V4L2 capture backends into isolated staging sysroots, filter CSI and UVC V4L2_CAP_VIDEO_CAPTURE nodes away from the i.MX6ULL /dev/video0 PXP mem2mem engine while converting YUYV 4:2:2 frames to RGB888, and bridge cv::Mat strides and reference-counted lifetimes safely into QImage with worker-thread photo encoding.
Prerequisites in this module
What ./check.sh verifies
- Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
- Fix compiler warnings or errors in files/core.cpp.
- Archives core.o into libcore.a and links independent TAP verifier.
- Preserve public declarations in files/core.hpp so tests.cpp links.
step 1/15 · inspect starter files and specification
Production embedded camera HMIs on i.MX6ULL fail when they open /dev/video0 (imx-pxp M2M), wrap unclamped BT.601 YUYV highlights into dark uint8_t speckles, or hand QImage a stack-local BGR pointer without bytesPerLine alignment.
In this studio lab you will repair and benchmark an ISO C++20 vision-bridge library (files/core.cpp) that filters real V4L2_CAP_VIDEO_CAPTURE nodes, converts packed YUYV 4:2:2 frames to saturated RGB888, and produces lifetime-safe, 4-byte-row-aligned QImage buffers from arbitrary-stride BGR sources.
learner@ksa:~/gl-q04/lab-m01ls -lastarter/Makefilestarter/cli.cppstarter/core.cppstarter/core.hpplearner@ksa:~/gl-q04/lab-m01starter: starter/Makefile
learner@ksa:~/gl-q04/lab-m01$ bat starter/Makefile File: starter/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clistarter: starter/cli.cpp
learner@ksa:~/gl-q04/lab-m01$ bat starter/cli.cpp File: starter/cli.cpp #include "core.hpp" #include <algorithm> #include <cstdio> #include <cstring> #include <ctime> #include <vector> namespace { uint64_t mono_ns() { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<uint64_t>(ts.tv_nsec); } int run_bench() { std::vector<uint8_t> yuyv(320u * 240u * 2u, 128u); for (size_t i = 0; i < yuyv.size(); i += 4u) { yuyv[i] = static_cast<uint8_t>(16u + (i % 210u)); yuyv[i + 3u] = 200u; } std::vector<uint8_t> rgb; ksa_v4l2::OwnedQImage qimg; uint64_t samples[40]{}; volatile uint64_t sink = 0; for (int iter = 0; iter < 45; ++iter) { uint64_t t0 = mono_ns(); ksa_v4l2::convert_yuyv_to_rgb888(yuyv.data(), 320, 240, rgb); ksa_v4l2::bridge_bgr_mat_to_owned_qimage(rgb.data(), 319, 240, 320u * 3u, qimg); sink ^= qimg.scan_line(120)[0]; uint64_t dt = mono_ns() - t0; if (iter >= 5) samples[iter - 5] = dt; } std::sort(std::begin(samples), std::end(samples)); std::printf("BENCH lab_m01_opencv_v4l2_qimage (320x240 YUYV->RGB + 319x240 stride copy, 40 runs): " "p50=%llu ns p95=%llu ns p99=%llu ns (sink=%llu)\n", static_cast<unsigned long long>(samples[20]), static_cast<unsigned long long>(samples[38]), static_cast<unsigned long long>(samples[39]), static_cast<unsigned long long>(sink & 0xFFu)); return 0; } } // namespace int main(int argc, char** argv) { if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { return run_bench(); } using namespace ksa_v4l2; std::vector<V4l2NodeDesc> nodes = { {0, "imx-pxp", "pxp", V4L2_CAP_DEVICE_CAPS | V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING, V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING}, {1, "mx6s-capture", "OV5640 CSI", V4L2_CAP_DEVICE_CAPS | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING, V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING}, {2, "uvcvideo", "USB Cam Meta", V4L2_CAP_DEVICE_CAPS | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_META_CAPTURE, V4L2_CAP_META_CAPTURE | V4L2_CAP_STREAMING}, }; auto cams = select_capture_nodes(nodes); const uint8_t yuyv[4] = {245u, 90u, 16u, 240u}; std::vector<uint8_t> rgb; convert_yuyv_to_rgb888(yuyv, 2, 1, rgb); std::vector<uint8_t> bgr(976u * 2u, 0u); bgr[976u + 0u] = 0x11u; // B bgr[976u + 1u] = 0x22u; // G bgr[976u + 2u] = 0x33u; // R OwnedQImage qimg; bridge_bgr_mat_to_owned_qimage(bgr.data(), 319, 2, 976u, qimg); std::fill(bgr.begin(), bgr.end(), 0xFFu); // Mutate/destroy source after bridge! std::printf("V4L2 selected=%zu first=/dev/video%d | YUYV p0_rgb=(%u,%u,%u)\n", cams.size(), cams.empty() ? -1 : cams[0], rgb[0], rgb[1], rgb[2]); std::printf("OwnedQImage 319x2: bytesPerLine=%zu row1_p0_rgb=(0x%02X,0x%02X,0x%02X)\n", qimg.bytes_per_line, qimg.scan_line(1)[0], qimg.scan_line(1)[1], qimg.scan_line(1)[2]); return 0; }starter: starter/core.cpp
learner@ksa:~/gl-q04/lab-m01$ bat starter/core.cpp File: starter/core.cpp #include "core.hpp" #include <algorithm> namespace ksa_v4l2 { std::vector<int> select_capture_nodes(const std::vector<V4l2NodeDesc>& nodes) { std::vector<int> out; constexpr uint32_t kNeed = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; for (const auto& n : nodes) { uint32_t caps = n.capabilities; // BUG: ignores device_caps & accepts M2M! if ((caps & V4L2_CAP_STREAMING) != 0u) { out.push_back(n.index); } } return out; } bool convert_yuyv_to_rgb888(const uint8_t* yuyv, int width, int height, std::vector<uint8_t>& rgb_out) { if (!yuyv || width <= 0 || height <= 0 || (width % 2) != 0) { return false; } const size_t total_px = static_cast<size_t>(width) * static_cast<size_t>(height); rgb_out.resize(total_px * 3u); const size_t pairs = total_px / 2u; for (size_t i = 0; i < pairs; ++i) { const int y0 = static_cast<int>(yuyv[i * 4u + 0u]); const int u0 = static_cast<int>(yuyv[i * 4u + 1u]) - 128; const int y1 = static_cast<int>(yuyv[i * 4u + 2u]); const int v0 = static_cast<int>(yuyv[i * 4u + 3u]) - 128; const int ys[2] = {y0, y1}; for (size_t p = 0; p < 2u; ++p) { const int c = ys[p] - 16; const int r = (298 * c + 409 * v0 + 128) >> 8; const int g = (298 * c - 100 * u0 - 208 * v0 + 128) >> 8; const int b = (298 * c + 516 * u0 + 128) >> 8; const size_t dst = (i * 2u + p) * 3u; rgb_out[dst + 0u] = static_cast<uint8_t>(r); // BUG: wraps uint8_t without [0..255] clamp! rgb_out[dst + 1u] = static_cast<uint8_t>(g); rgb_out[dst + 2u] = static_cast<uint8_t>(b); } } return true; } bool bridge_bgr_mat_to_owned_qimage(const uint8_t* src_bgr, int width, int height, size_t src_step, OwnedQImage& out) { if (!src_bgr || width <= 0 || height <= 0) { return false; } const size_t row_bytes = static_cast<size_t>(width) * 3u; if (src_step < row_bytes) { return false; } const size_t dst_step = (row_bytes + 3u) & ~size_t{3u}; out.width = width; out.height = height; out.bytes_per_line = dst_step; out.pixels.assign(dst_step * static_cast<size_t>(height), 0u); for (int y = 0; y < height; ++y) { const uint8_t* srow = src_bgr + static_cast<size_t>(y) * row_bytes; // BUG: ignores src_step & leaves BGR! uint8_t* drow = out.pixels.data() + static_cast<size_t>(y) * dst_step; for (int x = 0; x < width; ++x) { const size_t off = static_cast<size_t>(x) * 3u; drow[off + 0u] = srow[off + 0u]; drow[off + 1u] = srow[off + 1u]; drow[off + 2u] = srow[off + 2u]; } } return true; } } // namespace ksa_v4l2starter: starter/core.hpp
learner@ksa:~/gl-q04/lab-m01$ bat starter/core.hpp File: starter/core.hpp #ifndef GLQ04_M01_CORE_HPP #define GLQ04_M01_CORE_HPP #include <cstddef> #include <cstdint> #include <string> #include <vector> namespace ksa_v4l2 { constexpr uint32_t V4L2_CAP_VIDEO_CAPTURE = 0x00000001u; constexpr uint32_t V4L2_CAP_VIDEO_M2M = 0x00008000u; constexpr uint32_t V4L2_CAP_META_CAPTURE = 0x00800000u; constexpr uint32_t V4L2_CAP_STREAMING = 0x04000000u; constexpr uint32_t V4L2_CAP_DEVICE_CAPS = 0x80000000u; struct V4l2NodeDesc { int index = 0; std::string driver; std::string card; uint32_t capabilities = 0; uint32_t device_caps = 0; }; struct OwnedQImage { int width = 0; int height = 0; size_t bytes_per_line = 0; // Always 4-byte aligned: ((width * 3) + 3) & ~3 std::vector<uint8_t> pixels; const uint8_t* scan_line(int y) const { return pixels.data() + static_cast<size_t>(y) * bytes_per_line; } }; // Returns indices of real streaming capture cameras (rejecting M2M /dev/video0 and meta-only nodes). std::vector<int> select_capture_nodes(const std::vector<V4l2NodeDesc>& nodes); // Converts width*height YUYV 4:2:2 (width must be even, yuyv.size() >= width*height*2) into RGB888. bool convert_yuyv_to_rgb888(const uint8_t* yuyv, int width, int height, std::vector<uint8_t>& rgb_out); // Deep-copies a BGR888 source buffer with arbitrary src_step (>= width*3) into a 4-byte-row-aligned // RGB888 OwnedQImage whose storage remains valid after the caller frees src_bgr. bool bridge_bgr_mat_to_owned_qimage(const uint8_t* src_bgr, int width, int height, size_t src_step, OwnedQImage& out); } // namespace ksa_v4l2 #endifstep 2/15 · 2. learning objectives
- Filter
V4L2node descriptors viaV4L2_CAP_DEVICE_CAPSto select streaming capture cameras while rejectingM2M(/dev/video0) and metadata nodes. - Convert
YUYV4:2:2[Y0, U0, Y1, V0]scanlines intoRGB888using integerITU-R BT.601math with[0, 255]saturation. - Copy arbitrary-stride
BGR888ROI buffers (including odd widths like319px) into owned,4-byte-row-alignedRGB888OwnedQImageinstances.
step 3/15 · 3. environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
step 4/15 · 4. required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
i.MX6ULL(ARMv7-ACortex-A7) board withOV5640CSIor USBUVCcamera at/dev/video1+(v4l2-ctl --list-devices),OpenCV4.x (WITH_V4L=ON), andQt6.8 (linuxfb/eglfs).
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-q04/lab-m01$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.shstep 6/15 · 6. annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q04/lab-m01$ bat example.cpp File: example.cpp std::vector<int> select_capture_nodes(const std::vector<V4l2NodeDesc>& nodes) { std::vector<int> out; constexpr uint32_t kNeed = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; for (const auto& n : nodes) { uint32_t caps = (n.capabilities & V4L2_CAP_DEVICE_CAPS) ? n.device_caps : n.capabilities; if ((caps & kNeed) == kNeed && (caps & V4L2_CAP_VIDEO_M2M) == 0u) { out.push_back(n.index); } } return out; }starter/core.cpp injects three authentic defects: (1) reading n.capabilities without filtering V4L2_CAP_DEVICE_CAPS, V4L2_CAP_VIDEO_CAPTURE, or V4L2_CAP_VIDEO_M2M, (2) narrowing BT.601 r, g, b integers directly to uint8_t without std::clamp(..., 0, 255), and (3) stepping src_bgr by width * 3 instead of src_step while leaving BGR channels unswapped.
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q04/lab-m01$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - filters V4L2_CAP_DEVICE_CAPS to accept streaming capture cameras and skip /dev/video0 M2M + meta nodes ok 4 - converts packed YUYV 4:2:2 scanlines to RGB888 with [0, 255] BT.601 saturation and rejects odd widths ok 5 - bridges arbitrary-stride BGR888 ROIs into 4-byte-aligned RGB888 OwnedQImage buffers safely # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q04/lab-m01$ bat listing.txt File: listing.txt V4L2 selected=1 first=/dev/video1 | YUYV p0_rgb=(255,190,190) OwnedQImage 319x2: bytesPerLine=960 row1_p0_rgb=(0x33,0x22,0x11)Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 8. explanation of observed behavior
Passing 5/5 TAP version 13 assertions proves that /dev/video0 (imx-pxp M2M) and /dev/video3 (uvcvideo metadata) are excluded, full-swing YUYV highlights clamp cleanly at 0 and 255, and a 319-pixel sub-ROI (src_step = 976) copies into a 4-byte-aligned (960 B/row) RGB888 buffer that survives destruction of the source cv::Mat.
step 9/15 · 9. experiment variations
- Near transfer: Add
QImage::Format_BGR888zero-swizzle mode tobridge_bgr_mat_to_owned_qimageand measure theCLOCK_MONOTONICspeedup ofstd::memcpyper row versus per-pixelBGR -> RGBswapping in--bench. - Far transfer: Vectorize
convert_yuyv_to_rgb888usingARMv7-ANEONintrinsics (<arm_neon.h>,vld2_u8+vqmovun_s16behind#ifdef __ARM_NEON) while retaining the exact ISO C++20 scalar reference for host equivalence tests.
step 10/15 · 10. performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q04/lab-m01$ bat listing.txt File: listing.txt BENCH lab_m01_opencv_v4l2_qimage (320x240 YUYV->RGB + 319x240 stride copy, 40 runs): p50=595481 ns p95=614047 ns p99=616823 ns (sink=175)./files/lab_cli --bench measures 320x240 YUYV -> RGB888 expansion plus 319x240 stride-aligned BGR -> RGB copying in host RAM via CLOCK_MONOTONIC. Never extrapolate host x86_64 cache timings to 792 MHz Cortex-A7 DDR3 memory bandwidth or OV5640 CSI frame intervals (33.3 ms at 30 fps).
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix | |
|---|---|---|---|
not ok 3 (expected [1, 2], got count=4 first=0) | select_capture_nodes read n.capabilities instead of n.device_caps and forgot !(caps & V4L2_CAP_VIDEO_M2M) | Select n.device_caps when V4L2_CAP_DEVICE_CAPS is set, require `CAPTURE | STREAMING, and reject M2M`. |
not ok 4 (BT.601 saturation failed) | Casting signed int (> 255 or < 0) directly to uint8_t wrapped modulo 256 | Wrap r, g, and b in std::clamp(val, 0, 255) before casting to uint8_t. | |
not ok 5 (BGR->RGB or src_step skew at (318,2)) | Source row pointer advanced by width * 3 (957) instead of src_step (976) or omitted BGR -> RGB swap | Compute srow = src_bgr + y * src_step and write drow[off + 0] = srow[off + 2], drow[off + 2] = srow[off + 0]. |
step 12/15 · 12. guided questions
- Why must
OwnedQImage::bytes_per_lineequal960instead of957whenwidth == 319inFormat_RGB888?
- *Hint 1:* Check
QImage's scanline alignment requirement acrossQPainterrasterizers. - *Hint 2:*
QImagerequires every scanline start address offset to be32-bit (4-byte) aligned:(319 * 3 + 3) & ~3 = 960(3pad bytes per row).
- Why did
test_v4l2_filtersetV4L2_CAP_VIDEO_CAPTUREinsiden.capabilitieson node3(usb-meta) while omitting it fromn.device_caps?
- *Hint 1:* Recall how the
Linux kerneluvcvideodriver populatesv4l2_capabilityon multi-node USB webcams. - *Hint 2:*
vcap.capabilitiesadvertises the combined capabilities of the whole physical USB camera, whereasvcap.device_capsreports the exact capability of that individual/dev/video3file node!
step 13/15 · 13. independent challenges
Write a small command-line utility using <linux/videodev2.h> (VIDIOC_QUERYCAP + VIDIOC_ENUM_FRAMESIZES) that prints every capture-capable /dev/videoN node on a Linux host or i.MX6ULL board along with its supported FourCC codes and discrete resolutions.
step 14/15 · 14. solutions and explanations
Checking n.device_caps against CAPTURE | STREAMING (!M2M), clamping BT.601 channels via std::clamp, and indexing source rows by src_step while swapping BGR -> RGB into 4-byte-aligned dst_step turns all 5/5 TAP checks green.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-q04/lab-m01./files/lab_clilearner@ksa:~/gl-q04/lab-m01V4L2 selected=1 first=/dev/video1 | YUYV p0_rgb=(255,190,190)OwnedQImage 319x2: bytesPerLine=960 row1_p0_rgb=(0x33,0x22,0x11)Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-q04/lab-m01$ bat files/Makefile File: files/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clisolution: files/cli.cpp
learner@ksa:~/gl-q04/lab-m01$ bat files/cli.cpp File: files/cli.cpp #include "core.hpp" #include <algorithm> #include <cstdio> #include <cstring> #include <ctime> #include <vector> namespace { uint64_t mono_ns() { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<uint64_t>(ts.tv_nsec); } int run_bench() { std::vector<uint8_t> yuyv(320u * 240u * 2u, 128u); for (size_t i = 0; i < yuyv.size(); i += 4u) { yuyv[i] = static_cast<uint8_t>(16u + (i % 210u)); yuyv[i + 3u] = 200u; } std::vector<uint8_t> rgb; ksa_v4l2::OwnedQImage qimg; uint64_t samples[40]{}; volatile uint64_t sink = 0; for (int iter = 0; iter < 45; ++iter) { uint64_t t0 = mono_ns(); ksa_v4l2::convert_yuyv_to_rgb888(yuyv.data(), 320, 240, rgb); ksa_v4l2::bridge_bgr_mat_to_owned_qimage(rgb.data(), 319, 240, 320u * 3u, qimg); sink ^= qimg.scan_line(120)[0]; uint64_t dt = mono_ns() - t0; if (iter >= 5) samples[iter - 5] = dt; } std::sort(std::begin(samples), std::end(samples)); std::printf("BENCH lab_m01_opencv_v4l2_qimage (320x240 YUYV->RGB + 319x240 stride copy, 40 runs): " "p50=%llu ns p95=%llu ns p99=%llu ns (sink=%llu)\n", static_cast<unsigned long long>(samples[20]), static_cast<unsigned long long>(samples[38]), static_cast<unsigned long long>(samples[39]), static_cast<unsigned long long>(sink & 0xFFu)); return 0; } } // namespace int main(int argc, char** argv) { if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { return run_bench(); } using namespace ksa_v4l2; std::vector<V4l2NodeDesc> nodes = { {0, "imx-pxp", "pxp", V4L2_CAP_DEVICE_CAPS | V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING, V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING}, {1, "mx6s-capture", "OV5640 CSI", V4L2_CAP_DEVICE_CAPS | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING, V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING}, {2, "uvcvideo", "USB Cam Meta", V4L2_CAP_DEVICE_CAPS | V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_META_CAPTURE, V4L2_CAP_META_CAPTURE | V4L2_CAP_STREAMING}, }; auto cams = select_capture_nodes(nodes); const uint8_t yuyv[4] = {245u, 90u, 16u, 240u}; std::vector<uint8_t> rgb; convert_yuyv_to_rgb888(yuyv, 2, 1, rgb); std::vector<uint8_t> bgr(976u * 2u, 0u); bgr[976u + 0u] = 0x11u; // B bgr[976u + 1u] = 0x22u; // G bgr[976u + 2u] = 0x33u; // R OwnedQImage qimg; bridge_bgr_mat_to_owned_qimage(bgr.data(), 319, 2, 976u, qimg); std::fill(bgr.begin(), bgr.end(), 0xFFu); // Mutate/destroy source after bridge! std::printf("V4L2 selected=%zu first=/dev/video%d | YUYV p0_rgb=(%u,%u,%u)\n", cams.size(), cams.empty() ? -1 : cams[0], rgb[0], rgb[1], rgb[2]); std::printf("OwnedQImage 319x2: bytesPerLine=%zu row1_p0_rgb=(0x%02X,0x%02X,0x%02X)\n", qimg.bytes_per_line, qimg.scan_line(1)[0], qimg.scan_line(1)[1], qimg.scan_line(1)[2]); return 0; }solution: files/core.cpp
learner@ksa:~/gl-q04/lab-m01$ bat files/core.cpp File: files/core.cpp #include "core.hpp" #include <algorithm> namespace ksa_v4l2 { std::vector<int> select_capture_nodes(const std::vector<V4l2NodeDesc>& nodes) { std::vector<int> out; constexpr uint32_t kNeed = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; for (const auto& n : nodes) { uint32_t caps = (n.capabilities & V4L2_CAP_DEVICE_CAPS) ? n.device_caps : n.capabilities; if ((caps & kNeed) == kNeed && (caps & V4L2_CAP_VIDEO_M2M) == 0u) { out.push_back(n.index); } } return out; } bool convert_yuyv_to_rgb888(const uint8_t* yuyv, int width, int height, std::vector<uint8_t>& rgb_out) { if (!yuyv || width <= 0 || height <= 0 || (width % 2) != 0) { return false; } const size_t total_px = static_cast<size_t>(width) * static_cast<size_t>(height); rgb_out.resize(total_px * 3u); const size_t pairs = total_px / 2u; for (size_t i = 0; i < pairs; ++i) { const int y0 = static_cast<int>(yuyv[i * 4u + 0u]); const int u0 = static_cast<int>(yuyv[i * 4u + 1u]) - 128; const int y1 = static_cast<int>(yuyv[i * 4u + 2u]); const int v0 = static_cast<int>(yuyv[i * 4u + 3u]) - 128; const int ys[2] = {y0, y1}; for (size_t p = 0; p < 2u; ++p) { const int c = ys[p] - 16; const int r = (298 * c + 409 * v0 + 128) >> 8; const int g = (298 * c - 100 * u0 - 208 * v0 + 128) >> 8; const int b = (298 * c + 516 * u0 + 128) >> 8; const size_t dst = (i * 2u + p) * 3u; rgb_out[dst + 0u] = static_cast<uint8_t>(std::clamp(r, 0, 255)); rgb_out[dst + 1u] = static_cast<uint8_t>(std::clamp(g, 0, 255)); rgb_out[dst + 2u] = static_cast<uint8_t>(std::clamp(b, 0, 255)); } } return true; } bool bridge_bgr_mat_to_owned_qimage(const uint8_t* src_bgr, int width, int height, size_t src_step, OwnedQImage& out) { if (!src_bgr || width <= 0 || height <= 0) { return false; } const size_t row_bytes = static_cast<size_t>(width) * 3u; if (src_step < row_bytes) { return false; } const size_t dst_step = (row_bytes + 3u) & ~size_t{3u}; out.width = width; out.height = height; out.bytes_per_line = dst_step; out.pixels.assign(dst_step * static_cast<size_t>(height), 0u); for (int y = 0; y < height; ++y) { const uint8_t* srow = src_bgr + static_cast<size_t>(y) * src_step; uint8_t* drow = out.pixels.data() + static_cast<size_t>(y) * dst_step; for (int x = 0; x < width; ++x) { const size_t off = static_cast<size_t>(x) * 3u; drow[off + 0u] = srow[off + 2u]; // R <- B_src[2] drow[off + 1u] = srow[off + 1u]; // G <- G_src[1] drow[off + 2u] = srow[off + 0u]; // B <- B_src[0] } } return true; } } // namespace ksa_v4l2solution: files/core.hpp
learner@ksa:~/gl-q04/lab-m01$ bat files/core.hpp File: files/core.hpp #ifndef GLQ04_M01_CORE_HPP #define GLQ04_M01_CORE_HPP #include <cstddef> #include <cstdint> #include <string> #include <vector> namespace ksa_v4l2 { constexpr uint32_t V4L2_CAP_VIDEO_CAPTURE = 0x00000001u; constexpr uint32_t V4L2_CAP_VIDEO_M2M = 0x00008000u; constexpr uint32_t V4L2_CAP_META_CAPTURE = 0x00800000u; constexpr uint32_t V4L2_CAP_STREAMING = 0x04000000u; constexpr uint32_t V4L2_CAP_DEVICE_CAPS = 0x80000000u; struct V4l2NodeDesc { int index = 0; std::string driver; std::string card; uint32_t capabilities = 0; uint32_t device_caps = 0; }; struct OwnedQImage { int width = 0; int height = 0; size_t bytes_per_line = 0; // Always 4-byte aligned: ((width * 3) + 3) & ~3 std::vector<uint8_t> pixels; const uint8_t* scan_line(int y) const { return pixels.data() + static_cast<size_t>(y) * bytes_per_line; } }; // Returns indices of real streaming capture cameras (rejecting M2M /dev/video0 and meta-only nodes). std::vector<int> select_capture_nodes(const std::vector<V4l2NodeDesc>& nodes); // Converts width*height YUYV 4:2:2 (width must be even, yuyv.size() >= width*height*2) into RGB888. bool convert_yuyv_to_rgb888(const uint8_t* yuyv, int width, int height, std::vector<uint8_t>& rgb_out); // Deep-copies a BGR888 source buffer with arbitrary src_step (>= width*3) into a 4-byte-row-aligned // RGB888 OwnedQImage whose storage remains valid after the caller frees src_bgr. bool bridge_bgr_mat_to_owned_qimage(const uint8_t* src_bgr, int width, int height, size_t src_step, OwnedQImage& out); } // namespace ksa_v4l2 #endifRun the check
From labs/lab_m01_opencv_v4l2_qimage/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-q04/lab-m01./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - filters V4L2_CAP_DEVICE_CAPS to accept streaming capture cameras and skip /dev/video0 M2M + meta nodesok 4 - converts packed YUYV 4:2:2 scanlines to RGB888 with [0, 255] BT.601 saturation and rejects odd widthsok 5 - bridges arbitrary-stride BGR888 ROIs into 4-byte-aligned RGB888 OwnedQImage buffers safely# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-q04/lab-m01./check.shTAP version 131..5not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticFAIL: fix compiler warnings or errors in files/core.cppok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - filters V4L2_CAP_DEVICE_CAPS to accept streaming capture cameras and skip /dev/video0 M2M + meta nodesok 4 - converts packed YUYV 4:2:2 scanlines to RGB888 with [0, 255] BT.601 saturation and rejects odd widthsok 5 - bridges arbitrary-stride BGR888 ROIs into 4-byte-aligned RGB888 OwnedQImage buffers safely# pass 4/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-q04/lab-m01$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM cp -R files "$WORK/files" printf 'TAP version 13\n1..5\n' if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' PASS=$((PASS + 1)) else printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' printf 'FAIL: fix compiler warnings or errors in files/core.cpp\n' fi if [ -f "$WORK/files/libcore.a" ] && g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2 -I"$WORK/files" tests.cpp "$WORK/files/libcore.a" -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' PASS=$((PASS + 1)) else printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' printf 'FAIL: preserve public declarations in files/core.hpp so tests.cpp links\n' fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then printf 'ok 3 - filters V4L2_CAP_DEVICE_CAPS to accept streaming capture cameras and skip /dev/video0 M2M + meta nodes\n' PASS=$((PASS + 1)) else printf 'not ok 3 - filters V4L2_CAP_DEVICE_CAPS to accept streaming capture cameras and skip /dev/video0 M2M + meta nodes\n' printf 'FAIL: check vcap.device_caps when V4L2_CAP_DEVICE_CAPS is set, require CAPTURE|STREAMING, and exclude V4L2_CAP_VIDEO_M2M\n' printf " ---\n message: 'got %s'\n hint: 'check vcap.device_caps when V4L2_CAP_DEVICE_CAPS is set, require CAPTURE|STREAMING, and exclude V4L2_CAP_VIDEO_M2M'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - converts packed YUYV 4:2:2 scanlines to RGB888 with [0, 255] BT.601 saturation and rejects odd widths\n' PASS=$((PASS + 1)) else printf 'not ok 4 - converts packed YUYV 4:2:2 scanlines to RGB888 with [0, 255] BT.601 saturation and rejects odd widths\n' printf 'FAIL: clamp integer BT.601 r, g, b values with std::clamp(val, 0, 255) before casting to uint8_t in convert_yuyv_to_rgb888\n' printf " ---\n message: 'got %s'\n hint: 'clamp integer BT.601 r, g, b values with std::clamp(val, 0, 255) before casting to uint8_t in convert_yuyv_to_rgb888'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - bridges arbitrary-stride BGR888 ROIs into 4-byte-aligned RGB888 OwnedQImage buffers safely\n' PASS=$((PASS + 1)) else printf 'not ok 5 - bridges arbitrary-stride BGR888 ROIs into 4-byte-aligned RGB888 OwnedQImage buffers safely\n' printf 'FAIL: advance source rows by src_step (not width*3) and swap BGR->RGB into 4-byte-aligned dst_step in bridge_bgr_mat_to_owned_qimage\n' printf " ---\n message: 'got %s'\n hint: 'advance source rows by src_step (not width*3) and swap BGR->RGB into 4-byte-aligned dst_step in bridge_bgr_mat_to_owned_qimage'\n ...\n" "${OUT:-build_failed}" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m01_opencv_v4l2_qimage/ so relative paths to files/ resolve directly.