写一个C++使用ffmpeg实现rtsp推流的代码
时间: 2023-03-21 11:00:21 浏览: 267
以下是使用FFmpeg实现RTSP推流的示例C代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
int main(int argc, char **argv)
{
AVFormatContext *fmt_ctx = NULL;
AVOutputFormat *out_fmt = NULL;
AVStream *video_st = NULL;
AVCodecContext *codec_ctx = NULL;
AVCodec *codec = NULL;
AVDictionary *options = NULL;
int ret;
const char *rtsp_url = "rtsp://your_rtsp_server_url";
const char *out_filename = "rtsp_stream_output";
// Register all available codecs and formats
av_register_all();
avformat_network_init();
// Allocate output format context
avformat_alloc_output_context2(&fmt_ctx, NULL, "rtsp", out_filename);
if (!fmt_ctx) {
fprintf(stderr, "Could not create output format context\n");
return -1;
}
// Find video encoder codec
codec = avcodec_find_encoder_by_name("h264");
if (!codec) {
fprintf(stderr, "Could not find video encoder codec\n");
return -1;
}
// Allocate codec context and set options
codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
fprintf(stderr, "Could not allocate codec context\n");
return -1;
}
codec_ctx->bit_rate = 400000;
codec_ctx->width = 640;
codec_ctx->height = 480;
codec_ctx->time_base = (AVRational){1, 25};
codec_ctx->gop_size = 10;
codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
av_opt_set(codec_ctx->priv_data, "preset", "ultrafast", 0);
av_opt_set(codec_ctx->priv_data, "tune", "zerolatency", 0);
// Open codec
if ((ret = avcodec_open2(codec_ctx, codec, &options)) < 0) {
fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
return -1;
}
// Add video stream to output format context
video_st = avformat_new_stream(fmt_ctx, codec);
if (!video_st) {
fprintf(stderr, "Could not create new video stream\n");
return -1;
}
avcodec_parameters_from_context(video_st->codecpar, codec_ctx);
// Open output file or URL
if ((ret = avio_open(&fmt_ctx->pb, rtsp_url, AVIO_FLAG_WRITE)) < 0) {
fprintf(stderr, "Could not open output file or URL: %s\n", av_err2str(ret));
return -1;
}
// Write header to output format context
if ((ret = avformat_write_header(fmt_ctx, &options)) < 0) {
fprintf(stderr, "Could not write header to output format context: %s\n", av_err2str(ret));
return -1;
}
// Main loop to write video frames
for (int i = 0; i < 1000; i++) {
AVFrame *frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
return -1;
}
// Fill video frame with data
// ...
// Set frame PTS and duration
frame->
阅读全文