| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712 |
- // 取流层 + 黄金语料导出自检(**不需要相机、不需要 GStreamer**)。
- //
- // 覆盖范围(对应本轮落地的 A1 / B-lite):
- // [1] 帧槽 FrameSlot:只保留最新帧 / "新帧"标记只被消费一次 / last_ts 与 fresh 判据
- // [2] 合成帧源(零依赖):确定性(同 seed 逐字节一致)/ 尺寸 / 索引递增 / 位移开关 / 非法场景名
- // [3] 取流类型与 GStreamer 管线拼装:类型表 / uri 推断 / 管线字符串的每一段 / 引号防护 / 工厂报错
- // [4] redact_uri:日志里不留明文口令
- // [5] 黄金语料导出:PGM 头部与像素、JSONL 字段、gray_crc32(与独立实现的 CRC-32/IEEE 互检)、
- // every=N 抽样、未开启导出时是空操作
- // [6] 配置层联动:source.* 解析 / 非法取值启动即报错 / describe 里能看到取流与 GStreamer 能力
- // [7] images 源(PGM 序列):现场片段离线复盘用 —— 文件名排序 = 时间序、逐字节一致、
- // 读到尾部(loop)、坏帧/坏目录/尺寸不符一律明确报错(游标不推进、不静默跳帧)
- //
- // 说明:断言描述用 ASCII(GBK 控制台下中文会乱码,影响现场排错),源码注释保持中文。
- #include <cmath>
- #include <cstdint>
- #include <cstdio>
- #include <cstring>
- #include <string>
- #include <utility>
- #include <vector>
- #include "portcv/app_config.hpp"
- #include "portcv/capture.hpp"
- #include "portcv/frame_dump.hpp"
- #include "portcv/schema.hpp"
- namespace {
- int g_pass = 0;
- int g_fail = 0;
- void check(bool ok, const std::string& what) {
- if (ok) {
- ++g_pass;
- std::printf(" [OK] %s\n", what.c_str());
- } else {
- ++g_fail;
- std::printf(" [FAIL] %s\n", what.c_str());
- }
- }
- void check_eq(long long got, long long want, const std::string& what) {
- if (got == want) {
- ++g_pass;
- std::printf(" [OK] %s (=%lld)\n", what.c_str(), got);
- } else {
- ++g_fail;
- std::printf(" [FAIL] %s: got %lld want %lld\n", what.c_str(), got, want);
- }
- }
- void check_near(double got, double want, double tol, const std::string& what) {
- if (std::fabs(got - want) <= tol) {
- ++g_pass;
- std::printf(" [OK] %s (%.4f)\n", what.c_str(), got);
- } else {
- ++g_fail;
- std::printf(" [FAIL] %s: got %.6f want %.6f\n", what.c_str(), got, want);
- }
- }
- void check_text(const std::string& got, const std::string& want, const std::string& what) {
- if (got == want) {
- ++g_pass;
- std::printf(" [OK] %s (%s)\n", what.c_str(), got.c_str());
- } else {
- ++g_fail;
- std::printf(" [FAIL] %s: got \"%s\" want \"%s\"\n", what.c_str(), got.c_str(),
- want.c_str());
- }
- }
- void check_has(const std::string& haystack, const std::string& needle, const std::string& what) {
- if (haystack.find(needle) != std::string::npos) {
- ++g_pass;
- std::printf(" [OK] %s\n", what.c_str());
- } else {
- ++g_fail;
- std::printf(" [FAIL] %s: \"%s\" not found in \"%s\"\n", what.c_str(), needle.c_str(),
- haystack.c_str());
- }
- }
- /// 读整个文件(二进制)。
- bool read_file(const std::string& path, std::string* out) {
- std::FILE* fp = std::fopen(path.c_str(), "rb");
- if (fp == nullptr) { return false; }
- char buf[4096];
- out->clear();
- std::size_t n = 0;
- while ((n = std::fread(buf, 1, sizeof(buf), fp)) > 0) { out->append(buf, n); }
- std::fclose(fp);
- return true;
- }
- /// CRC-32/IEEE(独立实现,用于与 frame_dump.cpp 里写进 JSONL 的值互检;
- /// 与 Python `zlib.crc32` 同算法 —— 三个实现互检,避免"自己验自己")。
- uint32_t ref_crc32(const uint8_t* data, std::size_t len) {
- uint32_t crc = 0xFFFFFFFFu;
- for (std::size_t i = 0; i < len; ++i) {
- crc ^= data[i];
- for (int k = 0; k < 8; ++k) {
- crc = (crc & 1u) != 0u ? (0xEDB88320u ^ (crc >> 1)) : (crc >> 1);
- }
- }
- return crc ^ 0xFFFFFFFFu;
- }
- /// 自检用输出目录(与 scripts/soak_watch.py 一样落在 runs/,已 gitignore)。
- const char* kOutDir = "runs/selftest_capture";
- std::string out_path(const std::string& name) { return std::string(kOutDir) + "/" + name; }
- } // namespace
- // ---------------------------------------------------------------- [1] 帧槽
- void test_frame_slot() {
- std::printf("[1] FrameSlot: keep-the-latest frame, consume-once, stale judgement\n");
- portcv::FrameSlot slot;
- portcv::CapturedFrame out;
- check(!slot.take(&out), "empty slot: take() = false");
- check(!slot.has_new(), "empty slot: has_new() = false");
- check_eq(static_cast<long long>(slot.version()), 0, "empty slot: version = 0");
- check_near(slot.last_ts(), -1.0, 1e-12, "empty slot: last_ts = -1");
- check(!slot.fresh(100.0, 0.6), "empty slot: never fresh (PLC must not trust it)");
- check(!slot.peek(&out), "empty slot: peek() = false");
- portcv::CapturedFrame f1;
- f1.gray.reset(4, 3, 7);
- f1.index = 10;
- f1.ts = 100.0;
- f1.valid = true;
- slot.publish(std::move(f1));
- check(slot.has_new(), "after publish: has_new() = true");
- check_eq(static_cast<long long>(slot.version()), 1, "after publish: version = 1");
- check_near(slot.last_ts(), 100.0, 1e-12, "after publish: last_ts = frame ts");
- check(slot.fresh(100.5, 0.6), "fresh: 0.5s old, stale_frame_s=0.6 -> fresh");
- check(!slot.fresh(100.7, 0.6), "stale: 0.7s old, stale_frame_s=0.6 -> not fresh");
- check(slot.take(&out), "take() after publish = true");
- check_eq(out.index, 10, "take() returns the published frame");
- check_eq(static_cast<long long>(out.gray.data.size()), 12, "take() carries the pixels (4x3)");
- check_eq(static_cast<long long>(out.gray.at(0, 0)), 7, "take() carries pixel value");
- check(!slot.has_new(), "new-frame flag is consumed exactly once");
- check(!slot.take(&out), "second take() without a new publish = false");
- check_near(slot.last_ts(), 100.0, 1e-12, "take() does not change last_ts (stale judgement)");
- // 发布两帧但只取一次 → 必须拿到**最新**那帧(丢旧帧,不排队)
- portcv::CapturedFrame f2;
- f2.gray.reset(2, 2, 1);
- f2.index = 11;
- f2.ts = 101.0;
- slot.publish(std::move(f2));
- portcv::CapturedFrame f3;
- f3.gray.reset(2, 2, 2);
- f3.index = 12;
- f3.ts = 102.0;
- slot.publish(std::move(f3));
- check(slot.take(&out), "drop-old: take() = true");
- check_eq(out.index, 12, "drop-old: newest frame wins (index 12)");
- check_eq(static_cast<long long>(out.gray.at(0, 0)), 2, "drop-old: pixels come from the newest");
- check_eq(static_cast<long long>(slot.version()), 3LL,
- "version counts every publish (dropped frames included)");
- }
- // ---------------------------------------------------------------- [2] 合成帧源
- void test_synth_source() {
- std::printf("[2] synth source: deterministic, no camera, no external library\n");
- portcv::SourceConfig cfg;
- cfg.type = "synth";
- cfg.uri = "gondola";
- std::string error;
- std::unique_ptr<portcv::FrameSource> src = portcv::make_synth_source(cfg, &error);
- check(src != nullptr, "make_synth_source(gondola) = ok (" + error + ")");
- if (!src) { return; }
- check_text(src->name(), "synth", "backend name");
- check_has(src->describe(), "gondola", "describe() names the scene");
- portcv::CapturedFrame f0;
- check(src->next(&f0, &error), "next() = true");
- check(f0.valid, "frame marked valid");
- check_eq(f0.gray.width, 960, "default render width (evidence working size)");
- check_eq(f0.gray.height, 540, "default render height");
- check_eq(f0.index, 0, "first frame index = 0");
- check_eq(static_cast<long long>(f0.gray.data.size()), 960LL * 540LL, "pixels allocated");
- portcv::CapturedFrame f1;
- check(src->next(&f1, &error), "second next() = true");
- check_eq(f1.index, 1, "index increments");
- check(f1.gray.data == f0.gray.data, "static scene: consecutive frames identical");
- // 确定性:同 seed 的两个源渲染逐字节一致(CI 才能做黄金语料回归)
- std::unique_ptr<portcv::FrameSource> same = portcv::make_synth_source(cfg, &error);
- check(same != nullptr, "second source with the same seed");
- portcv::CapturedFrame f0b;
- check(same->next(&f0b, &error), "second source next()");
- check(f0b.gray.data == f0.gray.data, "same seed -> byte-identical pixels");
- // 换 seed → 噪声不同 → 不再逐字节一致(否则"确定性"是假的)
- portcv::SourceConfig other = cfg;
- other.synth_seed = 12345u;
- std::unique_ptr<portcv::FrameSource> other_src = portcv::make_synth_source(other, &error);
- check(other_src != nullptr, "source with a different seed");
- portcv::CapturedFrame f0c;
- check(other_src->next(&f0c, &error), "different seed next()");
- check(!(f0c.gray.data == f0.gray.data), "different seed -> different pixels");
- // 尺寸覆盖:source.width/height 只影响 synth 渲染(真机取流以管线为准)
- portcv::SourceConfig small = cfg;
- small.width = 320;
- small.height = 200;
- std::unique_ptr<portcv::FrameSource> small_src = portcv::make_synth_source(small, &error);
- check(small_src != nullptr, "size override honoured");
- portcv::CapturedFrame fs;
- check(small_src->next(&fs, &error), "size override next()");
- check_eq(fs.gray.width, 320, "source.width = 320");
- check_eq(fs.gray.height, 200, "source.height = 200");
- // 位移开关:synth_shift_px>0 → 帧间有位移(运动门控台架验收用)
- portcv::SourceConfig moving = cfg;
- moving.synth_shift_px = 4.0;
- std::unique_ptr<portcv::FrameSource> move_src = portcv::make_synth_source(moving, &error);
- check(move_src != nullptr, "shift source");
- portcv::CapturedFrame m0;
- portcv::CapturedFrame m1;
- check(move_src->next(&m0, &error) && move_src->next(&m1, &error), "shift source next() x2");
- check(!(m1.gray.data == m0.gray.data), "synth_shift_px>0 -> consecutive frames differ");
- // 四个场景名都能渲染;非法场景名 / 空 uri 行为明确
- const char* const scenes[] = {"gondola", "flatbed", "ground", "empty"};
- for (const char* name : scenes) {
- portcv::SourceConfig sc = cfg;
- sc.uri = name;
- std::unique_ptr<portcv::FrameSource> s = portcv::make_synth_source(sc, &error);
- portcv::CapturedFrame frame;
- const bool ok = s != nullptr && s->next(&frame, &error) && !frame.gray.empty();
- check(ok, std::string("scene \"") + name + "\" renders");
- }
- check(portcv::synth_scene_known("gondola"), "synth_scene_known(gondola) = true");
- check(portcv::synth_scene_known(""), "synth_scene_known(\"\") = true (default gondola)");
- check(!portcv::synth_scene_known("cam0"), "synth_scene_known(cam0) = false");
- portcv::SourceConfig bad = cfg;
- bad.uri = "nope";
- error.clear();
- std::unique_ptr<portcv::FrameSource> bad_src = portcv::make_synth_source(bad, &error);
- check(bad_src == nullptr, "unknown scene name -> nullptr");
- check_has(error, "gondola", "unknown scene name -> error lists valid names");
- // close() 后可再用(断流重连路径不允许"关了就再也开不了")
- src->close();
- portcv::CapturedFrame after_close;
- check(src->next(&after_close, &error), "next() after close() re-opens");
- }
- // ---------------------------------------------------------------- [3] 类型与 GStreamer 管线
- void test_types_and_pipeline() {
- std::printf("[3] source types + GStreamer pipeline building (no GStreamer needed)\n");
- check(portcv::source_type_known("none"), "known: none");
- check(portcv::source_type_known("synth"), "known: synth");
- check(portcv::source_type_known("gst"), "known: gst");
- check(portcv::source_type_known("rtsp"), "known: rtsp");
- check(portcv::source_type_known("file"), "known: file");
- check(portcv::source_type_known("usb"), "known: usb");
- check(portcv::source_type_known("images"), "known: images (PGM sequence, zero-dep)");
- check(!portcv::source_type_known("synthetic"), "unknown: synthetic");
- check(!portcv::source_type_known(""), "unknown: empty");
- check(portcv::source_type_available("none"), "available: none (always)");
- check(portcv::source_type_available("synth"), "available: synth (always)");
- check(portcv::source_type_available("images"),
- "available: images (always; no GStreamer, no image codec)");
- check_eq(static_cast<long long>(portcv::source_type_available("rtsp")),
- static_cast<long long>(portcv::gst_available()),
- "available: rtsp mirrors the build flag (-DPORTCV_WITH_GSTREAMER)");
- check_has(portcv::source_type_help(), "source.type", "type help mentions the key");
- check_text(portcv::source_type_from_uri("rtsp://a/b"), "rtsp", "infer rtsp://");
- check_text(portcv::source_type_from_uri("rtsps://a/b"), "rtsp", "infer rtsps://");
- check_text(portcv::source_type_from_uri("/dev/video0"), "usb", "infer /dev/video*");
- check_text(portcv::source_type_from_uri("0"), "usb", "infer camera index 0");
- check_text(portcv::source_type_from_uri("filesrc location=a.mp4 ! decodebin"), "gst",
- "infer gst pipeline (contains '!')");
- check_text(portcv::source_type_from_uri("samples/demo.mp4"), "file", "infer file path");
- portcv::SourceConfig cfg;
- cfg.type = "gst";
- cfg.uri = "videotestsrc ! videoconvert ! appsink name=portcv_sink";
- check_text(portcv::gst_pipeline_for(cfg), cfg.uri, "type=gst: uri is used verbatim");
- cfg.type = "rtsp";
- cfg.uri = "rtsp://cam/stream";
- cfg.buffer_size = 1;
- const std::string rtsp = portcv::gst_pipeline_for(cfg);
- check_has(rtsp, "rtspsrc location=\"rtsp://cam/stream\"", "rtsp: rtspsrc + quoted location");
- check_has(rtsp, "decodebin", "rtsp: decodebin picks the decoder (hw or sw)");
- check_has(rtsp, "video/x-raw,format=GRAY8", "sink side converts to GRAY8 (what evidence needs)");
- check_has(rtsp, "appsink name=portcv_sink", "sink is named portcv_sink");
- check_has(rtsp, "max-buffers=1", "buffer_size=1 -> max-buffers=1");
- check_has(rtsp, "drop=true", "drop=true (keep the latest frame)");
- check_has(rtsp, "sync=false", "sync=false (no clock sync: lowest latency)");
- cfg.buffer_size = 4;
- check_has(portcv::gst_pipeline_for(cfg), "max-buffers=4", "buffer_size=4 -> max-buffers=4");
- cfg.buffer_size = 0;
- check_has(portcv::gst_pipeline_for(cfg), "max-buffers=1", "buffer_size=0 -> clamped to 1");
- cfg.type = "file";
- cfg.uri = "samples/demo.mp4";
- check_has(portcv::gst_pipeline_for(cfg), "filesrc location=\"samples/demo.mp4\"",
- "file: filesrc + quoted path");
- cfg.type = "usb";
- cfg.uri = "/dev/video0";
- check_has(portcv::gst_pipeline_for(cfg), "v4l2src device=\"/dev/video0\"",
- "usb: v4l2src + quoted device");
- // 引号防护:配置里的一个 " 不能把整条管线改成别的东西
- cfg.type = "rtsp";
- cfg.uri = "rtsp://cam/a\" evil";
- check_text(portcv::gst_pipeline_for(cfg), "", "uri containing a quote -> empty pipeline");
- // 工厂:none 是正常配置;未知类型 / 未编译进来的类型必须给明确原因
- std::string error;
- std::unique_ptr<portcv::FrameSource> src;
- portcv::SourceConfig none;
- check(portcv::make_frame_source(none, &src, &error), "make_frame_source(none) = true");
- check(src == nullptr, "type=none -> no source object (legacy loop path)");
- portcv::SourceConfig bogus;
- bogus.type = "camera";
- error.clear();
- check(!portcv::make_frame_source(bogus, &src, &error), "unknown type -> false");
- check_has(error, "source.type", "unknown type -> error names the key");
- portcv::SourceConfig gst;
- gst.type = "rtsp";
- gst.uri = "rtsp://cam/stream";
- error.clear();
- const bool made = portcv::make_frame_source(gst, &src, &error);
- if (portcv::gst_available()) {
- check(made || !error.empty(), "with GStreamer: build either succeeds or reports why");
- } else {
- check(!made, "without GStreamer: rtsp -> false (no silent downgrade)");
- check_has(error, "GStreamer", "without GStreamer: error says how to enable it");
- }
- }
- // ---------------------------------------------------------------- [4] 口令掩码
- void test_redact() {
- std::printf("[4] redact_uri: no plaintext password in the startup log\n");
- const std::string masked = portcv::redact_uri("rtsp://admin:secret@192.168.1.64:554/x");
- check(masked.find("secret") == std::string::npos, "password removed");
- check_has(masked, "***", "password replaced with ***");
- check_has(masked, "192.168.1.64", "host preserved");
- check_text(portcv::redact_uri("rtsp://192.168.1.64:554/x"), "rtsp://192.168.1.64:554/x",
- "no userinfo -> unchanged");
- check_text(portcv::redact_uri("samples/demo.mp4"), "samples/demo.mp4",
- "no scheme -> unchanged");
- }
- // ---------------------------------------------------------------- [5] 黄金语料导出
- void test_dump() {
- std::printf("[5] golden dump: PGM pixels + JSONL evidence (tuning / regression path)\n");
- std::string error;
- check(portcv::ensure_dir(kOutDir, &error), "ensure_dir(" + std::string(kOutDir) + "): " + error);
- portcv::GrayImage img(5, 4, 0);
- for (int y = 0; y < 4; ++y) {
- for (int x = 0; x < 5; ++x) { img.set(x, y, static_cast<uint8_t>(x * 10 + y)); }
- }
- const std::string pgm = out_path("unit.pgm");
- check(portcv::write_pgm(pgm, img, &error), "write_pgm: " + error);
- std::string blob;
- check(read_file(pgm, &blob), "pgm readable");
- check_eq(static_cast<long long>(blob.size()), 11LL + 20LL, "pgm = header(11) + 5*4 pixels");
- check_text(blob.substr(0, 11), std::string("P5\n5 4\n255\n"), "pgm P5 header (single space)");
- check_eq(static_cast<long long>(static_cast<unsigned char>(blob[11])), 0, "pixel (0,0) = 0");
- check_eq(static_cast<long long>(static_cast<unsigned char>(blob[11 + 5])), 1, "pixel (0,1) = 1");
- check_eq(static_cast<long long>(static_cast<unsigned char>(blob[11 + 4])), 40,
- "pixel (4,0) = 40 (row-major)");
- portcv::VisionSnapshot snap;
- snap.state = 2;
- snap.confidence = 870;
- snap.flags = 0x0006;
- snap.seq = 7;
- snap.heartbeat = 3;
- snap.fps_x10 = 150;
- snap.latency_ms = 22;
- portcv::Evidence ev;
- ev.set(portcv::EvidenceKey::F1, true);
- ev.set(portcv::EvidenceKey::F2, true);
- ev.score_b = 1.7;
- ev.box_h_px = 311.5;
- ev.px_per_m = 120.25;
- ev.segments_total = 42;
- ev.scale_ok = true;
- ev.diag = portcv::EdgeDiag::NONE;
- const std::string jsonl = out_path("unit.jsonl");
- portcv::DumpConfig dc;
- dc.jsonl_path = jsonl;
- dc.image_dir = out_path("frames");
- dc.every = 2;
- portcv::FrameDumper dumper;
- check(dumper.open(dc, &error), "dumper.open: " + error);
- check(dumper.enabled(), "enabled() after open");
- check(dumper.wants(0) && !dumper.wants(1) && dumper.wants(2), "every=2 sampling rule");
- const uint32_t want_crc = ref_crc32(img.data.data(), img.data.size());
- for (long index = 0; index < 3; ++index) {
- portcv::DumpFrame df;
- df.index = index;
- df.ts = 1000.0 + static_cast<double>(index);
- df.gray = &img;
- df.snap = &snap;
- df.evidence = &ev;
- df.summary = "[F1 F2 ] sB=1.7";
- df.reason = "unit";
- df.edge_state = 2;
- df.edge_conf = 0.8700;
- df.vote_state = 2;
- check(dumper.write(df, &error), "dumper.write(frame) #" + std::to_string(index));
- }
- check_eq(static_cast<long long>(dumper.written()), 2, "every=2 -> 2 of 3 frames written");
- dumper.close();
- std::string lines;
- check(read_file(jsonl, &lines), "jsonl readable");
- check_has(lines, "\"frame\":0", "jsonl line for frame 0");
- check_has(lines, "\"frame\":2", "jsonl line for frame 2");
- check(lines.find("\"frame\":1") == std::string::npos, "frame 1 skipped (every=2)");
- check_has(lines, "\"state\":2", "jsonl carries state");
- check_has(lines, "\"edge_state\":2", "jsonl carries the per-frame edge verdict");
- check_has(lines, "\"edge_conf\":0.8700",
- "jsonl carries the per-frame verdict confidence (not the held one)");
- check_has(lines, "\"vote_state\":2", "jsonl carries the voted state (pre publish gate)");
- check_has(lines, "\"conf_x1000\":870", "jsonl carries confidence (per-mille)");
- check_has(lines, "\"flags\":6", "jsonl carries the flags word");
- check_has(lines, "\"ev\":{\"P1\":false", "jsonl carries every evidence key in a fixed order");
- check_has(lines, "\"F2\":true", "jsonl carries the hit evidence");
- check_has(lines, "\"image\":\"frame_000000.pgm\"", "jsonl names the PGM");
- check_has(lines, "\"gray_crc32\":" + std::to_string(want_crc),
- "gray_crc32 matches an independent CRC-32/IEEE implementation");
- check(read_file(out_path("frames/frame_000000.pgm"), &blob), "PGM written for frame 0");
- check(!read_file(out_path("frames/frame_000001.pgm"), &blob), "no PGM for the skipped frame");
- portcv::FrameDumper off;
- portcv::DumpConfig empty;
- check(off.open(empty, &error), "open with empty path = ok (dumping disabled)");
- check(!off.enabled(), "empty path -> disabled");
- portcv::DumpFrame df;
- df.gray = &img;
- check(off.write(df, &error), "write while disabled = true (no-op)");
- check_eq(static_cast<long long>(off.written()), 0, "nothing written while disabled");
- }
- // ---------------------------------------------------------------- [6] 配置层联动
- void test_config_layer() {
- std::printf("[6] config layer: source.* keys (same names as portcv/config.py)\n");
- const std::string json =
- "{\"run\":{\"backend\":\"edge\"},"
- "\"source\":{\"type\":\"synth\",\"uri\":\"ground\",\"buffer_size\":3,"
- "\"reconnect_s\":1.5,\"stale_frame_s\":0.8,\"loop\":true,\"synth_shift_px\":2,"
- "\"synth_seed\":7},"
- "\"plc\":{\"enabled\":false}}";
- portcv::AppConfig cfg;
- std::string error;
- check(portcv::app_config_from_text(json, &cfg, &error), "source.* config loads: " + error);
- check_text(cfg.source.type, "synth", "source.type");
- check_text(cfg.source.uri, "ground", "source.uri");
- check_eq(cfg.source.buffer_size, 3, "source.buffer_size");
- check_near(cfg.source.reconnect_s, 1.5, 1e-12, "source.reconnect_s");
- check_near(cfg.source.stale_frame_s, 0.8, 1e-12, "source.stale_frame_s");
- check(cfg.source.loop, "source.loop");
- check_near(cfg.source.synth_shift_px, 2.0, 1e-12, "source.synth_shift_px");
- check_eq(static_cast<long long>(cfg.source.synth_seed), 7, "source.synth_seed");
- const std::string sheet = portcv::describe_app_config(cfg);
- check_has(sheet, "source.type=synth", "sheet shows the source type");
- check_has(sheet, "stale_frame_s=0.80", "sheet shows the stale timeout");
- check_has(sheet, "GStreamer", "sheet shows the build capability");
- // 不写 source.* → 不取流(旧行为);默认值与 Python 同值(buffer_size / stale_frame_s)
- portcv::AppConfig d;
- check(portcv::app_config_from_text("{\"plc\":{\"enabled\":false}}", &d, &error),
- "config without source.* loads");
- check_text(d.source.type, "none", "default source.type = none (legacy loop path kept)");
- check_eq(d.source.buffer_size, 2, "default source.buffer_size = 2 (same as Python)");
- check_near(d.source.stale_frame_s, 0.6, 1e-12, "default stale_frame_s = 0.6 (same as Python)");
- check_near(d.source.reconnect_s, 2.0, 1e-12, "default reconnect_s = 2.0 (same as Python)");
- struct Case {
- const char* json;
- const char* needle;
- };
- const Case cases[] = {
- {"{\"source\":{\"type\":\"camera\"}}", "source.type"},
- {"{\"source\":{\"type\":\"images\"}}", "source.uri"},
- {"{\"source\":{\"type\":\"rtsp\"}}", "source.uri"},
- {"{\"source\":{\"type\":\"synth\",\"uri\":\"cam0\"}}", "source.uri"},
- {"{\"source\":{\"type\":\"file\",\"uri\":\"a\\\"b\"}}", "双引号"},
- {"{\"source\":{\"buffer_size\":-1}}", "source.buffer_size"},
- {"{\"source\":{\"reconnect_s\":0}}", "source.reconnect_s"},
- {"{\"source\":{\"stale_frame_s\":0}}", "source.stale_frame_s"},
- {"{\"source\":{\"width\":-1}}", "source.width"},
- {"{\"source\":{\"type\":123}}", "source.type"},
- };
- for (const Case& c : cases) {
- portcv::AppConfig bad;
- std::string bad_error;
- const bool ok = portcv::app_config_from_text(c.json, &bad, &bad_error);
- check(!ok && bad_error.find(c.needle) != std::string::npos,
- std::string("rejected with a clear reason: ") + c.json);
- }
- }
- // ---------------------------------------------------------------- [7] images 源(PGM 序列)
- /// 写原始字节(造坏文件用)。
- bool write_bytes(const std::string& path, const std::string& blob) {
- std::FILE* fp = std::fopen(path.c_str(), "wb");
- if (fp == nullptr) { return false; }
- const std::size_t n = std::fwrite(blob.data(), 1, blob.size(), fp);
- std::fclose(fp);
- return n == blob.size();
- }
- void test_images_source() {
- std::printf("[7] images source: field-footage PGM sequence (no camera, no GStreamer)\n");
- std::string error;
- const std::string dir = out_path("images_seq");
- check(portcv::ensure_dir(dir, &error), "ensure_dir(" + dir + "): " + error);
- portcv::GrayImage f0(4, 3, 11);
- portcv::GrayImage f1(4, 3, 22);
- portcv::GrayImage f2(4, 3, 33);
- check(portcv::write_pgm(dir + "/frame_000000.pgm", f0, &error), "write frame 0: " + error);
- check(portcv::write_pgm(dir + "/frame_000001.pgm", f1, &error), "write frame 1: " + error);
- check(portcv::write_pgm(dir + "/frame_000010.pgm", f2, &error), "write frame 10: " + error);
- check(write_bytes(dir + "/notes.txt", "not an image"), "non-PGM file present (must be ignored)");
- check(write_bytes(dir + "/frame_000002.raw", "xxxx"), "non-PGM frame name (ignored)");
- portcv::SourceConfig cfg;
- cfg.type = "images";
- cfg.uri = dir;
- std::unique_ptr<portcv::FrameSource> src = portcv::make_images_source(cfg, &error);
- check(src != nullptr, "make_images_source: " + error);
- if (src == nullptr) { // 后面全是它的行为断言;空指针解引用会把真因埋在崩溃里
- check(false, "cannot continue: images source was not created");
- return;
- }
- check_text(src->name(), "images", "backend name");
- check_has(src->describe(), "frames=3", "describe() counts only *.pgm");
- check_has(src->describe(), "loop=0", "describe() shows loop=0");
- portcv::CapturedFrame a;
- portcv::CapturedFrame b;
- portcv::CapturedFrame c;
- check(src->next(&a, &error) && src->next(&b, &error) && src->next(&c, &error),
- "3 frames readable in name order");
- check(a.gray.data == f0.data, "frame 0 pixels byte-identical to the PGM on disk");
- check(b.gray.data == f1.data, "frame 1 pixels byte-identical");
- check(c.gray.data == f2.data, "frame 000010 last (sorted: 000000 < 000001 < 000010)");
- check_eq(a.index, 0, "index starts at 0");
- check_eq(c.index, 2, "index increments per frame");
- check(a.ts <= c.ts, "timestamps are non-decreasing");
- check(c.valid, "frames are marked valid");
- check(c.gray.width == 4 && c.gray.height == 3, "size follows the PGM header");
- portcv::CapturedFrame end;
- check(!src->next(&end, &error), "loop=false: reading past the end returns false");
- check_has(error, "已读完", "end of sequence is reported (no silent fake frame)");
- src->close();
- portcv::CapturedFrame again;
- check(src->next(&again, &error), "next() after close() re-opens");
- check(again.gray.data == f0.data, "re-open restarts at frame 0");
- // loop=true:回绕(本拍 false,下一拍从第 0 帧接着出)
- portcv::SourceConfig looping = cfg;
- looping.loop = true;
- std::unique_ptr<portcv::FrameSource> loop_src = portcv::make_images_source(looping, &error);
- check(loop_src != nullptr, "loop=true source: " + error);
- portcv::CapturedFrame l0;
- portcv::CapturedFrame l1;
- portcv::CapturedFrame l2;
- portcv::CapturedFrame l3;
- check(loop_src->next(&l0, &error) && loop_src->next(&l1, &error) && loop_src->next(&l2, &error),
- "loop: first pass over 3 frames");
- check(!loop_src->next(&l3, &error), "loop: rewind tick yields no frame");
- check_has(error, "回绕", "loop: rewind is reported");
- check(loop_src->next(&l3, &error), "loop: next tick starts over");
- check(l3.gray.data == f0.data, "loop: back to frame 0");
- // 走工厂这条路(--source-type images 走的就是它)
- std::unique_ptr<portcv::FrameSource> via_factory;
- error.clear();
- check(portcv::make_frame_source(cfg, &via_factory, &error),
- "make_frame_source(type=images): " + error);
- check_text(via_factory != nullptr ? via_factory->name() : std::string(), "images",
- "factory returns the images source");
- // 负向:目录不存在 / 空目录 / 没给 uri / 坏文件 —— 一律**启动即报错**(不静默变成"没有画面")
- portcv::SourceConfig missing = cfg;
- missing.uri = out_path("images_missing");
- error.clear();
- check(portcv::make_images_source(missing, &error) == nullptr, "missing dir -> nullptr");
- check_has(error, "source.uri", "missing dir -> error names source.uri");
- const std::string empty_dir = out_path("images_empty");
- check(portcv::ensure_dir(empty_dir, &error), "ensure_dir(" + empty_dir + ")");
- portcv::SourceConfig empty_cfg = cfg;
- empty_cfg.uri = empty_dir;
- error.clear();
- check(portcv::make_images_source(empty_cfg, &error) == nullptr, "dir without *.pgm -> nullptr");
- check_has(error, "没有 *.pgm", "empty dir -> error says what is missing");
- portcv::SourceConfig no_uri = cfg;
- no_uri.uri.clear();
- error.clear();
- check(portcv::make_images_source(no_uri, &error) == nullptr, "empty uri -> nullptr");
- check_has(error, "source.uri", "empty uri -> error names the key");
- // 坏文件:不是 P5 / 像素截断 / 16 bit —— 报错要能直接指导现场怎么修
- struct BadCase {
- const char* dir_name;
- const char* blob;
- const char* needle;
- };
- const BadCase bads[] = {
- {"images_notp5", "P2\n4 3\n255\n1 2 3 4", "P5"},
- {"images_trunc", "P5\n4 3\n255\nabc", "像素不完整"},
- {"images_16bit", "P5\n2 2\n65535\n01234567", "8 bit"},
- };
- for (const BadCase& bc : bads) {
- const std::string bdir = out_path(bc.dir_name);
- check(portcv::ensure_dir(bdir, &error), std::string("ensure_dir(") + bc.dir_name + ")");
- check(write_bytes(bdir + "/frame_000000.pgm", bc.blob), "write a bad PGM");
- portcv::SourceConfig bad_cfg = cfg;
- bad_cfg.uri = bdir;
- error.clear();
- check(portcv::make_images_source(bad_cfg, &error) == nullptr,
- std::string(bc.dir_name) + " -> nullptr");
- check_has(error, bc.needle, std::string(bc.dir_name) + " -> actionable error");
- }
- // 尺寸不符:写了 source.width 就必须一致(**不静默缩放**)
- portcv::SourceConfig sized = cfg;
- sized.width = 5;
- error.clear();
- check(portcv::make_images_source(sized, &error) == nullptr, "width mismatch -> nullptr");
- check_has(error, "source.width", "width mismatch -> error names source.width");
- // 容忍注释与 maxval<255(别人用 magick 转的图也能读);像素按原值读入(不缩放)
- const std::string tol_dir = out_path("images_tolerant");
- check(portcv::ensure_dir(tol_dir, &error), "ensure_dir(images_tolerant)");
- check(write_bytes(tol_dir + "/frame_000000.pgm",
- "P5\n# made by magick\n2 2\n15\n\x01\x02\x03\x04"),
- "write a PGM with a comment line");
- portcv::SourceConfig tol_cfg = cfg;
- tol_cfg.uri = tol_dir;
- std::unique_ptr<portcv::FrameSource> tol_src = portcv::make_images_source(tol_cfg, &error);
- check(tol_src != nullptr, "comment header parses: " + error);
- if (tol_src == nullptr) {
- check(false, "cannot continue: tolerant-PGM source was not created");
- return;
- }
- portcv::CapturedFrame tol_frame;
- check(tol_src->next(&tol_frame, &error), "tolerant PGM frame read");
- check(tol_frame.gray.width == 2 && tol_frame.gray.height == 2, "tolerant PGM size");
- check_eq(static_cast<long long>(tol_frame.gray.at(1, 1)), 4, "pixels taken as-is (maxval 15)");
- // 中间一帧坏了:报错 + **游标不推进**(不静默跳过 —— 跳帧会让结论与像素对不上)
- const std::string mid_dir = out_path("images_midbroken");
- check(portcv::ensure_dir(mid_dir, &error), "ensure_dir(images_midbroken)");
- check(portcv::write_pgm(mid_dir + "/frame_000000.pgm", f0, &error), "mid: frame 0 ok");
- check(write_bytes(mid_dir + "/frame_000001.pgm", "P5\n4 3\n255\nab"), "mid: frame 1 truncated");
- check(portcv::write_pgm(mid_dir + "/frame_000002.pgm", f2, &error), "mid: frame 2 ok");
- portcv::SourceConfig mid_cfg = cfg;
- mid_cfg.uri = mid_dir;
- std::unique_ptr<portcv::FrameSource> mid_src = portcv::make_images_source(mid_cfg, &error);
- check(mid_src != nullptr, "mid-broken source opens (first frame is valid)");
- if (mid_src == nullptr) {
- check(false, "cannot continue: mid-broken source was not created");
- return;
- }
- portcv::CapturedFrame mid0;
- check(mid_src->next(&mid0, &error), "mid: frame 0 read");
- portcv::CapturedFrame mid1;
- check(!mid_src->next(&mid1, &error), "mid: broken frame reports false");
- check_has(error, "像素不完整", "mid: broken frame says why");
- check(!mid_src->next(&mid1, &error), "mid: retry hits the SAME frame (cursor does not skip)");
- check_has(error, "frame_000001.pgm", "mid: error names the offending file");
- }
- int main() {
- // 不缓冲 stdout:Windows 下 stdout 接管道时是**全缓冲**的,一旦哪条断言把进程打崩
- // (自检的价值就在于暴露崩溃),最后的输出会留在缓冲区里丢掉 —— 现场只能看到"崩了",
- // 看不到崩在哪一条。逐行刷出后,崩溃点直接落在最后一行 [OK]/[FAIL] 上。
- std::setvbuf(stdout, nullptr, _IONBF, 0);
- std::printf("portcv capture selftest (docs/runtime_route_decision.md; A1 + B-lite)\n");
- test_frame_slot();
- test_synth_source();
- test_types_and_pipeline();
- test_redact();
- test_dump();
- test_config_layer();
- test_images_source();
- std::printf("\n=================================================\n");
- std::printf("%d passed / %d failed\n", g_pass, g_fail);
- return g_fail == 0 ? 0 : 1;
- }
|