| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368 |
- // PGM 序列源(`source.type=images`)—— 把离线取证出的**现场帧**当成相机喂给证据模块。
- //
- // 为什么需要它(决策见 docs/runtime_route_decision.md):
- // * 现场片段(mp4)只能在 PC 上解帧;板卡没上(或板卡 BSP 没带 GStreamer)时,
- // `docs/edge_evidence.md` §7 的阈值表就**整定不了**。本源让 C++ 证据链直接吃
- // PC 侧 `scripts/extract_frames.py` 导出的 PGM 序列,"现场画面 → 证据 → 结论 → 寄存器"
- // 整条链路在没有相机、没有 GStreamer 的机器上也能跑;
- // * 与 Python `portcv/io/capture.py` 的 `images` 类型**同名同义**(`source.uri` = 目录),
- // 差别只有一条、且在这里写清:C++ 只读 PGM(P5),**不引入任何图像解码库**(交付形态
- // 要求"核心零外部依赖",见 cpp/README.md §1);jpg/png 由 `scripts/extract_frames.py`
- // 先转成 PGM(同一份契约,`scripts/replay_check.py` 也读 PGM)。
- //
- // 语义(刻意与 GStreamer 源的 `file` 源逐条对齐,现场只需记一套):
- // * 只认目录里的 `*.pgm`(P5,maxval ∈ [1,255];16 bit 明确拒绝并给出转法),
- // 按**文件名排序 = 时间序**(`frame_000123.pgm` 这类零填充命名);
- // * 读到尾部:`source.loop=true` → 回绕到第 0 帧(本拍返回 false,下一拍接着出帧);
- // `source.loop=false` → 如实报告"已读完",上层按 `source.stale_frame_s` 处置
- // (置 `flags.FRAME_TIMEOUT` + 状态 255),**不假装还有画面**;
- // * 单帧读失败(截断 / 不是 P5 / 尺寸与 `source.width/height` 不符)→ 本拍返回 false
- // + 明确原因,游标**不推进**(下一拍重试同一帧)。为什么不跳过:跳一帧会让
- // "第 N 帧的结论"和落盘的像素对不上,黄金语料(B-lite)就失去意义。
- #include <algorithm>
- #include <cctype>
- #include <cstddef>
- #include <cstdio>
- #include <string>
- #include <vector>
- #include "portcv/capture.hpp"
- #ifdef _WIN32
- #include <windows.h>
- #else
- #include <dirent.h>
- #endif
- namespace portcv {
- namespace {
- /// 路径拼接(保留原目录的分隔符风格)。
- std::string join_path(const std::string& dir, const std::string& name) {
- if (dir.empty()) { return name; }
- const char last = dir[dir.size() - 1];
- if (last == '/' || last == '\\') { return dir + name; }
- return dir + "/" + name;
- }
- /// 文件名是否以 `.pgm` 结尾(大小写不敏感:`.PGM` 也认)。
- bool ends_with_pgm(const std::string& name) {
- if (name.size() < 4) { return false; }
- std::string tail = name.substr(name.size() - 4);
- for (char& c : tail) { c = static_cast<char>(std::tolower(static_cast<unsigned char>(c))); }
- return tail == ".pgm";
- }
- /// 列出目录里的 PGM 文件名(不含路径),升序 —— 与 Python `sorted(glob(...))` 同序。
- bool list_pgm_files(const std::string& dir, std::vector<std::string>* out, std::string* error) {
- out->clear();
- #ifdef _WIN32
- const std::string pattern = join_path(dir, "*");
- WIN32_FIND_DATAA fd;
- HANDLE handle = ::FindFirstFileA(pattern.c_str(), &fd);
- if (handle == INVALID_HANDLE_VALUE) {
- if (error != nullptr) { *error = "打不开目录(source.uri):" + dir; }
- return false;
- }
- do {
- if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { continue; }
- const std::string name = fd.cFileName;
- if (ends_with_pgm(name)) { out->push_back(name); }
- } while (::FindNextFileA(handle, &fd) != 0);
- ::FindClose(handle);
- #else
- DIR* dp = ::opendir(dir.c_str());
- if (dp == nullptr) {
- if (error != nullptr) { *error = "打不开目录(source.uri):" + dir; }
- return false;
- }
- while (struct dirent* ent = ::readdir(dp)) {
- const std::string name = ent->d_name;
- if (name == "." || name == "..") { continue; }
- if (ends_with_pgm(name)) { out->push_back(name); }
- }
- ::closedir(dp);
- #endif
- std::sort(out->begin(), out->end());
- return true;
- }
- /// 读整个文件(二进制)。失败原因写进 error。
- bool read_binary_file(const std::string& path, std::string* out, std::string* error) {
- std::FILE* fp = std::fopen(path.c_str(), "rb");
- if (fp == nullptr) {
- if (error != nullptr) { *error = "打不开文件:" + path; }
- return false;
- }
- if (std::fseek(fp, 0, SEEK_END) != 0) {
- std::fclose(fp);
- if (error != nullptr) { *error = "定位文件失败:" + path; }
- return false;
- }
- const long size = std::ftell(fp);
- std::fseek(fp, 0, SEEK_SET);
- if (size <= 0) {
- std::fclose(fp);
- if (error != nullptr) { *error = "空文件:" + path; }
- return false;
- }
- out->assign(static_cast<std::size_t>(size), '\0');
- const std::size_t got = std::fread(&(*out)[0], 1, out->size(), fp);
- std::fclose(fp);
- if (got != out->size()) {
- if (error != nullptr) { *error = "读取不完整:" + path; }
- return false;
- }
- return true;
- }
- /// P5 头解析结果。
- struct PgmHeader {
- int width = 0;
- int height = 0;
- int maxval = 0;
- std::size_t pixel_offset = 0;
- };
- /// 解析 P5 头(容忍 `#` 注释与任意空白,与 PGM 规范及 `scripts/replay_check.py` 的
- /// `read_pgm` 同口径:别人用 ImageMagick 转出来的图也能读)。
- bool parse_pgm_header(const std::string& blob, PgmHeader* head, std::string* error) {
- std::size_t i = 0;
- const auto skip_blanks = [&blob, &i]() {
- for (;;) {
- while (i < blob.size() && std::isspace(static_cast<unsigned char>(blob[i])) != 0) {
- ++i;
- }
- if (i < blob.size() && blob[i] == '#') { // 注释到行尾
- while (i < blob.size() && blob[i] != '\n') { ++i; }
- continue;
- }
- break;
- }
- };
- const auto next_token = [&blob, &i, &skip_blanks]() {
- skip_blanks();
- const std::size_t start = i;
- while (i < blob.size() && std::isspace(static_cast<unsigned char>(blob[i])) == 0) { ++i; }
- return blob.substr(start, i - start);
- };
- const auto to_int = [](const std::string& token, int* value) {
- if (token.empty()) { return false; }
- long acc = 0;
- for (char c : token) {
- if (c < '0' || c > '9') { return false; }
- acc = acc * 10 + (c - '0');
- if (acc > 100000000L) { return false; }
- }
- *value = static_cast<int>(acc);
- return true;
- };
- const std::string magic = next_token();
- if (magic != "P5") {
- if (error != nullptr) {
- *error = "只支持 P5(二进制灰度)PGM,文件头是 \"" + magic +
- "\"。用 python scripts/extract_frames.py 转,"
- "或 magick in.jpg -colorspace gray -depth 8 out.pgm";
- }
- return false;
- }
- if (!to_int(next_token(), &head->width) || head->width <= 0 ||
- !to_int(next_token(), &head->height) || head->height <= 0 ||
- !to_int(next_token(), &head->maxval)) {
- if (error != nullptr) { *error = "PGM 头不合法(读不到 宽 高 最大灰度)"; }
- return false;
- }
- if (head->maxval <= 0 || head->maxval > 255) {
- if (error != nullptr) {
- char buf[256];
- std::snprintf(buf, sizeof(buf),
- "PGM 最大灰度 = %d,本模块只吃 8 bit(maxval 1..255);"
- "16 bit 请先转:magick in.pgm -depth 8 out.pgm",
- head->maxval);
- *error = buf;
- }
- return false;
- }
- // 头与像素之间**恰好一个**空白字节(PGM 规范:多一个会被当成第一个像素)。
- // 注意**不能**在这里 skip_blanks:像素的首字节本身可能就是空白字符
- // (0x09/0x0A/0x0B/0x0C/0x0D/0x20),一次跳掉所有空白会把整幅栅格"吃"掉
- // —— 自检里常量 11(=0x0B,VT)的帧就是这样把它抓出来的。
- // scripts/replay_check.py 的 read_pgm 同口径(只吃一个 \r 或 \n)。
- if (i < blob.size() && std::isspace(static_cast<unsigned char>(blob[i])) != 0) { ++i; }
- head->pixel_offset = i;
- const std::size_t want = static_cast<std::size_t>(head->width) *
- static_cast<std::size_t>(head->height);
- if (blob.size() < head->pixel_offset + want) {
- if (error != nullptr) {
- char buf[256];
- std::snprintf(buf, sizeof(buf),
- "像素不完整:头声明 %dx%d = %lu 字节,文件只剩 %lu 字节(被截断?)",
- head->width, head->height, static_cast<unsigned long>(want),
- static_cast<unsigned long>(blob.size() - head->pixel_offset));
- *error = buf;
- }
- return false;
- }
- return true;
- }
- /// PGM 序列源(只留最新帧那一套在 FrameSlot,这里只管"下一帧")。
- class PgmSequenceSource : public FrameSource {
- public:
- explicit PgmSequenceSource(const SourceConfig& cfg) : cfg_(cfg) {}
- std::string name() const override { return "images"; }
- std::string describe() const override {
- char buf[384];
- std::snprintf(buf, sizeof(buf), "images dir=%s frames=%lu cursor=%lu loop=%d size=%dx%d",
- dir_.c_str(), static_cast<unsigned long>(files_.size()),
- static_cast<unsigned long>(cursor_), cfg_.loop ? 1 : 0, last_w_, last_h_);
- return std::string(buf);
- }
- bool open(std::string* error) override {
- if (error != nullptr) { error->clear(); }
- opened_ = false;
- if (cfg_.uri.empty()) {
- if (error != nullptr) {
- *error =
- "source.type=images 必须给 source.uri(PGM 目录)。\n"
- " 生成:python scripts/extract_frames.py --clip 现场片段.mp4 --out runs/frames\n"
- " (本源零依赖,只读 P5 PGM;jpg/png 请先转成 PGM)";
- }
- return false;
- }
- dir_ = cfg_.uri;
- if (!list_pgm_files(dir_, &files_, error)) { return false; }
- if (files_.empty()) {
- if (error != nullptr) {
- *error = "目录里没有 *.pgm(source.uri):" + dir_ +
- "\n 生成:python scripts/extract_frames.py --clip 现场片段.mp4 --out " + dir_;
- }
- return false;
- }
- // 启动即校验第一帧:目录写错 / 格式不对**当场**报出来,而不是跑起来才发现没有画面。
- GrayImage probe;
- std::string reason;
- if (!load_frame(join_path(dir_, files_[0]), files_[0], &probe, &reason)) {
- if (error != nullptr) { *error = reason + "\n (source.uri=" + dir_ + ")"; }
- return false;
- }
- last_w_ = probe.width;
- last_h_ = probe.height;
- cursor_ = 0;
- index_ = 0;
- opened_ = true;
- return true;
- }
- bool next(CapturedFrame* out, std::string* error) override {
- if (out == nullptr) { return false; }
- if (error != nullptr) { error->clear(); }
- if (!opened_ && !open(error)) { return false; }
- if (cursor_ >= files_.size()) {
- if (cfg_.loop) {
- // 与 GStreamer 源的 file 源同处置:回绕后本拍**不**出帧,下一拍从头上接着出。
- cursor_ = 0;
- if (error != nullptr) {
- *error = "PGM 序列回绕(source.loop=true):" + std::to_string(files_.size()) +
- " 帧,从第 0 帧重新开始";
- }
- return false;
- }
- if (error != nullptr) {
- *error = "PGM 序列已读完(" + std::to_string(files_.size()) +
- " 帧,source.loop=false):" + dir_ +
- ";上层按 source.stale_frame_s 置 FRAME_TIMEOUT + 255";
- }
- return false;
- }
- const std::string& name = files_[cursor_];
- std::string reason;
- if (!load_frame(join_path(dir_, name), name, &out->gray, &reason)) {
- // 游标不推进:下一拍重试同一帧(跳帧会让"结论"和像素对不上)。
- if (error != nullptr) { *error = reason; }
- return false;
- }
- out->index = index_;
- out->ts = capture_now_seconds();
- out->valid = true;
- ++index_;
- ++cursor_;
- last_w_ = out->gray.width;
- last_h_ = out->gray.height;
- return true;
- }
- void close() override {
- files_.clear();
- dir_.clear();
- cursor_ = 0;
- index_ = 0;
- last_w_ = 0;
- last_h_ = 0;
- opened_ = false;
- }
- private:
- /// 读一帧并校验尺寸(`source.width/height` 写了就必须一致:**不做静默缩放**,
- /// 否则"整定出来的阈值"和实际分辨率对不上,现场会误判)。
- bool load_frame(const std::string& path, const std::string& label, GrayImage* out,
- std::string* error) const {
- std::string blob;
- if (!read_binary_file(path, &blob, error)) { return false; }
- PgmHeader head;
- std::string parse_error;
- if (!parse_pgm_header(blob, &head, &parse_error)) {
- if (error != nullptr) { *error = "帧 " + label + ":" + parse_error; }
- return false;
- }
- if (cfg_.width > 0 && head.width != cfg_.width) {
- if (error != nullptr) {
- *error = "帧 " + label + " 宽 " + std::to_string(head.width) +
- " ≠ source.width=" + std::to_string(cfg_.width) +
- "(本源不缩放;请用 extract_frames.py --long-side/--width 输出目标尺寸)";
- }
- return false;
- }
- if (cfg_.height > 0 && head.height != cfg_.height) {
- if (error != nullptr) {
- *error = "帧 " + label + " 高 " + std::to_string(head.height) +
- " ≠ source.height=" + std::to_string(cfg_.height) + "(本源不缩放)";
- }
- return false;
- }
- out->reset(head.width, head.height, 0);
- const std::size_t want = static_cast<std::size_t>(head.width) *
- static_cast<std::size_t>(head.height);
- for (std::size_t i = 0; i < want; ++i) {
- out->data[i] = static_cast<uint8_t>(blob[head.pixel_offset + i]);
- }
- return true;
- }
- SourceConfig cfg_;
- std::string dir_;
- std::vector<std::string> files_;
- std::size_t cursor_ = 0;
- long index_ = 0;
- int last_w_ = 0;
- int last_h_ = 0;
- bool opened_ = false;
- };
- } // namespace
- /// 建 PGM 序列源(`source.type=images`):`uri` = 目录,零依赖,不需要相机 / 解码库。
- std::unique_ptr<FrameSource> make_images_source(const SourceConfig& cfg, std::string* error) {
- std::unique_ptr<FrameSource> src(new PgmSequenceSource(cfg));
- if (!src->open(error)) { return nullptr; }
- return src;
- }
- } // namespace portcv
|