写一份ffmpeg推流代码
时间: 2023-03-20 22:01:07 浏览: 138
简单的ffmpeg推流demo
ffmpeg是一个开源的多媒体框架,可以对音频和视频进行编解码、转码和推流等操作。下面是一份使用ffmpeg推流的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
int main(int argc, char **argv) {
AVFormatContext *fmt_ctx = NULL;
AVOutputFormat *fmt = NULL;
AVStream *video_st = NULL;
AVCodecContext *codec_ctx = NULL;
AVCodec *codec = NULL;
AVDictionary *options = NULL;
int ret, i;
const char *stream_url = "rtmp://example.com/live/stream";
// Initialize libavformat
av_register_all();
avformat_network_init();
// Open output URL
if ((ret = avformat_alloc_output_context2(&fmt_ctx, NULL, "flv", stream_url)) < 0) {
fprintf(stderr, "Could not allocate output context: %s\n", av_err2str(ret));
exit(1);
}
fmt = fmt_ctx->oformat;
// Add video stream to output context
video_st = avformat_new_stream(fmt_ctx, NULL);
if (!video_st) {
fprintf(stderr, "Could not create video stream\n");
exit(1);
}
codec = avcodec_find_encoder(fmt->video_codec);
if (!codec) {
fprintf(stderr, "Could not find encoder for '%s'\n", avcodec_get_name(fmt->video_codec));
exit(1);
}
codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
fprintf(stderr, "Could not allocate codec context\n");
exit(1);
}
// Set codec parameters
codec_ctx->codec_id = fmt->video_codec;
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;
// Set codec options
av_opt_set(codec_ctx->priv_data, "preset", "fast", 0);
// Open codec
if ((ret = avcodec_open2(codec_ctx, codec, &options)) < 0) {
fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
exit(1);
}
// Set stream parameters
video_st->codecpar->codec_id = fmt->video_codec;
video_st->codecpar->bit_rate = 400000;
video_st->codecpar->width = 640;
video_st->codecpar->height = 480;
video_st->codecpar->format = codec_ctx->pix_fmt;
video_st->time_base = codec_ctx->time_base;
// Allocate output buffer
ret = avformat_write_header(fmt_ctx, &options);
if (ret < 0) {
fprintf(stderr, "Could not write header: %s\n", av_err2str(ret));
exit(1);
}
// Start streaming
for (i = 0; i < 10000; i++) {
AVFrame *frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate frame\n");
exit(1);
}
// Fill frame with data
阅读全文