capture.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // 取流层:相机 / 视频 / RTSP → 当帧灰度图(**唯一**进入证据模块的图像来源)。
  2. //
  3. // 为什么单独成一层(而不是继续写在 main.cpp 里):
  4. // * docs/technical_route.md §5.2 的"线程 A 取帧/解码"从此是真线程:取帧在 A、推理在 B、
  5. // Modbus 在 C。A 阻塞在解码/重连上时,C 照常应答 PLC 的 FC4(读的仍是最近一张完整快照);
  6. // * 语义与 Python `portcv/io/capture.py` 的 `FrameGrabber` **逐项对齐**:
  7. // 配置键同名同义(`source.type/uri/buffer_size/reconnect_s/stale_frame_s`)、
  8. // "只保留最新帧"(丢帧,不排队)、断流按 `reconnect_s` 重连、
  9. // 超过 `stale_frame_s` 没新帧 → `flags.FRAME_TIMEOUT`(见 portcv/service/runner.py);
  10. // * 零外部依赖:`synth` 源(合成帧,台架/CI 用)不需要任何库;真机取流走 GStreamer
  11. // (`-DPORTCV_WITH_GSTREAMER=ON`),**不引入 OpenCV** —— 见 docs/edge_evidence.md §11 第 9 条
  12. // 与 cpp/README.md §1"核心零外部依赖"的交付形态要求。
  13. //
  14. // 取值纪律(与 app_config.cpp 同一条):类型不认识 / 未编译进来一律**启动即报错**,
  15. // 绝不静默降级成"没有画面也能跑"(那会让 PLC 拿到 255 却以为是相机问题)。
  16. #pragma once
  17. #include <chrono>
  18. #include <cstdint>
  19. #include <memory>
  20. #include <mutex>
  21. #include <string>
  22. #include "portcv/edge_image.hpp"
  23. namespace portcv {
  24. /// 取流层的统一时基:steady 秒(与 main.cpp / 帧槽 / stale 判据同一时基,不用墙上时钟)。
  25. inline double capture_now_seconds() {
  26. using namespace std::chrono;
  27. return duration_cast<duration<double>>(steady_clock::now().time_since_epoch()).count();
  28. }
  29. /// 取流配置(键名与 Python `source.*` 同名同义,见 portcv/config.py DEFAULTS)。
  30. struct SourceConfig {
  31. /// `none` | `synth` | `images` | `gst` | `rtsp` | `file` | `usb`
  32. /// * none = 不取流(默认;此时主循环行为与旧版一致:`Frame.gray = nullptr`);
  33. /// * synth = 合成帧(`uri` 取场景名 gondola|flatbed|ground|empty),台架/CI 用,零依赖;
  34. /// * images = PGM 序列(`uri` = 目录,按文件名排序 = 时间序),**零依赖**;
  35. /// 现场片段先 `python scripts/extract_frames.py --clip 片段.mp4 --out <目录>` 转成 P5 PGM
  36. /// —— 于是"没上板卡 / 板卡没带 GStreamer"也能把现场画面灌进 C++ 证据链整定阈值;
  37. /// * gst = `uri` 就是一条完整 GStreamer 管线(现场最灵活,硬件解码写在管线里);
  38. /// * rtsp / file / usb = 按 `uri` 自动拼管线(GStreamer 可用时),省得现场手写管线串。
  39. std::string type = "none";
  40. std::string uri;
  41. int width = 0; ///< 0 = 用源分辨率(`synth` 时 = 渲染宽度,默认 960)
  42. int height = 0; ///< 0 = 用源分辨率(`synth` 时 = 渲染高度,默认 540)
  43. int buffer_size = 2; ///< 解码缓冲帧数(→ appsink `max-buffers`;越小延迟越低)
  44. double reconnect_s = 2.0; ///< 断流后重连间隔(秒)
  45. double stale_frame_s = 0.6; ///< 超过该时间没新帧 → FRAME_TIMEOUT(与 Python 同键同义)
  46. bool loop = false; ///< `file` 源读到尾部是否重开(离线复盘循环)
  47. // ---- 取流层的实现级补充键(Python 侧没有;`source.*` 里对应 §7 表的地位)----
  48. /// `synth` 每帧横向平移像素(>0 → 制造"车辆行走"运动,用于运动门控台架验收)。
  49. double synth_shift_px = 0.0;
  50. /// `synth` 合成场景的随机种子(固定 → 逐像素可复现,CI 用)。
  51. uint32_t synth_seed = 20261010u;
  52. };
  53. /// 一帧(含自增序号与采集时刻)。`valid=false` 表示"这一拍没拿到画面"。
  54. struct CapturedFrame {
  55. GrayImage gray;
  56. long index = 0; ///< 单调递增(丢帧也递增 → 丢帧率可算)
  57. double ts = 0.0; ///< 采集时刻(steady 秒,与 main.cpp 同一时基)
  58. bool valid = false;
  59. };
  60. /// 取流后端接口(与 `Detector` 同风格:open → next* → close)。
  61. class FrameSource {
  62. public:
  63. virtual ~FrameSource() = default;
  64. /// 后端名(日志用):`synth` / `gst`。
  65. virtual std::string name() const = 0;
  66. /// 一行参数摘要(启动日志;不含 uri 里的口令)。
  67. virtual std::string describe() const = 0;
  68. /// 打开/首次连接;失败返回 false 并把原因写进 error。
  69. virtual bool open(std::string* error) = 0;
  70. /// 取下一帧(阻塞至多一个内部超时)。
  71. /// 返回 false = 本拍没拿到画面(掉线 / 超时 / 读到尾),原因写进 error(可空);
  72. /// **不是致命错误**:调用方(取帧线程)按 reconnect_s 重试,状态交给 stale 判据处理。
  73. virtual bool next(CapturedFrame* out, std::string* error) = 0;
  74. /// 释放资源(可重复调用)。
  75. virtual void close() = 0;
  76. };
  77. /// "只保留最新帧"的取帧槽(线程 A 写、线程 B 读)。
  78. ///
  79. /// 为什么不是队列:推理比取帧慢时队列会累积成几秒延迟(吊装场景不可接受)。这里**永远只留
  80. /// 最后一帧**:B 取走时若已有更新的一帧,旧帧直接丢弃 —— 与 `portcv/io/capture.py` 的
  81. /// FrameGrabber 同一取舍。publish/take 都用 swap,不做整帧拷贝。
  82. class FrameSlot {
  83. public:
  84. /// 发布一帧(覆盖尚未被取走的旧帧)。
  85. void publish(CapturedFrame&& frame) {
  86. std::lock_guard<std::mutex> lock(mu_);
  87. frame_.gray.data.swap(frame.gray.data);
  88. frame_.gray.width = frame.gray.width;
  89. frame_.gray.height = frame.gray.height;
  90. frame_.index = frame.index;
  91. frame_.ts = frame.ts;
  92. frame_.valid = frame.valid;
  93. has_ = true;
  94. is_new_ = true;
  95. last_ts_ = frame.ts;
  96. ++version_;
  97. }
  98. /// 取走最新帧(只有存在"尚未取走的新帧"才返回 true;否则 `*out` 不动)。
  99. bool take(CapturedFrame* out) {
  100. if (out == nullptr) { return false; }
  101. std::lock_guard<std::mutex> lock(mu_);
  102. if (!has_ || !is_new_) { return false; }
  103. out->gray.data.swap(frame_.gray.data);
  104. out->gray.width = frame_.gray.width;
  105. out->gray.height = frame_.gray.height;
  106. out->index = frame_.index;
  107. out->ts = frame_.ts;
  108. out->valid = frame_.valid;
  109. is_new_ = false;
  110. return true;
  111. }
  112. /// 看一眼最新帧(不消耗"新帧"标记;会拷贝一次整帧,仅自检/诊断用)。
  113. bool peek(CapturedFrame* out) const {
  114. if (out == nullptr) { return false; }
  115. std::lock_guard<std::mutex> lock(mu_);
  116. if (!has_) { return false; }
  117. out->gray = frame_.gray;
  118. out->index = frame_.index;
  119. out->ts = frame_.ts;
  120. out->valid = frame_.valid;
  121. return true;
  122. }
  123. /// 当前是否有一帧尚未被取走。
  124. bool has_new() const {
  125. std::lock_guard<std::mutex> lock(mu_);
  126. return has_ && is_new_;
  127. }
  128. /// 发布总次数(单调递增;日志里与"推理帧数"相减即丢帧数)。
  129. uint64_t version() const {
  130. std::lock_guard<std::mutex> lock(mu_);
  131. return version_;
  132. }
  133. /// 最近一次发布时刻(steady 秒);从未发布 → -1.0。
  134. /// `stale_frame_s` 判 FRAME_TIMEOUT 就看它(与 Python `grabber.latest.ts` 同义)。
  135. double last_ts() const {
  136. std::lock_guard<std::mutex> lock(mu_);
  137. return last_ts_;
  138. }
  139. /// 最近一帧是否新鲜(`now - last_ts <= stale_s`);从未发布 → false。
  140. bool fresh(double now, double stale_s) const {
  141. const double ts = last_ts();
  142. if (ts < 0.0) { return false; }
  143. return (now - ts) <= stale_s;
  144. }
  145. private:
  146. mutable std::mutex mu_;
  147. CapturedFrame frame_;
  148. bool has_ = false;
  149. bool is_new_ = false;
  150. uint64_t version_ = 0;
  151. double last_ts_ = -1.0;
  152. };
  153. /// 建合成帧源(`source.type=synth`):确定性渲染,不需要相机/模型/任何外部库。
  154. /// `uri` 取场景名:`gondola`(敞车落箱)/ `flatbed`(平车落箱)/ `ground`(地面堆场)/ `empty`(空画面)。
  155. std::unique_ptr<FrameSource> make_synth_source(const SourceConfig& cfg, std::string* error);
  156. /// 合成场景名是否合法(空串 = 用默认 gondola,视为合法)。启动校验用,不建源。
  157. bool synth_scene_known(const std::string& name);
  158. /// 建 PGM 序列源(`source.type=images`):`uri` = 存放 P5 PGM 的目录(文件名排序 = 时间序)。
  159. /// 零依赖(不需要相机 / GStreamer / 图像解码库)。读到尾部:`source.loop=true` 回绕,
  160. /// 否则如实报"已读完"(上层按 `stale_frame_s` → FRAME_TIMEOUT + 255)。
  161. std::unique_ptr<FrameSource> make_images_source(const SourceConfig& cfg, std::string* error);
  162. /// 建 GStreamer 源(`source.type` = gst/rtsp/file/usb)。
  163. /// 未用 `-DPORTCV_WITH_GSTREAMER=ON` 构建时返回 nullptr,并把"怎么开"写进 error(不静默降级)。
  164. std::unique_ptr<FrameSource> make_gst_source(const SourceConfig& cfg, std::string* error);
  165. /// 本次构建是否带 GStreamer。
  166. bool gst_available();
  167. /// 由配置拼出 GStreamer 管线字符串(纯函数,无需 GStreamer 即可自检)。
  168. /// * `gst` → 原样返回 `uri`(现场自写管线,硬件解码写在这里);
  169. /// * `rtsp` → `rtspsrc location=<uri> latency=... ! ... ! decodebin ! ...appsink`;
  170. /// * `file` → `filesrc location=<uri> ! decodebin ! ...appsink`;
  171. /// * `usb` → `v4l2src device=<uri> ! ...appsink`。
  172. /// 统一收尾:`videoconvert ! video/x-raw,format=GRAY8 ! appsink name=portcv_sink
  173. /// max-buffers=<buffer_size> drop=true sync=false` —— 正好是证据模块要的单通道灰度。
  174. /// **解码用 `decodebin` 而不是写死 `mppvideodec`/`nvdec`**:BSP 装了哪个硬件解码器就自动用哪个,
  175. /// 没装则退回软解,现场不必因为"板子换型号"改管线。
  176. std::string gst_pipeline_for(const SourceConfig& cfg);
  177. /// 类型是否属于本项目定义的取流类型(语法层校验;与"当前构建能不能用"是两件事)。
  178. bool source_type_known(const std::string& type);
  179. /// 按 uri 推断取流类型(`--source-uri` 用;现场少写一个参数):
  180. /// `rtsp://` / `rtsps://` → `rtsp`;`/dev/video*` 或纯数字 → `usb`;
  181. /// 含 `!`(GStreamer 管线)→ `gst`;其余 → `file`。
  182. std::string source_type_from_uri(const std::string& uri);
  183. /// 该类型在当前构建下是否可用(`gst/rtsp/file/usb` 需要 GStreamer;`none/synth/images` 恒可用)。
  184. bool source_type_available(const std::string& type);
  185. /// 取流类型的可读清单(报错文案用)。
  186. std::string source_type_help();
  187. /// 掩掉文本里 `scheme://user:pass@host` 的口令(启动日志用;管线字符串同样适用)。
  188. std::string redact_uri(const std::string& text);
  189. /// 按配置建源。
  190. /// * `type=none` → 返回 true 且 `*out = nullptr`(**正常配置**:不取流,主循环行为同旧版);
  191. /// * 建好 → 返回 true;类型不认识 / 未编译进来 → 返回 false 并给出**明确原因**;
  192. /// 调用方拿到 false 应直接退出(启动即失败,不静默降级)。
  193. bool make_frame_source(const SourceConfig& cfg, std::unique_ptr<FrameSource>* out,
  194. std::string* error);
  195. } // namespace portcv