给我写一份ffmpeg读取rtsp的代码
时间: 2023-03-20 11:01:07 浏览: 133
ffmpeg_rtsp_mpp:ffmpeg 拉取rtsp h264流, 使用mpp解码, 目前在firefly 板子上跑通了
5星 · 资源好评率100%
好的,以下是一份使用FFmpeg读取RTSP流的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libavutil/avutil.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
int main(int argc, char *argv[]) {
AVFormatContext *format_ctx = NULL;
AVCodecContext *codec_ctx = NULL;
AVCodec *codec = NULL;
AVPacket packet;
int video_stream_index = -1;
int ret;
if (argc < 2) {
printf("Usage: %s rtsp_url\n", argv[0]);
return 1;
}
av_register_all();
// 打开输入流
if ((ret = avformat_open_input(&format_ctx, argv[1], NULL, NULL)) < 0) {
printf("Could not open input stream.\n");
return 1;
}
// 查找视频流
if ((ret = avformat_find_stream_info(format_ctx, NULL)) < 0) {
printf("Could not find stream info.\n");
return 1;
}
// 打印视频信息
av_dump_format(format_ctx, 0, argv[1], 0);
// 查找视频流索引
for (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) {
printf("Could not find video stream.\n");
return 1;
}
// 获取视频解码器
codec = avcodec_find_decoder(format_ctx->streams[video_stream_index]->codecpar->codec_id);
if (codec == NULL) {
printf("Could not find video decoder.\n");
return 1;
}
// 打开视频解码器
codec_ctx = avcodec_alloc_context3(codec);
if (codec_ctx == NULL) {
printf("Could not allocate codec context.\n");
return 1;
}
if ((ret = avcodec_parameters_to_context(codec_ctx, format_ctx->streams[video_stream_index]->codecpar)) < 0) {
printf("Could not copy codec parameters to codec context.\n");
return 1;
}
if ((ret = avcodec_open2(codec_ctx, codec, NULL)) < 0) {
printf("Could not open codec.\n");
return 1;
}
// 读取视频流
while (1) {
if ((ret = av_read_frame(format_ctx, &packet)) < 0) {
printf("Could not read frame.\n");
break;
}
// 解码视频帧
if (packet.stream_index == video_stream_index) {
AVFrame *frame = av_frame_alloc();
if (frame == NULL) {
printf("Could not allocate video frame.\n");
break;
}
ret = avcodec_send_packet(codec_ctx, &packet);
if (ret < 0) {
printf("Error sending a packet for decoding.\n");
break;
}
while (ret >= 0) {
ret = avcodec_receive_frame(codec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < 0
阅读全文