| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307 |
- // GStreamer 取流源(真机路径)—— `-DPORTCV_WITH_GSTREAMER=ON` 才编进来。
- //
- // 为什么用 GStreamer 而不是 OpenCV:
- // * docs/edge_evidence.md §11 第 9 条"是否允许引入 OpenCV"**尚未确认**,而交付形态要求核心零外部
- // 依赖(cpp/README.md §1)。GStreamer 是 Ubuntu 22.04 / JetPack / RK BSP 都自带的组件,
- // 且能把硬件解码(mppvideodec / nvdec)留在管线里 —— 板卡上不占 CPU;
- // * 我们只要**单通道灰度**:管线尾部 `videoconvert ! video/x-raw,format=GRAY8`,
- // 证据模块直接吃,不需要 OpenCV 做色彩空间转换。
- //
- // 取帧模型:不做 callback(new-sample 信号),而是**取帧线程里同步 pull**:
- // `gst_app_sink_try_pull_sample(sink, timeout)` + `appsink max-buffers=1 drop=true`。
- // 这样"只保留最新帧"的语义与 Python FrameGrabber 一致,且没有跨线程回调要同步。
- #include "portcv/capture.hpp"
- #include <chrono>
- #include <cstdio>
- #include <cstring>
- #include <mutex>
- #include <string>
- #include <thread>
- #if defined(PORTCV_HAVE_GSTREAMER)
- #include <gst/app/gstappsink.h>
- #include <gst/gst.h>
- namespace portcv {
- namespace {
- bool g_gst_ready = false;
- std::string g_gst_error;
- std::once_flag g_gst_once;
- bool ensure_gst_initialized(std::string* error) {
- std::call_once(g_gst_once, []() {
- GError* err = nullptr;
- g_gst_ready = (gst_init_check(nullptr, nullptr, &err) != FALSE);
- if (!g_gst_ready) {
- g_gst_error = err != nullptr ? err->message : "gst_init_check 失败";
- }
- if (err != nullptr) { g_error_free(err); }
- });
- if (!g_gst_ready && error != nullptr) {
- *error = "GStreamer 初始化失败:" + g_gst_error;
- }
- return g_gst_ready;
- }
- /// 掩掉 `rtsp://user:pass@host` 里的口令(启动日志会进 systemd journal,明文口令不该进去)。
- /// 实现只有一份:capture.cpp 的 `redact_uri`(这里转一手,避免两处逻辑漂移)。
- std::string redact(const std::string& pipeline) { return redact_uri(pipeline); }
- /// 同步 pull 模式的 GStreamer 源。
- class GstFrameSource : public FrameSource {
- public:
- explicit GstFrameSource(const SourceConfig& cfg) : cfg_(cfg) {}
- ~GstFrameSource() override { close(); }
- std::string name() const override { return "gst"; }
- std::string describe() const override {
- char buf[160];
- std::snprintf(buf, sizeof(buf), "gst(重连 %.1fs / stale %.2fs) pipeline=",
- cfg_.reconnect_s, cfg_.stale_frame_s);
- return std::string(buf) + redact(pipeline_str_);
- }
- bool open(std::string* error) override {
- if (error != nullptr) { error->clear(); }
- if (!ensure_gst_initialized(error)) { return false; }
- if (pipeline_str_.empty()) {
- pipeline_str_ = gst_pipeline_for(cfg_);
- if (pipeline_str_.empty()) {
- if (error != nullptr) {
- *error = "source.type=" + cfg_.type + " 的 uri / max-buffers 拼不出管线";
- }
- return false;
- }
- }
- return build(error);
- }
- bool next(CapturedFrame* out, std::string* error) override {
- if (out == nullptr) { return false; }
- if (!opened_ && !open(error)) { return false; }
- GstSample* sample = gst_app_sink_try_pull_sample(GST_APP_SINK(sink_), kPullTimeoutNs);
- if (sample == nullptr) {
- if (gst_app_sink_is_eos(GST_APP_SINK(sink_))) {
- // 读到尾(file 源):loop=true 时回绕到 0,实现"离线复盘循环播放";
- // 不 loop 就如实报告结束 —— 上层按 stale_frame_s 处置(不假装有画面)。
- if (cfg_.loop && seek_to_start(error)) {
- return false; // 本拍没画面,下一拍从头上接着出帧
- }
- if (error != nullptr) { *error = "流已结束(EOS)"; }
- return false;
- }
- ++fail_count_;
- if (error != nullptr) {
- char buf[200];
- std::snprintf(buf, sizeof(buf), "取帧超时(%.0f ms 内无新样,连续第 %d 次)",
- static_cast<double>(kPullTimeoutNs) / 1e6, fail_count_);
- *error = buf;
- }
- if (fail_count_ >= kFailBeforeReconnect) { reconnect(); }
- return false;
- }
- fail_count_ = 0;
- const bool ok = copy_sample(sample, out, error);
- gst_sample_unref(sample);
- if (ok) {
- out->index = index_;
- out->ts = capture_now_seconds();
- out->valid = true;
- ++index_;
- }
- return ok;
- }
- void close() override {
- teardown();
- opened_ = false;
- }
- private:
- static constexpr int64_t kPullTimeoutNs = 200 * 1000000; // 200 ms;到点返回,让上层能处置断流
- static constexpr int kFailBeforeReconnect = 3;
- bool build(std::string* error);
- void reconnect();
- bool seek_to_start(std::string* error);
- bool copy_sample(GstSample* sample, CapturedFrame* out, std::string* error);
- void teardown();
- SourceConfig cfg_;
- std::string pipeline_str_;
- GstElement* pipeline_ = nullptr;
- GstElement* sink_ = nullptr;
- long index_ = 0;
- int fail_count_ = 0;
- bool opened_ = false;
- };
- /// 建管线、拿 appsink、进 PLAYING。失败一律拆干净(不留半开资源)。
- bool GstFrameSource::build(std::string* error) {
- GError* err = nullptr;
- pipeline_ = gst_parse_launch(pipeline_str_.c_str(), &err);
- if (pipeline_ == nullptr) {
- if (error != nullptr) {
- *error = std::string("GStreamer 管线解析失败:") +
- (err != nullptr ? err->message : "未知错误") + "\n 管线:" +
- redact(pipeline_str_);
- }
- if (err != nullptr) { g_error_free(err); }
- return false;
- }
- if (err != nullptr) { // gst_parse_launch 报的告警:不带着"半条管线"跑
- if (error != nullptr) { *error = std::string("GStreamer 管线告警:") + err->message; }
- g_error_free(err);
- teardown();
- return false;
- }
- sink_ = gst_bin_get_by_name(GST_BIN(pipeline_), "portcv_sink");
- if (sink_ == nullptr || GST_IS_APP_SINK(sink_) == FALSE) {
- if (error != nullptr) {
- *error =
- "管线里找不到名为 portcv_sink 的 appsink。\n"
- " 自写管线(source.type=gst)请把出口写成:\n"
- " … ! videoconvert ! video/x-raw,format=GRAY8 ! "
- "appsink name=portcv_sink max-buffers=1 drop=true sync=false\n"
- " 或直接用 source.type=rtsp|file|usb,让程序自动拼管线。";
- }
- teardown();
- return false;
- }
- gst_element_set_state(pipeline_, GST_STATE_PLAYING);
- GstState state = GST_STATE_NULL;
- const GstStateChangeReturn ret =
- gst_element_get_state(pipeline_, &state, nullptr, 5 * 1000000000LL); // 最多等 5 s
- if (ret == GST_STATE_CHANGE_FAILURE || state != GST_STATE_PLAYING) {
- if (error != nullptr) {
- *error = std::string("管线进入 PLAYING 失败(") +
- (cfg_.type == "rtsp" ? "检查相机 IP / 账号 / 网络可达性"
- : "检查 uri 是否存在、插件是否齐全") +
- "):" + redact(pipeline_str_);
- }
- teardown();
- return false;
- }
- opened_ = true;
- return true;
- }
- /// 断流重连:拆掉管线 → 等 reconnect_s → 重建(与 Python FrameGrabber 的 release→wait→open 同序)。
- void GstFrameSource::reconnect() {
- teardown();
- opened_ = false;
- const double wait_s = cfg_.reconnect_s > 0.0 ? cfg_.reconnect_s : 0.2;
- std::this_thread::sleep_for(std::chrono::duration<double>(wait_s));
- std::string ignored;
- if (build(&ignored)) { fail_count_ = 0; }
- }
- bool GstFrameSource::seek_to_start(std::string* error) {
- if (pipeline_ == nullptr) { return false; }
- const gboolean ok = gst_element_seek_simple(
- pipeline_, GST_FORMAT_TIME,
- static_cast<GstSeekFlags>(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT), 0);
- if (ok == FALSE && error != nullptr) { *error = "文件源回绕失败(seek 到 0 被拒)"; }
- return ok != FALSE;
- }
- void GstFrameSource::teardown() {
- if (sink_ != nullptr) {
- gst_object_unref(sink_);
- sink_ = nullptr;
- }
- if (pipeline_ != nullptr) {
- gst_element_set_state(pipeline_, GST_STATE_NULL);
- gst_object_unref(pipeline_);
- pipeline_ = nullptr;
- }
- fail_count_ = 0;
- }
- bool GstFrameSource::copy_sample(GstSample* sample, CapturedFrame* out, std::string* error) {
- GstCaps* caps = gst_sample_get_caps(sample);
- if (caps == nullptr || gst_caps_get_size(caps) < 1) {
- if (error != nullptr) { *error = "取到的样没有 caps"; }
- return false;
- }
- const GstStructure* info = gst_caps_get_structure(caps, 0);
- int width = 0;
- int height = 0;
- gst_structure_get_int(info, "width", &width);
- gst_structure_get_int(info, "height", &height);
- const gchar* format = gst_structure_get_string(info, "format");
- if (format == nullptr || std::strcmp(format, "GRAY8") != 0) {
- if (error != nullptr) {
- *error = std::string("appsink 出口格式必须是 GRAY8,实际是 ") +
- (format != nullptr ? format : "(未给 format)") +
- ";请在管线尾部加 `videoconvert ! video/x-raw,format=GRAY8`";
- }
- return false;
- }
- if (width <= 0 || height <= 0) {
- if (error != nullptr) { *error = "取到的样宽高非法"; }
- return false;
- }
- GstBuffer* buffer = gst_sample_get_buffer(sample);
- if (buffer == nullptr) {
- if (error != nullptr) { *error = "取到的样没有 buffer"; }
- return false;
- }
- GstMapInfo map;
- if (gst_buffer_map(buffer, &map, GST_MAP_READ) == FALSE) {
- if (error != nullptr) { *error = "buffer 映射失败(内存不足 / 已释放)"; }
- return false;
- }
- out->gray.reset(width, height);
- // GRAY8 每行可能有 stride 填充(宽不是 4/8 的倍数时)→ 逐行按 min(width, stride) 拷。
- const std::size_t rows = static_cast<std::size_t>(height);
- const std::size_t cols = static_cast<std::size_t>(width);
- const std::size_t stride = map.size >= rows * cols ? map.size / rows : cols;
- const std::size_t row_bytes = stride < cols ? stride : cols;
- for (std::size_t y = 0; y < rows; ++y) {
- std::memcpy(&out->gray.data[y * cols], map.data + y * stride, row_bytes);
- }
- gst_buffer_unmap(buffer, &map);
- return true;
- }
- } // namespace
- std::unique_ptr<FrameSource> make_gst_source(const SourceConfig& cfg, std::string* error) {
- std::unique_ptr<FrameSource> src(new GstFrameSource(cfg));
- if (!src->open(error)) { return nullptr; }
- return src;
- }
- } // namespace portcv
- #else // ---------------------------------------------------------- 未带 GStreamer 的构建
- namespace portcv {
- std::unique_ptr<FrameSource> make_gst_source(const SourceConfig& cfg, std::string* error) {
- if (error != nullptr) {
- *error = "source.type=" + cfg.type +
- " 需要 GStreamer,但本次构建未开启。\n"
- " 目标机上:sudo apt install libgstreamer1.0-dev "
- "libgstreamer-plugins-base1.0-dev\n"
- " 再配置:cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release "
- "-DPORTCV_WITH_GSTREAMER=ON\n"
- " (RK3588 另装 rockchip mpp 插件;Jetson 装 nvdec 插件 —— "
- "管线里的 decodebin 会自动选硬解,没装硬解则退软解)\n"
- " 先不接相机也可以:--edge-demo gondola|flatbed|ground 用合成帧跑通整条链路。";
- }
- return nullptr;
- }
- } // namespace portcv
- #endif
|