找到H264编码器 然后创建输出流 然后创建编码器上下文,设置编码器参数 打开编码器
时间: 2024-05-11 14:19:56 浏览: 115
好的,以下是用FFmpeg库实现的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
#include <libavutil/imgutils.h>
int main(int argc, char *argv[])
{
AVCodec *codec;
AVCodecContext *codec_ctx;
AVFrame *frame;
AVPacket pkt;
int ret, i, j, k;
int width = 640, height = 480;
int bitrate = 1000000;
int fps = 25;
int gop_size = 10;
int max_b_frames = 0;
char *output_file = "output.h264";
FILE *output_fp;
avcodec_register_all();
codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!codec) {
fprintf(stderr, "Codec not found\n");
return -1;
}
codec_ctx = avcodec_alloc_context3(codec);
codec_ctx->bit_rate = bitrate;
codec_ctx->width = width;
codec_ctx->height = height;
codec_ctx->time_base = (AVRational){1, fps};
codec_ctx->gop_size = gop_size;
codec_ctx->max_b_frames = max_b_frames;
codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
fprintf(stderr, "Failed to open codec\n");
return -1;
}
frame = av_frame_alloc();
frame->format = codec_ctx->pix_fmt;
frame->width = codec_ctx->width;
frame->height = codec_ctx->height;
ret = av_frame_get_buffer(frame, 32);
if (ret < 0) {
fprintf(stderr, "Failed to allocate picture\n");
return -1;
}
output_fp = fopen(output_file, "wb");
if (!output_fp) {
fprintf(stderr, "Failed to open output file\n");
return -1;
}
for (i = 0; i < 100; i++) {
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
ret = av_frame_make_writable(frame);
if (ret < 0) {
fprintf(stderr, "Failed to make frame writable\n");
break;
}
for (j = 0; j < height; j++) {
for (k = 0; k < width; k++) {
frame->data[0][j * frame->linesize[0] + k] = j + i * 3;
}
}
for (j = 0; j < height / 2; j++) {
for (k = 0; k < width / 2; k++) {
frame->data[1][j * frame->linesize[1] + k] = 128 + j + i * 2;
frame->data[2][j * frame->linesize[2] + k] = 64 + k + i * 5;
}
}
frame->pts = i;
ret = avcodec_send_frame(codec_ctx, frame);
if (ret < 0) {
fprintf(stderr, "Failed to send frame\n");
break;
}
while (ret >= 0) {
ret = avcodec_receive_packet(codec_ctx, &pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < 0) {
fprintf(stderr, "Failed to receive packet\n");
break;
}
fwrite(pkt.data, 1, pkt.size, output_fp);
av_packet_unref(&pkt);
}
}
avcodec_send_frame(codec_ctx, NULL);
while (ret >= 0) {
ret = avcodec_receive_packet(codec_ctx, &pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < 0) {
fprintf(stderr, "Failed to receive packet\n");
break;
}
fwrite(pkt.data, 1, pkt.size, output_fp);
av_packet_unref(&pkt);
}
fclose(output_fp);
av_frame_free(&frame);
avcodec_free_context(&codec_ctx);
return 0;
}
```
以上代码实现了以下功能:
1. 找到H264编码器
2. 创建编码器上下文,设置编码器参数
3. 打开编码器
4. 创建输出文件
5. 循环编码并输出到文件
6. 关闭编码器和输出文件
你可以根据自己的需要修改代码中的参数和输入数据来进行测试。
阅读全文