代码对一些数据没做判断,仅仅是做个备忘!请谨慎参考!
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <stdio.h>
void encode_to_h264(AVCodecContext *codec_ctx, AVFrame *frame, AVPacket *pkt,
FILE *file_out) {
int ret;
ret = avcodec_send_frame(codec_ctx, frame);
while (!ret) {
ret = avcodec_receive_packet(codec_ctx, pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
printf("AVERROR(EAGAIN) or AVERROR_EOF\n");
return;
} else if (ret < 0) {
printf("error 8\n");
exit(1);
}
printf("ENCODE SUCCESS\n");
fwrite(pkt->data, 1, pkt->size, file_out);
av_packet_unref(pkt);
}
}
int main(int argc, char **argv) {
AVCodecContext *codec_ctx;
AVCodec *codec;
FILE *file_in;
FILE *file_out;
uint8_t *in_buf;
size_t in_size;
char *in_yuv;
char *out_h264;
AVFrame *frame;
AVPacket *pkt;
int ret;
if (argc != 3) {
printf("error 0\n");
exit(1);
}
in_yuv = argv[1];
out_h264 = argv[2];
file_in = fopen(in_yuv, "rb");
file_out = fopen(out_h264, "wb");
codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!codec) {
printf("error 1\n");
exit(1);
}
codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
printf("error 2\n");
exit(1);
}
codec_ctx->width = 320;
codec_ctx->height = 240;
codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
codec_ctx->gop_size = 12;
codec_ctx->max_b_frames = 2;
codec_ctx->framerate = (AVRational){25, 1};
codec_ctx->time_base = (AVRational){1, 25};
codec_ctx->bit_rate = 516 * 1024;
ret = avcodec_open2(codec_ctx, codec, NULL);
if (ret) {
printf("error 5\n");
exit(1);
}
in_size = av_image_get_buffer_size(codec_ctx->pix_fmt, codec_ctx->width,
codec_ctx->height, 1);
in_buf = av_malloc(in_size);
frame = av_frame_alloc();
frame->width = codec_ctx->width;
frame->height = codec_ctx->height;
frame->format = codec_ctx->pix_fmt;
ret = av_frame_get_buffer(frame, 0);
if (ret) {
printf("error 3\n");
exit(1);
}
pkt = av_packet_alloc();
av_init_packet(pkt);
int pts = 0;
while (fread(in_buf, 1, in_size, file_in) == in_size) {
ret = av_image_fill_arrays(frame->data, frame->linesize, in_buf,
codec_ctx->pix_fmt, codec_ctx->width,
codec_ctx->height, 1);
if (ret < 0) {
printf("error 4\n");
exit(1);
}
frame->width = codec_ctx->width;
frame->height = codec_ctx->height;
frame->format = codec_ctx->pix_fmt;
frame->pts = pts++;
encode_to_h264(codec_ctx, frame, pkt, file_out);
av_frame_unref(frame);
}
encode_to_h264(codec_ctx, NULL, pkt, file_out);
end:
fclose(file_in);
fclose(file_out);
av_frame_free(&frame);
av_packet_free(&pkt);
avcodec_free_context(&codec_ctx);
av_freep(&in_buf);
printf("Finished!\n");
return 0;
}