下面【】内是我给大模型提的要求,大模型输出的内容如""" """所示。要求: 1.在"""… · The Chat Archive下面【】内是我给大模型提的要求,大模型输出的内容如""" """所示。要求: 1.在"""…
Download ▾
下面【】内是我给大模型提的要求,大模型输出的内容如""" """所示。要求:
1.在""" """中的第三部分,给出了main函数,还有FrameProcessor、ImageStorageManager、AlarmRecorder、ResourceManager这4个类给出了,要求把优化后的视频捕获实现的VideoCapture类补充完整,gboolean handleBusMessage(GstBus* bus, GstMessage* message)这个地方开始补充,最后给出VideoCapture类的.h和.cpp
的两个代码文件的完整源代码。如果有其他需要补充的,也可以直接给出源代码。
【
现在需要写一个c++的视频分析服务,目前算法分析服务triton server已经部署好了,并且部署了10种算法模型,可以通过【】内的TritonInference推理客户端调用triton server部署的算法算法模型(有10类算法:人员检测、车辆检测、船只检测、土壤裸露、烟火检测、违法捕捞、非法垂钓、违法搭建、垃圾裸露、鸟类检测),TritonInference推理客户端的源代码和一个调用的demo示例如【】所示,对应的CMakeLists.txt如""" """所示。视频分析服务需要考虑并发,考虑任务调度,考虑视频抽帧为图片性能。核心功能:通过GStreamer并发发接入多路视频流,然后调用ffmpeng来抽帧,抽帧形成图片数据,发送给triton server,然后将返回的分析结果传给上层应用。核心难点:多路并发、高性能、高可靠、系统调用,高效的图片抽帧、报警录像等等。具体需求如下:
(1) 系统配置:有个ini的配置文件,配置文件内容:50个摄像头的信息。每个摄像头对应的信息有:摄像头名称、rtsp流的地址,本摄像头对应的多个算法名称(有10类算法:人员检测、车辆检测、船只检测、土壤裸露、烟火检测、违法捕捞、非法垂钓、违法搭建、垃圾裸露、鸟类检测),抽帧时间间隔,报警策略(比如:船只检测:只要出现船就进行报警,人员检测:只要人员超过2个就进行报警,具体的策略可以变),报警录像的存储位置等6个变量。注意读配置文件的类,不要用开源的INIReader类库。
(2) 读取配置文件,读取摄像头名称和rtsp地址。视频服务中集成第三方服务GStreamer,利用其rtsp的方式去接收50路实时视频流。视频接入部分需要详细设计和代码的健壮性。针对每一路的视频流,按照本摄像头的在配置文件中的抽帧时间间隔,通过ffmpeg来抽帧形成图片,文本保存存储目录分为三类,第一类正常保存图片文件的目录:ffmpeg抽帧形成图片保存位置,此目录下超过10分钟以上的图片,系统自动判断来进行删除;第二类报警保存图片文件目录:存储此图片通过分析服务后,发生异常报警,此报警图片按照月份分文件夹,永不删除;第三类报警录像保存的视频文件目录:当分析结果,发生异常报警时,GStreamer流媒体要录10秒钟的实时视频,视频保存在此目录,按照月份分文件夹,永不删除;
(3) 针对第(2)步中,通过ffmpeg来抽帧形成图片,一边正常保存图片的目录,一边通过(5)中的TritonInference推理客户端异步发送给算法分析服务。
(4) 算法分析服务triton server已经部署好了,并且部署了10种算法模型,也已经有了一个封装好的调用triton server算法服务的TritonInference推理客户端,具体代码如【】所示,其代码对应的CMakefile.List的文件如""" """所示。
在c++视频分析服务中需要集成TritonInference推理客户端。TritonInference推理客户端构造函数两个参数算法服务triton server的地址和算法分析模型的名称,调用TritonInference推理客户端的接口infer接口,来调用算法服务triton server的模型,然后返回检测后的目标及目标对应的坐标位置(detections这里),整个TritonInference推理客户端调用过程采用多路并发、异步的方式实现。
(5) 针对(3)中多路视频截图,根据图片所在的视频名称,然后根据视频名称找到对应配置文件中要调用的算法,TritonInference推理客户端将调用infer接口将图片发送给算法分析服务,并接收检测后的目标及目标对应的坐标位置,同时将检测后的目标名称、目标位置,分析的时间,已经对应的图片名称,对应的摄像头名称,已经对应的(3)中图片存储的目录位置,组合成一个json,通过post方式发送到上层java的业务应用。多路视频图片并发、异步发送算法分析服务triton server。
(6) c++的视频分析服务还需要做一些业务逻辑判,比如人车目标检测,当有人或者车的目标出现时,触发报警,当触发报警的时候,需要录一段10秒钟实时视频,视频保存在配置文件中的报警录像的存储位置,也就是(2)中提到第三类文件保存位置,报警录像永远不删除。
(7) 报警图片和报警录像,需要放到txt文本中记录下,报警图片和录像的的报警时间,及文件的存储位置,及对应的摄像头信息等。
(8) 整体服务,多任务,多线程,异步,高效、高性能。
(9)给出整体项目的源代码,包括完整的代码文件(.h文件和.cpp文件)以及代码文件中包括的头文件,以及CMakeLists.txt。
(10) 系统要在控制台输出关键信息,如加载配置文件成功,成功接入视频流,发送图片分析,接收到反馈信息等等,需要在控制台输出,异常出错的处理,关键信息需要日志的记录。
(11)如何涉及到第三方的依赖库,请给出库的安装流程及其环境配置。
(12)最后输出整体的解决方案、流程和关键点。
】
"""
我将分步骤提供一个完整的解决方案。
第一部分:首先,我们需要定义项目的整体架构:
video_analysis_service/
├── CMakeLists.txt
├── config/
│ └── camera_config.ini
├── include/
│ ├── config_manager.h
│ ├── video_capture.h
│ ├── frame_processor.h
│ ├── alarm_manager.h
│ ├── triton_client_wrapper.h
│ └── logger.h
├── src/
│ ├── config_manager.cpp
│ ├── video_capture.cpp
│ ├── frame_processor.cpp
│ ├── alarm_manager.cpp
│ ├── triton_client_wrapper.cpp
│ ├── logger.cpp
│ └── main.cpp
└── build/
第二部分:在(1)中列举的部分文件此处省略
......
第三部分:最后的几个文件内容:
主程序入口优化:
int main(int argc, char** argv) {
try {
// 初始化日志
Logger::init("video_analysis_service.log");
LOG_INFO("Starting Video Analysis Service...");
Assistant
// 初始化GStreamer
gst_init(&argc, &argv);
// 加载配置
if (!ConfigManager::getInstance().loadConfig("config/camera_config.ini")) {
LOG_ERROR("Failed to load configuration");
return EXIT_FAILURE;
}
LOG_INFO("Configuration loaded successfully");
// 初始化存储管理器
auto storage_manager = std::make_shared<ImageStorageManager>("/data/images");
// 初始化报警记录器
auto alarm_recorder = std::make_shared<AlarmRecorder>("/data/videos");
// 初始化帧处理器
auto frame_processor = std::make_shared<FrameProcessor>(4); // 4个处理线程
// 创建视频捕获实例
std::vector<std::unique_ptr<VideoCapture>> video_captures;
for (const auto& config : ConfigManager::getInstance().getCameraConfigs()) {
try {
auto capture = std::make_unique<VideoCapture>(
config,
frame_processor,
storage_manager,
alarm_recorder
);
if (capture->start()) {
video_captures.push_back(std::move(capture));
LOG_INFO("Started video capture for camera: " + config.name);
} else {
LOG_ERROR("Failed to start video capture for camera: " +
config.name);
}
} catch (const std::exception& e) {
LOG_ERROR("Error creating video capture for camera " +
config.name + ": " + e.what());
}
}
// 启动系统监控
std::thread monitor_thread([]() {
while (true) {
try {
auto report = SystemMonitor::getInstance().generateStatusReport();
LOG_INFO("System Status: " + report);
std::this_thread::sleep_for(std::chrono::minutes(1));
} catch (const std::exception& e) {
LOG_ERROR("Monitor thread error: " + std::string(e.what()));
}
}
});
// 信号处理
std::signal(SIGINT, [](int) {
LOG_INFO("Received shutdown signal, cleaning up...");
// 标记退出
g_running = false;
});
// 主循环
while (g_running) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// 清理资源
LOG_INFO("Shutting down video captures...");
video_captures.clear();
if (monitor_thread.joinable()) {
monitor_thread.join();
}
LOG_INFO("Video Analysis Service stopped successfully");
return EXIT_SUCCESS;
} catch (const std::exception& e) {
LOG_ERROR("Fatal error: " + std::string(e.what()));
return EXIT_FAILURE;
}
// 帧处理工作线程
class FrameProcessor {
public:
FrameProcessor(size_t num_threads = 4) {
for (size_t i = 0; i < num_threads; ++i) {
workers_.emplace_back([this] { processFrames(); });
}
}
~FrameProcessor() {
frame_queue_.stop();
for (auto& worker : workers_) {
if (worker.joinable()) {
worker.join();
}
}
}
private:
void processFrames() {
std::pair<cv::Mat, std::string> frame_data;
while (frame_queue_.pop(frame_data)) {
try {
auto& [frame, camera_name] = frame_data;
// 获取相机配置
const auto& camera_config = ConfigManager::getInstance()
.getCameraConfig(camera_name);
// 对每个配置的算法进行处理
for (const auto& algo : camera_config.algorithms) {
auto result = triton_client_->infer(frame, algo);
handleDetectionResult(camera_name, algo, result);
}
// 更新处理状态
SystemMonitor::getInstance().updateProcessingStatus(
camera_name,
++processed_frames_[camera_name],
alarm_counts_[camera_name]
);
} catch (const std::exception& e) {
LOG_ERROR("Frame processing error: " + std::string(e.what()));
}
}
}
FrameQueue frame_queue_;
std::vector<std::thread> workers_;
std::map<std::string, int> processed_frames_;
std::map<std::string, int> alarm_counts_;
class ImageStorageManager {
public:
ImageStorageManager(const std::string& base_path)
: base_path_(base_path) {
// 创建基础目录结构
fs::create_directories(base_path + "/normal");
fs::create_directories(base_path + "/alarm");
// 启动清理线程
cleanup_thread_ = std::thread([this] { cleanupTask(); });
}
~ImageStorageManager() {
should_stop_ = true;
if (cleanup_thread_.joinable()) {
cleanup_thread_.join();
}
}
std::string saveNormalImage(const cv::Mat& image,
const std::string& camera_name) {
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);
std::string filename = base_path_ + "/normal/" +
camera_name + "_" +
std::to_string(timestamp) + ".jpg";
cv::imwrite(filename, image);
return filename;
}
std::string saveAlarmImage(const cv::Mat& image,
const std::string& camera_name) {
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);
// 创建月份目录
auto ltm = std::localtime(×tamp);
std::string month_dir = base_path_ + "/alarm/" +
std::to_string(1900 + ltm->tm_year) + "_" +
std::to_string(1 + ltm->tm_mon);
fs::create_directories(month_dir);
std::string filename = month_dir + "/" +
camera_name + "_" +
std::to_string(timestamp) + ".jpg";
cv::imwrite(filename, image);
return filename;
}
private:
void cleanupTask() {
while (!should_stop_) {
try {
cleanupNormalImages();
// 每小时检查一次
std::this_thread::sleep_for(std::chrono::hours(1));
} catch (const std::exception& e) {
LOG_ERROR("Cleanup task error: " + std::string(e.what()));
}
}
}
void cleanupNormalImages() {
const int MAX_AGE_MINUTES = 10;
auto now = std::chrono::system_clock::now();
for (const auto& entry : fs::directory_iterator(base_path_ + "/normal")) {
try {
auto last_write_time = fs::last_write_time(entry.path());
auto duration = std::chrono::duration_cast<std::chrono::minutes>(
now - std::chrono::clock_cast<std::chrono::system_clock>(
last_write_time));
if (duration.count() > MAX_AGE_MINUTES) {
fs::remove(entry.path());
LOG_INFO("Removed old image: " + entry.path().string());
}
} catch (const std::exception& e) {
LOG_ERROR("Error cleaning up file: " + entry.path().string() +
" - " + e.what());
}
}
}
std::string base_path_;
std::thread cleanup_thread_;
std::atomic<bool> should_stop_{false};
class AlarmRecorder {
public:
AlarmRecorder(const std::string& storage_path)
: storage_path_(storage_path) {
fs::create_directories(storage_path);
}
void startRecording(const std::string& camera_name,
const std::string& rtsp_url) {
std::lock_guard<std::mutex> lock(mutex_);
if (active_recordings_.count(camera_name) > 0) {
LOG_WARNING("Recording already active for camera: " + camera_name);
return;
}
// 生成录像文件名
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);
std::string filename = storage_path_ + "/" +
camera_name + "_" +
std::to_string(timestamp) + ".mp4";
// 创建GStreamer管道
std::string pipeline_str =
"rtspsrc location=" + rtsp_url + " ! " +
"rtph264depay ! h264parse ! mp4mux ! " +
"filesink location=" + filename;
GError* error = nullptr;
GstElement* pipeline = gst_parse_launch(pipeline_str.c_str(), &error);
if (error) {
LOG_ERROR("Failed to create recording pipeline: " +
std::string(error->message));
g_error_free(error);
return;
}
// 启动录制
gst_element_set_state(pipeline, GST_STATE_PLAYING);
// 记录活动录制
active_recordings_[camera_name] = {
pipeline,
filename,
std::chrono::system_clock::now()
};
// 启动定时器以停止录制
std::thread([this, camera_name]() {
std::this_thread::sleep_for(std::chrono::seconds(10));
stopRecording(camera_name);
}).detach();
}
void stopRecording(const std::string& camera_name) {
std::lock_guard<std::mutex> lock(mutex_);
auto it = active_recordings_.find(camera_name);
if (it == active_recordings_.end()) {
return;
}
// 停止GStreamer管道
GstElement* pipeline = it->second.pipeline;
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(pipeline);
// 记录报警信息
recordAlarmVideo(camera_name, it->second.filename);
// 移除活动录制记录
active_recordings_.erase(it);
}
private:
struct RecordingInfo {
GstElement* pipeline;
std::string filename;
std::chrono::system_clock::time_point start_time;
};
void recordAlarmVideo(const std::string& camera_name,
const std::string& filename) {
std::ofstream log_file(storage_path_ + "/alarm_videos.log",
std::ios::app);
if (log_file.is_open()) {
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);
log_file << "Camera: " << camera_name << "\n"
<< "Time: " << std::ctime(×tamp)
<< "File: " << filename << "\n"
<< "-------------------\n";
}
}
std::string storage_path_;
std::mutex mutex_;
std::map<std::string, RecordingInfo> active_recordings_;
class ResourceManager {
public:
static ResourceManager& getInstance() {
static ResourceManager instance;
return instance;
}
void initializeResources(size_t max_threads) {
thread_pool_ = std::make_unique<ThreadPool>(max_threads);
// 预分配内存池
for (size_t i = 0; i < max_threads; ++i) {
frame_buffer_pool_.push_back(
cv::Mat(1080, 1920, CV_8UC3)
);
}
}
cv::Mat& getFrameBuffer() {
std::lock_guard<std::mutex> lock(buffer_mutex_);
if (frame_buffer_pool_.empty()) {
// 如果池空,创建新的缓冲区
frame_buffer_pool_.push_back(
cv::Mat(1080, 1920, CV_8UC3)
);
}
cv::Mat& buffer = frame_buffer_pool_.back();
frame_buffer_pool_.pop_back();
return buffer;
}
void returnFrameBuffer(cv::Mat& buffer) {
std::lock_guard<std::mutex> lock(buffer_mutex_);
frame_buffer_pool_.push_back(buffer);
}
template<typename F>
void enqueueTask(F&& task) {
thread_pool_->enqueue(std::forward<F>(task));
}
private:
std::unique_ptr thread_pool_;
std::vectorcv::Mat frame_buffer_pool_;
std::mutex buffer_mutex_;
};
class VideoCapture {
public:
VideoCapture(const CameraConfig& config,
std::shared_ptr processor,
std::shared_ptr storage_manager,
std::shared_ptr alarm_recorder)
: config_(config),
processor_(processor),
storage_manager_(storage_manager),
alarm_recorder_(alarm_recorder),
pipeline_(nullptr),
last_frame_time_(std::chrono::steady_clock::now()),
is_running_(false) {
}
bool start() {
try {
// 构建GStreamer管道
std::string pipeline_str = buildPipelineString();
GError* error = nullptr;
pipeline_ = gst_parse_launch(pipeline_str.c_str(), &error);
if (error) {
LOG_ERROR("Failed to create pipeline for camera " +
config_.name + ": " + error->message);
g_error_free(error);
return false;
}
// 设置bus监听
GstBus* bus = gst_element_get_bus(pipeline_);
gst_bus_add_watch(bus, (GstBusFunc)busCallback, this);
gst_object_unref(bus);
// 获取appsink元素
appsink_ = gst_bin_get_by_name(GST_BIN(pipeline_), "appsink");
g_object_set(G_OBJECT(appsink_),
"emit-signals", TRUE,
"max-buffers", 1,
"drop", TRUE,
NULL);
// 设置新样本回调
g_signal_connect(appsink_, "new-sample",
G_CALLBACK(onNewSample), this);
// 启动pipeline
GstStateChangeReturn ret =
gst_element_set_state(pipeline_, GST_STATE_PLAYING);
if (ret == GST_STATE_CHANGE_FAILURE) {
LOG_ERROR("Failed to start pipeline for camera " + config_.name);
return false;
}
is_running_ = true;
LOG_INFO("Started video capture for camera " + config_.name);
return true;
} catch (const std::exception& e) {
LOG_ERROR("Error starting video capture for camera " +
config_.name + ": " + e.what());
return false;
}
}
void stop() {
if (pipeline_) {
gst_element_set_state(pipeline_, GST_STATE_NULL);
gst_object_unref(pipeline_);
pipeline_ = nullptr;
}
if (appsink_) {
gst_object_unref(appsink_);
appsink_ = nullptr;
}
is_running_ = false;
}
private:
std::string buildPipelineString() {
return "rtspsrc location=" + config_.rtsp_url +
" ! rtph264depay ! h264parse ! avdec_h264" +
" ! videoconvert ! video/x-raw,format=BGR" +
" ! appsink name=appsink";
}
static GstFlowReturn onNewSample(GstElement* sink, gpointer data) {
VideoCapture* self = static_cast<VideoCapture*>(data);
return self->handleNewSample(sink);
}
GstFlowReturn handleNewSample(GstElement* sink) {
// 检查帧间隔
auto now = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_frame_time_).count();
if (duration < config_.frame_interval) {
return GST_FLOW_OK;
}
last_frame_time_ = now;
// 获取样本
GstSample* sample = gst_app_sink_pull_sample(GST_APP_SINK(sink));
if (!sample) {
return GST_FLOW_ERROR;
}
try {
// 获取缓冲区
GstBuffer* buffer = gst_sample_get_buffer(sample);
GstMapInfo map;
if (!gst_buffer_map(buffer, &map, GST_MAP_READ)) {
gst_sample_unref(sample);
return GST_FLOW_ERROR;
}
// 获取caps
GstCaps* caps = gst_sample_get_caps(sample);
GstStructure* structure = gst_caps_get_structure(caps, 0);
int width, height;
gst_structure_get_int(structure, "width", &width);
gst_structure_get_int(structure, "height", &height);
// 创建OpenCV矩阵
cv::Mat frame(height, width, CV_8UC3, (void*)map.data);
// 获取帧缓冲区
auto& frame_buffer = ResourceManager::getInstance().getFrameBuffer();
frame.copyTo(frame_buffer);
// 异步处理帧
ResourceManager::getInstance().enqueueTask([this, frame_buffer]() {
auto start_time = std::chrono::steady_clock::now();
try {
// 保存正常帧
std::string image_path =
storage_manager_->saveNormalImage(frame_buffer,
config_.name);
// 处理帧
processor_->processFrame(frame_buffer, config_.name);
// 记录处理时间
auto end_time = std::chrono::steady_clock::now();
double processing_time =
std::chrono::duration_cast<std::chrono::milliseconds>(
end_time - start_time).count();
PerformanceMonitor::getInstance().recordFrameProcessingTime(
config_.name, processing_time);
} catch (const std::exception& e) {
LOG_ERROR("Frame processing error for camera " +
config_.name + ": " + e.what());
}
// 返回帧缓冲区到池
ResourceManager::getInstance().returnFrameBuffer(frame_buffer);
});
// 解除映射和释放样本
gst_buffer_unmap(buffer, &map);
gst_sample_unref(sample);
return GST_FLOW_OK;
} catch (const std::exception& e) {
LOG_ERROR("Error handling new sample for camera " +
config_.name + ": " + e.what());
gst_sample_unref(sample);
return GST_FLOW_ERROR;
}
}
static gboolean busCallback(GstBus* bus, GstMessage* message, gpointer data) {
VideoCapture* self = static_cast<VideoCapture*>(data);
return self->handleBusMessage(bus, message);
}
gboolean handleBusMessage(GstBus* bus, GstMessage* message) {
switch (GST_MESSAGE_TYPE(message)) {
case GST_MESSAGE_ERROR: {
GError
好的,以下是完成后的 VideoCapture 类的完整源代码,包括 .h 和 .cpp 文件。handleBusMessage 函数已补充完整,并完善了其他必要的部分。
VideoCapture.h
// VideoCapture.h
#ifndef VIDEO_CAPTURE_H
#define VIDEO_CAPTURE_H
#include <string>
#include <memory>
#include <chrono>
#include <gst/gst.h>
#include <gst/app/gstappsink.h>
#include <opencv2/opencv.hpp>
#include "ConfigManager.h"
#include "FrameProcessor.h"
#include "ImageStorageManager.h"
#include "AlarmRecorder.h"
#include "ResourceManager.h"
class VideoCapture {
public:
VideoCapture(const CameraConfig& config,
std::shared_ptr<FrameProcessor> processor,
std::shared_ptr<ImageStorageManager> storage_manager,
std::shared_ptr<AlarmRecorder> alarm_recorder);
bool start();
void stop();
private:
std::string buildPipelineString();
// GStreamer 回调函数
static GstFlowReturn onNewSample(GstElement* sink, gpointer data);
GstFlowReturn handleNewSample(GstElement* sink);
static gboolean busCallback(GstBus* bus, GstMessage* message, gpointer data);
gboolean handleBusMessage(GstBus* bus, GstMessage* message);
// 成员变量
CameraConfig config_;
std::shared_ptr<FrameProcessor> processor_;
std::shared_ptr<ImageStorageManager> storage_manager_;
std::shared_ptr<AlarmRecorder> alarm_recorder_;
GstElement* pipeline_;
GstElement* appsink_;
std::chrono::time_point<std::chrono::steady_clock> last_frame_time_;
bool is_running_;
};
#endif // VIDEO_CAPTURE_H
VideoCapture.cpp
// VideoCapture.cpp
#include "VideoCapture.h"
#include "Logger.h"
VideoCapture::VideoCapture(const CameraConfig& config,
std::shared_ptr<FrameProcessor> processor,
std::shared_ptr<ImageStorageManager> storage_manager,
std::shared_ptr<AlarmRecorder> alarm_recorder)
: config_(config),
processor_(processor),
storage_manager_(storage_manager),
alarm_recorder_(alarm_recorder),
pipeline_(nullptr),
appsink_(nullptr),
last_frame_time_(std::chrono::steady_clock::now()),
is_running_(false) {
}
bool VideoCapture::start() {
try {
// 构建 GStreamer 管道
std::string pipeline_str = buildPipelineString();
GError* error = nullptr;
pipeline_ = gst_parse_launch(pipeline_str.c_str(), &error);
if (error) {
LOG_ERROR("Failed to create pipeline for camera " +
config_.name + ": " + error->message);
g_error_free(error);
return false;
}
// 设置 bus 监听
GstBus* bus = gst_element_get_bus(pipeline_);
gst_bus_add_watch(bus, (GstBusFunc)busCallback, this);
gst_object_unref(bus);
// 获取 appsink 元素
appsink_ = gst_bin_get_by_name(GST_BIN(pipeline_), "appsink");
g_object_set(G_OBJECT(appsink_),
"emit-signals", TRUE,
"max-buffers", 1,
"drop", TRUE,
NULL);
// 设置新样本回调
g_signal_connect(appsink_, "new-sample",
G_CALLBACK(onNewSample), this);
// 启动 pipeline
GstStateChangeReturn ret =
gst_element_set_state(pipeline_, GST_STATE_PLAYING);
if (ret == GST_STATE_CHANGE_FAILURE) {
LOG_ERROR("Failed to start pipeline for camera " + config_.name);
return false;
}
is_running_ = true;
LOG_INFO("Started video capture for camera " + config_.name);
return true;
} catch (const std::exception& e) {
LOG_ERROR("Error starting video capture for camera " +
config_.name + ": " + e.what());
return false;
}
}
void VideoCapture::stop() {
if (pipeline_) {
gst_element_set_state(pipeline_, GST_STATE_NULL);
gst_object_unref(pipeline_);
pipeline_ = nullptr;
}
if (appsink_) {
gst_object_unref(appsink_);
appsink_ = nullptr;
}
is_running_ = false;
}
std::string VideoCapture::buildPipelineString() {
return "rtspsrc location=" + config_.rtsp_url +
" ! rtph264depay ! h264parse ! avdec_h264" +
" ! videoconvert ! video/x-raw,format=BGR" +
" ! appsink name=appsink";
}
GstFlowReturn VideoCapture::onNewSample(GstElement* sink, gpointer data) {
VideoCapture* self = static_cast<VideoCapture*>(data);
return self->handleNewSample(sink);
}
GstFlowReturn VideoCapture::handleNewSample(GstElement* sink) {
// 检查抽帧时间间隔
auto now = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_frame_time_).count();
if (duration < config_.frame_interval) {
return GST_FLOW_OK;
}
last_frame_time_ = now;
// 获取样本
GstSample* sample = gst_app_sink_pull_sample(GST_APP_SINK(sink));
if (!sample) {
return GST_FLOW_ERROR;
}
try {
// 获取缓冲区
GstBuffer* buffer = gst_sample_get_buffer(sample);
GstMapInfo map;
if (!gst_buffer_map(buffer, &map, GST_MAP_READ)) {
gst_sample_unref(sample);
return GST_FLOW_ERROR;
}
// 获取图像信息
GstCaps* caps = gst_sample_get_caps(sample);
GstStructure* structure = gst_caps_get_structure(caps, 0);
int width = 0, height = 0;
gst_structure_get_int(structure, "width", &width);
gst_structure_get_int(structure, "height", &height);
// 创建 OpenCV 矩阵
cv::Mat frame(height, width, CV_8UC3, (void*)map.data);
// 克隆帧数据,确保数据安全
cv::Mat frame_copy = frame.clone();
// 保存正常图片
std::string image_path = storage_manager_->saveNormalImage(frame_copy, config_.name);
// 异步处理帧
processor_->processFrame(frame_copy, config_.name);
// 解除映射和释放样本
gst_buffer_unmap(buffer, &map);
gst_sample_unref(sample);
return GST_FLOW_OK;
} catch (const std::exception& e) {
LOG_ERROR("Error handling new sample for camera " + config_.name + ": " + e.what());
gst_sample_unref(sample);
return GST_FLOW_ERROR;
}
}
gboolean VideoCapture::busCallback(GstBus* bus, GstMessage* message, gpointer data) {
VideoCapture* self = static_cast<VideoCapture*>(data);
return self->handleBusMessage(bus, message);
}
gboolean VideoCapture::handleBusMessage(GstBus* bus, GstMessage* message) {
switch (GST_MESSAGE_TYPE(message)) {
case GST_MESSAGE_ERROR: {
GError* err = nullptr;
gchar* debug_info = nullptr;
gst_message_parse_error(message, &err, &debug_info);
LOG_ERROR("Error received from element " + std::string(GST_OBJECT_NAME(message->src)) +
": " + std::string(err->message));
if (debug_info) {
LOG_ERROR("Debugging information: " + std::string(debug_info));
} else {
LOG_ERROR("No debugging information available");
}
g_clear_error(&err);
g_free(debug_info);
is_running_ = false;
gst_element_set_state(pipeline_, GST_STATE_NULL);
return FALSE; // 停止监听 bus
}
case GST_MESSAGE_EOS: {
LOG_INFO("End-Of-Stream reached for camera " + config_.name);
is_running_ = false;
gst_element_set_state(pipeline_, GST_STATE_NULL);
return FALSE; // 停止监听 bus
}
default:
break;
}
return TRUE; // 继续监听 bus
}
说明
-
handleBusMessage 函数补充:在 handleBusMessage 函数中,处理了 GST_MESSAGE_ERROR 和 GST_MESSAGE_EOS 两种消息类型。当收到错误消息时,解析错误信息,打印日志,并停止管道。当收到流结束消息时,记录日志并停止管道。
-
handleNewSample 函数优化:
- 增加了抽帧时间间隔的检查,确保按照配置文件中的时间间隔抽帧。
- 使用
cv::Mat::clone() 深拷贝帧数据,避免数据在异步处理过程中被覆盖。
- 异步调用
FrameProcessor 的 processFrame 函数进行帧处理。
- 处理完毕后,解除映射并释放
GstSample。
-
资源管理:确保在停止捕获时,正确释放 GStreamer 元素和资源,防止内存泄漏。
-
日志输出:在关键步骤和异常情况下,添加了日志输出,便于调试和监控。
如果还有其他需要补充的部分,或者对代码有任何疑问,请随时提出。
Not yet included in a published release.