selftest_capture.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. // 取流层 + 黄金语料导出自检(**不需要相机、不需要 GStreamer**)。
  2. //
  3. // 覆盖范围(对应本轮落地的 A1 / B-lite):
  4. // [1] 帧槽 FrameSlot:只保留最新帧 / "新帧"标记只被消费一次 / last_ts 与 fresh 判据
  5. // [2] 合成帧源(零依赖):确定性(同 seed 逐字节一致)/ 尺寸 / 索引递增 / 位移开关 / 非法场景名
  6. // [3] 取流类型与 GStreamer 管线拼装:类型表 / uri 推断 / 管线字符串的每一段 / 引号防护 / 工厂报错
  7. // [4] redact_uri:日志里不留明文口令
  8. // [5] 黄金语料导出:PGM 头部与像素、JSONL 字段、gray_crc32(与独立实现的 CRC-32/IEEE 互检)、
  9. // every=N 抽样、未开启导出时是空操作
  10. // [6] 配置层联动:source.* 解析 / 非法取值启动即报错 / describe 里能看到取流与 GStreamer 能力
  11. // [7] images 源(PGM 序列):现场片段离线复盘用 —— 文件名排序 = 时间序、逐字节一致、
  12. // 读到尾部(loop)、坏帧/坏目录/尺寸不符一律明确报错(游标不推进、不静默跳帧)
  13. //
  14. // 说明:断言描述用 ASCII(GBK 控制台下中文会乱码,影响现场排错),源码注释保持中文。
  15. #include <cmath>
  16. #include <cstdint>
  17. #include <cstdio>
  18. #include <cstring>
  19. #include <string>
  20. #include <utility>
  21. #include <vector>
  22. #include "portcv/app_config.hpp"
  23. #include "portcv/capture.hpp"
  24. #include "portcv/frame_dump.hpp"
  25. #include "portcv/schema.hpp"
  26. namespace {
  27. int g_pass = 0;
  28. int g_fail = 0;
  29. void check(bool ok, const std::string& what) {
  30. if (ok) {
  31. ++g_pass;
  32. std::printf(" [OK] %s\n", what.c_str());
  33. } else {
  34. ++g_fail;
  35. std::printf(" [FAIL] %s\n", what.c_str());
  36. }
  37. }
  38. void check_eq(long long got, long long want, const std::string& what) {
  39. if (got == want) {
  40. ++g_pass;
  41. std::printf(" [OK] %s (=%lld)\n", what.c_str(), got);
  42. } else {
  43. ++g_fail;
  44. std::printf(" [FAIL] %s: got %lld want %lld\n", what.c_str(), got, want);
  45. }
  46. }
  47. void check_near(double got, double want, double tol, const std::string& what) {
  48. if (std::fabs(got - want) <= tol) {
  49. ++g_pass;
  50. std::printf(" [OK] %s (%.4f)\n", what.c_str(), got);
  51. } else {
  52. ++g_fail;
  53. std::printf(" [FAIL] %s: got %.6f want %.6f\n", what.c_str(), got, want);
  54. }
  55. }
  56. void check_text(const std::string& got, const std::string& want, const std::string& what) {
  57. if (got == want) {
  58. ++g_pass;
  59. std::printf(" [OK] %s (%s)\n", what.c_str(), got.c_str());
  60. } else {
  61. ++g_fail;
  62. std::printf(" [FAIL] %s: got \"%s\" want \"%s\"\n", what.c_str(), got.c_str(),
  63. want.c_str());
  64. }
  65. }
  66. void check_has(const std::string& haystack, const std::string& needle, const std::string& what) {
  67. if (haystack.find(needle) != std::string::npos) {
  68. ++g_pass;
  69. std::printf(" [OK] %s\n", what.c_str());
  70. } else {
  71. ++g_fail;
  72. std::printf(" [FAIL] %s: \"%s\" not found in \"%s\"\n", what.c_str(), needle.c_str(),
  73. haystack.c_str());
  74. }
  75. }
  76. /// 读整个文件(二进制)。
  77. bool read_file(const std::string& path, std::string* out) {
  78. std::FILE* fp = std::fopen(path.c_str(), "rb");
  79. if (fp == nullptr) { return false; }
  80. char buf[4096];
  81. out->clear();
  82. std::size_t n = 0;
  83. while ((n = std::fread(buf, 1, sizeof(buf), fp)) > 0) { out->append(buf, n); }
  84. std::fclose(fp);
  85. return true;
  86. }
  87. /// CRC-32/IEEE(独立实现,用于与 frame_dump.cpp 里写进 JSONL 的值互检;
  88. /// 与 Python `zlib.crc32` 同算法 —— 三个实现互检,避免"自己验自己")。
  89. uint32_t ref_crc32(const uint8_t* data, std::size_t len) {
  90. uint32_t crc = 0xFFFFFFFFu;
  91. for (std::size_t i = 0; i < len; ++i) {
  92. crc ^= data[i];
  93. for (int k = 0; k < 8; ++k) {
  94. crc = (crc & 1u) != 0u ? (0xEDB88320u ^ (crc >> 1)) : (crc >> 1);
  95. }
  96. }
  97. return crc ^ 0xFFFFFFFFu;
  98. }
  99. /// 自检用输出目录(与 scripts/soak_watch.py 一样落在 runs/,已 gitignore)。
  100. const char* kOutDir = "runs/selftest_capture";
  101. std::string out_path(const std::string& name) { return std::string(kOutDir) + "/" + name; }
  102. } // namespace
  103. // ---------------------------------------------------------------- [1] 帧槽
  104. void test_frame_slot() {
  105. std::printf("[1] FrameSlot: keep-the-latest frame, consume-once, stale judgement\n");
  106. portcv::FrameSlot slot;
  107. portcv::CapturedFrame out;
  108. check(!slot.take(&out), "empty slot: take() = false");
  109. check(!slot.has_new(), "empty slot: has_new() = false");
  110. check_eq(static_cast<long long>(slot.version()), 0, "empty slot: version = 0");
  111. check_near(slot.last_ts(), -1.0, 1e-12, "empty slot: last_ts = -1");
  112. check(!slot.fresh(100.0, 0.6), "empty slot: never fresh (PLC must not trust it)");
  113. check(!slot.peek(&out), "empty slot: peek() = false");
  114. portcv::CapturedFrame f1;
  115. f1.gray.reset(4, 3, 7);
  116. f1.index = 10;
  117. f1.ts = 100.0;
  118. f1.valid = true;
  119. slot.publish(std::move(f1));
  120. check(slot.has_new(), "after publish: has_new() = true");
  121. check_eq(static_cast<long long>(slot.version()), 1, "after publish: version = 1");
  122. check_near(slot.last_ts(), 100.0, 1e-12, "after publish: last_ts = frame ts");
  123. check(slot.fresh(100.5, 0.6), "fresh: 0.5s old, stale_frame_s=0.6 -> fresh");
  124. check(!slot.fresh(100.7, 0.6), "stale: 0.7s old, stale_frame_s=0.6 -> not fresh");
  125. check(slot.take(&out), "take() after publish = true");
  126. check_eq(out.index, 10, "take() returns the published frame");
  127. check_eq(static_cast<long long>(out.gray.data.size()), 12, "take() carries the pixels (4x3)");
  128. check_eq(static_cast<long long>(out.gray.at(0, 0)), 7, "take() carries pixel value");
  129. check(!slot.has_new(), "new-frame flag is consumed exactly once");
  130. check(!slot.take(&out), "second take() without a new publish = false");
  131. check_near(slot.last_ts(), 100.0, 1e-12, "take() does not change last_ts (stale judgement)");
  132. // 发布两帧但只取一次 → 必须拿到**最新**那帧(丢旧帧,不排队)
  133. portcv::CapturedFrame f2;
  134. f2.gray.reset(2, 2, 1);
  135. f2.index = 11;
  136. f2.ts = 101.0;
  137. slot.publish(std::move(f2));
  138. portcv::CapturedFrame f3;
  139. f3.gray.reset(2, 2, 2);
  140. f3.index = 12;
  141. f3.ts = 102.0;
  142. slot.publish(std::move(f3));
  143. check(slot.take(&out), "drop-old: take() = true");
  144. check_eq(out.index, 12, "drop-old: newest frame wins (index 12)");
  145. check_eq(static_cast<long long>(out.gray.at(0, 0)), 2, "drop-old: pixels come from the newest");
  146. check_eq(static_cast<long long>(slot.version()), 3LL,
  147. "version counts every publish (dropped frames included)");
  148. }
  149. // ---------------------------------------------------------------- [2] 合成帧源
  150. void test_synth_source() {
  151. std::printf("[2] synth source: deterministic, no camera, no external library\n");
  152. portcv::SourceConfig cfg;
  153. cfg.type = "synth";
  154. cfg.uri = "gondola";
  155. std::string error;
  156. std::unique_ptr<portcv::FrameSource> src = portcv::make_synth_source(cfg, &error);
  157. check(src != nullptr, "make_synth_source(gondola) = ok (" + error + ")");
  158. if (!src) { return; }
  159. check_text(src->name(), "synth", "backend name");
  160. check_has(src->describe(), "gondola", "describe() names the scene");
  161. portcv::CapturedFrame f0;
  162. check(src->next(&f0, &error), "next() = true");
  163. check(f0.valid, "frame marked valid");
  164. check_eq(f0.gray.width, 960, "default render width (evidence working size)");
  165. check_eq(f0.gray.height, 540, "default render height");
  166. check_eq(f0.index, 0, "first frame index = 0");
  167. check_eq(static_cast<long long>(f0.gray.data.size()), 960LL * 540LL, "pixels allocated");
  168. portcv::CapturedFrame f1;
  169. check(src->next(&f1, &error), "second next() = true");
  170. check_eq(f1.index, 1, "index increments");
  171. check(f1.gray.data == f0.gray.data, "static scene: consecutive frames identical");
  172. // 确定性:同 seed 的两个源渲染逐字节一致(CI 才能做黄金语料回归)
  173. std::unique_ptr<portcv::FrameSource> same = portcv::make_synth_source(cfg, &error);
  174. check(same != nullptr, "second source with the same seed");
  175. portcv::CapturedFrame f0b;
  176. check(same->next(&f0b, &error), "second source next()");
  177. check(f0b.gray.data == f0.gray.data, "same seed -> byte-identical pixels");
  178. // 换 seed → 噪声不同 → 不再逐字节一致(否则"确定性"是假的)
  179. portcv::SourceConfig other = cfg;
  180. other.synth_seed = 12345u;
  181. std::unique_ptr<portcv::FrameSource> other_src = portcv::make_synth_source(other, &error);
  182. check(other_src != nullptr, "source with a different seed");
  183. portcv::CapturedFrame f0c;
  184. check(other_src->next(&f0c, &error), "different seed next()");
  185. check(!(f0c.gray.data == f0.gray.data), "different seed -> different pixels");
  186. // 尺寸覆盖:source.width/height 只影响 synth 渲染(真机取流以管线为准)
  187. portcv::SourceConfig small = cfg;
  188. small.width = 320;
  189. small.height = 200;
  190. std::unique_ptr<portcv::FrameSource> small_src = portcv::make_synth_source(small, &error);
  191. check(small_src != nullptr, "size override honoured");
  192. portcv::CapturedFrame fs;
  193. check(small_src->next(&fs, &error), "size override next()");
  194. check_eq(fs.gray.width, 320, "source.width = 320");
  195. check_eq(fs.gray.height, 200, "source.height = 200");
  196. // 位移开关:synth_shift_px>0 → 帧间有位移(运动门控台架验收用)
  197. portcv::SourceConfig moving = cfg;
  198. moving.synth_shift_px = 4.0;
  199. std::unique_ptr<portcv::FrameSource> move_src = portcv::make_synth_source(moving, &error);
  200. check(move_src != nullptr, "shift source");
  201. portcv::CapturedFrame m0;
  202. portcv::CapturedFrame m1;
  203. check(move_src->next(&m0, &error) && move_src->next(&m1, &error), "shift source next() x2");
  204. check(!(m1.gray.data == m0.gray.data), "synth_shift_px>0 -> consecutive frames differ");
  205. // 四个场景名都能渲染;非法场景名 / 空 uri 行为明确
  206. const char* const scenes[] = {"gondola", "flatbed", "ground", "empty"};
  207. for (const char* name : scenes) {
  208. portcv::SourceConfig sc = cfg;
  209. sc.uri = name;
  210. std::unique_ptr<portcv::FrameSource> s = portcv::make_synth_source(sc, &error);
  211. portcv::CapturedFrame frame;
  212. const bool ok = s != nullptr && s->next(&frame, &error) && !frame.gray.empty();
  213. check(ok, std::string("scene \"") + name + "\" renders");
  214. }
  215. check(portcv::synth_scene_known("gondola"), "synth_scene_known(gondola) = true");
  216. check(portcv::synth_scene_known(""), "synth_scene_known(\"\") = true (default gondola)");
  217. check(!portcv::synth_scene_known("cam0"), "synth_scene_known(cam0) = false");
  218. portcv::SourceConfig bad = cfg;
  219. bad.uri = "nope";
  220. error.clear();
  221. std::unique_ptr<portcv::FrameSource> bad_src = portcv::make_synth_source(bad, &error);
  222. check(bad_src == nullptr, "unknown scene name -> nullptr");
  223. check_has(error, "gondola", "unknown scene name -> error lists valid names");
  224. // close() 后可再用(断流重连路径不允许"关了就再也开不了")
  225. src->close();
  226. portcv::CapturedFrame after_close;
  227. check(src->next(&after_close, &error), "next() after close() re-opens");
  228. }
  229. // ---------------------------------------------------------------- [3] 类型与 GStreamer 管线
  230. void test_types_and_pipeline() {
  231. std::printf("[3] source types + GStreamer pipeline building (no GStreamer needed)\n");
  232. check(portcv::source_type_known("none"), "known: none");
  233. check(portcv::source_type_known("synth"), "known: synth");
  234. check(portcv::source_type_known("gst"), "known: gst");
  235. check(portcv::source_type_known("rtsp"), "known: rtsp");
  236. check(portcv::source_type_known("file"), "known: file");
  237. check(portcv::source_type_known("usb"), "known: usb");
  238. check(portcv::source_type_known("images"), "known: images (PGM sequence, zero-dep)");
  239. check(!portcv::source_type_known("synthetic"), "unknown: synthetic");
  240. check(!portcv::source_type_known(""), "unknown: empty");
  241. check(portcv::source_type_available("none"), "available: none (always)");
  242. check(portcv::source_type_available("synth"), "available: synth (always)");
  243. check(portcv::source_type_available("images"),
  244. "available: images (always; no GStreamer, no image codec)");
  245. check_eq(static_cast<long long>(portcv::source_type_available("rtsp")),
  246. static_cast<long long>(portcv::gst_available()),
  247. "available: rtsp mirrors the build flag (-DPORTCV_WITH_GSTREAMER)");
  248. check_has(portcv::source_type_help(), "source.type", "type help mentions the key");
  249. check_text(portcv::source_type_from_uri("rtsp://a/b"), "rtsp", "infer rtsp://");
  250. check_text(portcv::source_type_from_uri("rtsps://a/b"), "rtsp", "infer rtsps://");
  251. check_text(portcv::source_type_from_uri("/dev/video0"), "usb", "infer /dev/video*");
  252. check_text(portcv::source_type_from_uri("0"), "usb", "infer camera index 0");
  253. check_text(portcv::source_type_from_uri("filesrc location=a.mp4 ! decodebin"), "gst",
  254. "infer gst pipeline (contains '!')");
  255. check_text(portcv::source_type_from_uri("samples/demo.mp4"), "file", "infer file path");
  256. portcv::SourceConfig cfg;
  257. cfg.type = "gst";
  258. cfg.uri = "videotestsrc ! videoconvert ! appsink name=portcv_sink";
  259. check_text(portcv::gst_pipeline_for(cfg), cfg.uri, "type=gst: uri is used verbatim");
  260. cfg.type = "rtsp";
  261. cfg.uri = "rtsp://cam/stream";
  262. cfg.buffer_size = 1;
  263. const std::string rtsp = portcv::gst_pipeline_for(cfg);
  264. check_has(rtsp, "rtspsrc location=\"rtsp://cam/stream\"", "rtsp: rtspsrc + quoted location");
  265. check_has(rtsp, "decodebin", "rtsp: decodebin picks the decoder (hw or sw)");
  266. check_has(rtsp, "video/x-raw,format=GRAY8", "sink side converts to GRAY8 (what evidence needs)");
  267. check_has(rtsp, "appsink name=portcv_sink", "sink is named portcv_sink");
  268. check_has(rtsp, "max-buffers=1", "buffer_size=1 -> max-buffers=1");
  269. check_has(rtsp, "drop=true", "drop=true (keep the latest frame)");
  270. check_has(rtsp, "sync=false", "sync=false (no clock sync: lowest latency)");
  271. cfg.buffer_size = 4;
  272. check_has(portcv::gst_pipeline_for(cfg), "max-buffers=4", "buffer_size=4 -> max-buffers=4");
  273. cfg.buffer_size = 0;
  274. check_has(portcv::gst_pipeline_for(cfg), "max-buffers=1", "buffer_size=0 -> clamped to 1");
  275. cfg.type = "file";
  276. cfg.uri = "samples/demo.mp4";
  277. check_has(portcv::gst_pipeline_for(cfg), "filesrc location=\"samples/demo.mp4\"",
  278. "file: filesrc + quoted path");
  279. cfg.type = "usb";
  280. cfg.uri = "/dev/video0";
  281. check_has(portcv::gst_pipeline_for(cfg), "v4l2src device=\"/dev/video0\"",
  282. "usb: v4l2src + quoted device");
  283. // 引号防护:配置里的一个 " 不能把整条管线改成别的东西
  284. cfg.type = "rtsp";
  285. cfg.uri = "rtsp://cam/a\" evil";
  286. check_text(portcv::gst_pipeline_for(cfg), "", "uri containing a quote -> empty pipeline");
  287. // 工厂:none 是正常配置;未知类型 / 未编译进来的类型必须给明确原因
  288. std::string error;
  289. std::unique_ptr<portcv::FrameSource> src;
  290. portcv::SourceConfig none;
  291. check(portcv::make_frame_source(none, &src, &error), "make_frame_source(none) = true");
  292. check(src == nullptr, "type=none -> no source object (legacy loop path)");
  293. portcv::SourceConfig bogus;
  294. bogus.type = "camera";
  295. error.clear();
  296. check(!portcv::make_frame_source(bogus, &src, &error), "unknown type -> false");
  297. check_has(error, "source.type", "unknown type -> error names the key");
  298. portcv::SourceConfig gst;
  299. gst.type = "rtsp";
  300. gst.uri = "rtsp://cam/stream";
  301. error.clear();
  302. const bool made = portcv::make_frame_source(gst, &src, &error);
  303. if (portcv::gst_available()) {
  304. check(made || !error.empty(), "with GStreamer: build either succeeds or reports why");
  305. } else {
  306. check(!made, "without GStreamer: rtsp -> false (no silent downgrade)");
  307. check_has(error, "GStreamer", "without GStreamer: error says how to enable it");
  308. }
  309. }
  310. // ---------------------------------------------------------------- [4] 口令掩码
  311. void test_redact() {
  312. std::printf("[4] redact_uri: no plaintext password in the startup log\n");
  313. const std::string masked = portcv::redact_uri("rtsp://admin:secret@192.168.1.64:554/x");
  314. check(masked.find("secret") == std::string::npos, "password removed");
  315. check_has(masked, "***", "password replaced with ***");
  316. check_has(masked, "192.168.1.64", "host preserved");
  317. check_text(portcv::redact_uri("rtsp://192.168.1.64:554/x"), "rtsp://192.168.1.64:554/x",
  318. "no userinfo -> unchanged");
  319. check_text(portcv::redact_uri("samples/demo.mp4"), "samples/demo.mp4",
  320. "no scheme -> unchanged");
  321. }
  322. // ---------------------------------------------------------------- [5] 黄金语料导出
  323. void test_dump() {
  324. std::printf("[5] golden dump: PGM pixels + JSONL evidence (tuning / regression path)\n");
  325. std::string error;
  326. check(portcv::ensure_dir(kOutDir, &error), "ensure_dir(" + std::string(kOutDir) + "): " + error);
  327. portcv::GrayImage img(5, 4, 0);
  328. for (int y = 0; y < 4; ++y) {
  329. for (int x = 0; x < 5; ++x) { img.set(x, y, static_cast<uint8_t>(x * 10 + y)); }
  330. }
  331. const std::string pgm = out_path("unit.pgm");
  332. check(portcv::write_pgm(pgm, img, &error), "write_pgm: " + error);
  333. std::string blob;
  334. check(read_file(pgm, &blob), "pgm readable");
  335. check_eq(static_cast<long long>(blob.size()), 11LL + 20LL, "pgm = header(11) + 5*4 pixels");
  336. check_text(blob.substr(0, 11), std::string("P5\n5 4\n255\n"), "pgm P5 header (single space)");
  337. check_eq(static_cast<long long>(static_cast<unsigned char>(blob[11])), 0, "pixel (0,0) = 0");
  338. check_eq(static_cast<long long>(static_cast<unsigned char>(blob[11 + 5])), 1, "pixel (0,1) = 1");
  339. check_eq(static_cast<long long>(static_cast<unsigned char>(blob[11 + 4])), 40,
  340. "pixel (4,0) = 40 (row-major)");
  341. portcv::VisionSnapshot snap;
  342. snap.state = 2;
  343. snap.confidence = 870;
  344. snap.flags = 0x0006;
  345. snap.seq = 7;
  346. snap.heartbeat = 3;
  347. snap.fps_x10 = 150;
  348. snap.latency_ms = 22;
  349. portcv::Evidence ev;
  350. ev.set(portcv::EvidenceKey::F1, true);
  351. ev.set(portcv::EvidenceKey::F2, true);
  352. ev.score_b = 1.7;
  353. ev.box_h_px = 311.5;
  354. ev.px_per_m = 120.25;
  355. ev.segments_total = 42;
  356. ev.scale_ok = true;
  357. ev.diag = portcv::EdgeDiag::NONE;
  358. const std::string jsonl = out_path("unit.jsonl");
  359. portcv::DumpConfig dc;
  360. dc.jsonl_path = jsonl;
  361. dc.image_dir = out_path("frames");
  362. dc.every = 2;
  363. portcv::FrameDumper dumper;
  364. check(dumper.open(dc, &error), "dumper.open: " + error);
  365. check(dumper.enabled(), "enabled() after open");
  366. check(dumper.wants(0) && !dumper.wants(1) && dumper.wants(2), "every=2 sampling rule");
  367. const uint32_t want_crc = ref_crc32(img.data.data(), img.data.size());
  368. for (long index = 0; index < 3; ++index) {
  369. portcv::DumpFrame df;
  370. df.index = index;
  371. df.ts = 1000.0 + static_cast<double>(index);
  372. df.gray = &img;
  373. df.snap = &snap;
  374. df.evidence = &ev;
  375. df.summary = "[F1 F2 ] sB=1.7";
  376. df.reason = "unit";
  377. df.edge_state = 2;
  378. df.edge_conf = 0.8700;
  379. df.vote_state = 2;
  380. check(dumper.write(df, &error), "dumper.write(frame) #" + std::to_string(index));
  381. }
  382. check_eq(static_cast<long long>(dumper.written()), 2, "every=2 -> 2 of 3 frames written");
  383. dumper.close();
  384. std::string lines;
  385. check(read_file(jsonl, &lines), "jsonl readable");
  386. check_has(lines, "\"frame\":0", "jsonl line for frame 0");
  387. check_has(lines, "\"frame\":2", "jsonl line for frame 2");
  388. check(lines.find("\"frame\":1") == std::string::npos, "frame 1 skipped (every=2)");
  389. check_has(lines, "\"state\":2", "jsonl carries state");
  390. check_has(lines, "\"edge_state\":2", "jsonl carries the per-frame edge verdict");
  391. check_has(lines, "\"edge_conf\":0.8700",
  392. "jsonl carries the per-frame verdict confidence (not the held one)");
  393. check_has(lines, "\"vote_state\":2", "jsonl carries the voted state (pre publish gate)");
  394. check_has(lines, "\"conf_x1000\":870", "jsonl carries confidence (per-mille)");
  395. check_has(lines, "\"flags\":6", "jsonl carries the flags word");
  396. check_has(lines, "\"ev\":{\"P1\":false", "jsonl carries every evidence key in a fixed order");
  397. check_has(lines, "\"F2\":true", "jsonl carries the hit evidence");
  398. check_has(lines, "\"image\":\"frame_000000.pgm\"", "jsonl names the PGM");
  399. check_has(lines, "\"gray_crc32\":" + std::to_string(want_crc),
  400. "gray_crc32 matches an independent CRC-32/IEEE implementation");
  401. check(read_file(out_path("frames/frame_000000.pgm"), &blob), "PGM written for frame 0");
  402. check(!read_file(out_path("frames/frame_000001.pgm"), &blob), "no PGM for the skipped frame");
  403. portcv::FrameDumper off;
  404. portcv::DumpConfig empty;
  405. check(off.open(empty, &error), "open with empty path = ok (dumping disabled)");
  406. check(!off.enabled(), "empty path -> disabled");
  407. portcv::DumpFrame df;
  408. df.gray = &img;
  409. check(off.write(df, &error), "write while disabled = true (no-op)");
  410. check_eq(static_cast<long long>(off.written()), 0, "nothing written while disabled");
  411. }
  412. // ---------------------------------------------------------------- [6] 配置层联动
  413. void test_config_layer() {
  414. std::printf("[6] config layer: source.* keys (same names as portcv/config.py)\n");
  415. const std::string json =
  416. "{\"run\":{\"backend\":\"edge\"},"
  417. "\"source\":{\"type\":\"synth\",\"uri\":\"ground\",\"buffer_size\":3,"
  418. "\"reconnect_s\":1.5,\"stale_frame_s\":0.8,\"loop\":true,\"synth_shift_px\":2,"
  419. "\"synth_seed\":7},"
  420. "\"plc\":{\"enabled\":false}}";
  421. portcv::AppConfig cfg;
  422. std::string error;
  423. check(portcv::app_config_from_text(json, &cfg, &error), "source.* config loads: " + error);
  424. check_text(cfg.source.type, "synth", "source.type");
  425. check_text(cfg.source.uri, "ground", "source.uri");
  426. check_eq(cfg.source.buffer_size, 3, "source.buffer_size");
  427. check_near(cfg.source.reconnect_s, 1.5, 1e-12, "source.reconnect_s");
  428. check_near(cfg.source.stale_frame_s, 0.8, 1e-12, "source.stale_frame_s");
  429. check(cfg.source.loop, "source.loop");
  430. check_near(cfg.source.synth_shift_px, 2.0, 1e-12, "source.synth_shift_px");
  431. check_eq(static_cast<long long>(cfg.source.synth_seed), 7, "source.synth_seed");
  432. const std::string sheet = portcv::describe_app_config(cfg);
  433. check_has(sheet, "source.type=synth", "sheet shows the source type");
  434. check_has(sheet, "stale_frame_s=0.80", "sheet shows the stale timeout");
  435. check_has(sheet, "GStreamer", "sheet shows the build capability");
  436. // 不写 source.* → 不取流(旧行为);默认值与 Python 同值(buffer_size / stale_frame_s)
  437. portcv::AppConfig d;
  438. check(portcv::app_config_from_text("{\"plc\":{\"enabled\":false}}", &d, &error),
  439. "config without source.* loads");
  440. check_text(d.source.type, "none", "default source.type = none (legacy loop path kept)");
  441. check_eq(d.source.buffer_size, 2, "default source.buffer_size = 2 (same as Python)");
  442. check_near(d.source.stale_frame_s, 0.6, 1e-12, "default stale_frame_s = 0.6 (same as Python)");
  443. check_near(d.source.reconnect_s, 2.0, 1e-12, "default reconnect_s = 2.0 (same as Python)");
  444. struct Case {
  445. const char* json;
  446. const char* needle;
  447. };
  448. const Case cases[] = {
  449. {"{\"source\":{\"type\":\"camera\"}}", "source.type"},
  450. {"{\"source\":{\"type\":\"images\"}}", "source.uri"},
  451. {"{\"source\":{\"type\":\"rtsp\"}}", "source.uri"},
  452. {"{\"source\":{\"type\":\"synth\",\"uri\":\"cam0\"}}", "source.uri"},
  453. {"{\"source\":{\"type\":\"file\",\"uri\":\"a\\\"b\"}}", "双引号"},
  454. {"{\"source\":{\"buffer_size\":-1}}", "source.buffer_size"},
  455. {"{\"source\":{\"reconnect_s\":0}}", "source.reconnect_s"},
  456. {"{\"source\":{\"stale_frame_s\":0}}", "source.stale_frame_s"},
  457. {"{\"source\":{\"width\":-1}}", "source.width"},
  458. {"{\"source\":{\"type\":123}}", "source.type"},
  459. };
  460. for (const Case& c : cases) {
  461. portcv::AppConfig bad;
  462. std::string bad_error;
  463. const bool ok = portcv::app_config_from_text(c.json, &bad, &bad_error);
  464. check(!ok && bad_error.find(c.needle) != std::string::npos,
  465. std::string("rejected with a clear reason: ") + c.json);
  466. }
  467. }
  468. // ---------------------------------------------------------------- [7] images 源(PGM 序列)
  469. /// 写原始字节(造坏文件用)。
  470. bool write_bytes(const std::string& path, const std::string& blob) {
  471. std::FILE* fp = std::fopen(path.c_str(), "wb");
  472. if (fp == nullptr) { return false; }
  473. const std::size_t n = std::fwrite(blob.data(), 1, blob.size(), fp);
  474. std::fclose(fp);
  475. return n == blob.size();
  476. }
  477. void test_images_source() {
  478. std::printf("[7] images source: field-footage PGM sequence (no camera, no GStreamer)\n");
  479. std::string error;
  480. const std::string dir = out_path("images_seq");
  481. check(portcv::ensure_dir(dir, &error), "ensure_dir(" + dir + "): " + error);
  482. portcv::GrayImage f0(4, 3, 11);
  483. portcv::GrayImage f1(4, 3, 22);
  484. portcv::GrayImage f2(4, 3, 33);
  485. check(portcv::write_pgm(dir + "/frame_000000.pgm", f0, &error), "write frame 0: " + error);
  486. check(portcv::write_pgm(dir + "/frame_000001.pgm", f1, &error), "write frame 1: " + error);
  487. check(portcv::write_pgm(dir + "/frame_000010.pgm", f2, &error), "write frame 10: " + error);
  488. check(write_bytes(dir + "/notes.txt", "not an image"), "non-PGM file present (must be ignored)");
  489. check(write_bytes(dir + "/frame_000002.raw", "xxxx"), "non-PGM frame name (ignored)");
  490. portcv::SourceConfig cfg;
  491. cfg.type = "images";
  492. cfg.uri = dir;
  493. std::unique_ptr<portcv::FrameSource> src = portcv::make_images_source(cfg, &error);
  494. check(src != nullptr, "make_images_source: " + error);
  495. if (src == nullptr) { // 后面全是它的行为断言;空指针解引用会把真因埋在崩溃里
  496. check(false, "cannot continue: images source was not created");
  497. return;
  498. }
  499. check_text(src->name(), "images", "backend name");
  500. check_has(src->describe(), "frames=3", "describe() counts only *.pgm");
  501. check_has(src->describe(), "loop=0", "describe() shows loop=0");
  502. portcv::CapturedFrame a;
  503. portcv::CapturedFrame b;
  504. portcv::CapturedFrame c;
  505. check(src->next(&a, &error) && src->next(&b, &error) && src->next(&c, &error),
  506. "3 frames readable in name order");
  507. check(a.gray.data == f0.data, "frame 0 pixels byte-identical to the PGM on disk");
  508. check(b.gray.data == f1.data, "frame 1 pixels byte-identical");
  509. check(c.gray.data == f2.data, "frame 000010 last (sorted: 000000 < 000001 < 000010)");
  510. check_eq(a.index, 0, "index starts at 0");
  511. check_eq(c.index, 2, "index increments per frame");
  512. check(a.ts <= c.ts, "timestamps are non-decreasing");
  513. check(c.valid, "frames are marked valid");
  514. check(c.gray.width == 4 && c.gray.height == 3, "size follows the PGM header");
  515. portcv::CapturedFrame end;
  516. check(!src->next(&end, &error), "loop=false: reading past the end returns false");
  517. check_has(error, "已读完", "end of sequence is reported (no silent fake frame)");
  518. src->close();
  519. portcv::CapturedFrame again;
  520. check(src->next(&again, &error), "next() after close() re-opens");
  521. check(again.gray.data == f0.data, "re-open restarts at frame 0");
  522. // loop=true:回绕(本拍 false,下一拍从第 0 帧接着出)
  523. portcv::SourceConfig looping = cfg;
  524. looping.loop = true;
  525. std::unique_ptr<portcv::FrameSource> loop_src = portcv::make_images_source(looping, &error);
  526. check(loop_src != nullptr, "loop=true source: " + error);
  527. portcv::CapturedFrame l0;
  528. portcv::CapturedFrame l1;
  529. portcv::CapturedFrame l2;
  530. portcv::CapturedFrame l3;
  531. check(loop_src->next(&l0, &error) && loop_src->next(&l1, &error) && loop_src->next(&l2, &error),
  532. "loop: first pass over 3 frames");
  533. check(!loop_src->next(&l3, &error), "loop: rewind tick yields no frame");
  534. check_has(error, "回绕", "loop: rewind is reported");
  535. check(loop_src->next(&l3, &error), "loop: next tick starts over");
  536. check(l3.gray.data == f0.data, "loop: back to frame 0");
  537. // 走工厂这条路(--source-type images 走的就是它)
  538. std::unique_ptr<portcv::FrameSource> via_factory;
  539. error.clear();
  540. check(portcv::make_frame_source(cfg, &via_factory, &error),
  541. "make_frame_source(type=images): " + error);
  542. check_text(via_factory != nullptr ? via_factory->name() : std::string(), "images",
  543. "factory returns the images source");
  544. // 负向:目录不存在 / 空目录 / 没给 uri / 坏文件 —— 一律**启动即报错**(不静默变成"没有画面")
  545. portcv::SourceConfig missing = cfg;
  546. missing.uri = out_path("images_missing");
  547. error.clear();
  548. check(portcv::make_images_source(missing, &error) == nullptr, "missing dir -> nullptr");
  549. check_has(error, "source.uri", "missing dir -> error names source.uri");
  550. const std::string empty_dir = out_path("images_empty");
  551. check(portcv::ensure_dir(empty_dir, &error), "ensure_dir(" + empty_dir + ")");
  552. portcv::SourceConfig empty_cfg = cfg;
  553. empty_cfg.uri = empty_dir;
  554. error.clear();
  555. check(portcv::make_images_source(empty_cfg, &error) == nullptr, "dir without *.pgm -> nullptr");
  556. check_has(error, "没有 *.pgm", "empty dir -> error says what is missing");
  557. portcv::SourceConfig no_uri = cfg;
  558. no_uri.uri.clear();
  559. error.clear();
  560. check(portcv::make_images_source(no_uri, &error) == nullptr, "empty uri -> nullptr");
  561. check_has(error, "source.uri", "empty uri -> error names the key");
  562. // 坏文件:不是 P5 / 像素截断 / 16 bit —— 报错要能直接指导现场怎么修
  563. struct BadCase {
  564. const char* dir_name;
  565. const char* blob;
  566. const char* needle;
  567. };
  568. const BadCase bads[] = {
  569. {"images_notp5", "P2\n4 3\n255\n1 2 3 4", "P5"},
  570. {"images_trunc", "P5\n4 3\n255\nabc", "像素不完整"},
  571. {"images_16bit", "P5\n2 2\n65535\n01234567", "8 bit"},
  572. };
  573. for (const BadCase& bc : bads) {
  574. const std::string bdir = out_path(bc.dir_name);
  575. check(portcv::ensure_dir(bdir, &error), std::string("ensure_dir(") + bc.dir_name + ")");
  576. check(write_bytes(bdir + "/frame_000000.pgm", bc.blob), "write a bad PGM");
  577. portcv::SourceConfig bad_cfg = cfg;
  578. bad_cfg.uri = bdir;
  579. error.clear();
  580. check(portcv::make_images_source(bad_cfg, &error) == nullptr,
  581. std::string(bc.dir_name) + " -> nullptr");
  582. check_has(error, bc.needle, std::string(bc.dir_name) + " -> actionable error");
  583. }
  584. // 尺寸不符:写了 source.width 就必须一致(**不静默缩放**)
  585. portcv::SourceConfig sized = cfg;
  586. sized.width = 5;
  587. error.clear();
  588. check(portcv::make_images_source(sized, &error) == nullptr, "width mismatch -> nullptr");
  589. check_has(error, "source.width", "width mismatch -> error names source.width");
  590. // 容忍注释与 maxval<255(别人用 magick 转的图也能读);像素按原值读入(不缩放)
  591. const std::string tol_dir = out_path("images_tolerant");
  592. check(portcv::ensure_dir(tol_dir, &error), "ensure_dir(images_tolerant)");
  593. check(write_bytes(tol_dir + "/frame_000000.pgm",
  594. "P5\n# made by magick\n2 2\n15\n\x01\x02\x03\x04"),
  595. "write a PGM with a comment line");
  596. portcv::SourceConfig tol_cfg = cfg;
  597. tol_cfg.uri = tol_dir;
  598. std::unique_ptr<portcv::FrameSource> tol_src = portcv::make_images_source(tol_cfg, &error);
  599. check(tol_src != nullptr, "comment header parses: " + error);
  600. if (tol_src == nullptr) {
  601. check(false, "cannot continue: tolerant-PGM source was not created");
  602. return;
  603. }
  604. portcv::CapturedFrame tol_frame;
  605. check(tol_src->next(&tol_frame, &error), "tolerant PGM frame read");
  606. check(tol_frame.gray.width == 2 && tol_frame.gray.height == 2, "tolerant PGM size");
  607. check_eq(static_cast<long long>(tol_frame.gray.at(1, 1)), 4, "pixels taken as-is (maxval 15)");
  608. // 中间一帧坏了:报错 + **游标不推进**(不静默跳过 —— 跳帧会让结论与像素对不上)
  609. const std::string mid_dir = out_path("images_midbroken");
  610. check(portcv::ensure_dir(mid_dir, &error), "ensure_dir(images_midbroken)");
  611. check(portcv::write_pgm(mid_dir + "/frame_000000.pgm", f0, &error), "mid: frame 0 ok");
  612. check(write_bytes(mid_dir + "/frame_000001.pgm", "P5\n4 3\n255\nab"), "mid: frame 1 truncated");
  613. check(portcv::write_pgm(mid_dir + "/frame_000002.pgm", f2, &error), "mid: frame 2 ok");
  614. portcv::SourceConfig mid_cfg = cfg;
  615. mid_cfg.uri = mid_dir;
  616. std::unique_ptr<portcv::FrameSource> mid_src = portcv::make_images_source(mid_cfg, &error);
  617. check(mid_src != nullptr, "mid-broken source opens (first frame is valid)");
  618. if (mid_src == nullptr) {
  619. check(false, "cannot continue: mid-broken source was not created");
  620. return;
  621. }
  622. portcv::CapturedFrame mid0;
  623. check(mid_src->next(&mid0, &error), "mid: frame 0 read");
  624. portcv::CapturedFrame mid1;
  625. check(!mid_src->next(&mid1, &error), "mid: broken frame reports false");
  626. check_has(error, "像素不完整", "mid: broken frame says why");
  627. check(!mid_src->next(&mid1, &error), "mid: retry hits the SAME frame (cursor does not skip)");
  628. check_has(error, "frame_000001.pgm", "mid: error names the offending file");
  629. }
  630. int main() {
  631. // 不缓冲 stdout:Windows 下 stdout 接管道时是**全缓冲**的,一旦哪条断言把进程打崩
  632. // (自检的价值就在于暴露崩溃),最后的输出会留在缓冲区里丢掉 —— 现场只能看到"崩了",
  633. // 看不到崩在哪一条。逐行刷出后,崩溃点直接落在最后一行 [OK]/[FAIL] 上。
  634. std::setvbuf(stdout, nullptr, _IONBF, 0);
  635. std::printf("portcv capture selftest (docs/runtime_route_decision.md; A1 + B-lite)\n");
  636. test_frame_slot();
  637. test_synth_source();
  638. test_types_and_pipeline();
  639. test_redact();
  640. test_dump();
  641. test_config_layer();
  642. test_images_source();
  643. std::printf("\n=================================================\n");
  644. std::printf("%d passed / %d failed\n", g_pass, g_fail);
  645. return g_fail == 0 ? 0 : 1;
  646. }