使用ffmpeg在线修改分辨率
由于之前做过ffmpeg针对视频的转码,使流程: decoder –> filter –> encoder。现在需求要求增加修改分辨率,并且要求添加到之前的流程中。
经过测试,可以用如下流程: decoder –> sws_scale –> filter –> encoder。
- sws_scale初始化操作
初始化context
struct SwsContext *g_sws_ctx;
g_sws_ctx = sws_getContext(g_src_ctx->width, g_src_ctx->height, g_src_ctx->pix_fmt,
g_dest_ctx->width, g_dest_ctx->height, g_dest_ctx->pix_fmt,
SWS_BICUBIC, NULL, NULL, NULL);
if (!g_sws_ctx) {
fprintf(stderr,
"Impossible to create scale context for the conversion "
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
av_get_pix_fmt_name(g_src_ctx->pix_fmt), g_src_ctx->width, g_src_ctx->height,
av_get_pix_fmt_name(g_dest_ctx->pix_fmt), g_dest_ctx->width, g_dest_ctx->height);
ret = AVERROR(EINVAL);
return -1;
}
- frame的初始化
frame初始化需要手动额外的分配空间
AVFrame *frame1; // source frame, from decoder
AVFrame *scaleframe; // scale dest frame
scaleframe = av_frame_alloc();
if (!scaleframe) {
fprintf(stderr, "Could not allocate video scaleframe\n");
exit(1);
}
scaleframe->format = pix_fmt;
scaleframe->width = width;
scaleframe->height = height;
// 下面是给scaleframe->data[0]分配空间, 在使用完后,scaleframe->data[0]也需要手动释放.
ret = av_image_alloc(scaleframe->data, scaleframe->linesize, scaleframe->width, scaleframe->height, scaleframe->format, 32);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw picture buffer\n");
exit(1);
}
- 修改分辨率
缩放后的frame数据,需要给format, width, height, pts几个字段单独赋值后,才能放到filter,或者encoder模块使用.
ret = sws_scale(g_sws_ctx, frame->data,frame->linesize
, 0, g_src_ctx->height, scaleframe->data, scaleframe->linesize);
scaleframe->pts = frame->pts;
- 释放
av_freep(&scaleframe->data[0]);
av_frame_free(&scaleframe);
在所有数据处理完后,释放context
sws_freeContext(g_sws_ctx);