ffmpeg 获取 rtsp 视频流 c++ 代码实现
时间: 2023-10-02 10:09:33 浏览: 65
下面是一个简单的 C++ 代码示例,演示了如何使用 FFmpeg 库从 RTSP 服务器获取视频流:
```c++
#include <iostream>
extern "C"
{
#include <libavformat/avformat.h>
}
int main(int argc, char* argv[])
{
AVFormatContext* format_ctx = nullptr;
AVPacket packet;
int stream_index = -1;
int video_stream_index = -1;
const char* url = "rtsp://example.com/stream";
av_register_all();
avformat_network_init();
if (avformat_open_input(&format_ctx, url, nullptr, nullptr) != 0) {
std::cerr << "Failed to open input file" << std::endl;
return -1;
}
if (avformat_find_stream_info(format_ctx, nullptr) < 0) {
std::cerr << "Failed to retrieve input stream information" << std::endl;
return -1;
}
for (unsigned int i = 0; i < format_ctx->nb_streams; i++) {
if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_index = i;
break;
}
}
if (video_stream_index == -1) {
std::cerr << "Failed to find video stream" << std::endl;
return -1;
}
av_init_packet(&packet);
while (av_read_frame(format_ctx, &packet) >= 0) {
if (packet.stream_index == video_stream_index) {
// process video frame here
}
av_packet_unref(&packet);
}
avformat_close_input(&format_ctx);
avformat_network_deinit();
return 0;
}
```
在此代码示例中,我们首先初始化 FFmpeg 库,然后使用 `avformat_open_input` 函数打开 RTSP 输入流。接下来,我们使用 `avformat_find_stream_info` 函数查找输入流的信息,以确定视频流的索引。然后,我们进入一个循环,不断读取新的数据包,直到输入流被关闭。在循环内,我们使用 `av_read_frame` 函数读取每个数据包,并检查其流索引,以确定它是否属于视频流。如果是,则可以对视频帧进行处理(这部分代码未在示例中提供)。最后,在循环结束时,我们释放内存并关闭输入流。
需要注意的是,本示例只是一个基本示例,没有对异常情况进行处理。在实际应用中,您需要添加适当的错误处理和异常处理代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)