capture_gst.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // GStreamer 取流源(真机路径)—— `-DPORTCV_WITH_GSTREAMER=ON` 才编进来。
  2. //
  3. // 为什么用 GStreamer 而不是 OpenCV:
  4. // * docs/edge_evidence.md §11 第 9 条"是否允许引入 OpenCV"**尚未确认**,而交付形态要求核心零外部
  5. // 依赖(cpp/README.md §1)。GStreamer 是 Ubuntu 22.04 / JetPack / RK BSP 都自带的组件,
  6. // 且能把硬件解码(mppvideodec / nvdec)留在管线里 —— 板卡上不占 CPU;
  7. // * 我们只要**单通道灰度**:管线尾部 `videoconvert ! video/x-raw,format=GRAY8`,
  8. // 证据模块直接吃,不需要 OpenCV 做色彩空间转换。
  9. //
  10. // 取帧模型:不做 callback(new-sample 信号),而是**取帧线程里同步 pull**:
  11. // `gst_app_sink_try_pull_sample(sink, timeout)` + `appsink max-buffers=1 drop=true`。
  12. // 这样"只保留最新帧"的语义与 Python FrameGrabber 一致,且没有跨线程回调要同步。
  13. #include "portcv/capture.hpp"
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <cstring>
  17. #include <mutex>
  18. #include <string>
  19. #include <thread>
  20. #if defined(PORTCV_HAVE_GSTREAMER)
  21. #include <gst/app/gstappsink.h>
  22. #include <gst/gst.h>
  23. namespace portcv {
  24. namespace {
  25. bool g_gst_ready = false;
  26. std::string g_gst_error;
  27. std::once_flag g_gst_once;
  28. bool ensure_gst_initialized(std::string* error) {
  29. std::call_once(g_gst_once, []() {
  30. GError* err = nullptr;
  31. g_gst_ready = (gst_init_check(nullptr, nullptr, &err) != FALSE);
  32. if (!g_gst_ready) {
  33. g_gst_error = err != nullptr ? err->message : "gst_init_check 失败";
  34. }
  35. if (err != nullptr) { g_error_free(err); }
  36. });
  37. if (!g_gst_ready && error != nullptr) {
  38. *error = "GStreamer 初始化失败:" + g_gst_error;
  39. }
  40. return g_gst_ready;
  41. }
  42. /// 掩掉 `rtsp://user:pass@host` 里的口令(启动日志会进 systemd journal,明文口令不该进去)。
  43. /// 实现只有一份:capture.cpp 的 `redact_uri`(这里转一手,避免两处逻辑漂移)。
  44. std::string redact(const std::string& pipeline) { return redact_uri(pipeline); }
  45. /// 同步 pull 模式的 GStreamer 源。
  46. class GstFrameSource : public FrameSource {
  47. public:
  48. explicit GstFrameSource(const SourceConfig& cfg) : cfg_(cfg) {}
  49. ~GstFrameSource() override { close(); }
  50. std::string name() const override { return "gst"; }
  51. std::string describe() const override {
  52. char buf[160];
  53. std::snprintf(buf, sizeof(buf), "gst(重连 %.1fs / stale %.2fs) pipeline=",
  54. cfg_.reconnect_s, cfg_.stale_frame_s);
  55. return std::string(buf) + redact(pipeline_str_);
  56. }
  57. bool open(std::string* error) override {
  58. if (error != nullptr) { error->clear(); }
  59. if (!ensure_gst_initialized(error)) { return false; }
  60. if (pipeline_str_.empty()) {
  61. pipeline_str_ = gst_pipeline_for(cfg_);
  62. if (pipeline_str_.empty()) {
  63. if (error != nullptr) {
  64. *error = "source.type=" + cfg_.type + " 的 uri / max-buffers 拼不出管线";
  65. }
  66. return false;
  67. }
  68. }
  69. return build(error);
  70. }
  71. bool next(CapturedFrame* out, std::string* error) override {
  72. if (out == nullptr) { return false; }
  73. if (!opened_ && !open(error)) { return false; }
  74. GstSample* sample = gst_app_sink_try_pull_sample(GST_APP_SINK(sink_), kPullTimeoutNs);
  75. if (sample == nullptr) {
  76. if (gst_app_sink_is_eos(GST_APP_SINK(sink_))) {
  77. // 读到尾(file 源):loop=true 时回绕到 0,实现"离线复盘循环播放";
  78. // 不 loop 就如实报告结束 —— 上层按 stale_frame_s 处置(不假装有画面)。
  79. if (cfg_.loop && seek_to_start(error)) {
  80. return false; // 本拍没画面,下一拍从头上接着出帧
  81. }
  82. if (error != nullptr) { *error = "流已结束(EOS)"; }
  83. return false;
  84. }
  85. ++fail_count_;
  86. if (error != nullptr) {
  87. char buf[200];
  88. std::snprintf(buf, sizeof(buf), "取帧超时(%.0f ms 内无新样,连续第 %d 次)",
  89. static_cast<double>(kPullTimeoutNs) / 1e6, fail_count_);
  90. *error = buf;
  91. }
  92. if (fail_count_ >= kFailBeforeReconnect) { reconnect(); }
  93. return false;
  94. }
  95. fail_count_ = 0;
  96. const bool ok = copy_sample(sample, out, error);
  97. gst_sample_unref(sample);
  98. if (ok) {
  99. out->index = index_;
  100. out->ts = capture_now_seconds();
  101. out->valid = true;
  102. ++index_;
  103. }
  104. return ok;
  105. }
  106. void close() override {
  107. teardown();
  108. opened_ = false;
  109. }
  110. private:
  111. static constexpr int64_t kPullTimeoutNs = 200 * 1000000; // 200 ms;到点返回,让上层能处置断流
  112. static constexpr int kFailBeforeReconnect = 3;
  113. bool build(std::string* error);
  114. void reconnect();
  115. bool seek_to_start(std::string* error);
  116. bool copy_sample(GstSample* sample, CapturedFrame* out, std::string* error);
  117. void teardown();
  118. SourceConfig cfg_;
  119. std::string pipeline_str_;
  120. GstElement* pipeline_ = nullptr;
  121. GstElement* sink_ = nullptr;
  122. long index_ = 0;
  123. int fail_count_ = 0;
  124. bool opened_ = false;
  125. };
  126. /// 建管线、拿 appsink、进 PLAYING。失败一律拆干净(不留半开资源)。
  127. bool GstFrameSource::build(std::string* error) {
  128. GError* err = nullptr;
  129. pipeline_ = gst_parse_launch(pipeline_str_.c_str(), &err);
  130. if (pipeline_ == nullptr) {
  131. if (error != nullptr) {
  132. *error = std::string("GStreamer 管线解析失败:") +
  133. (err != nullptr ? err->message : "未知错误") + "\n 管线:" +
  134. redact(pipeline_str_);
  135. }
  136. if (err != nullptr) { g_error_free(err); }
  137. return false;
  138. }
  139. if (err != nullptr) { // gst_parse_launch 报的告警:不带着"半条管线"跑
  140. if (error != nullptr) { *error = std::string("GStreamer 管线告警:") + err->message; }
  141. g_error_free(err);
  142. teardown();
  143. return false;
  144. }
  145. sink_ = gst_bin_get_by_name(GST_BIN(pipeline_), "portcv_sink");
  146. if (sink_ == nullptr || GST_IS_APP_SINK(sink_) == FALSE) {
  147. if (error != nullptr) {
  148. *error =
  149. "管线里找不到名为 portcv_sink 的 appsink。\n"
  150. " 自写管线(source.type=gst)请把出口写成:\n"
  151. " … ! videoconvert ! video/x-raw,format=GRAY8 ! "
  152. "appsink name=portcv_sink max-buffers=1 drop=true sync=false\n"
  153. " 或直接用 source.type=rtsp|file|usb,让程序自动拼管线。";
  154. }
  155. teardown();
  156. return false;
  157. }
  158. gst_element_set_state(pipeline_, GST_STATE_PLAYING);
  159. GstState state = GST_STATE_NULL;
  160. const GstStateChangeReturn ret =
  161. gst_element_get_state(pipeline_, &state, nullptr, 5 * 1000000000LL); // 最多等 5 s
  162. if (ret == GST_STATE_CHANGE_FAILURE || state != GST_STATE_PLAYING) {
  163. if (error != nullptr) {
  164. *error = std::string("管线进入 PLAYING 失败(") +
  165. (cfg_.type == "rtsp" ? "检查相机 IP / 账号 / 网络可达性"
  166. : "检查 uri 是否存在、插件是否齐全") +
  167. "):" + redact(pipeline_str_);
  168. }
  169. teardown();
  170. return false;
  171. }
  172. opened_ = true;
  173. return true;
  174. }
  175. /// 断流重连:拆掉管线 → 等 reconnect_s → 重建(与 Python FrameGrabber 的 release→wait→open 同序)。
  176. void GstFrameSource::reconnect() {
  177. teardown();
  178. opened_ = false;
  179. const double wait_s = cfg_.reconnect_s > 0.0 ? cfg_.reconnect_s : 0.2;
  180. std::this_thread::sleep_for(std::chrono::duration<double>(wait_s));
  181. std::string ignored;
  182. if (build(&ignored)) { fail_count_ = 0; }
  183. }
  184. bool GstFrameSource::seek_to_start(std::string* error) {
  185. if (pipeline_ == nullptr) { return false; }
  186. const gboolean ok = gst_element_seek_simple(
  187. pipeline_, GST_FORMAT_TIME,
  188. static_cast<GstSeekFlags>(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT), 0);
  189. if (ok == FALSE && error != nullptr) { *error = "文件源回绕失败(seek 到 0 被拒)"; }
  190. return ok != FALSE;
  191. }
  192. void GstFrameSource::teardown() {
  193. if (sink_ != nullptr) {
  194. gst_object_unref(sink_);
  195. sink_ = nullptr;
  196. }
  197. if (pipeline_ != nullptr) {
  198. gst_element_set_state(pipeline_, GST_STATE_NULL);
  199. gst_object_unref(pipeline_);
  200. pipeline_ = nullptr;
  201. }
  202. fail_count_ = 0;
  203. }
  204. bool GstFrameSource::copy_sample(GstSample* sample, CapturedFrame* out, std::string* error) {
  205. GstCaps* caps = gst_sample_get_caps(sample);
  206. if (caps == nullptr || gst_caps_get_size(caps) < 1) {
  207. if (error != nullptr) { *error = "取到的样没有 caps"; }
  208. return false;
  209. }
  210. const GstStructure* info = gst_caps_get_structure(caps, 0);
  211. int width = 0;
  212. int height = 0;
  213. gst_structure_get_int(info, "width", &width);
  214. gst_structure_get_int(info, "height", &height);
  215. const gchar* format = gst_structure_get_string(info, "format");
  216. if (format == nullptr || std::strcmp(format, "GRAY8") != 0) {
  217. if (error != nullptr) {
  218. *error = std::string("appsink 出口格式必须是 GRAY8,实际是 ") +
  219. (format != nullptr ? format : "(未给 format)") +
  220. ";请在管线尾部加 `videoconvert ! video/x-raw,format=GRAY8`";
  221. }
  222. return false;
  223. }
  224. if (width <= 0 || height <= 0) {
  225. if (error != nullptr) { *error = "取到的样宽高非法"; }
  226. return false;
  227. }
  228. GstBuffer* buffer = gst_sample_get_buffer(sample);
  229. if (buffer == nullptr) {
  230. if (error != nullptr) { *error = "取到的样没有 buffer"; }
  231. return false;
  232. }
  233. GstMapInfo map;
  234. if (gst_buffer_map(buffer, &map, GST_MAP_READ) == FALSE) {
  235. if (error != nullptr) { *error = "buffer 映射失败(内存不足 / 已释放)"; }
  236. return false;
  237. }
  238. out->gray.reset(width, height);
  239. // GRAY8 每行可能有 stride 填充(宽不是 4/8 的倍数时)→ 逐行按 min(width, stride) 拷。
  240. const std::size_t rows = static_cast<std::size_t>(height);
  241. const std::size_t cols = static_cast<std::size_t>(width);
  242. const std::size_t stride = map.size >= rows * cols ? map.size / rows : cols;
  243. const std::size_t row_bytes = stride < cols ? stride : cols;
  244. for (std::size_t y = 0; y < rows; ++y) {
  245. std::memcpy(&out->gray.data[y * cols], map.data + y * stride, row_bytes);
  246. }
  247. gst_buffer_unmap(buffer, &map);
  248. return true;
  249. }
  250. } // namespace
  251. std::unique_ptr<FrameSource> make_gst_source(const SourceConfig& cfg, std::string* error) {
  252. std::unique_ptr<FrameSource> src(new GstFrameSource(cfg));
  253. if (!src->open(error)) { return nullptr; }
  254. return src;
  255. }
  256. } // namespace portcv
  257. #else // ---------------------------------------------------------- 未带 GStreamer 的构建
  258. namespace portcv {
  259. std::unique_ptr<FrameSource> make_gst_source(const SourceConfig& cfg, std::string* error) {
  260. if (error != nullptr) {
  261. *error = "source.type=" + cfg.type +
  262. " 需要 GStreamer,但本次构建未开启。\n"
  263. " 目标机上:sudo apt install libgstreamer1.0-dev "
  264. "libgstreamer-plugins-base1.0-dev\n"
  265. " 再配置:cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release "
  266. "-DPORTCV_WITH_GSTREAMER=ON\n"
  267. " (RK3588 另装 rockchip mpp 插件;Jetson 装 nvdec 插件 —— "
  268. "管线里的 decodebin 会自动选硬解,没装硬解则退软解)\n"
  269. " 先不接相机也可以:--edge-demo gondola|flatbed|ground 用合成帧跑通整条链路。";
  270. }
  271. return nullptr;
  272. }
  273. } // namespace portcv
  274. #endif