From 2e0d363df25226be184b2c83b27b29dbe405eb57 Mon Sep 17 00:00:00 2001 From: yunjul Date: Wed, 25 Nov 2026 21:20:14 +0800 Subject: [PATCH 1/4] camera_streamer: support the S56C and SHF3L cameras Signed-off-by: yunjul --- .../argus_sender/CMakeLists.txt | 5 +- .../argus_sender/src/SiplCapture.cpp | 302 ++++++++++++++++-- 2 files changed, 284 insertions(+), 23 deletions(-) diff --git a/examples/camera_streamer/argus_sender/CMakeLists.txt b/examples/camera_streamer/argus_sender/CMakeLists.txt index 073e88dd53..afd765d19a 100644 --- a/examples/camera_streamer/argus_sender/CMakeLists.txt +++ b/examples/camera_streamer/argus_sender/CMakeLists.txt @@ -194,8 +194,10 @@ if(WITH_SIPL) find_library(NVSCIBUF_LIBRARY NAMES nvscibuf HINTS ${NVIDIA_LIBRARY_DIRS}) find_library(NVSCISYNC_LIBRARY NAMES nvscisync HINTS ${NVIDIA_LIBRARY_DIRS}) find_library(NVBUFSURFACE_NVSCI_LIBRARY NAMES nvbufsurface_nvsci HINTS ${NVIDIA_LIBRARY_DIRS}) + # The VIC converts a YUV camera's UYVY capture output to NV12 for the encoder. + find_library(NVBUFSURFTRANSFORM_LIBRARY NAMES nvbufsurftransform HINTS ${NVIDIA_LIBRARY_DIRS}) foreach(sipl_var SIPL_INCLUDE_DIR SIPL_QUERY_INCLUDE_DIR NVSCI_INCLUDE_DIR NVSIPL_LIBRARY NVSIPL_QUERY_LIBRARY - NVSCIBUF_LIBRARY NVSCISYNC_LIBRARY NVBUFSURFACE_NVSCI_LIBRARY) + NVSCIBUF_LIBRARY NVSCISYNC_LIBRARY NVBUFSURFACE_NVSCI_LIBRARY NVBUFSURFTRANSFORM_LIBRARY) if(NOT ${sipl_var}) message(FATAL_ERROR "WITH_SIPL=ON but ${sipl_var} was not found") endif() @@ -220,6 +222,7 @@ if(WITH_SIPL) ${NVSCISYNC_LIBRARY} ${NVBUFSURFACE_LIBRARY} ${NVBUFSURFACE_NVSCI_LIBRARY} + ${NVBUFSURFTRANSFORM_LIBRARY} Threads::Threads ) target_sources(argus_sender PRIVATE src/SiplSender.cpp) diff --git a/examples/camera_streamer/argus_sender/src/SiplCapture.cpp b/examples/camera_streamer/argus_sender/src/SiplCapture.cpp index e5305e925b..9dd97286e7 100644 --- a/examples/camera_streamer/argus_sender/src/SiplCapture.cpp +++ b/examples/camera_streamer/argus_sender/src/SiplCapture.cpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -// SIPL capture. The ISP0 surface is handed on as native NV12 and returned to SIPL when +// SIPL capture. A raw sensor's ISP0 surface is handed on as native NV12 and returned to SIPL when // the consumer drops its lease; there is no RGBA conversion. Needs C++17 because the SIPL headers do. #include "SiplCapture.h" @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -27,8 +28,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -212,6 +215,66 @@ std::vector flatten(const nvsipl::sensorconfig::SensorSystemCo return out; } +// Calls fn(sensor) for every sensor of the configuration; the nesting is the one `flatten` walks. +template +void forEachSensor(Config& config, Fn fn) +{ + for (auto& module : config.modules) + { + std::visit( + [&](auto& moduleType) + { + for (auto& sensorVariant : moduleType.sensorConfigs) + std::visit(fn, sensorVariant); + }, + module.moduleType); + } +} + +// Sensors that share a sensor group (a stereo pair) run as one SIPL pipeline group: the sensor with device index 0 +// is the primary, and the others take its ISP program and auto control. Returns the ids of those others. +std::set groupSecondaries(const nvsipl::sensorconfig::SensorSystemConfig& config) +{ + std::set out; + forEachSensor(config, + [&](const auto& sensor) + { + if (sensor.sensorGroup > 0 && sensor.deviceIndex > 0) + out.insert(sensor.id); + }); + return out; +} + +// A virtual channel with no Bayer order (cfa 0, which no NVSIPL_PIXEL_ORDER_* value is) belongs to a YUV camera with +// its own ISP. The query library leaves such a channel at its RAW12 default, which SIPL rejects at +// GetImageAttributes, so it is declared YUV422/UYVY before SetPlatformCfg. Returns the ids of the sensors corrected. +std::set declareYuv422Sensors(nvsipl::sensorconfig::SensorSystemConfig& config) +{ + std::set out; + forEachSensor(config, + [&](auto& sensor) + { + for (auto& vc : sensor.vcInfoList) + { + if (vc.cfa != 0) + continue; + vc.inputFormat = NVSIPL_CAP_INPUT_FORMAT_TYPE_YUV422; + vc.cfa = NVSIPL_PIXEL_ORDER_UYVY; + out.insert(sensor.id); + } + }); + return out; +} + +// One value of a reconciled buffer attribute list. +template +T attrValue(const NvSciBufAttrKeyValuePair& attr) +{ + if (attr.value == nullptr) + throw std::runtime_error("the capture buffer attributes lack a plane geometry key"); + return *static_cast(attr.value); +} + } // namespace std::vector querySiplCameras(const std::string& platformConfigJson, @@ -239,11 +302,20 @@ struct SiplCapture::Impl NvBufSurface* surface = nullptr; }; - // The newest frame the consumer has not taken. A frame replaced before it is taken goes straight back to SIPL. + // An NV12 picture converted from a YUV camera's capture output. Leased to the consumer like a SIPL buffer. + struct Nv12Out + { + NvBufSurface* surface = nullptr; + bool inUse = false; + }; + + // The newest frame the consumer has not taken. A frame replaced before it is taken goes straight back to its + // owner: SIPL for an ISP0 buffer, the sensor's NV12 pool for a converted picture (`nv12`; `buffer` is then null). struct Pending { INvSIPLClient::INvSIPLBuffer* buffer = nullptr; - const Slot* slot = nullptr; + Nv12Out* nv12 = nullptr; + const NvBufSurface* surface = nullptr; uint64_t sequence = 0; // The capture timestamp as a platform TSC in nanoseconds; 0 unless the mapping check passed. uint64_t sensorTscNs = 0; @@ -258,6 +330,11 @@ struct SiplCapture::Impl struct Sensor { CameraDescriptor info; + // In a sensor group without being its primary; see groupSecondaries. + bool groupSecondary = false; + // A YUV camera: pictures come from the capture output (ICP) as UYVY and are converted to NV12 by the VIC; + // the ISP is not used and there is no NITO. See declareYuv422Sensors. + bool yuvPassthrough = false; nvsipl::NvSIPLPipelineConfiguration pipelineConfig{}; nvsipl::NvSIPLPipelineQueues queues{}; NvSciBufAttrList bufAttrs = nullptr; @@ -266,6 +343,9 @@ struct SiplCapture::Impl NvSciBufAttrList icpAttrs = nullptr; std::vector icpBufObjects; std::vector slots; + // YUV cameras only: the NV12 pictures handed to the consumer. + std::vector nv12Pool; + bool nv12Starved = false; NvSciSyncObj syncObj = nullptr; // One wait context can wait on only one fence at a time, so each sensor's frame thread has its own. NvSciSyncCpuWaitContext cpuWaitContext = nullptr; @@ -337,11 +417,23 @@ struct SiplCapture::Impl throw std::runtime_error(failureMessage.empty() ? "SIPL capture failed" : failureMessage); } + // sensor.mutex held by the caller. + static void releasePending(Pending& pending) + { + if (pending.buffer) + pending.buffer->Release(); + if (pending.nv12) + pending.nv12->inUse = false; + pending.buffer = nullptr; + pending.nv12 = nullptr; + } + void configure(); void allocateBuffers(Sensor& sensor); void allocateIcpBuffers(Sensor& sensor); + void allocateYuvBuffers(Sensor& sensor); void registerBuffers(Sensor& sensor); - void allocateSync(Sensor& sensor); + void allocateSync(Sensor& sensor, INvSIPLClient::ConsumerDesc::OutputType output); void registerNito(Sensor& sensor); void frameLoop(Sensor& sensor); void eventLoop(Sensor& sensor); @@ -372,6 +464,10 @@ void SiplCapture::Impl::configure() throw std::runtime_error("no modules left in '" + config.platformConfigName + "' after applying the link masks; check the masks against the configuration"); + const std::set yuvSensors = declareYuv422Sensors(*systemConfig); + for (uint32_t id : yuvSensors) + std::fprintf(stderr, "[sipl] sensor %u: YUV422/UYVY camera, capture output converted to NV12 by the VIC\n", id); + descriptors = flatten(*systemConfig); if (descriptors.empty()) throw std::runtime_error("platform configuration '" + config.platformConfigName + "' declares no sensors"); @@ -381,21 +477,27 @@ void SiplCapture::Impl::configure() throw std::runtime_error("INvSIPLCamera::GetInstance returned null"); checkSipl(camera->SetPlatformCfg(*systemConfig), "SetPlatformCfg"); + const std::set secondaries = groupSecondaries(*systemConfig); for (const auto& info : descriptors) { std::unique_ptr sensor(new Sensor()); sensor->info = info; + sensor->groupSecondary = secondaries.count(info.id) != 0; + sensor->yuvPassthrough = yuvSensors.count(info.id) != 0; checkSci(NvSciSyncCpuWaitContextAlloc(syncModule, &sensor->cpuWaitContext), "NvSciSyncCpuWaitContextAlloc"); SensorClockMap::Config clockConfig; sensor->clockMap.reset(new SensorTimeMapper(counterHz, clockConfig, readCounterPair)); - // ISP0 only: ICP would double the capture bandwidth for a raw stream nothing here consumes. - sensor->pipelineConfig.captureOutputRequested = false; - sensor->pipelineConfig.isp0OutputRequested = true; + // ISP0 only for a raw sensor: ICP would double the capture bandwidth for a raw stream nothing here consumes. + // A YUV camera is the opposite: its capture output is the picture and the ISP cannot take it. + sensor->pipelineConfig.captureOutputRequested = sensor->yuvPassthrough; + sensor->pipelineConfig.isp0OutputRequested = !sensor->yuvPassthrough; sensor->pipelineConfig.isp1OutputRequested = false; sensor->pipelineConfig.isp2OutputRequested = false; // Subframe is enabled by default and then needs a slice count that is not set here. sensor->pipelineConfig.disableSubframe = true; sensor->pipelineConfig.bufferCfg.maxIsp0BufferCount = config.isp0Buffers; + if (sensor->yuvPassthrough) + sensor->pipelineConfig.bufferCfg.maxCaptureBufferCount = config.isp0Buffers; checkSipl(camera->SetPipelineCfg(info.id, sensor->pipelineConfig, sensor->queues), "SetPipelineCfg"); sensors.push_back(std::move(sensor)); } @@ -405,13 +507,26 @@ void SiplCapture::Impl::configure() // out of order, and the first Register call then fails with NVSIPL_STATUS_INVALID_STATE. for (auto& sensor : sensors) { + if (sensor->yuvPassthrough) + { + allocateYuvBuffers(*sensor); + allocateSync(*sensor, kIcp); + continue; + } allocateIcpBuffers(*sensor); allocateBuffers(*sensor); - allocateSync(*sensor); + allocateSync(*sensor, kIsp0); } checkSipl(camera->Init(), "INvSIPLCamera::Init"); for (auto& sensor : sensors) registerBuffers(*sensor); + // Auto control comes after every sensor's images: a group primary is refused with NVSIPL_STATUS_INVALID_STATE + // while its secondary has none registered. + for (auto& sensor : sensors) + { + if (!sensor->groupSecondary && !sensor->yuvPassthrough) + registerNito(*sensor); + } } void SiplCapture::Impl::allocateBuffers(Sensor& sensor) @@ -473,16 +588,102 @@ void SiplCapture::Impl::allocateIcpBuffers(Sensor& sensor) } } +// A YUV camera's capture output: UYVY buffers SIPL fills, each with an NvBufSurface view the VIC reads, and the NV12 +// pictures the VIC writes for the encoder. NvmmImageFillNvSciBufAttrList knows no UYVY, so the buffers are allocated +// from SIPL's attributes alone and each view is imported from the DMA-BUF and the reconciled geometry. +void SiplCapture::Impl::allocateYuvBuffers(Sensor& sensor) +{ + NvSciBufAttrList siplAttrs = nullptr; + NvSciBufAttrList conflict = nullptr; + checkSci(NvSciBufAttrListCreate(bufModule, &siplAttrs), "NvSciBufAttrListCreate icp"); + NvSciBufType bufType = NvSciBufType_Image; + NvSciBufAttrValAccessPerm perm = NvSciBufAccessPerm_ReadWrite; + NvSciBufAttrKeyValuePair kvp[] = { + { NvSciBufGeneralAttrKey_Types, &bufType, sizeof(bufType) }, + { NvSciBufGeneralAttrKey_RequiredPerm, &perm, sizeof(perm) }, + }; + checkSci(NvSciBufAttrListSetAttrs(siplAttrs, kvp, 2), "NvSciBufAttrListSetAttrs icp"); + checkSipl(camera->GetImageAttributes(sensor.info.id, kIcp, siplAttrs), "GetImageAttributes ICP"); + NvSciBufAttrList unreconciled[] = { siplAttrs }; + checkSci(NvSciBufAttrListReconcile(unreconciled, 1U, &sensor.bufAttrs, &conflict), "NvSciBufAttrListReconcile icp"); + NvSciBufAttrListFree(siplAttrs); + if (conflict) + NvSciBufAttrListFree(conflict); + + NvSciBufAttrKeyValuePair geometry[] = { + { NvSciBufImageAttrKey_PlaneCount, nullptr, 0 }, { NvSciBufImageAttrKey_PlaneWidth, nullptr, 0 }, + { NvSciBufImageAttrKey_PlaneHeight, nullptr, 0 }, { NvSciBufImageAttrKey_PlanePitch, nullptr, 0 }, + { NvSciBufImageAttrKey_PlaneOffset, nullptr, 0 }, { NvSciBufImageAttrKey_PlaneAlignedSize, nullptr, 0 }, + { NvSciBufImageAttrKey_Size, nullptr, 0 }, { NvSciBufImageAttrKey_Layout, nullptr, 0 }, + }; + checkSci(NvSciBufAttrListGetAttrs(sensor.bufAttrs, geometry, sizeof(geometry) / sizeof(geometry[0])), + "NvSciBufAttrListGetAttrs icp geometry"); + if (attrValue(geometry[0]) != 1) + throw std::runtime_error("expected one UYVY plane from the capture output"); + NvBufSurfaceMapParams map{}; + map.num_planes = 1; + map.gpuId = static_cast(config.gpuId); + map.memType = NVBUF_MEM_SURFACE_ARRAY; + map.scanformat = NVBUF_DISPLAYSCANFORMAT_PROGRESSIVE; + map.colorFormat = NVBUF_COLOR_FORMAT_UYVY; + map.planes[0].width = attrValue(geometry[1]); + map.planes[0].height = attrValue(geometry[2]); + map.planes[0].pitch = attrValue(geometry[3]); + map.planes[0].offset = static_cast(attrValue(geometry[4])); + map.planes[0].psize = static_cast(attrValue(geometry[5])); + map.totalSize = static_cast(attrValue(geometry[6])); + map.layout = attrValue(geometry[7]) == NvSciBufImage_PitchLinearType ? + NVBUF_LAYOUT_PITCH : + NVBUF_LAYOUT_BLOCK_LINEAR; + + sensor.slots.resize(config.isp0Buffers); + for (uint32_t i = 0; i < config.isp0Buffers; ++i) + { + Slot& slot = sensor.slots[i]; + checkSci(NvSciBufObjAlloc(sensor.bufAttrs, &slot.buf), "NvSciBufObjAlloc icp"); + sensor.bufObjects.push_back(slot.buf); + int fd = -1; + checkSci(NvSciBufObjGetDmaBufFd(slot.buf, &fd), "NvSciBufObjGetDmaBufFd"); + map.fd = static_cast(fd); + if (NvBufSurfaceImport(&slot.surface, &map) != 0 || slot.surface == nullptr) + throw std::runtime_error("NvBufSurfaceImport failed for a UYVY capture buffer"); + slot.surface->numFilled = 1; + } + + // Block-linear NV12 like the ISP0 path. The _709_ER tag asks the VIC to expand the camera's limited range, so + // every stream of a SIPL profile is full range as the consumers are told. + sensor.nv12Pool.resize(config.isp0Buffers); + for (Nv12Out& out : sensor.nv12Pool) + { + NvBufSurfaceAllocateParams alloc{}; + alloc.params.width = sensor.info.width; + alloc.params.height = sensor.info.height; + alloc.params.layout = NVBUF_LAYOUT_BLOCK_LINEAR; + alloc.params.colorFormat = NVBUF_COLOR_FORMAT_NV12_709_ER; + alloc.params.memType = NVBUF_MEM_SURFACE_ARRAY; + alloc.memtag = NvBufSurfaceTag_CAMERA; + if (NvBufSurfaceAllocate(&out.surface, 1, &alloc) != 0 || out.surface == nullptr) + throw std::runtime_error("NvBufSurfaceAllocate NV12 failed"); + out.surface->numFilled = 1; + } +} + void SiplCapture::Impl::registerBuffers(Sensor& sensor) { + if (sensor.yuvPassthrough) + { + checkSipl(camera->RegisterImages(sensor.info.id, kIcp, sensor.bufObjects), "RegisterImages ICP"); + checkSipl(camera->RegisterNvSciSyncObj(sensor.info.id, kIcp, nvsipl::NVSIPL_EOFSYNCOBJ, sensor.syncObj), + "RegisterNvSciSyncObj ICP"); + return; + } checkSipl(camera->RegisterImages(sensor.info.id, kIcp, sensor.icpBufObjects), "RegisterImages ICP"); checkSipl(camera->RegisterImages(sensor.info.id, kIsp0, sensor.bufObjects), "RegisterImages ISP0"); checkSipl(camera->RegisterNvSciSyncObj(sensor.info.id, kIsp0, nvsipl::NVSIPL_EOFSYNCOBJ, sensor.syncObj), "RegisterNvSciSyncObj"); - registerNito(sensor); } -void SiplCapture::Impl::allocateSync(Sensor& sensor) +void SiplCapture::Impl::allocateSync(Sensor& sensor, INvSIPLClient::ConsumerDesc::OutputType output) { NvSciSyncAttrList signaler = nullptr; NvSciSyncAttrList waiter = nullptr; @@ -499,8 +700,8 @@ void SiplCapture::Impl::allocateSync(Sensor& sensor) { NvSciSyncAttrKey_RequiredPerm, &perm, sizeof(perm) }, }; checkSci(NvSciSyncAttrListSetAttrs(waiter, kvp, 2), "NvSciSyncAttrListSetAttrs"); - checkSipl( - camera->FillNvSciSyncAttrList(sensor.info.id, kIsp0, signaler, nvsipl::SIPL_SIGNALER), "FillNvSciSyncAttrList"); + checkSipl(camera->FillNvSciSyncAttrList(sensor.info.id, output, signaler, nvsipl::SIPL_SIGNALER), + "FillNvSciSyncAttrList"); NvSciSyncAttrList unreconciled[] = { signaler, waiter }; checkSci(NvSciSyncAttrListReconcile(unreconciled, 2U, &reconciled, &conflict), "NvSciSyncAttrListReconcile"); @@ -526,7 +727,7 @@ void SiplCapture::Impl::dropPending(Sensor& sensor) std::lock_guard guard(sensor.mutex); if (sensor.hasPending) { - sensor.pending.buffer->Release(); + releasePending(sensor.pending); sensor.hasPending = false; } } @@ -535,10 +736,20 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) { try { + nvsipl::INvSIPLFrameCompletionQueue* queue = + sensor.yuvPassthrough ? sensor.queues.captureCompletionQueue : sensor.queues.isp0CompletionQueue; + if (sensor.yuvPassthrough) + { + // Transform session parameters are per thread. + NvBufSurfTransformConfigParams session{}; + session.compute_mode = NvBufSurfTransformCompute_VIC; + if (NvBufSurfTransformSetSessionParams(&session) != NvBufSurfTransformError_Success) + throw std::runtime_error("NvBufSurfTransformSetSessionParams failed"); + } while (running.load()) { INvSIPLClient::INvSIPLBuffer* buffer = nullptr; - const SIPLStatus status = sensor.queues.isp0CompletionQueue->Get(buffer, config.frameTimeoutMs * 1000U); + const SIPLStatus status = queue->Get(buffer, config.frameTimeoutMs * 1000U); if (status == nvsipl::NVSIPL_STATUS_TIMED_OUT) continue; if (status == nvsipl::NVSIPL_STATUS_EOF) @@ -571,11 +782,45 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) } } if (!slot) - throw std::runtime_error("ISP0 delivered a buffer this process never registered"); + throw std::runtime_error("SIPL delivered a buffer this process never registered"); Pending next; next.buffer = buffer; - next.slot = slot; + next.surface = slot->surface; + if (sensor.yuvPassthrough) + { + Nv12Out* out = nullptr; + { + std::lock_guard guard(sensor.mutex); + for (Nv12Out& candidate : sensor.nv12Pool) + { + if (!candidate.inUse) + { + candidate.inUse = true; + out = &candidate; + break; + } + } + } + // Every NV12 picture pending or with the encoder: this capture goes back to SIPL unconverted. + if (!out && !sensor.nv12Starved) + std::fprintf(stderr, "[sipl] sensor %u: no free NV12 picture, dropping\n", sensor.info.id); + sensor.nv12Starved = !out; + if (!out) + continue; + // Same size, whole picture: a format conversion only. The call returns when the VIC has written. + NvBufSurfTransformParams transform{}; + if (NvBufSurfTransform(slot->surface, out->surface, &transform) != NvBufSurfTransformError_Success) + { + std::lock_guard guard(sensor.mutex); + out->inUse = false; + throw std::runtime_error("NvBufSurfTransform UYVY to NV12 failed"); + } + // The consumer gets the NV12 picture; `owned` returns the capture buffer to SIPL. + next.buffer = nullptr; + next.nv12 = out; + next.surface = out->surface; + } // The capture counter in the SIPL clock domain, unscaled: the start-of-frame value, not end-of-frame. next.readyMonotonicNs = monotonicNs(); // The start-of-frame value counts the platform counter's ticks (measured against CNTVCT_EL0 on the board); @@ -608,12 +853,13 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) { std::lock_guard guard(sensor.mutex); if (sensor.hasPending) - sensor.pending.buffer->Release(); + releasePending(sensor.pending); next.sequence = ++sensor.received; sensor.pending = next; sensor.hasPending = true; - // `pending` owns the buffer now, and its release path (a replacement or stop) takes over. - owned.dismiss(); + // `pending` owns the SIPL buffer now, and its release path (a replacement or stop) takes over. + if (next.buffer) + owned.dismiss(); } std::lock_guard wakeGuard(wakeMutex); wake.notify_all(); @@ -694,6 +940,12 @@ void SiplCapture::Impl::cleanup() } sensor->slots.clear(); sensor->bufObjects.clear(); + for (Nv12Out& out : sensor->nv12Pool) + { + if (out.surface) + NvBufSurfaceDestroy(out.surface); + } + sensor->nv12Pool.clear(); for (NvSciBufObj obj : sensor->icpBufObjects) NvSciBufObjFree(obj); sensor->icpBufObjects.clear(); @@ -815,7 +1067,7 @@ bool SiplCapture::acquireLatest(uint32_t cameraId, CaptureFrame* frame) sensor->hasPending = false; } - const NvBufSurfaceParams& params = taken.slot->surface->surfaceList[0]; + const NvBufSurfaceParams& params = taken.surface->surfaceList[0]; CaptureFrame out; out.cameraId = cameraId; out.sessionEpoch = m_impl->config.sessionEpoch; @@ -839,9 +1091,15 @@ bool SiplCapture::acquireLatest(uint32_t cameraId, CaptureFrame* frame) out.surface.offsetBytes[plane] = params.planeParams.offset[plane]; } out.surface.blockLinear = params.layout == NVBUF_LAYOUT_BLOCK_LINEAR; + // ISP0 writes BT.709 extended range; a YUV camera's picture is converted to the same by the VIC. out.surface.colorRange = COLOR_RANGE_FULL; - INvSIPLClient::INvSIPLBuffer* buffer = taken.buffer; - out.lease = FrameLease([buffer]() { buffer->Release(); }); + Impl::Pending held = taken; + out.lease = FrameLease( + [sensor, held]() mutable + { + std::lock_guard guard(sensor->mutex); + Impl::releasePending(held); + }); *frame = std::move(out); return true; } From 998a70e59c4c6ed0b8d0ad0b7720d566c242b1b2 Mon Sep 17 00:00:00 2001 From: yunjul Date: Wed, 25 Nov 2026 21:20:24 +0800 Subject: [PATCH 2/4] egocap: start an S56C + 2x SHF3L camera rig Signed-off-by: yunjul --- examples/egocap/CAMERA_SETTINGS.md | 6 +- .../egocap/tests/tools/test_start_system.py | 71 ++++++--- examples/egocap/tools/start_system.py | 141 ++++++++++-------- 3 files changed, 137 insertions(+), 81 deletions(-) diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index 4bbde3eaf4..3e049c6436 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -31,8 +31,10 @@ camera on the SIPL backend: HEVC at 30 fps and 4 Mbit/s. The file is specific to that rig. A different SIPL platform or camera changes the `sipl` block (platform file, config name, link masks, tuning directory) and possibly the stream id and size. The Argus backend has no `sipl` block: it selects a sensor mode with `cameras[].mode`, can set `capture.mode` and `alignment`, enforces `output.fps` with a rate -limiter and can set output dimensions. Keep one file per rig and pass the right one with `--sender-config`. The launcher itself supports one stream per -file and requires an explicit `output.fps`. +limiter and can set output dimensions. Keep one file per rig and pass the right one with `--sender-config`. The launcher itself supports +mono streams only: each becomes one receiver stream and one LiveKit track named `sensing-`. The streams share one +explicit `output.fps`; a stream whose sensor size differs from `--width`/`--height` sets its own `output.width` and +`output.height`. `--fps` and `--bitrate-mbps` apply to every stream. `tools/start_system.py` loads this file by default. Command-line overrides (`--fps`, `--bitrate-mbps`, `--sender-port`) are applied to the loaded mapping, and the result is what is uploaded. The same diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index 1faa14fceb..bf7f0ed3ce 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -53,11 +53,11 @@ def test_publisher_token_is_a_verifiable_hs256_jwt(): def test_generated_configs_parse_and_carry_parameters(): - streams = yaml.safe_load(ss.streams_yaml("ws://h:1", "r", "p", "trk", 640, 480, 30, "b", "head")) + streams = yaml.safe_load(ss.streams_yaml("ws://h:1", "r", "p", [("head", 640, 480)], 30, "b")) stream = streams["livekit"]["streams"][0] - assert (stream["track"], stream["width"], stream["height"]) == ("trk", 640, 480) + assert (stream["track"], stream["width"], stream["height"]) == ("sensing-head", 640, 480) - receiver = yaml.safe_load(ss.receiver_yaml("h", 5555, "/tmp/s.sock", 640, 480, "head")) + receiver = yaml.safe_load(ss.receiver_yaml("h", 5555, "/tmp/s.sock", [("head", 640, 480)])) assert receiver["receiver"]["port"] == 5555 assert (receiver["streams"][0]["width"], receiver["streams"][0]["height"]) == (640, 480) @@ -172,7 +172,7 @@ def record_start(self, name, command, *_, **__): def test_default_profile_gives_the_head_camera_settings(): config = ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG) assert ss.sender_settings(config) == ss.SenderSettings( - port=5000, fps=30, bitrate_mbps=4, stream_id="head", full_range=True, sipl=True + port=5000, fps=30, bitrate_mbps=4, stream_ids=("head",), full_range=True, sipl=True, sizes=((None, None),) ) @@ -185,7 +185,7 @@ def test_argus_backend_is_not_full_range(): def test_overrides_replace_only_their_values(): config = ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG, 60, 9, 5100) assert ss.sender_settings(config) == ss.SenderSettings( - port=5100, fps=60, bitrate_mbps=9, stream_id="head", full_range=True, sipl=True + port=5100, fps=60, bitrate_mbps=9, stream_ids=("head",), full_range=True, sipl=True, sizes=((None, None),) ) partial = ss.sender_settings(ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG, fps=15)) assert (partial.fps, partial.bitrate_mbps, partial.port) == (15, 4, 5000) @@ -209,13 +209,13 @@ def test_sender_settings_rejects_an_incomplete_profile(mutate): ss.sender_settings(config) -def test_load_sender_config_rejects_missing_file_and_two_streams(tmp_path: Path): +def test_load_sender_config_rejects_missing_file_and_no_streams(tmp_path: Path): with pytest.raises(ss.StartupError): ss.load_sender_config(tmp_path / "absent.yaml") - two = tmp_path / "two.yaml" - two.write_text("streams:\n - {id: a}\n - {id: b}\n") + empty = tmp_path / "empty.yaml" + empty.write_text("streams: []\n") with pytest.raises(ss.StartupError): - ss.load_sender_config(two) + ss.load_sender_config(empty) def _profile_with(tmp_path: Path, mutate) -> Path: @@ -441,7 +441,7 @@ def interrupted_wait(*args, **kwargs): def test_mock_sender_command_follows_the_profile(): settings = ss.sender_settings(ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG)) - command = ss.mock_sender_command("python", Path("mock.py"), settings, 2560, 1984) + command = ss.mock_sender_command("python", Path("mock.py"), settings, [("head", 2560, 1984)]) assert command == ["python", "mock.py", "--port", "5000", "--stream", "head:2560x1984@30"] @@ -1046,29 +1046,64 @@ def test_load_sender_config_refuses_a_stream_that_is_not_mono(tmp_path: Path): ss.load_sender_config(_profile_with(tmp_path, _stereo_profile)) +def _head_and_wrist(config: dict) -> None: + head = config["streams"][0] + wrist = {**head, "id": "wrist", "output": {**head["output"], "width": 1920, "height": 1536}} + config["streams"] = [head, wrist] + + +def test_streams_keep_their_own_sizes_and_must_share_the_rate(tmp_path: Path): + config = ss.load_sender_config(_profile_with(tmp_path, _head_and_wrist), bitrate_mbps=6) + settings = ss.sender_settings(config) + assert (settings.stream_ids, settings.bitrate_mbps) == (("head", "wrist"), 12) + assert settings.sizes == ((None, None), (1920, 1536)) + config["streams"][1]["output"]["fps"] = 60 + with pytest.raises(ss.StartupError, match="share"): + ss.sender_settings(config) + + +def test_main_carries_every_stream_at_its_own_size(recorded_main, tmp_path: Path): + mock_sender = tmp_path / "mock_sender.py" + mock_sender.write_text("") + argv = ["--mock", "--bridge", "b", "--livekit-server", "l", "--mock-sender", str(mock_sender)] + assert ss.main([*argv, "--sender-config", str(_profile_with(tmp_path, _head_and_wrist))]) == 0 + assert "--stream head:2560x1984@30 --stream wrist:1920x1536@30" in _command(recorded_main, "mock-sender") + assert "--stream head=sensing-head:2 --stream wrist=sensing-wrist:2" in _command(recorded_main, "bridge") + received = yaml.safe_load((recorded_main.workdir / "receiver.yaml").read_text())["streams"] + assert [(r["index"], r["name"], r["width"], r["height"]) for r in received] == [ + (0, "head", 2560, 1984), + (1, "wrist", 1920, 1536), + ] + declared = yaml.safe_load((recorded_main.workdir / "streams.yaml").read_text())["livekit"]["streams"] + assert [(d["name"], d["track"], d["width"], d["height"]) for d in declared] == [ + ("head", "sensing-head", 1280, 992), + ("wrist", "sensing-wrist", 960, 768), + ] + + def test_frame_size_defaults_to_the_sensor_size_and_follows_the_flags(): settings = ss.sender_settings(ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG)) - assert ss.frame_size(settings, None, None) == (2560, 1984) - assert ss.frame_size(settings, 640, 480) == (640, 480) + assert ss.frame_size(settings.sizes[0], None, None) == (2560, 1984) + assert ss.frame_size(settings.sizes[0], 640, 480) == (640, 480) with pytest.raises(ss.StartupError, match="divide"): - ss.frame_size(settings, 641, 480) + ss.frame_size(settings.sizes[0], 641, 480) def test_frame_size_follows_the_profile_and_refuses_contradicting_flags(tmp_path: Path): config = yaml.safe_load(_profile_with(tmp_path, _sized(1280, 960)).read_text()) settings = ss.sender_settings(config) - assert ss.frame_size(settings, None, None) == (1280, 960) - assert ss.frame_size(settings, 1280, 960) == (1280, 960) + assert ss.frame_size(settings.sizes[0], None, None) == (1280, 960) + assert ss.frame_size(settings.sizes[0], 1280, 960) == (1280, 960) with pytest.raises(ss.StartupError, match="--width 2560 contradicts"): - ss.frame_size(settings, 2560, None) + ss.frame_size(settings.sizes[0], 2560, None) with pytest.raises(ss.StartupError, match="--height"): - ss.frame_size(settings, None, 1984) + ss.frame_size(settings.sizes[0], None, 1984) def test_frame_size_refuses_a_profile_that_sets_only_one_dimension(tmp_path: Path): config = ss.load_sender_config(_profile_with(tmp_path, _sized(1280, None))) with pytest.raises(ss.StartupError, match="both"): - ss.frame_size(ss.sender_settings(config), None, None) + ss.frame_size(ss.sender_settings(config).sizes[0], None, None) def test_main_writes_the_profile_output_size_into_the_receiver_and_the_descriptor(recorded_main, tmp_path: Path): diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index cdbac17e43..dd53349a91 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -116,10 +116,15 @@ def publisher_token(key: str, secret: str, room: str, identity: str, hours: int return f"{header}.{body}.{signature}" +def stream_track(name: str) -> str: + """The LiveKit track the bridge publishes the sender stream ``name`` on.""" + return f"sensing-{name}" + + def streams_yaml( - url: str, room: str, publisher: str, track: str, width: int, height: int, fps: int, basis: str, name: str + url: str, room: str, publisher: str, streams: Sequence[tuple[str, int, int]], fps: int, basis: str ) -> str: - """The CaptureServer ``--livekit-streams`` file for one camera published by the bridge.""" + """The CaptureServer ``--livekit-streams`` file: one (name, width, height) per stream the bridge publishes.""" # Dumped from a mapping because the stream name comes from a user-edited profile. descriptor = { "livekit": { @@ -127,14 +132,17 @@ def streams_yaml( "room": room, "publisher": publisher, "timestamp_basis": basis, - "streams": [{"name": name, "track": track, "width": width, "height": height, "fps": fps}], + "streams": [ + {"name": name, "track": stream_track(name), "width": width, "height": height, "fps": fps} + for name, width, height in streams + ], } } return yaml.safe_dump(descriptor, sort_keys=False) -def receiver_yaml(host: str, port: int, socket_path: str, width: int, height: int, name: str) -> str: - """The camera receiver's config: connect to the sender and expose one mono stream over CUDA IPC.""" +def receiver_yaml(host: str, port: int, socket_path: str, streams: Sequence[tuple[str, int, int]]) -> str: + """The camera receiver's config: connect to the sender and expose each (name, width, height) mono stream.""" config = { "version": 1, "receiver": { @@ -147,7 +155,7 @@ def receiver_yaml(host: str, port: int, socket_path: str, width: int, height: in "ipc": {"socket_path": socket_path, "owner_name": "egocap_start_system", "queue_size": 1024}, "streams": [ { - "index": 0, + "index": index, "name": name, "type": "mono", "width": width, @@ -156,6 +164,7 @@ def receiver_yaml(host: str, port: int, socket_path: str, width: int, height: in "ring_depth": 6, "ipc": {"mono": name}, } + for index, (name, width, height) in enumerate(streams) ], } return yaml.safe_dump(config, sort_keys=False) @@ -168,12 +177,11 @@ class SenderSettings: port: int fps: int bitrate_mbps: int - stream_id: str + stream_ids: tuple[str, ...] full_range: bool sipl: bool - # The profile's output size; None leaves the sensor mode's native size, which --width and --height describe. - width: int | None = None - height: int | None = None + # Each stream's output size; None leaves the sensor mode's native size, which --width and --height describe. + sizes: tuple[tuple[int | None, int | None], ...] def _section(parent: dict, key: str, path: Path) -> dict: @@ -201,21 +209,21 @@ def load_sender_config( config = yaml.safe_load(path.read_text()) except (OSError, yaml.YAMLError) as error: raise StartupError(f"cannot read the sender config {path}: {error}; pass --sender-config") from error - if not isinstance(config, dict) or not isinstance(config.get("streams"), list) or len(config["streams"]) != 1: - raise StartupError(f"{path}: the launcher supports exactly one stream in the sender config") - stream = config["streams"][0] - if not isinstance(stream, dict): - raise StartupError(f"{path}: streams[0] must be a mapping") - # The receiver stream the launcher writes is mono, so another type would deploy a sender it cannot receive. - if stream.get("type") != "mono": - raise StartupError(f"{path}: the launcher supports only a mono stream, got type {stream.get('type')!r}") + if not isinstance(config, dict) or not isinstance(config.get("streams"), list) or not config["streams"]: + raise StartupError(f"{path}: the sender config needs at least one stream") network = _section(config, "network", path) - output = _section(stream, "output", path) - # An override replaces the profile's value; the profile stays the source of everything else. - if fps is not None: - output["fps"] = fps - if bitrate_mbps is not None: - output["bitrate_mbps"] = bitrate_mbps + for index, stream in enumerate(config["streams"]): + if not isinstance(stream, dict): + raise StartupError(f"{path}: streams[{index}] must be a mapping") + # The receiver stream the launcher writes is mono, so another type would deploy a sender it cannot receive. + if stream.get("type") != "mono": + raise StartupError(f"{path}: the launcher supports only mono streams, got {stream.get('type')!r}") + output = _section(stream, "output", path) + # An override replaces the profile's value; the profile stays the source of everything else. + if fps is not None: + output["fps"] = fps + if bitrate_mbps is not None: + output["bitrate_mbps"] = bitrate_mbps if sender_port is not None: network["port"] = sender_port return config @@ -224,29 +232,32 @@ def load_sender_config( def sender_settings(config: dict) -> SenderSettings: """The values other components need from a loaded sender config, refusing one that cannot give a latency.""" network = config.get("network", {}) - stream = config["streams"][0] - output = stream.get("output", {}) + streams = config["streams"] + outputs = [stream.get("output", {}) for stream in streams] # The deploy builds the SIPL backend only for a SIPL profile, and the bridge's range flag follows the backend, # so neither may be guessed from an `auto` or missing value. if config.get("capture_backend") not in ("sipl", "argus"): raise StartupError("the sender config must set capture_backend to sipl or argus") - if not stream.get("id"): - raise StartupError("the sender config must set streams[0].id") - # The bridge and the descriptor need a number, and a native-rate profile (fps 0) has none until runtime. - if not output.get("fps"): - raise StartupError( - "the sender config must set streams[0].output.fps; the bridge and descriptor need a rate" - ) + for index, stream in enumerate(streams): + if not stream.get("id"): + raise StartupError(f"the sender config must set streams[{index}].id") + # The bridge and the descriptor need a number, and a native-rate profile (fps 0) has none until runtime. + if not outputs[index].get("fps"): + raise StartupError( + f"the sender config must set streams[{index}].output.fps; the bridge and descriptor need a rate" + ) + # The bridge takes one rate for every stream. + if len({output["fps"] for output in outputs}) != 1: + raise StartupError("every stream in the sender config must share one output.fps") return SenderSettings( port=int(network.get("port", 5000)), - fps=int(output["fps"]), - bitrate_mbps=int(output.get("bitrate_mbps", 0)), - stream_id=str(stream["id"]), + fps=int(outputs[0]["fps"]), + bitrate_mbps=sum(int(output.get("bitrate_mbps", 0)) for output in outputs), + stream_ids=tuple(str(stream["id"]) for stream in streams), # SIPL produces full-range pictures; the bridge must say so or the encoded stream signals limited range. full_range=config["capture_backend"] == "sipl", sipl=config["capture_backend"] == "sipl", - width=_output_dimension(output, "width"), - height=_output_dimension(output, "height"), + sizes=tuple((_output_dimension(o, "width"), _output_dimension(o, "height")) for o in outputs), ) @@ -256,13 +267,13 @@ def _output_dimension(output: dict, key: str) -> int | None: return None if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise StartupError( - f"the sender config's streams[0].output.{key} must be a positive integer, got {value!r}" + f"the sender config's streams[*].output.{key} must be a positive integer, got {value!r}" ) return value -def frame_size(settings: SenderSettings, width: int | None, height: int | None) -> tuple[int, int]: - """The picture size the sender delivers: the profile's output size when it sets one, else the sensor's. +def frame_size(profile: tuple[int | None, int | None], width: int | None, height: int | None) -> tuple[int, int]: + """The picture size of one stream: the profile's output size when it sets one, else the sensor's. The receiver, the bridge and the descriptor all follow this, so a profile that resizes its output cannot disagree with them. A --width or --height that contradicts the profile is refused. @@ -270,13 +281,13 @@ def frame_size(settings: SenderSettings, width: int | None, height: int | None) for name, flag in (("--width", width), ("--height", height)): if flag is not None and flag <= 0: raise StartupError(f"{name} must be positive, got {flag}") - if (settings.width is None) != (settings.height is None): - raise StartupError("the sender config must set both streams[0].output.width and height, or neither") - if settings.width is not None: - for name, flag, value in (("--width", width, settings.width), ("--height", height, settings.height)): + if (profile[0] is None) != (profile[1] is None): + raise StartupError("the sender config must set both streams[*].output.width and height, or neither") + if profile[0] is not None: + for name, flag, value in (("--width", width, profile[0]), ("--height", height, profile[1])): if flag is not None and flag != value: raise StartupError(f"{name} {flag} contradicts the sender config's output size {value}") - size = (settings.width, settings.height) + size = profile else: size = (width or DEFAULT_SENSOR_WIDTH, height or DEFAULT_SENSOR_HEIGHT) if size[0] % (2 * BRIDGE_DOWNSCALE) or size[1] % (2 * BRIDGE_DOWNSCALE): @@ -284,15 +295,20 @@ def frame_size(settings: SenderSettings, width: int | None, height: int | None) return size -def mock_sender_command(python: str, script: Path, settings: SenderSettings, width: int, height: int) -> list[str]: - """The local mock sender that stands in for the Orin: one HEVC stream shaped like the real one.""" +def mock_sender_command( + python: str, script: Path, settings: SenderSettings, streams: Sequence[tuple[str, int, int]] +) -> list[str]: + """The local mock sender that stands in for the Orin: HEVC streams shaped like the real ones.""" return [ python, str(script), "--port", str(settings.port), - "--stream", - f"{settings.stream_id}:{width}x{height}@{settings.fps}", + *( + arg + for name, width, height in streams + for arg in ("--stream", f"{name}:{width}x{height}@{settings.fps}") + ), ] @@ -706,7 +722,7 @@ def main(argv: Sequence[str] | None = None) -> int: """Bring the stack up in dependency order, print how to use it, then wait until interrupted.""" args = parse_args(argv) orin_host = args.orin.rsplit("@", 1)[-1] if args.orin else None - room, publisher, track = "egocap-room", "egocap-bridge", "sensing-head" + room, publisher = "egocap-room", "egocap-bridge" livekit_url = "ws://127.0.0.1:7880" workdir = Path(tempfile.mkdtemp(prefix="egocap-start-")) ipc_socket = str(workdir / "camera_receiver.sock") @@ -739,7 +755,10 @@ def main(argv: Sequence[str] | None = None) -> int: # One loaded profile is the source for the sender, the receiver, the bridge and the descriptor. sender_config = load_sender_config(args.sender_config, args.fps, args.bitrate_mbps, args.sender_port) sender = sender_settings(sender_config) - width, height = frame_size(sender, args.width, args.height) + streams = [ + (name, *frame_size(size, args.width, args.height)) + for name, size in zip(sender.stream_ids, sender.sizes, strict=True) + ] # The bridge identifies the Orin's chrony by the reference id of its IPv4 address. if args.orin: try: @@ -752,19 +771,16 @@ def main(argv: Sequence[str] | None = None) -> int: livekit_url, room, publisher, - track, - width // BRIDGE_DOWNSCALE, - height // BRIDGE_DOWNSCALE, + [(name, width // BRIDGE_DOWNSCALE, height // BRIDGE_DOWNSCALE) for name, width, height in streams], sender.fps, basis, - sender.stream_id, ) ) (workdir / "receiver.yaml").write_text( - receiver_yaml(orin_host or "127.0.0.1", sender.port, ipc_socket, width, height, sender.stream_id) + receiver_yaml(orin_host or "127.0.0.1", sender.port, ipc_socket, streams) ) if args.mock: - print(f"mock sender: {sender.fps} fps stream {sender.stream_id!r}, timestamps are frame-ready time") + print(f"mock sender: {sender.fps} fps streams {sender.stream_ids}, timestamps are frame-ready time") else: print( f"sender config {args.sender_config}: {sender.fps} fps, {sender.bitrate_mbps} Mbit/s, " @@ -831,7 +847,7 @@ def main(argv: Sequence[str] | None = None) -> int: mock_sender = None if chain and args.mock: mock_sender = stack.start( - "mock-sender", mock_sender_command(python, args.mock_sender, sender, width, height) + "mock-sender", mock_sender_command(python, args.mock_sender, sender, streams) ) # 2. LiveKit carries the video from the bridge to the browser and the recorder. if args.livekit_server: @@ -900,8 +916,11 @@ def main(argv: Sequence[str] | None = None) -> int: str(token_file), "--socket", ipc_socket, - "--stream", - f"{sender.stream_id}={track}:{BRIDGE_DOWNSCALE}", + *( + arg + for name in sender.stream_ids + for arg in ("--stream", f"{name}={stream_track(name)}:{BRIDGE_DOWNSCALE}") + ), "--fps", str(sender.fps), *bridge_timing_arguments( From bbb1b2e10d6a9be60a0e07f1147fadaeb47082b6 Mon Sep 17 00:00:00 2001 From: yunjul Date: Thu, 26 Nov 2026 16:06:16 +0800 Subject: [PATCH 3/4] camera_streamer, egocap: address review of the S56C + SHF3L support Signed-off-by: yunjul --- .../argus_sender/src/Config.cpp | 8 +- .../camera_streamer/argus_sender/src/Config.h | 2 + .../argus_sender/src/SiplCapture.cpp | 118 ++++++++++++------ .../argus_sender/src/SiplCapture.h | 7 +- .../argus_sender/src/SiplSender.cpp | 1 + .../argus_sender/tests/test_config.cpp | 4 + examples/egocap/CAMERA_SETTINGS.md | 7 +- .../egocap/tests/tools/test_start_system.py | 24 +++- examples/egocap/tools/start_system.py | 26 ++-- 9 files changed, 140 insertions(+), 57 deletions(-) diff --git a/examples/camera_streamer/argus_sender/src/Config.cpp b/examples/camera_streamer/argus_sender/src/Config.cpp index 663ee249e4..da714fe2b6 100644 --- a/examples/camera_streamer/argus_sender/src/Config.cpp +++ b/examples/camera_streamer/argus_sender/src/Config.cpp @@ -320,14 +320,16 @@ bool loadConfigFile(const std::string& path, AppConfig* config, std::string* err if (root["sipl"]) { const YAML::Node sipl = root["sipl"]; - const std::set allowed = { "platform_config_json", "platform_config_name", "link_masks", - "nito_dir", "isp0_buffers" }; + const std::set allowed = { "platform_config_json", "platform_config_name", + "link_masks", "nito_dir", + "isp0_buffers", "yuv_cameras" }; if (!rejectUnknown(sipl, allowed, "sipl", error) || !readOptional(sipl, "platform_config_json", "sipl", &config->sipl.platformConfigJson, error) || !readOptional(sipl, "platform_config_name", "sipl", &config->sipl.platformConfigName, error) || !readOptional(sipl, "link_masks", "sipl", &config->sipl.linkMasks, error) || !readOptional(sipl, "nito_dir", "sipl", &config->sipl.nitoDir, error) || - !readUint32(sipl, "isp0_buffers", "sipl", &config->sipl.isp0Buffers, error)) + !readUint32(sipl, "isp0_buffers", "sipl", &config->sipl.isp0Buffers, error) || + !readOptional(sipl, "yuv_cameras", "sipl", &config->sipl.yuvCameras, error)) { return false; } diff --git a/examples/camera_streamer/argus_sender/src/Config.h b/examples/camera_streamer/argus_sender/src/Config.h index f32e072b77..7ea8936c3e 100644 --- a/examples/camera_streamer/argus_sender/src/Config.h +++ b/examples/camera_streamer/argus_sender/src/Config.h @@ -126,6 +126,8 @@ struct SiplSettings std::vector linkMasks; std::string nitoDir = "/var/nvidia/nvcam/settings/sipl"; uint32_t isp0Buffers = 6; + // Pipeline indexes of the YUV422/UYVY cameras, which bypass the ISP. + std::vector yuvCameras; }; struct AppConfig diff --git a/examples/camera_streamer/argus_sender/src/SiplCapture.cpp b/examples/camera_streamer/argus_sender/src/SiplCapture.cpp index 9dd97286e7..af121c3297 100644 --- a/examples/camera_streamer/argus_sender/src/SiplCapture.cpp +++ b/examples/camera_streamer/argus_sender/src/SiplCapture.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -215,7 +216,7 @@ std::vector flatten(const nvsipl::sensorconfig::SensorSystemCo return out; } -// Calls fn(sensor) for every sensor of the configuration; the nesting is the one `flatten` walks. +// Calls fn(module, sensor) for every sensor of the configuration; the nesting is the one `flatten` walks. template void forEachSensor(Config& config, Fn fn) { @@ -225,45 +226,68 @@ void forEachSensor(Config& config, Fn fn) [&](auto& moduleType) { for (auto& sensorVariant : moduleType.sensorConfigs) - std::visit(fn, sensorVariant); + std::visit([&](auto& sensor) { fn(module, sensor); }, sensorVariant); }, module.moduleType); } } -// Sensors that share a sensor group (a stereo pair) run as one SIPL pipeline group: the sensor with device index 0 -// is the primary, and the others take its ISP program and auto control. Returns the ids of those others. -std::set groupSecondaries(const nvsipl::sensorconfig::SensorSystemConfig& config) +// Sensors of one module that share a sensor group (a stereo pair) run as one SIPL pipeline group: the one with the +// lowest device index is the primary, and the others take its ISP program and auto control. Group numbers repeat +// across modules, and independent cameras all leave theirs at 0. Returns each grouped sensor's id and whether it is +// the primary. +std::map groupedSensors(const nvsipl::sensorconfig::SensorSystemConfig& config) { - std::set out; + // (module, sensor group) -> device index -> sensor id + std::map, std::map> groups; forEachSensor(config, - [&](const auto& sensor) - { - if (sensor.sensorGroup > 0 && sensor.deviceIndex > 0) - out.insert(sensor.id); + [&](const auto& module, const auto& sensor) { + groups[{ &module, sensor.sensorGroup }][sensor.deviceIndex] = sensor.id; }); + std::map out; + for (const auto& group : groups) + { + if (group.second.size() < 2) + continue; + for (const auto& member : group.second) + out[member.second] = member.first == group.second.begin()->first; + } return out; } -// A virtual channel with no Bayer order (cfa 0, which no NVSIPL_PIXEL_ORDER_* value is) belongs to a YUV camera with -// its own ISP. The query library leaves such a channel at its RAW12 default, which SIPL rejects at -// GetImageAttributes, so it is declared YUV422/UYVY before SetPlatformCfg. Returns the ids of the sensors corrected. -std::set declareYuv422Sensors(nvsipl::sensorconfig::SensorSystemConfig& config) +// Checks the cameras the sender config lists as YUV (sipl.yuv_cameras) against the platform configuration. The query +// library leaves a YUV camera's virtual channel without a pixel order (cfa 0, which no NVSIPL_PIXEL_ORDER_* value is) +// and at its RAW12 default, which SIPL rejects at GetImageAttributes, so a listed camera's channel is declared +// YUV422/UYVY before SetPlatformCfg. An unlisted camera in that state is refused, not silently reconfigured. +void declareYuv422Sensors(nvsipl::sensorconfig::SensorSystemConfig& config, const std::set& yuvCameras) { - std::set out; + std::set found; forEachSensor(config, - [&](auto& sensor) + [&](const auto& module, auto& sensor) { + const bool listed = yuvCameras.count(sensor.id) != 0; + const std::string name = std::to_string(sensor.id) + " (" + module.name + ")"; for (auto& vc : sensor.vcInfoList) { - if (vc.cfa != 0) - continue; - vc.inputFormat = NVSIPL_CAP_INPUT_FORMAT_TYPE_YUV422; - vc.cfa = NVSIPL_PIXEL_ORDER_UYVY; - out.insert(sensor.id); + if (vc.cfa == 0 && !listed) + throw std::runtime_error("SIPL sensor " + name + + " has no pixel order, which is a YUV camera: list it in " + "sipl.yuv_cameras"); + if (vc.cfa == 0) + { + vc.inputFormat = NVSIPL_CAP_INPUT_FORMAT_TYPE_YUV422; + vc.cfa = NVSIPL_PIXEL_ORDER_UYVY; + } + if (listed && (vc.inputFormat != NVSIPL_CAP_INPUT_FORMAT_TYPE_YUV422 || + vc.cfa != NVSIPL_PIXEL_ORDER_UYVY)) + throw std::runtime_error("SIPL sensor " + name + + " is in sipl.yuv_cameras but is not a YUV422/UYVY camera"); } + if (listed) + found.insert(sensor.id); }); - return out; + if (found != yuvCameras) + throw std::runtime_error("sipl.yuv_cameras names a sensor the platform configuration does not have"); } // One value of a reconciled buffer attribute list. @@ -295,7 +319,8 @@ std::vector querySiplCameras(const std::string& platformConfig struct SiplCapture::Impl { - // One ISP0 buffer. SIPL owns it between registration and Stop; the NvBufSurface view is created once. + // One ISP0 buffer, or one capture buffer of a YUV camera. SIPL owns it between registration and Stop; the + // NvBufSurface view is created once. struct Slot { NvSciBufObj buf = nullptr; @@ -330,10 +355,11 @@ struct SiplCapture::Impl struct Sensor { CameraDescriptor info; - // In a sensor group without being its primary; see groupSecondaries. + // In a sensor group, as its primary or not; see groupedSensors. + bool groupPrimary = false; bool groupSecondary = false; - // A YUV camera: pictures come from the capture output (ICP) as UYVY and are converted to NV12 by the VIC; - // the ISP is not used and there is no NITO. See declareYuv422Sensors. + // A YUV camera (sipl.yuv_cameras): pictures come from the capture output (ICP) as UYVY and are converted to + // NV12 by the VIC; the ISP is not used and there is no NITO. bool yuvPassthrough = false; nvsipl::NvSIPLPipelineConfiguration pipelineConfig{}; nvsipl::NvSIPLPipelineQueues queues{}; @@ -464,9 +490,8 @@ void SiplCapture::Impl::configure() throw std::runtime_error("no modules left in '" + config.platformConfigName + "' after applying the link masks; check the masks against the configuration"); - const std::set yuvSensors = declareYuv422Sensors(*systemConfig); - for (uint32_t id : yuvSensors) - std::fprintf(stderr, "[sipl] sensor %u: YUV422/UYVY camera, capture output converted to NV12 by the VIC\n", id); + const std::set yuvSensors(config.yuvCameras.begin(), config.yuvCameras.end()); + declareYuv422Sensors(*systemConfig, yuvSensors); descriptors = flatten(*systemConfig); if (descriptors.empty()) @@ -477,13 +502,20 @@ void SiplCapture::Impl::configure() throw std::runtime_error("INvSIPLCamera::GetInstance returned null"); checkSipl(camera->SetPlatformCfg(*systemConfig), "SetPlatformCfg"); - const std::set secondaries = groupSecondaries(*systemConfig); + const std::map grouped = groupedSensors(*systemConfig); for (const auto& info : descriptors) { std::unique_ptr sensor(new Sensor()); sensor->info = info; - sensor->groupSecondary = secondaries.count(info.id) != 0; + const auto group = grouped.find(info.id); + sensor->groupPrimary = group != grouped.end() && group->second; + sensor->groupSecondary = group != grouped.end() && !group->second; sensor->yuvPassthrough = yuvSensors.count(info.id) != 0; + std::fprintf(stderr, "[sipl] sensor %u (%s): %s%s\n", info.id, info.name.c_str(), + sensor->yuvPassthrough ? "YUV passthrough, UYVY converted to NV12 by the VIC" : "ISP0", + sensor->groupPrimary ? ", group primary" : + sensor->groupSecondary ? ", group secondary" : + ""); checkSci(NvSciSyncCpuWaitContextAlloc(syncModule, &sensor->cpuWaitContext), "NvSciSyncCpuWaitContextAlloc"); SensorClockMap::Config clockConfig; sensor->clockMap.reset(new SensorTimeMapper(counterHz, clockConfig, readCounterPair)); @@ -519,12 +551,16 @@ void SiplCapture::Impl::configure() } checkSipl(camera->Init(), "INvSIPLCamera::Init"); for (auto& sensor : sensors) + { registerBuffers(*sensor); - // Auto control comes after every sensor's images: a group primary is refused with NVSIPL_STATUS_INVALID_STATE - // while its secondary has none registered. + if (!sensor->groupPrimary && !sensor->groupSecondary && !sensor->yuvPassthrough) + registerNito(*sensor); + } + // A group's auto control comes after every sensor's images: the primary is refused with + // NVSIPL_STATUS_INVALID_STATE while its secondary has none registered. for (auto& sensor : sensors) { - if (!sensor->groupSecondary && !sensor->yuvPassthrough) + if (sensor->groupPrimary && !sensor->yuvPassthrough) registerNito(*sensor); } } @@ -625,7 +661,8 @@ void SiplCapture::Impl::allocateYuvBuffers(Sensor& sensor) map.gpuId = static_cast(config.gpuId); map.memType = NVBUF_MEM_SURFACE_ARRAY; map.scanformat = NVBUF_DISPLAYSCANFORMAT_PROGRESSIVE; - map.colorFormat = NVBUF_COLOR_FORMAT_UYVY; + // BT.709 limited range: the SHF3L's vendor states BT.709, and its black measures 16. + map.colorFormat = NVBUF_COLOR_FORMAT_UYVY_709; map.planes[0].width = attrValue(geometry[1]); map.planes[0].height = attrValue(geometry[2]); map.planes[0].pitch = attrValue(geometry[3]); @@ -644,14 +681,15 @@ void SiplCapture::Impl::allocateYuvBuffers(Sensor& sensor) sensor.bufObjects.push_back(slot.buf); int fd = -1; checkSci(NvSciBufObjGetDmaBufFd(slot.buf, &fd), "NvSciBufObjGetDmaBufFd"); + // The surface takes the descriptor over, and NvBufSurfaceDestroy closes it. map.fd = static_cast(fd); if (NvBufSurfaceImport(&slot.surface, &map) != 0 || slot.surface == nullptr) throw std::runtime_error("NvBufSurfaceImport failed for a UYVY capture buffer"); slot.surface->numFilled = 1; } - // Block-linear NV12 like the ISP0 path. The _709_ER tag asks the VIC to expand the camera's limited range, so - // every stream of a SIPL profile is full range as the consumers are told. + // Block-linear NV12 like the ISP0 path. The _709_ER tag has the VIC expand the camera's limited range, so every + // stream of a SIPL profile is BT.709 full range as the consumers are told. sensor.nv12Pool.resize(config.isp0Buffers); for (Nv12Out& out : sensor.nv12Pool) { @@ -754,7 +792,7 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) continue; if (status == nvsipl::NVSIPL_STATUS_EOF) break; - checkSipl(status, "isp0CompletionQueue->Get"); + checkSipl(status, "completion queue Get"); if (!buffer) continue; @@ -762,9 +800,9 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) ScopedRelease owned(buffer); INvSIPLClient::INvSIPLNvMBuffer* nvm = dynamic_cast(buffer); if (!nvm) - throw std::runtime_error("ISP0 buffer is not an INvSIPLNvMBuffer"); + throw std::runtime_error("SIPL buffer is not an INvSIPLNvMBuffer"); - // The ISP is still writing until this fence clears. + // SIPL is still writing until this fence clears. NvSciSyncFence fence = NvSciSyncFenceInitializer; checkSipl(nvm->GetEOFNvSciSyncFence(&fence), "GetEOFNvSciSyncFence"); const NvSciError wait = NvSciSyncFenceWait(&fence, sensor.cpuWaitContext, config.frameTimeoutMs * 1000UL); diff --git a/examples/camera_streamer/argus_sender/src/SiplCapture.h b/examples/camera_streamer/argus_sender/src/SiplCapture.h index 3dd18e9001..d6a2fb244c 100644 --- a/examples/camera_streamer/argus_sender/src/SiplCapture.h +++ b/examples/camera_streamer/argus_sender/src/SiplCapture.h @@ -7,7 +7,8 @@ #ifndef ARGUS_SENDER_SIPL_CAPTURE_H #define ARGUS_SENDER_SIPL_CAPTURE_H -// SIPL capture of every sensor in one platform configuration, ISP0 native NV12 out. The SIPL and NvSci headers stay +// SIPL capture of every sensor in one platform configuration, native NV12 out: ISP0's for a raw sensor, the VIC's +// conversion of the capture output for a YUV camera. The SIPL and NvSci headers stay // inside SiplCapture.cpp: they pull in macros that collide with other libraries. #include "CameraCapture.h" @@ -30,7 +31,9 @@ struct SiplConfig // Directory holding .nito; the ISP has no tuning without it. std::string nitoDir = "/var/nvidia/nvcam/settings/sipl"; int gpuId = 0; - // ISP0 buffers per sensor. A frame an encoder still holds is one fewer for the ISP. + // Pipeline indexes of the YUV422/UYVY cameras, which bypass the ISP. + std::vector yuvCameras; + // Picture buffers per sensor. A frame an encoder still holds is one fewer for capture. uint32_t isp0Buffers = 6; uint32_t frameTimeoutMs = 1000; // Stamped on every frame; the caller changes it whenever capture is rebuilt. diff --git a/examples/camera_streamer/argus_sender/src/SiplSender.cpp b/examples/camera_streamer/argus_sender/src/SiplSender.cpp index 2f3a9af0a9..320f431d97 100644 --- a/examples/camera_streamer/argus_sender/src/SiplSender.cpp +++ b/examples/camera_streamer/argus_sender/src/SiplSender.cpp @@ -31,6 +31,7 @@ bool runSiplSender(const AppConfig& config, bool* receiverDisconnected, bool app siplConfig.linkMasks = config.sipl.linkMasks; siplConfig.nitoDir = config.sipl.nitoDir; siplConfig.isp0Buffers = config.sipl.isp0Buffers; + siplConfig.yuvCameras = config.sipl.yuvCameras; const uint64_t sessionId = createCaptureSessionId(); siplConfig.sessionEpoch = sessionId; diff --git a/examples/camera_streamer/argus_sender/tests/test_config.cpp b/examples/camera_streamer/argus_sender/tests/test_config.cpp index a7f03541e3..fe376d247f 100644 --- a/examples/camera_streamer/argus_sender/tests/test_config.cpp +++ b/examples/camera_streamer/argus_sender/tests/test_config.cpp @@ -134,6 +134,10 @@ int main() test, static_cast(backend.captureBackend), static_cast(argus_sender::CAPTURE_BACKEND_SIPL)); TEST_CHECK_EQ(test, backend.sipl.linkMasks.size(), static_cast(2)); TEST_CHECK_EQ(test, backend.sipl.platformConfigName, std::string("RIG")); + TEST_CHECK(test, backend.sipl.yuvCameras.empty()); + TEST_CHECK(test, loadText("version: 1\ncapture_backend: sipl\n" + sipl + " yuv_cameras: [4, 5]\n" + streams, + &backend, &error)); + TEST_CHECK_EQ(test, backend.sipl.yuvCameras.size(), static_cast(2)); TEST_CHECK( test, !loadText( diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index 3e049c6436..ddf694463b 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -33,8 +33,8 @@ name, link masks, tuning directory) and possibly the stream id and size. The Arg selects a sensor mode with `cameras[].mode`, can set `capture.mode` and `alignment`, enforces `output.fps` with a rate limiter and can set output dimensions. Keep one file per rig and pass the right one with `--sender-config`. The launcher itself supports mono streams only: each becomes one receiver stream and one LiveKit track named `sensing-`. The streams share one -explicit `output.fps`; a stream whose sensor size differs from `--width`/`--height` sets its own `output.width` and -`output.height`. `--fps` and `--bitrate-mbps` apply to every stream. +explicit `output.fps` and each needs its own `id`; a profile with several streams sets every stream's `output.width` +and `output.height`. `--fps` and `--bitrate-mbps` apply to every stream. `tools/start_system.py` loads this file by default. Command-line overrides (`--fps`, `--bitrate-mbps`, `--sender-port`) are applied to the loaded mapping, and the result is what is uploaded. The same @@ -100,7 +100,8 @@ shipped profile. | `sipl.platform_config_name` | Empty; required for SIPL | Named platform inside the database/JSON. | | `sipl.link_masks` | Empty; required for SIPL | Sequence of unsigned masks, one per deserializer in transport order; passed to `ApplyMask`. Not an FPS knob. | | `sipl.nito_dir` | `/var/nvidia/nvcam/settings/sipl` | ISP tuning directory; loads `.nito` on the Orin. Not a YAML sensor-mode selector. | -| `sipl.isp0_buffers` | `6`; at least 2 | Number of ISP0 surfaces allocated/registered per sensor. Surface ownership and return timing affect pressure; increasing the count does not directly select FPS. | +| `sipl.isp0_buffers` | `6`; at least 2 | Number of picture surfaces allocated/registered per sensor: ISP0 surfaces for a raw sensor, capture buffers and converted pictures for a YUV camera. Surface ownership and return timing affect pressure; increasing the count does not directly select FPS. | +| `sipl.yuv_cameras` | Empty | SIPL pipeline indexes of the YUV422/UYVY cameras. Their capture output bypasses the ISP and is converted to NV12; a YUV camera that is not listed is refused. | | `network.bind` | `0.0.0.0`; nonempty | Sender TCP listening address. | | `network.port` | `5000`; 1–65535 | AVS1 TCP listening port. Receiver must connect here. | | `network.reconnect_ms` | `1000` | Retry delay for failed listen setup. Not a per-frame sleep or FPS limiter. | diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index bf7f0ed3ce..321b718c0d 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -1048,7 +1048,13 @@ def test_load_sender_config_refuses_a_stream_that_is_not_mono(tmp_path: Path): def _head_and_wrist(config: dict) -> None: head = config["streams"][0] - wrist = {**head, "id": "wrist", "output": {**head["output"], "width": 1920, "height": 1536}} + head["output"].update(width=2560, height=1984) + wrist = { + **head, + "id": "wrist", + "cameras": [{"device": 1, "mode": 0}], + "output": {**head["output"], "width": 1920, "height": 1536}, + } config["streams"] = [head, wrist] @@ -1056,12 +1062,26 @@ def test_streams_keep_their_own_sizes_and_must_share_the_rate(tmp_path: Path): config = ss.load_sender_config(_profile_with(tmp_path, _head_and_wrist), bitrate_mbps=6) settings = ss.sender_settings(config) assert (settings.stream_ids, settings.bitrate_mbps) == (("head", "wrist"), 12) - assert settings.sizes == ((None, None), (1920, 1536)) + assert settings.sizes == ((2560, 1984), (1920, 1536)) config["streams"][1]["output"]["fps"] = 60 with pytest.raises(ss.StartupError, match="share"): ss.sender_settings(config) +def test_several_streams_need_their_own_ids_and_sizes(tmp_path: Path): + config = ss.load_sender_config(_profile_with(tmp_path, _head_and_wrist)) + del config["streams"][1]["output"]["width"] + with pytest.raises(ss.StartupError, match="every stream's output.width"): + ss.sender_settings(config) + config["streams"][1]["output"]["width"] = 0 + with pytest.raises(ss.StartupError, match=r"streams\[1\].output.width"): + ss.sender_settings(config) + config["streams"][1]["output"]["width"] = 1920 + config["streams"][1]["id"] = "head" + with pytest.raises(ss.StartupError, match="its own id"): + ss.sender_settings(config) + + def test_main_carries_every_stream_at_its_own_size(recorded_main, tmp_path: Path): mock_sender = tmp_path / "mock_sender.py" mock_sender.write_text("") diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index dd53349a91..330ef2825d 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -180,7 +180,8 @@ class SenderSettings: stream_ids: tuple[str, ...] full_range: bool sipl: bool - # Each stream's output size; None leaves the sensor mode's native size, which --width and --height describe. + # Each stream's output size; None, for a lone stream only, leaves the sensor mode's native size, which --width + # and --height describe. sizes: tuple[tuple[int | None, int | None], ...] @@ -249,25 +250,36 @@ def sender_settings(config: dict) -> SenderSettings: # The bridge takes one rate for every stream. if len({output["fps"] for output in outputs}) != 1: raise StartupError("every stream in the sender config must share one output.fps") + # The id names the stream's track and its IPC stream, so two streams cannot share one. + stream_ids = tuple(str(stream["id"]) for stream in streams) + if len(set(stream_ids)) != len(stream_ids): + raise StartupError("every stream in the sender config must have its own id") + sizes = tuple( + (_output_dimension(output, "width", index), _output_dimension(output, "height", index)) + for index, output in enumerate(outputs) + ) + # --width and --height describe one sensor, so they cannot stand in for several streams' sizes. + if len(streams) > 1 and any(None in size for size in sizes): + raise StartupError("a sender config with several streams must set every stream's output.width and height") return SenderSettings( port=int(network.get("port", 5000)), fps=int(outputs[0]["fps"]), bitrate_mbps=sum(int(output.get("bitrate_mbps", 0)) for output in outputs), - stream_ids=tuple(str(stream["id"]) for stream in streams), + stream_ids=stream_ids, # SIPL produces full-range pictures; the bridge must say so or the encoded stream signals limited range. full_range=config["capture_backend"] == "sipl", sipl=config["capture_backend"] == "sipl", - sizes=tuple((_output_dimension(o, "width"), _output_dimension(o, "height")) for o in outputs), + sizes=sizes, ) -def _output_dimension(output: dict, key: str) -> int | None: +def _output_dimension(output: dict, key: str, index: int) -> int | None: value = output.get(key) if value is None: return None if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise StartupError( - f"the sender config's streams[*].output.{key} must be a positive integer, got {value!r}" + f"the sender config's streams[{index}].output.{key} must be a positive integer, got {value!r}" ) return value @@ -669,7 +681,7 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: "descriptor declares it divided by the bridge shrink", ) parser.add_argument("--fps", type=int, help="override the profile's output.fps") - parser.add_argument("--bitrate-mbps", type=int, help="override the profile's HEVC bitrate") + parser.add_argument("--bitrate-mbps", type=int, help="override every stream's HEVC bitrate") parser.add_argument("--sender-port", type=int, help="override the profile's TCP video port") parser.add_argument( "--timesync-tool", @@ -783,7 +795,7 @@ def main(argv: Sequence[str] | None = None) -> int: print(f"mock sender: {sender.fps} fps streams {sender.stream_ids}, timestamps are frame-ready time") else: print( - f"sender config {args.sender_config}: {sender.fps} fps, {sender.bitrate_mbps} Mbit/s, " + f"sender config {args.sender_config}: {sender.fps} fps, {sender.bitrate_mbps} Mbit/s total, " f"release {args.release}" ) if args.orin: From f7c95bc8cf13778a0d494475f1a0a990139967af Mon Sep 17 00:00:00 2001 From: yunjul Date: Wed, 2 Dec 2026 11:35:07 +0800 Subject: [PATCH 4/4] camera_streamer, egocap: address the second review of the S56C + SHF3L support The frame lease no longer touches its Sensor, a sensor group needs a non-zero group number, and a YUV camera reports its conversion time and drops once per log interval. The launcher's summed bitrate field is total_bitrate_mbps, and the S56C + SHF3L sender profile is added. Co-Authored-By: Claude Fable 5.2 Signed-off-by: yunjul --- .../camera_streamer/argus_sender/README.md | 4 +- .../argus_sender/src/SiplCapture.cpp | 129 ++++++++++-------- .../argus_sender/src/SiplCapture.h | 2 + .../argus_sender/src/SiplSender.cpp | 1 + examples/egocap/CAMERA_SETTINGS.md | 5 +- .../configs/default-camera-settings.yaml | 2 +- .../configs/s56c-shf3l-camera-settings.yaml | 46 +++++++ .../egocap/tests/tools/test_start_system.py | 33 ++++- examples/egocap/tools/start_system.py | 6 +- 9 files changed, 160 insertions(+), 68 deletions(-) create mode 100644 examples/egocap/configs/s56c-shf3l-camera-settings.yaml diff --git a/examples/camera_streamer/argus_sender/README.md b/examples/camera_streamer/argus_sender/README.md index 72ce67f5a4..ca49142a4d 100644 --- a/examples/camera_streamer/argus_sender/README.md +++ b/examples/camera_streamer/argus_sender/README.md @@ -264,7 +264,9 @@ acquire average/max and selected-frame gaps once per `runtime.log_interval_s` (one second by default), even with `runtime.kpi: false`; set the interval to zero to disable it. The SOF latency is `n/a` when comparable TSC metadata is unavailable. With KPI enabled, `[head-handoff:]` also reports -priority slot overwrites and alignment drops once per interval. A priority +priority slot overwrites and alignment drops once per interval, and the SIPL +backend reports each YUV camera's UYVY-to-NV12 conversion time (mean and +maximum) and the captures it dropped with no free NV12 picture. A priority camera exits after 10 seconds without its first new frame or 1 second without a subsequent new frame, including repeated acquisitions of the same frame number; the service can then restart it. diff --git a/examples/camera_streamer/argus_sender/src/SiplCapture.cpp b/examples/camera_streamer/argus_sender/src/SiplCapture.cpp index af121c3297..2acf1fa67f 100644 --- a/examples/camera_streamer/argus_sender/src/SiplCapture.cpp +++ b/examples/camera_streamer/argus_sender/src/SiplCapture.cpp @@ -182,41 +182,7 @@ std::vector loadNito(const std::string& dir, const std::string& module) return blob; } -// module -> variant -> sensorConfigs -> variant; `id` is the pipeline index SetPipelineCfg wants. -std::vector flatten(const nvsipl::sensorconfig::SensorSystemConfig& config) -{ - std::vector out; - for (const auto& module : config.modules) - { - std::visit( - [&](const auto& moduleType) - { - for (const auto& sensorVariant : moduleType.sensorConfigs) - { - std::visit( - [&](const auto& sensor) - { - CameraDescriptor info; - info.id = sensor.id; - info.name = module.name; - if (!sensor.vcInfoList.empty()) - { - const auto& vc = sensor.vcInfoList.front(); - info.width = vc.resolution.width; - info.height = vc.resolution.height; - info.fps = static_cast(vc.fps); - } - out.push_back(std::move(info)); - }, - sensorVariant); - } - }, - module.moduleType); - } - return out; -} - -// Calls fn(module, sensor) for every sensor of the configuration; the nesting is the one `flatten` walks. +// Calls fn(module, sensor) for every sensor of the configuration: module -> variant -> sensorConfigs -> variant. template void forEachSensor(Config& config, Fn fn) { @@ -232,17 +198,41 @@ void forEachSensor(Config& config, Fn fn) } } +// `id` is the pipeline index SetPipelineCfg wants. +std::vector flatten(const nvsipl::sensorconfig::SensorSystemConfig& config) +{ + std::vector out; + forEachSensor(config, + [&](const auto& module, const auto& sensor) + { + CameraDescriptor info; + info.id = sensor.id; + info.name = module.name; + if (!sensor.vcInfoList.empty()) + { + const auto& vc = sensor.vcInfoList.front(); + info.width = vc.resolution.width; + info.height = vc.resolution.height; + info.fps = static_cast(vc.fps); + } + out.push_back(std::move(info)); + }); + return out; +} + // Sensors of one module that share a sensor group (a stereo pair) run as one SIPL pipeline group: the one with the // lowest device index is the primary, and the others take its ISP program and auto control. Group numbers repeat -// across modules, and independent cameras all leave theirs at 0. Returns each grouped sensor's id and whether it is -// the primary. +// across modules; independent cameras all leave theirs at 0, which is never a group. Returns each grouped sensor's id +// and whether it is the primary. std::map groupedSensors(const nvsipl::sensorconfig::SensorSystemConfig& config) { // (module, sensor group) -> device index -> sensor id std::map, std::map> groups; forEachSensor(config, - [&](const auto& module, const auto& sensor) { - groups[{ &module, sensor.sensorGroup }][sensor.deviceIndex] = sensor.id; + [&](const auto& module, const auto& sensor) + { + if (sensor.sensorGroup > 0) + groups[{ &module, sensor.sensorGroup }][sensor.deviceIndex] = sensor.id; }); std::map out; for (const auto& group : groups) @@ -331,7 +321,8 @@ struct SiplCapture::Impl struct Nv12Out { NvBufSurface* surface = nullptr; - bool inUse = false; + // Set by the sensor's frame thread, cleared by whichever thread drops the lease. + std::atomic inUse{ false }; }; // The newest frame the consumer has not taken. A frame replaced before it is taken goes straight back to its @@ -443,7 +434,7 @@ struct SiplCapture::Impl throw std::runtime_error(failureMessage.empty() ? "SIPL capture failed" : failureMessage); } - // sensor.mutex held by the caller. + // Returns a frame to its owner. For sensor.pending, sensor.mutex is held by the caller. static void releasePending(Pending& pending) { if (pending.buffer) @@ -690,7 +681,7 @@ void SiplCapture::Impl::allocateYuvBuffers(Sensor& sensor) // Block-linear NV12 like the ISP0 path. The _709_ER tag has the VIC expand the camera's limited range, so every // stream of a SIPL profile is BT.709 full range as the consumers are told. - sensor.nv12Pool.resize(config.isp0Buffers); + sensor.nv12Pool = std::vector(config.isp0Buffers); for (Nv12Out& out : sensor.nv12Pool) { NvBufSurfaceAllocateParams alloc{}; @@ -784,6 +775,16 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) if (NvBufSurfTransformSetSessionParams(&session) != NvBufSurfTransformError_Success) throw std::runtime_error("NvBufSurfTransformSetSessionParams failed"); } + // A YUV camera's conversions since its last summary. + struct + { + uint64_t frames = 0; + uint64_t totalNs = 0; + uint64_t maxNs = 0; + uint64_t dropped = 0; + } conversion; + const uint64_t summaryNs = config.logIntervalSeconds * 1000000000ULL; + uint64_t summaryAtNs = monotonicNs() + summaryNs; while (running.load()) { INvSIPLClient::INvSIPLBuffer* buffer = nullptr; @@ -827,17 +828,26 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) next.surface = slot->surface; if (sensor.yuvPassthrough) { + if (summaryNs > 0 && monotonicNs() >= summaryAtNs) + { + std::fprintf(stderr, + "[sipl] sensor %u: UYVY to NV12 %.2f ms mean, %.2f ms max over %llu frame(s), %llu " + "dropped with no free NV12 picture\n", + sensor.info.id, conversion.frames ? conversion.totalNs / 1e6 / conversion.frames : 0.0, + conversion.maxNs / 1e6, static_cast(conversion.frames), + static_cast(conversion.dropped)); + conversion = {}; + summaryAtNs += summaryNs; + } + // Only this thread takes a picture from the pool; a lease gives one back from any thread. Nv12Out* out = nullptr; + for (Nv12Out& candidate : sensor.nv12Pool) { - std::lock_guard guard(sensor.mutex); - for (Nv12Out& candidate : sensor.nv12Pool) + if (!candidate.inUse) { - if (!candidate.inUse) - { - candidate.inUse = true; - out = &candidate; - break; - } + candidate.inUse = true; + out = &candidate; + break; } } // Every NV12 picture pending or with the encoder: this capture goes back to SIPL unconverted. @@ -845,15 +855,23 @@ void SiplCapture::Impl::frameLoop(Sensor& sensor) std::fprintf(stderr, "[sipl] sensor %u: no free NV12 picture, dropping\n", sensor.info.id); sensor.nv12Starved = !out; if (!out) + { + ++conversion.dropped; continue; + } // Same size, whole picture: a format conversion only. The call returns when the VIC has written. NvBufSurfTransformParams transform{}; + const uint64_t began = monotonicNs(); if (NvBufSurfTransform(slot->surface, out->surface, &transform) != NvBufSurfTransformError_Success) { - std::lock_guard guard(sensor.mutex); out->inUse = false; throw std::runtime_error("NvBufSurfTransform UYVY to NV12 failed"); } + const uint64_t took = monotonicNs() - began; + ++conversion.frames; + conversion.totalNs += took; + if (took > conversion.maxNs) + conversion.maxNs = took; // The consumer gets the NV12 picture; `owned` returns the capture buffer to SIPL. next.buffer = nullptr; next.nv12 = out; @@ -1131,13 +1149,8 @@ bool SiplCapture::acquireLatest(uint32_t cameraId, CaptureFrame* frame) out.surface.blockLinear = params.layout == NVBUF_LAYOUT_BLOCK_LINEAR; // ISP0 writes BT.709 extended range; a YUV camera's picture is converted to the same by the VIC. out.surface.colorRange = COLOR_RANGE_FULL; - Impl::Pending held = taken; - out.lease = FrameLease( - [sensor, held]() mutable - { - std::lock_guard guard(sensor->mutex); - Impl::releasePending(held); - }); + // The lease holds the frame alone, not its Sensor. + out.lease = FrameLease([taken]() mutable { Impl::releasePending(taken); }); *frame = std::move(out); return true; } diff --git a/examples/camera_streamer/argus_sender/src/SiplCapture.h b/examples/camera_streamer/argus_sender/src/SiplCapture.h index d6a2fb244c..0622b4b9f8 100644 --- a/examples/camera_streamer/argus_sender/src/SiplCapture.h +++ b/examples/camera_streamer/argus_sender/src/SiplCapture.h @@ -36,6 +36,8 @@ struct SiplConfig // Picture buffers per sensor. A frame an encoder still holds is one fewer for capture. uint32_t isp0Buffers = 6; uint32_t frameTimeoutMs = 1000; + // Seconds between a YUV camera's conversion summaries; 0 prints none. + uint32_t logIntervalSeconds = 0; // Stamped on every frame; the caller changes it whenever capture is rebuilt. uint64_t sessionEpoch = 0; }; diff --git a/examples/camera_streamer/argus_sender/src/SiplSender.cpp b/examples/camera_streamer/argus_sender/src/SiplSender.cpp index 320f431d97..a4d534747d 100644 --- a/examples/camera_streamer/argus_sender/src/SiplSender.cpp +++ b/examples/camera_streamer/argus_sender/src/SiplSender.cpp @@ -32,6 +32,7 @@ bool runSiplSender(const AppConfig& config, bool* receiverDisconnected, bool app siplConfig.nitoDir = config.sipl.nitoDir; siplConfig.isp0Buffers = config.sipl.isp0Buffers; siplConfig.yuvCameras = config.sipl.yuvCameras; + siplConfig.logIntervalSeconds = config.runtime.kpi ? config.runtime.logIntervalSeconds : 0; const uint64_t sessionId = createCaptureSessionId(); siplConfig.sessionEpoch = sessionId; diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index ddf694463b..d6ac452376 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -32,9 +32,12 @@ The file is specific to that rig. A different SIPL platform or camera changes th name, link masks, tuning directory) and possibly the stream id and size. The Argus backend has no `sipl` block: it selects a sensor mode with `cameras[].mode`, can set `capture.mode` and `alignment`, enforces `output.fps` with a rate limiter and can set output dimensions. Keep one file per rig and pass the right one with `--sender-config`. The launcher itself supports -mono streams only: each becomes one receiver stream and one LiveKit track named `sensing-`. The streams share one +mono streams only: each becomes one receiver stream and one LiveKit track named `sensing-`, so the default +profile's `head` stream is on `sensing-head` and a stream with another id is on another track. The streams share one explicit `output.fps` and each needs its own `id`; a profile with several streams sets every stream's `output.width` and `output.height`. `--fps` and `--bitrate-mbps` apply to every stream. +`configs/s56c-shf3l-camera-settings.yaml` is such a profile, for an S56C stereo head camera with two SHF3L wrist +cameras. `tools/start_system.py` loads this file by default. Command-line overrides (`--fps`, `--bitrate-mbps`, `--sender-port`) are applied to the loaded mapping, and the result is what is uploaded. The same diff --git a/examples/egocap/configs/default-camera-settings.yaml b/examples/egocap/configs/default-camera-settings.yaml index e5cbd27cc7..6f61a3e4c8 100644 --- a/examples/egocap/configs/default-camera-settings.yaml +++ b/examples/egocap/configs/default-camera-settings.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # Default camera settings for tools/start_system.py: what the Orin's camera sender runs with. -# It is the only profile for now and describes one rig, a single SHW5G head camera on the SIPL backend. Pass another +# It describes one rig, a single SHW5G head camera on the SIPL backend. Pass another # file with --sender-config for a different rig. CAMERA_SETTINGS.md describes every key. # # The launcher uploads this file to the Orin, where the sender reads it once at start; to change a value, stop the diff --git a/examples/egocap/configs/s56c-shf3l-camera-settings.yaml b/examples/egocap/configs/s56c-shf3l-camera-settings.yaml new file mode 100644 index 0000000000..9d42bad7f0 --- /dev/null +++ b/examples/egocap/configs/s56c-shf3l-camera-settings.yaml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Camera settings for an S56C stereo head camera with two SHF3L wrist cameras on the SIPL backend. Pass it to +# tools/start_system.py with --sender-config. CAMERA_SETTINGS.md describes every key. + +version: 1 +capture_backend: sipl + +# These paths are on the Orin. The platform file is the camera vendor's mixed S56C + SHF3L layout, here with the SHF3L +# cameras on deserializer links 0 and 1 and the S56C on link 2. +sipl: + platform_config_json: /opt/isaaccapture/camera-platform.json + platform_config_name: SHF3L_2_S56C_1 + link_masks: [273, 0] # 0x0111: links 0, 1 and 2 of the first deserializer + nito_dir: /var/nvidia/nvcam/settings/sipl + yuv_cameras: [4, 5] # the SHF3L cameras output YUV422, which bypasses the ISP + +network: + bind: 0.0.0.0 + port: 5000 + +runtime: + frames: 0 + kpi: true + log_interval_s: 1 + +# device is the SIPL pipeline index under this platform file: the S56C's eyes are 7 (left) and 6 (right), the SHF3L +# cameras 5 and 4. The streams share one fps, and several streams each state their size. +streams: + - id: head_left + type: mono + cameras: [{device: 7, mode: 0}] + output: {codec: hevc, fps: 30, bitrate_mbps: 8, width: 2560, height: 1984} + - id: head_right + type: mono + cameras: [{device: 6, mode: 0}] + output: {codec: hevc, fps: 30, bitrate_mbps: 8, width: 2560, height: 1984} + - id: wrist_left + type: mono + cameras: [{device: 5, mode: 0}] + output: {codec: hevc, fps: 30, bitrate_mbps: 4, width: 1920, height: 1536} + - id: wrist_right + type: mono + cameras: [{device: 4, mode: 0}] + output: {codec: hevc, fps: 30, bitrate_mbps: 4, width: 1920, height: 1536} diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index 321b718c0d..d0e42d96d1 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -172,7 +172,26 @@ def record_start(self, name, command, *_, **__): def test_default_profile_gives_the_head_camera_settings(): config = ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG) assert ss.sender_settings(config) == ss.SenderSettings( - port=5000, fps=30, bitrate_mbps=4, stream_ids=("head",), full_range=True, sipl=True, sizes=((None, None),) + port=5000, + fps=30, + total_bitrate_mbps=4, + stream_ids=("head",), + full_range=True, + sipl=True, + sizes=((None, None),), + ) + + +def test_s56c_shf3l_profile_gives_four_sized_streams(): + config = ss.load_sender_config(ss.EGOCAP_ROOT / "configs/s56c-shf3l-camera-settings.yaml") + assert ss.sender_settings(config) == ss.SenderSettings( + port=5000, + fps=30, + total_bitrate_mbps=24, + stream_ids=("head_left", "head_right", "wrist_left", "wrist_right"), + full_range=True, + sipl=True, + sizes=((2560, 1984), (2560, 1984), (1920, 1536), (1920, 1536)), ) @@ -185,10 +204,16 @@ def test_argus_backend_is_not_full_range(): def test_overrides_replace_only_their_values(): config = ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG, 60, 9, 5100) assert ss.sender_settings(config) == ss.SenderSettings( - port=5100, fps=60, bitrate_mbps=9, stream_ids=("head",), full_range=True, sipl=True, sizes=((None, None),) + port=5100, + fps=60, + total_bitrate_mbps=9, + stream_ids=("head",), + full_range=True, + sipl=True, + sizes=((None, None),), ) partial = ss.sender_settings(ss.load_sender_config(ss.DEFAULT_SENDER_CONFIG, fps=15)) - assert (partial.fps, partial.bitrate_mbps, partial.port) == (15, 4, 5000) + assert (partial.fps, partial.total_bitrate_mbps, partial.port) == (15, 4, 5000) @pytest.mark.parametrize( @@ -1061,7 +1086,7 @@ def _head_and_wrist(config: dict) -> None: def test_streams_keep_their_own_sizes_and_must_share_the_rate(tmp_path: Path): config = ss.load_sender_config(_profile_with(tmp_path, _head_and_wrist), bitrate_mbps=6) settings = ss.sender_settings(config) - assert (settings.stream_ids, settings.bitrate_mbps) == (("head", "wrist"), 12) + assert (settings.stream_ids, settings.total_bitrate_mbps) == (("head", "wrist"), 12) assert settings.sizes == ((2560, 1984), (1920, 1536)) config["streams"][1]["output"]["fps"] = 60 with pytest.raises(ss.StartupError, match="share"): diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index 330ef2825d..91aa318779 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -176,7 +176,7 @@ class SenderSettings: port: int fps: int - bitrate_mbps: int + total_bitrate_mbps: int stream_ids: tuple[str, ...] full_range: bool sipl: bool @@ -264,7 +264,7 @@ def sender_settings(config: dict) -> SenderSettings: return SenderSettings( port=int(network.get("port", 5000)), fps=int(outputs[0]["fps"]), - bitrate_mbps=sum(int(output.get("bitrate_mbps", 0)) for output in outputs), + total_bitrate_mbps=sum(int(output.get("bitrate_mbps", 0)) for output in outputs), stream_ids=stream_ids, # SIPL produces full-range pictures; the bridge must say so or the encoded stream signals limited range. full_range=config["capture_backend"] == "sipl", @@ -795,7 +795,7 @@ def main(argv: Sequence[str] | None = None) -> int: print(f"mock sender: {sender.fps} fps streams {sender.stream_ids}, timestamps are frame-ready time") else: print( - f"sender config {args.sender_config}: {sender.fps} fps, {sender.bitrate_mbps} Mbit/s total, " + f"sender config {args.sender_config}: {sender.fps} fps, {sender.total_bitrate_mbps} Mbit/s total, " f"release {args.release}" ) if args.orin: