ffmpeg h264编码 即保存文件 又推流 c++ 例程
时间: 2024-10-28 15:07:44 浏览: 130
FFmpeg是一个功能强大的多媒体处理工具库,它支持多种视频和音频编码格式,包括H264编码。要在C++中使用FFmpeg实现实时H264编码并同时保存文件和推流,你需要包含FFmpeg的动态链接库,并编写相应的代码来设置编码参数、打开输入和输出流。
下面是一个简单的例子,展示了如何使用FFmpeg的AVCodecContext结构体和AVFrame来创建一个H264编码器,并同时将数据输出到文件和RTMP服务器:
```cpp
#include <iostream>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/frame.h"
void encode_and_push(const std::string &input_file_path, const std::string &output_file_path, const std::string &rtmp_url) {
// 初始化FFmpeg上下文
av_register_all();
av_log_set_level(AV_LOG_INFO); // 设置日志级别
// 创建编码器
AVCodec *encoder = avcodec_find_encoder(AVCODEC_H264);
if (!encoder) {
throw std::runtime_error("Failed to find H264 encoder");
}
AVCodecContext *enc_ctx = avcodec_alloc_context3(encoder);
// 配置编码器参数
enc_ctx->bit_rate = 500000; // 500Kbps
enc_ctx->width = 640;
enc_ctx->height = 480;
enc_ctx->time_base.num = 1; // 帧率设置为每秒1帧
enc_ctx->time_base.den = 25; // 根据需要调整帧率,这里是25fps
avcodec_parameters_to_context(enc_ctx, av_codec_get_default_params(encoder));
// 打开编码器
if (avcodec_open2(enc_ctx, encoder, nullptr) != 0) {
throw std::runtime_error("Failed to open codec");
}
// 创建文件输出流
AVFormatContext *fmt_ctx_file = nullptr;
fmt_ctx_file = avformat_alloc_context();
if (!fmt_ctx_file || !avio_open(&fmt_ctx_file->pb, output_file_path.c_str(), AVIO_FLAG_WRITE)) {
throw std::runtime_error("Failed to create file output stream");
}
fmt_ctx_file->oformat = av_guess_format(NULL, output_file_path.c_str(), NULL);
AVStream *stream_file = avformat_new_stream(fmt_ctx_file, encoder);
stream_file->codecpar = enc_ctx;
// 开始编码过程
AVFrame *frame = av_frame_alloc();
while (true) { // 这里替换为实际的视频读取源
// 解码并编码数据...
// ...
// 将编码后的帧写入文件
int ret = av_interleaved_write_frame(fmt_ctx_file, frame);
if (ret < 0) {
throw std::runtime_error("Failed to write frame to file");
}
// 推送到RTMP服务器...
// 使用libavformat的ff_rtmp_push()函数或其他RTMP客户端库
// ...
av_frame_free(&frame);
frame = nullptr;
}
// 关闭和释放资源
avcodec_close(enc_ctx);
avformat_free_context(fmt_ctx_file);
}
阅读全文
相关推荐















