代码拉取完成,页面将自动刷新
#include "RTSPStream.h"
RTSPStream::RTSPStream(const std::string& url) : rtspUrl(url), formatCtx(nullptr), videoStreamIndex(-1) {}
RTSPStream::~RTSPStream() {
close();
}
bool RTSPStream::open() {
// 初始化FFmpeg网络组件
avformat_network_init();
// 分配AVFormatContext结构体
formatCtx = avformat_alloc_context();
// 创建并设置AVDictionary选项
AVDictionary* iformat_opts = nullptr;
av_dict_set(&iformat_opts, "buffer_size", "4096000", 0);
av_dict_set(&iformat_opts, "rtsp_transport", "tcp", 0);
av_dict_set(&iformat_opts, "stimeout", "5000000", 0);
av_dict_set(&iformat_opts, "max_delay", "500000", 0);
// 打开输入流
if (avformat_open_input(&formatCtx, rtspUrl.c_str(), nullptr, &iformat_opts) != 0) {
std::cerr << "avformat_open_input err" << std::endl;
av_dict_free(&iformat_opts); // 释放字典
return false;
}
av_dict_free(&iformat_opts); // 释放字典
// 查找流信息
if (avformat_find_stream_info(formatCtx, nullptr) < 0) {
std::cerr << "avformat_find_stream_info err" << std::endl;
return false;
}
// 查找视频流索引
for (int i = 0; i < formatCtx->nb_streams; i++) {
if (formatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStreamIndex = i;
break;
}
}
AVCodecParameters* codecpar = formatCtx->streams[videoStreamIndex]->codecpar;
AVCodecID codec_id = codecpar->codec_id;
const char* codec_name = avcodec_get_name(codec_id);
mCodeType = std::string(codec_name);
std::cout << "Video codec: " << codec_name << std::endl;
// 检查是否找到视频流
if (videoStreamIndex == -1) {
std::cerr << "videoStreamIndex err " << std::endl;
return false;
}
return true;
}
void RTSPStream::close() {
if (formatCtx) {
avformat_close_input(&formatCtx);
formatCtx = nullptr;
}
}
bool RTSPStream::readFrame(AVPacket* packet) {
while (av_read_frame(formatCtx, packet) >= 0) {
if (packet->stream_index == videoStreamIndex) {
return true;
}
av_packet_unref(packet);
}
return false;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。