编写一个基于ffmpeg的读取rtsp流的例程
时间: 2023-03-26 12:00:47 浏览: 122
好的,我可以回答这个问题。以下是一个基于ffmpeg的读取rtsp流的例程:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
int main(int argc, char *argv[]) {
AVFormatContext *fmt_ctx = NULL;
AVCodecContext *codec_ctx = NULL;
AVCodec *codec = NULL;
AVPacket pkt;
AVFrame *frame = NULL;
struct SwsContext *sws_ctx = NULL;
int video_stream_index = -1;
int ret = ;
if (argc < 2) {
fprintf(stderr, "Usage: %s <rtsp url>\n", argv[]);
return 1;
}
av_register_all();
if (avformat_open_input(&fmt_ctx, argv[1], NULL, NULL) < ) {
fprintf(stderr, "Could not open input file '%s'\n", argv[1]);
return 1;
}
if (avformat_find_stream_info(fmt_ctx, NULL) < ) {
fprintf(stderr, "Could not find stream information\n");
return 1;
}
av_dump_format(fmt_ctx, , argv[1], );
for (int i = ; i < fmt_ctx->nb_streams; i++) {
if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_index = i;
break;
}
}
if (video_stream_index == -1) {
fprintf(stderr, "Could not find video stream\n");
return 1;
}
codec_ctx = avcodec_alloc_context3(NULL);
if (!codec_ctx) {
fprintf(stderr, "Could not allocate codec context\n");
return 1;
}
ret = avcodec_parameters_to_context(codec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);
if (ret < ) {
fprintf(stderr, "Could not copy codec parameters to codec context\n");
return 1;
}
codec = avcodec_find_decoder(codec_ctx->codec_id);
if (!codec) {
fprintf(stderr, "Unsupported codec\n");
return 1;
}
ret = avcodec_open2(codec_ctx, codec, NULL);
if (ret < ) {
fprintf(stderr, "Could not open codec\n");
return 1;
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate frame\n");
return 1;
}
sws_ctx = sws_getContext(codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt,
codec_ctx->width, codec_ctx->height, AV_PIX_FMT_RGB24,
SWS_BILINEAR, NULL, NULL, NULL);
if (!sws_ctx) {
fprintf(stderr, "Could not initialize sws context\n");
return 1;
}
while (av_read_frame(fmt_ctx, &pkt) >= ) {
if (pkt.stream_index == video_stream_index) {
ret = avcodec_send_packet(codec_ctx, &pkt);
if (ret < ) {
fprintf(stderr, "Error sending packet to decoder\n");
break;
}
while (ret >= ) {
ret = avcodec_receive_frame(codec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < ) {
fprintf(stderr, "Error receiving frame from decoder\n");
break;
}
sws_scale(sws_ctx, frame->data, frame->linesize, , codec_ctx->height,
frame->data, frame->linesize);
// Do something with the RGB24 frame here
av_frame_unref(frame);
}
}
av_packet_unref(&pkt);
}
avformat_close_input(&fmt_ctx);
avcodec_free_context(&codec_ctx);
av_frame_free(&frame);
sws_freeContext(sws_ctx);
return ;
}
```
这个例程使用了ffmpeg库来读取rtsp流,并将视频帧转换为RGB24格式。你可以在`// Do something with the RGB24 frame here`处添加你自己的代码来处理视频帧。
阅读全文