ffmpeg sws_scale YUV420p 到 RGBA 没有给出正确的缩放结果 (c++)

ffmpeg sws_scale YUV420p to RGBA not giving correct scaling result (c++)

我正在尝试通过 sws_scale 将解码的 YUV420p 帧 (1018x700) 缩放到 RGBA,我正在将数据保存到原始视频文件,然后使用 ffplay 播放原始视频以查看结果。

这是我的代码:

sws_ctx = sws_getContext(video_dec_ctx->width, video_dec_ctx->height,AV_PIX_FMT_YUV420P, video_dec_ctx->width, video_dec_ctx->height, AV_PIX_FMT_BGR32, SWS_LANCZOS | SWS_ACCURATE_RND, 0, 0, 0);
ret = avcodec_decode_video2(video_dec_ctx, yuvframe, got_frame, &pkt);
    if (ret < 0) {
        std::cout<<"Error in decoding"<<std::endl;
        return ret;
    }else{
        //the source and destination heights and widths are the same
        int sourceX = video_dec_ctx->width;
        int sourceY = video_dec_ctx->height;
        int destX = video_dec_ctx->width;
        int destY = video_dec_ctx->height;

        //declare destination frame
        AVFrame avFrameRGB;
        avFrameRGB.linesize[0] = destX * 4;
        avFrameRGB.data[0] = (uint8_t*)malloc(avFrameRGB.linesize[0] * destY);

        //scale the frame to avFrameRGB
        sws_scale(sws_ctx, yuvframe->data, yuvframe->linesize, 0, yuvframe->height, avFrameRGB.data, avFrameRGB.linesize);

        //write to file
        fwrite(avFrameRGB.data[0], 1, video_dst_bufsize, video_dst_file);
 }

这是没有缩放的结果(即 YUV420p 格式)

这是使用 ffplay 播放时缩放后的效果(即 RGBA 格式)

我运行使用以下命令进行ffplay('video'是原始视频文件)

ffplay -f rawvideo -pix_fmt bgr32 -video_size 1018x700 video

我应该解决什么问题才能使 RGB32 正确缩放?

我找到了解决方案,这里的问题是我没有使用正确的缓冲区大小来写入文件。

fwrite(avFrameRGB.data[0], 1, video_dst_bufsize, video_dst_file);

变量video_dst_file取自

的return值
video_dst_bufsize = av_image_alloc(yuvframe.data, yuvframe.linesize, destX, destY, AV_PIX_FMT_YUV420P, 1);

解决方案是从中获取 return 值并在 fwrite 语句中使用它:

video_dst_bufsize_RGB = av_image_alloc(avFrameRGB.data, avFrameRGB.linesize, destX, destY, AV_PIX_FMT_BGR32, 1);

fwrite(avFrameRGB.data[0], 1, video_dst_bufsize_RGB, video_dst_file);