capture_images.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // PGM 序列源(`source.type=images`)—— 把离线取证出的**现场帧**当成相机喂给证据模块。
  2. //
  3. // 为什么需要它(决策见 docs/runtime_route_decision.md):
  4. // * 现场片段(mp4)只能在 PC 上解帧;板卡没上(或板卡 BSP 没带 GStreamer)时,
  5. // `docs/edge_evidence.md` §7 的阈值表就**整定不了**。本源让 C++ 证据链直接吃
  6. // PC 侧 `scripts/extract_frames.py` 导出的 PGM 序列,"现场画面 → 证据 → 结论 → 寄存器"
  7. // 整条链路在没有相机、没有 GStreamer 的机器上也能跑;
  8. // * 与 Python `portcv/io/capture.py` 的 `images` 类型**同名同义**(`source.uri` = 目录),
  9. // 差别只有一条、且在这里写清:C++ 只读 PGM(P5),**不引入任何图像解码库**(交付形态
  10. // 要求"核心零外部依赖",见 cpp/README.md §1);jpg/png 由 `scripts/extract_frames.py`
  11. // 先转成 PGM(同一份契约,`scripts/replay_check.py` 也读 PGM)。
  12. //
  13. // 语义(刻意与 GStreamer 源的 `file` 源逐条对齐,现场只需记一套):
  14. // * 只认目录里的 `*.pgm`(P5,maxval ∈ [1,255];16 bit 明确拒绝并给出转法),
  15. // 按**文件名排序 = 时间序**(`frame_000123.pgm` 这类零填充命名);
  16. // * 读到尾部:`source.loop=true` → 回绕到第 0 帧(本拍返回 false,下一拍接着出帧);
  17. // `source.loop=false` → 如实报告"已读完",上层按 `source.stale_frame_s` 处置
  18. // (置 `flags.FRAME_TIMEOUT` + 状态 255),**不假装还有画面**;
  19. // * 单帧读失败(截断 / 不是 P5 / 尺寸与 `source.width/height` 不符)→ 本拍返回 false
  20. // + 明确原因,游标**不推进**(下一拍重试同一帧)。为什么不跳过:跳一帧会让
  21. // "第 N 帧的结论"和落盘的像素对不上,黄金语料(B-lite)就失去意义。
  22. #include <algorithm>
  23. #include <cctype>
  24. #include <cstddef>
  25. #include <cstdio>
  26. #include <string>
  27. #include <vector>
  28. #include "portcv/capture.hpp"
  29. #ifdef _WIN32
  30. #include <windows.h>
  31. #else
  32. #include <dirent.h>
  33. #endif
  34. namespace portcv {
  35. namespace {
  36. /// 路径拼接(保留原目录的分隔符风格)。
  37. std::string join_path(const std::string& dir, const std::string& name) {
  38. if (dir.empty()) { return name; }
  39. const char last = dir[dir.size() - 1];
  40. if (last == '/' || last == '\\') { return dir + name; }
  41. return dir + "/" + name;
  42. }
  43. /// 文件名是否以 `.pgm` 结尾(大小写不敏感:`.PGM` 也认)。
  44. bool ends_with_pgm(const std::string& name) {
  45. if (name.size() < 4) { return false; }
  46. std::string tail = name.substr(name.size() - 4);
  47. for (char& c : tail) { c = static_cast<char>(std::tolower(static_cast<unsigned char>(c))); }
  48. return tail == ".pgm";
  49. }
  50. /// 列出目录里的 PGM 文件名(不含路径),升序 —— 与 Python `sorted(glob(...))` 同序。
  51. bool list_pgm_files(const std::string& dir, std::vector<std::string>* out, std::string* error) {
  52. out->clear();
  53. #ifdef _WIN32
  54. const std::string pattern = join_path(dir, "*");
  55. WIN32_FIND_DATAA fd;
  56. HANDLE handle = ::FindFirstFileA(pattern.c_str(), &fd);
  57. if (handle == INVALID_HANDLE_VALUE) {
  58. if (error != nullptr) { *error = "打不开目录(source.uri):" + dir; }
  59. return false;
  60. }
  61. do {
  62. if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { continue; }
  63. const std::string name = fd.cFileName;
  64. if (ends_with_pgm(name)) { out->push_back(name); }
  65. } while (::FindNextFileA(handle, &fd) != 0);
  66. ::FindClose(handle);
  67. #else
  68. DIR* dp = ::opendir(dir.c_str());
  69. if (dp == nullptr) {
  70. if (error != nullptr) { *error = "打不开目录(source.uri):" + dir; }
  71. return false;
  72. }
  73. while (struct dirent* ent = ::readdir(dp)) {
  74. const std::string name = ent->d_name;
  75. if (name == "." || name == "..") { continue; }
  76. if (ends_with_pgm(name)) { out->push_back(name); }
  77. }
  78. ::closedir(dp);
  79. #endif
  80. std::sort(out->begin(), out->end());
  81. return true;
  82. }
  83. /// 读整个文件(二进制)。失败原因写进 error。
  84. bool read_binary_file(const std::string& path, std::string* out, std::string* error) {
  85. std::FILE* fp = std::fopen(path.c_str(), "rb");
  86. if (fp == nullptr) {
  87. if (error != nullptr) { *error = "打不开文件:" + path; }
  88. return false;
  89. }
  90. if (std::fseek(fp, 0, SEEK_END) != 0) {
  91. std::fclose(fp);
  92. if (error != nullptr) { *error = "定位文件失败:" + path; }
  93. return false;
  94. }
  95. const long size = std::ftell(fp);
  96. std::fseek(fp, 0, SEEK_SET);
  97. if (size <= 0) {
  98. std::fclose(fp);
  99. if (error != nullptr) { *error = "空文件:" + path; }
  100. return false;
  101. }
  102. out->assign(static_cast<std::size_t>(size), '\0');
  103. const std::size_t got = std::fread(&(*out)[0], 1, out->size(), fp);
  104. std::fclose(fp);
  105. if (got != out->size()) {
  106. if (error != nullptr) { *error = "读取不完整:" + path; }
  107. return false;
  108. }
  109. return true;
  110. }
  111. /// P5 头解析结果。
  112. struct PgmHeader {
  113. int width = 0;
  114. int height = 0;
  115. int maxval = 0;
  116. std::size_t pixel_offset = 0;
  117. };
  118. /// 解析 P5 头(容忍 `#` 注释与任意空白,与 PGM 规范及 `scripts/replay_check.py` 的
  119. /// `read_pgm` 同口径:别人用 ImageMagick 转出来的图也能读)。
  120. bool parse_pgm_header(const std::string& blob, PgmHeader* head, std::string* error) {
  121. std::size_t i = 0;
  122. const auto skip_blanks = [&blob, &i]() {
  123. for (;;) {
  124. while (i < blob.size() && std::isspace(static_cast<unsigned char>(blob[i])) != 0) {
  125. ++i;
  126. }
  127. if (i < blob.size() && blob[i] == '#') { // 注释到行尾
  128. while (i < blob.size() && blob[i] != '\n') { ++i; }
  129. continue;
  130. }
  131. break;
  132. }
  133. };
  134. const auto next_token = [&blob, &i, &skip_blanks]() {
  135. skip_blanks();
  136. const std::size_t start = i;
  137. while (i < blob.size() && std::isspace(static_cast<unsigned char>(blob[i])) == 0) { ++i; }
  138. return blob.substr(start, i - start);
  139. };
  140. const auto to_int = [](const std::string& token, int* value) {
  141. if (token.empty()) { return false; }
  142. long acc = 0;
  143. for (char c : token) {
  144. if (c < '0' || c > '9') { return false; }
  145. acc = acc * 10 + (c - '0');
  146. if (acc > 100000000L) { return false; }
  147. }
  148. *value = static_cast<int>(acc);
  149. return true;
  150. };
  151. const std::string magic = next_token();
  152. if (magic != "P5") {
  153. if (error != nullptr) {
  154. *error = "只支持 P5(二进制灰度)PGM,文件头是 \"" + magic +
  155. "\"。用 python scripts/extract_frames.py 转,"
  156. "或 magick in.jpg -colorspace gray -depth 8 out.pgm";
  157. }
  158. return false;
  159. }
  160. if (!to_int(next_token(), &head->width) || head->width <= 0 ||
  161. !to_int(next_token(), &head->height) || head->height <= 0 ||
  162. !to_int(next_token(), &head->maxval)) {
  163. if (error != nullptr) { *error = "PGM 头不合法(读不到 宽 高 最大灰度)"; }
  164. return false;
  165. }
  166. if (head->maxval <= 0 || head->maxval > 255) {
  167. if (error != nullptr) {
  168. char buf[256];
  169. std::snprintf(buf, sizeof(buf),
  170. "PGM 最大灰度 = %d,本模块只吃 8 bit(maxval 1..255);"
  171. "16 bit 请先转:magick in.pgm -depth 8 out.pgm",
  172. head->maxval);
  173. *error = buf;
  174. }
  175. return false;
  176. }
  177. // 头与像素之间**恰好一个**空白字节(PGM 规范:多一个会被当成第一个像素)。
  178. // 注意**不能**在这里 skip_blanks:像素的首字节本身可能就是空白字符
  179. // (0x09/0x0A/0x0B/0x0C/0x0D/0x20),一次跳掉所有空白会把整幅栅格"吃"掉
  180. // —— 自检里常量 11(=0x0B,VT)的帧就是这样把它抓出来的。
  181. // scripts/replay_check.py 的 read_pgm 同口径(只吃一个 \r 或 \n)。
  182. if (i < blob.size() && std::isspace(static_cast<unsigned char>(blob[i])) != 0) { ++i; }
  183. head->pixel_offset = i;
  184. const std::size_t want = static_cast<std::size_t>(head->width) *
  185. static_cast<std::size_t>(head->height);
  186. if (blob.size() < head->pixel_offset + want) {
  187. if (error != nullptr) {
  188. char buf[256];
  189. std::snprintf(buf, sizeof(buf),
  190. "像素不完整:头声明 %dx%d = %lu 字节,文件只剩 %lu 字节(被截断?)",
  191. head->width, head->height, static_cast<unsigned long>(want),
  192. static_cast<unsigned long>(blob.size() - head->pixel_offset));
  193. *error = buf;
  194. }
  195. return false;
  196. }
  197. return true;
  198. }
  199. /// PGM 序列源(只留最新帧那一套在 FrameSlot,这里只管"下一帧")。
  200. class PgmSequenceSource : public FrameSource {
  201. public:
  202. explicit PgmSequenceSource(const SourceConfig& cfg) : cfg_(cfg) {}
  203. std::string name() const override { return "images"; }
  204. std::string describe() const override {
  205. char buf[384];
  206. std::snprintf(buf, sizeof(buf), "images dir=%s frames=%lu cursor=%lu loop=%d size=%dx%d",
  207. dir_.c_str(), static_cast<unsigned long>(files_.size()),
  208. static_cast<unsigned long>(cursor_), cfg_.loop ? 1 : 0, last_w_, last_h_);
  209. return std::string(buf);
  210. }
  211. bool open(std::string* error) override {
  212. if (error != nullptr) { error->clear(); }
  213. opened_ = false;
  214. if (cfg_.uri.empty()) {
  215. if (error != nullptr) {
  216. *error =
  217. "source.type=images 必须给 source.uri(PGM 目录)。\n"
  218. " 生成:python scripts/extract_frames.py --clip 现场片段.mp4 --out runs/frames\n"
  219. " (本源零依赖,只读 P5 PGM;jpg/png 请先转成 PGM)";
  220. }
  221. return false;
  222. }
  223. dir_ = cfg_.uri;
  224. if (!list_pgm_files(dir_, &files_, error)) { return false; }
  225. if (files_.empty()) {
  226. if (error != nullptr) {
  227. *error = "目录里没有 *.pgm(source.uri):" + dir_ +
  228. "\n 生成:python scripts/extract_frames.py --clip 现场片段.mp4 --out " + dir_;
  229. }
  230. return false;
  231. }
  232. // 启动即校验第一帧:目录写错 / 格式不对**当场**报出来,而不是跑起来才发现没有画面。
  233. GrayImage probe;
  234. std::string reason;
  235. if (!load_frame(join_path(dir_, files_[0]), files_[0], &probe, &reason)) {
  236. if (error != nullptr) { *error = reason + "\n (source.uri=" + dir_ + ")"; }
  237. return false;
  238. }
  239. last_w_ = probe.width;
  240. last_h_ = probe.height;
  241. cursor_ = 0;
  242. index_ = 0;
  243. opened_ = true;
  244. return true;
  245. }
  246. bool next(CapturedFrame* out, std::string* error) override {
  247. if (out == nullptr) { return false; }
  248. if (error != nullptr) { error->clear(); }
  249. if (!opened_ && !open(error)) { return false; }
  250. if (cursor_ >= files_.size()) {
  251. if (cfg_.loop) {
  252. // 与 GStreamer 源的 file 源同处置:回绕后本拍**不**出帧,下一拍从头上接着出。
  253. cursor_ = 0;
  254. if (error != nullptr) {
  255. *error = "PGM 序列回绕(source.loop=true):" + std::to_string(files_.size()) +
  256. " 帧,从第 0 帧重新开始";
  257. }
  258. return false;
  259. }
  260. if (error != nullptr) {
  261. *error = "PGM 序列已读完(" + std::to_string(files_.size()) +
  262. " 帧,source.loop=false):" + dir_ +
  263. ";上层按 source.stale_frame_s 置 FRAME_TIMEOUT + 255";
  264. }
  265. return false;
  266. }
  267. const std::string& name = files_[cursor_];
  268. std::string reason;
  269. if (!load_frame(join_path(dir_, name), name, &out->gray, &reason)) {
  270. // 游标不推进:下一拍重试同一帧(跳帧会让"结论"和像素对不上)。
  271. if (error != nullptr) { *error = reason; }
  272. return false;
  273. }
  274. out->index = index_;
  275. out->ts = capture_now_seconds();
  276. out->valid = true;
  277. ++index_;
  278. ++cursor_;
  279. last_w_ = out->gray.width;
  280. last_h_ = out->gray.height;
  281. return true;
  282. }
  283. void close() override {
  284. files_.clear();
  285. dir_.clear();
  286. cursor_ = 0;
  287. index_ = 0;
  288. last_w_ = 0;
  289. last_h_ = 0;
  290. opened_ = false;
  291. }
  292. private:
  293. /// 读一帧并校验尺寸(`source.width/height` 写了就必须一致:**不做静默缩放**,
  294. /// 否则"整定出来的阈值"和实际分辨率对不上,现场会误判)。
  295. bool load_frame(const std::string& path, const std::string& label, GrayImage* out,
  296. std::string* error) const {
  297. std::string blob;
  298. if (!read_binary_file(path, &blob, error)) { return false; }
  299. PgmHeader head;
  300. std::string parse_error;
  301. if (!parse_pgm_header(blob, &head, &parse_error)) {
  302. if (error != nullptr) { *error = "帧 " + label + ":" + parse_error; }
  303. return false;
  304. }
  305. if (cfg_.width > 0 && head.width != cfg_.width) {
  306. if (error != nullptr) {
  307. *error = "帧 " + label + " 宽 " + std::to_string(head.width) +
  308. " ≠ source.width=" + std::to_string(cfg_.width) +
  309. "(本源不缩放;请用 extract_frames.py --long-side/--width 输出目标尺寸)";
  310. }
  311. return false;
  312. }
  313. if (cfg_.height > 0 && head.height != cfg_.height) {
  314. if (error != nullptr) {
  315. *error = "帧 " + label + " 高 " + std::to_string(head.height) +
  316. " ≠ source.height=" + std::to_string(cfg_.height) + "(本源不缩放)";
  317. }
  318. return false;
  319. }
  320. out->reset(head.width, head.height, 0);
  321. const std::size_t want = static_cast<std::size_t>(head.width) *
  322. static_cast<std::size_t>(head.height);
  323. for (std::size_t i = 0; i < want; ++i) {
  324. out->data[i] = static_cast<uint8_t>(blob[head.pixel_offset + i]);
  325. }
  326. return true;
  327. }
  328. SourceConfig cfg_;
  329. std::string dir_;
  330. std::vector<std::string> files_;
  331. std::size_t cursor_ = 0;
  332. long index_ = 0;
  333. int last_w_ = 0;
  334. int last_h_ = 0;
  335. bool opened_ = false;
  336. };
  337. } // namespace
  338. /// 建 PGM 序列源(`source.type=images`):`uri` = 目录,零依赖,不需要相机 / 解码库。
  339. std::unique_ptr<FrameSource> make_images_source(const SourceConfig& cfg, std::string* error) {
  340. std::unique_ptr<FrameSource> src(new PgmSequenceSource(cfg));
  341. if (!src->open(error)) { return nullptr; }
  342. return src;
  343. }
  344. } // namespace portcv