废话不多说,直接上代码。
需要注意的是,FFmpeg的版本很多,最新版本可能有些函数已经换成别的了。如果无法自行更改代码,可以找我以前相关FFmpeg的文章,下载我x64版本的工程包,里面就有这个版本的FFmpeg。
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
}
void main()
{
AVFormatContext *pFormatCtx;
char filepath[] = "rtsp://192.168.50.171/live/stream0";
AVPacket *packet;
av_register_all();
avformat_network_init();
pFormatCtx = avformat_alloc_context();
AVDictionary* options = NULL;
av_dict_set(&options, "buffer_size", "102400", 0);
av_dict_set(&options, "rtsp_transport", "tcp", 0);
av_dict_set(&options, "stimeout", "2000000", 0);
av_dict_set(&options, "max_delay", "500000", 0);
packet = (AVPacket *)av_malloc(sizeof(AVPacket));
if (avformat_open_input(&pFormatCtx, filepath, NULL, NULL) != 0)
{
printf("Couldn't open input stream.\n");
return;
}
if (avformat_find_stream_info(pFormatCtx, NULL)<0)
{
printf("Couldn't find stream information.\n");
return;
}
int videoindex = -1;
for (int i = 0; i<pFormatCtx->nb_streams; i++)
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoindex = i;
break;
}
if (videoindex == -1)
{
printf("Didn't find a video stream.\n");
return;
}
FILE *fpSave;
fopen_s(&fpSave, "geth264.h264", "wb");
for (int i = 0; i < 1000; i++)
{
if (av_read_frame(pFormatCtx, packet) >= 0)
{
if (packet->stream_index == videoindex)
{
fwrite(packet->data, 1, packet->size, fpSave);
}
av_packet_unref(packet);
}
}
fclose(fpSave);
av_free(pFormatCtx);
av_free(packet);
}