version
#define LIBAVCODEC_VERSION_MAJOR 60
#define LIBAVCODEC_VERSION_MINOR 15
#define LIBAVCODEC_VERSION_MICRO 100
note
不使用AVOutputFormat
code
void CFfmpegOps::EncodeBGR24ToBMP(const char* infile, const char* width_str, const char* height_str, const char *outfile)
{
if ((!infile) || (!width_str) || (!height_str) || (!outfile))
{
return;
}
int width = 0;
int height = 0;
AVFrame *avframe = nullptr;
int frame_bytes = 0;
AVPixelFormat src_fmt = AV_PIX_FMT_BGR24;
int ret = -1;
FILE *in_fp = nullptr;
size_t n = 0;
AVPacket *avpacket = nullptr;
const AVCodec *encoder = nullptr;
AVCodecContext *encoder_ctx = nullptr;
FILE *out_fp = nullptr;
try
{
width = std::stoi(width_str);
height = std::stoi(height_str);
}
catch (const std::exception &e)
{
return;
}
avframe = av_frame_alloc();
if (!avframe)
{
printf("av_frame_alloc error\n");
goto end;
}
avframe->format = src_fmt;
avframe->width = width;
avframe->height = height;
frame_bytes = av_image_get_buffer_size(src_fmt, width, height, 1);
ret = av_frame_get_buffer(avframe, 0);
if (ret < 0)
{
printf("av_frame_get_buffer error(%s)\n", GetFfmpegERR(ret));
goto end;
}
in_fp = fopen(infile, "rb");
if (!in_fp)
{
printf("fopen error\n");
goto end;
}
n = fread(avframe->data[0], sizeof(uint8_t), frame_bytes, in_fp);
if ((int)n != (frame_bytes))
{
printf("n != (frame_bytes)\n");
goto end;
}
avpacket = av_packet_alloc();
if (!avpacket)
{
printf("av_packet_alloc error\n");
goto end;
}
encoder = avcodec_find_encoder(AV_CODEC_ID_BMP);
if (!encoder)
{
printf("avcodec_find_encoder error\n");
goto end;
}
encoder_ctx = avcodec_alloc_context3(encoder);
if (!encoder_ctx)
{
printf("avcodec_alloc_context3 error\n");
goto end;
}
encoder_ctx->pix_fmt = src_fmt;
encoder_ctx->width = width;
encoder_ctx->height = height;
encoder_ctx->time_base.num = 1;
encoder_ctx->time_base.den = 25;
encoder_ctx->framerate.num = 25;
encoder_ctx->framerate.den = 1;
encoder_ctx->bit_rate = frame_bytes * encoder_ctx->framerate.num * 8;
ret = avcodec_open2(encoder_ctx, encoder, nullptr);
if (ret < 0)
{
printf("avcodec_open2 error(%s)\n", GetFfmpegERR(ret));
goto end;
}
out_fp = fopen(outfile, "wb");
if (!out_fp)
{
printf("fopen error\n");
goto end;
}
ret = avcodec_send_frame(encoder_ctx, avframe);
if (ret != 0)
{
printf("avcodec_send_frame error(%s)\n", GetFfmpegERR(ret));
goto end;
}
while (1)
{
ret = avcodec_receive_packet(encoder_ctx, avpacket);
if (ret != 0)
{
if (ret == AVERROR(EAGAIN))
{
continue;
}
printf("avcodec_receive_packet error(%s)\n", GetFfmpegERR(ret));
break;
}
n = fwrite(avpacket->data, avpacket->size, sizeof(uint8_t), out_fp);
av_packet_unref(avpacket);
break;
}
end:
if (out_fp)
{
fclose(out_fp);
out_fp = nullptr;
}
if (encoder_ctx)
{
avcodec_free_context(&encoder_ctx);
encoder_ctx = nullptr;
}
if (avpacket)
{
av_packet_free(&avpacket);
avpacket = nullptr;
}
if (in_fp)
{
fclose(in_fp);
in_fp = nullptr;
}
if (avframe)
{
av_frame_free(&avframe);
avframe = nullptr;
}
}