// 取流层:相机 / 视频 / RTSP → 当帧灰度图(**唯一**进入证据模块的图像来源)。 // // 为什么单独成一层(而不是继续写在 main.cpp 里): // * docs/technical_route.md §5.2 的"线程 A 取帧/解码"从此是真线程:取帧在 A、推理在 B、 // Modbus 在 C。A 阻塞在解码/重连上时,C 照常应答 PLC 的 FC4(读的仍是最近一张完整快照); // * 语义与 Python `portcv/io/capture.py` 的 `FrameGrabber` **逐项对齐**: // 配置键同名同义(`source.type/uri/buffer_size/reconnect_s/stale_frame_s`)、 // "只保留最新帧"(丢帧,不排队)、断流按 `reconnect_s` 重连、 // 超过 `stale_frame_s` 没新帧 → `flags.FRAME_TIMEOUT`(见 portcv/service/runner.py); // * 零外部依赖:`synth` 源(合成帧,台架/CI 用)不需要任何库;真机取流走 GStreamer // (`-DPORTCV_WITH_GSTREAMER=ON`),**不引入 OpenCV** —— 见 docs/edge_evidence.md §11 第 9 条 // 与 cpp/README.md §1"核心零外部依赖"的交付形态要求。 // // 取值纪律(与 app_config.cpp 同一条):类型不认识 / 未编译进来一律**启动即报错**, // 绝不静默降级成"没有画面也能跑"(那会让 PLC 拿到 255 却以为是相机问题)。 #pragma once #include #include #include #include #include #include "portcv/edge_image.hpp" namespace portcv { /// 取流层的统一时基:steady 秒(与 main.cpp / 帧槽 / stale 判据同一时基,不用墙上时钟)。 inline double capture_now_seconds() { using namespace std::chrono; return duration_cast>(steady_clock::now().time_since_epoch()).count(); } /// 取流配置(键名与 Python `source.*` 同名同义,见 portcv/config.py DEFAULTS)。 struct SourceConfig { /// `none` | `synth` | `images` | `gst` | `rtsp` | `file` | `usb` /// * none = 不取流(默认;此时主循环行为与旧版一致:`Frame.gray = nullptr`); /// * synth = 合成帧(`uri` 取场景名 gondola|flatbed|ground|empty),台架/CI 用,零依赖; /// * images = PGM 序列(`uri` = 目录,按文件名排序 = 时间序),**零依赖**; /// 现场片段先 `python scripts/extract_frames.py --clip 片段.mp4 --out <目录>` 转成 P5 PGM /// —— 于是"没上板卡 / 板卡没带 GStreamer"也能把现场画面灌进 C++ 证据链整定阈值; /// * gst = `uri` 就是一条完整 GStreamer 管线(现场最灵活,硬件解码写在管线里); /// * rtsp / file / usb = 按 `uri` 自动拼管线(GStreamer 可用时),省得现场手写管线串。 std::string type = "none"; std::string uri; int width = 0; ///< 0 = 用源分辨率(`synth` 时 = 渲染宽度,默认 960) int height = 0; ///< 0 = 用源分辨率(`synth` 时 = 渲染高度,默认 540) int buffer_size = 2; ///< 解码缓冲帧数(→ appsink `max-buffers`;越小延迟越低) double reconnect_s = 2.0; ///< 断流后重连间隔(秒) double stale_frame_s = 0.6; ///< 超过该时间没新帧 → FRAME_TIMEOUT(与 Python 同键同义) bool loop = false; ///< `file` 源读到尾部是否重开(离线复盘循环) // ---- 取流层的实现级补充键(Python 侧没有;`source.*` 里对应 §7 表的地位)---- /// `synth` 每帧横向平移像素(>0 → 制造"车辆行走"运动,用于运动门控台架验收)。 double synth_shift_px = 0.0; /// `synth` 合成场景的随机种子(固定 → 逐像素可复现,CI 用)。 uint32_t synth_seed = 20261010u; }; /// 一帧(含自增序号与采集时刻)。`valid=false` 表示"这一拍没拿到画面"。 struct CapturedFrame { GrayImage gray; long index = 0; ///< 单调递增(丢帧也递增 → 丢帧率可算) double ts = 0.0; ///< 采集时刻(steady 秒,与 main.cpp 同一时基) bool valid = false; }; /// 取流后端接口(与 `Detector` 同风格:open → next* → close)。 class FrameSource { public: virtual ~FrameSource() = default; /// 后端名(日志用):`synth` / `gst`。 virtual std::string name() const = 0; /// 一行参数摘要(启动日志;不含 uri 里的口令)。 virtual std::string describe() const = 0; /// 打开/首次连接;失败返回 false 并把原因写进 error。 virtual bool open(std::string* error) = 0; /// 取下一帧(阻塞至多一个内部超时)。 /// 返回 false = 本拍没拿到画面(掉线 / 超时 / 读到尾),原因写进 error(可空); /// **不是致命错误**:调用方(取帧线程)按 reconnect_s 重试,状态交给 stale 判据处理。 virtual bool next(CapturedFrame* out, std::string* error) = 0; /// 释放资源(可重复调用)。 virtual void close() = 0; }; /// "只保留最新帧"的取帧槽(线程 A 写、线程 B 读)。 /// /// 为什么不是队列:推理比取帧慢时队列会累积成几秒延迟(吊装场景不可接受)。这里**永远只留 /// 最后一帧**:B 取走时若已有更新的一帧,旧帧直接丢弃 —— 与 `portcv/io/capture.py` 的 /// FrameGrabber 同一取舍。publish/take 都用 swap,不做整帧拷贝。 class FrameSlot { public: /// 发布一帧(覆盖尚未被取走的旧帧)。 void publish(CapturedFrame&& frame) { std::lock_guard lock(mu_); frame_.gray.data.swap(frame.gray.data); frame_.gray.width = frame.gray.width; frame_.gray.height = frame.gray.height; frame_.index = frame.index; frame_.ts = frame.ts; frame_.valid = frame.valid; has_ = true; is_new_ = true; last_ts_ = frame.ts; ++version_; } /// 取走最新帧(只有存在"尚未取走的新帧"才返回 true;否则 `*out` 不动)。 bool take(CapturedFrame* out) { if (out == nullptr) { return false; } std::lock_guard lock(mu_); if (!has_ || !is_new_) { return false; } out->gray.data.swap(frame_.gray.data); out->gray.width = frame_.gray.width; out->gray.height = frame_.gray.height; out->index = frame_.index; out->ts = frame_.ts; out->valid = frame_.valid; is_new_ = false; return true; } /// 看一眼最新帧(不消耗"新帧"标记;会拷贝一次整帧,仅自检/诊断用)。 bool peek(CapturedFrame* out) const { if (out == nullptr) { return false; } std::lock_guard lock(mu_); if (!has_) { return false; } out->gray = frame_.gray; out->index = frame_.index; out->ts = frame_.ts; out->valid = frame_.valid; return true; } /// 当前是否有一帧尚未被取走。 bool has_new() const { std::lock_guard lock(mu_); return has_ && is_new_; } /// 发布总次数(单调递增;日志里与"推理帧数"相减即丢帧数)。 uint64_t version() const { std::lock_guard lock(mu_); return version_; } /// 最近一次发布时刻(steady 秒);从未发布 → -1.0。 /// `stale_frame_s` 判 FRAME_TIMEOUT 就看它(与 Python `grabber.latest.ts` 同义)。 double last_ts() const { std::lock_guard lock(mu_); return last_ts_; } /// 最近一帧是否新鲜(`now - last_ts <= stale_s`);从未发布 → false。 bool fresh(double now, double stale_s) const { const double ts = last_ts(); if (ts < 0.0) { return false; } return (now - ts) <= stale_s; } private: mutable std::mutex mu_; CapturedFrame frame_; bool has_ = false; bool is_new_ = false; uint64_t version_ = 0; double last_ts_ = -1.0; }; /// 建合成帧源(`source.type=synth`):确定性渲染,不需要相机/模型/任何外部库。 /// `uri` 取场景名:`gondola`(敞车落箱)/ `flatbed`(平车落箱)/ `ground`(地面堆场)/ `empty`(空画面)。 std::unique_ptr make_synth_source(const SourceConfig& cfg, std::string* error); /// 合成场景名是否合法(空串 = 用默认 gondola,视为合法)。启动校验用,不建源。 bool synth_scene_known(const std::string& name); /// 建 PGM 序列源(`source.type=images`):`uri` = 存放 P5 PGM 的目录(文件名排序 = 时间序)。 /// 零依赖(不需要相机 / GStreamer / 图像解码库)。读到尾部:`source.loop=true` 回绕, /// 否则如实报"已读完"(上层按 `stale_frame_s` → FRAME_TIMEOUT + 255)。 std::unique_ptr make_images_source(const SourceConfig& cfg, std::string* error); /// 建 GStreamer 源(`source.type` = gst/rtsp/file/usb)。 /// 未用 `-DPORTCV_WITH_GSTREAMER=ON` 构建时返回 nullptr,并把"怎么开"写进 error(不静默降级)。 std::unique_ptr make_gst_source(const SourceConfig& cfg, std::string* error); /// 本次构建是否带 GStreamer。 bool gst_available(); /// 由配置拼出 GStreamer 管线字符串(纯函数,无需 GStreamer 即可自检)。 /// * `gst` → 原样返回 `uri`(现场自写管线,硬件解码写在这里); /// * `rtsp` → `rtspsrc location= latency=... ! ... ! decodebin ! ...appsink`; /// * `file` → `filesrc location= ! decodebin ! ...appsink`; /// * `usb` → `v4l2src device= ! ...appsink`。 /// 统一收尾:`videoconvert ! video/x-raw,format=GRAY8 ! appsink name=portcv_sink /// max-buffers= drop=true sync=false` —— 正好是证据模块要的单通道灰度。 /// **解码用 `decodebin` 而不是写死 `mppvideodec`/`nvdec`**:BSP 装了哪个硬件解码器就自动用哪个, /// 没装则退回软解,现场不必因为"板子换型号"改管线。 std::string gst_pipeline_for(const SourceConfig& cfg); /// 类型是否属于本项目定义的取流类型(语法层校验;与"当前构建能不能用"是两件事)。 bool source_type_known(const std::string& type); /// 按 uri 推断取流类型(`--source-uri` 用;现场少写一个参数): /// `rtsp://` / `rtsps://` → `rtsp`;`/dev/video*` 或纯数字 → `usb`; /// 含 `!`(GStreamer 管线)→ `gst`;其余 → `file`。 std::string source_type_from_uri(const std::string& uri); /// 该类型在当前构建下是否可用(`gst/rtsp/file/usb` 需要 GStreamer;`none/synth/images` 恒可用)。 bool source_type_available(const std::string& type); /// 取流类型的可读清单(报错文案用)。 std::string source_type_help(); /// 掩掉文本里 `scheme://user:pass@host` 的口令(启动日志用;管线字符串同样适用)。 std::string redact_uri(const std::string& text); /// 按配置建源。 /// * `type=none` → 返回 true 且 `*out = nullptr`(**正常配置**:不取流,主循环行为同旧版); /// * 建好 → 返回 true;类型不认识 / 未编译进来 → 返回 false 并给出**明确原因**; /// 调用方拿到 false 应直接退出(启动即失败,不静默降级)。 bool make_frame_source(const SourceConfig& cfg, std::unique_ptr* out, std::string* error); } // namespace portcv