libav c++ sw_scale返回BGR24缓冲区的可变字节大小



我正试图将我的本地/dev/video0 cam转换为BGR24格式。如果我调整图像的大小(虽然不是100%的时间,更像是85%的时间),但我希望保持与输入视频相同的大小。

我像这样初始化BGR映像,包括sws上下文:

AVPixelFormat outputPixFormat = AV_PIX_FMT_BGR24;
AVFrame* pFrameBGR = av_frame_alloc();
pFrameBGR->width = decoder->video_codec_context->width;
pFrameBGR->height = decoder->video_codec_context->height;
pFrameBGR->format = outputPixFormat;
int alloRet = av_image_alloc(pFrameBGR->data, pFrameBGR->linesize, decoder->video_codec_context->width, decoder->video_codec_context->height, outputPixFormat, 1);
if (alloRet < 0) {
logging("failed to allocate image");
return -1;
}
struct SwsContext *sws_ctx = NULL;
sws_ctx = sws_getContext(decoder->video_codec_context->width,
decoder->video_codec_context->height,
decoder->video_codec_context->pix_fmt,
decoder->video_codec_context->width,
decoder->video_codec_context->height,
outputPixFormat,
SWS_DIRECT_BGR,
0,
0,
0
);

这是我的解码循环的一部分:

int response = avcodec_send_packet(pCodecContext, pPacket);
if (response < 0) {
logging("Error while sending a packet to decoder: %s", av_err2str(response));
return response;
}
while (response >= 0) {
response = avcodec_receive_frame(pCodecContext, pFrame);
if (response == AVERROR(EAGAIN) || response == AVERROR_EOF) {
break;
} else if (response < 0) {
logging("Error while receiving a frame from the decoder: %s", av_err2str(response));
return response;
}
if (response >= 0) {
sws_scale(sws_ctx,  (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, pCodecContext->height, pFrameBGR->data, pFrameBGR->linesize);

THe question is how to copy the plane of AVFrame into a buffer:

size_t rgb_size = av_image_get_buffer_size(AV_PIX_FMT_BGR24, bgrFrame->width, bgrFrame->height, 1);
uint8_t *dst_data;
dst_data = (uint8_t *)(av_malloc(rgb_size));
av_image_copy_to_buffer(dst_data, rgb_size, (const uint8_t* const *)bgrFrame->data, bgrFrame->linesize, AV_PIX_FMT_BGR24, bgrFrame->width, bgrFrame->height, 1);

如果我尝试保存到文件,BGR图像被正确复制:

char filebuf[256];
snprintf(filebuf, sizeof filebuf, "%s%d%s", "out_", pPacket->dts, ".rgb");
std::FILE *output=fopen(filebuf,"wb+");  
fwrite(bgrFrame->data[0],(pFrame->width)*(pFrame->height)*3,1,output);  
std::fclose(output);

所以它看起来像我复制到缓冲函数是错误的,但我可以找出它的问题:

uint8_t *dst_data;
dst_data = (uint8_t *)(av_malloc(rgb_size));
av_image_copy_to_buffer(dst_data, rgb_size, (const uint8_t* const *)bgrFrame->data, bgrFrame->linesize, AV_PIX_FMT_BGR24, bgrFrame->width, bgrFrame->height, 1);

以上代码完全正确。问题是在随后的代码序列化dst_data缓冲区,我忽略/忘记缓冲区的长度。感谢@ surgonix为我指明了正确的方向。

相关内容

  • 没有找到相关文章

最新更新