RtspDecoderByFFmpeg/RTSPDecoder/RTSPDecoder.h

92 lines
2.4 KiB
C++

#ifndef RTSP_DECODER_H
#define RTSP_DECODER_H
#include <vector>
#include <string>
#include <memory>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <opencv2/opencv.hpp>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/hwcontext.h>
// #include <libavutil/hwcontext_cuda.h>
#include <libswscale/swscale.h>
}
class RTSPDecoder {
public:
struct DecoderConfig {
int max_streams = 60; // 最大支持流数
int gpu_id = -1; // 指定GPU ID (-1表示自动分配)
int width = 0; // 输出宽度 (0表示保持原始)
int height = 0; // 输出高度 (0表示保持原始)
int fps = 0; // 目标帧率 (0表示保持原始)
bool use_hw_accel = true; // 是否使用硬件加速
int buffer_size = 1024; // 帧缓冲队列大小
};
// 构造函数
RTSPDecoder();
// 析构函数
~RTSPDecoder();
// 初始化解码器
bool init(const DecoderConfig& config);
// 添加RTSP流
int addStream(const std::string& rtsp_url);
// 移除RTSP流
bool removeStream(int stream_id);
// 获取解码后的帧
bool getFrame(int stream_id, cv::Mat& frame, int timeout_ms = 1000);
// 获取当前活跃的流数量
int getActiveStreamCount() const;
// 获取GPU数量
static int getGPUCount();
private:
struct StreamContext {
AVFormatContext* format_ctx = nullptr;
AVCodecContext* codec_ctx = nullptr;
AVBufferRef* hw_device_ctx = nullptr;
SwsContext* sws_ctx = nullptr;
int video_stream_idx = -1;
int gpu_id = 0;
std::atomic<bool> running{false};
std::mutex mutex;
std::condition_variable cond;
std::queue<cv::Mat> frame_queue;
std::thread decode_thread;
};
DecoderConfig config_;
std::vector<std::unique_ptr<StreamContext>> streams_;
std::mutex streams_mutex_;
std::atomic<int> next_gpu_id_{0};
std::atomic<bool> initialized_{false};
// 初始化硬件加速
bool initHWAccel(StreamContext& ctx, int gpu_id);
// 解码线程函数
void decodeThreadFunc(int stream_id, StreamContext* ctx);
// 清理流上下文
void cleanupStream(StreamContext* ctx);
// 分配GPU
int allocateGPU();
};
#endif // RTSP_DECODER_H