如何在libavcodec中设置解码像素格式?

2024-03-05

我使用以下代码通过 libavcodec 解码视频:

//Open input file
if(avformat_open_input(&ctx, filename, NULL, NULL)!=0)
    return FALSE; // Couldn't open file
if(avformat_find_stream_info(ctx, NULL)<0)
    return FALSE; // Couldn't find stream information
videoStream = -1;
//find video stream
for(i=0; i<ctx->nb_streams; i++)
{       
    if((ctx->streams[i])->codec->codec_type==AVMEDIA_TYPE_VIDEO)
    {
        videoStream=i;
        break;
    }
}
if (videoStream == -1)
    return FALSE; // Didn't find a video stream
video_codec_ctx=ctx->streams[videoStream]->codec;
//find decoder
video_codec=avcodec_find_decoder(video_codec_ctx->codec_id);
if(video_codec==NULL)
    return FALSE; // Codec not found
if(avcodec_open(video_codec_ctx, video_codec)<0)
    return -1; // Could not open codec
video_frame=avcodec_alloc_frame();
scaled_frame=avcodec_alloc_frame();
static struct SwsContext *img_convert_ctx; 
if(img_convert_ctx == NULL) 
{
      int w = video_codec_ctx->width;
      int h = video_codec_ctx->height;
      img_convert_ctx = sws_getContext(w, h, 
                        video_codec_ctx->pix_fmt, 
                        w, h, dst_pix_fmt, SWS_BICUBIC, 
                        NULL, NULL, NULL);
      if(img_convert_ctx == NULL) {
        fprintf(stderr, "Cannot initialize the conversion context!\n");
        return FALSE;
      }
}
while(b_play) 
{
    if (av_read_frame(ctx, &packet) < 0)
    {
        break;
    }
    if(packet.stream_index==videoStream) {
    // Decode video frame   
        avcodec_decode_video2(video_codec_ctx, video_frame, &frameFinished,
                         &packet);
        // Did we get a video frame?
        if(frameFinished) 
        {
            if (video_codec_ctx->pix_fmt != dst_pix_fmt)
            {                       
                if (video_codec_ctx->pix_fmt != dst_pix_fmt)            
                     sws_scale(img_convert_ctx, video_frame->data, 
                              video_frame->linesize, 0, 
                              video_codec_ctx->height, 
                              scaled_frame->data, scaled_frame->linesize);              
            }           
        }
}
av_free_packet(&packet);
}

代码工作正常,但需要将每个帧转换为所需的格式。 是否可以设置解码的像素格式以获得正确的格式而无需 sws_scale ?

非常感谢您的回答。


ffmpeg's AVCodec实例(静态解码器“工厂”对象)每个都定义它们支持的像素格式数组,以值 -1 结尾。

The AVCodecContext(解码器实例)对象有一个名为的回调函数指针get_format:它是该结构中的函数指针。

在编解码器初始化的某个时刻调用此回调函数AVCodec工厂对象的受支持格式数组,回调应该从该数组中选择一种格式(有点像“选择一张卡,任何卡”)并返回该值。这个的默认实现get_format回调是一个名为的函数avcodec_default_get_format。 (这是安装的avcodec_get_context_defaults2)。这个默认函数非常简单地实现“选择格式”逻辑:它选择数组的第一个元素,该元素不是仅硬件加速的像素格式。

如果您希望编解码器使用不同的像素格式,您可以安装自己的编解码器get_format回调到上下文对象中。但是,回调必须返回数组中的值之一(例如从菜单中选择)。它不能返回任意值。编解码器将仅支持它在数组中指定的格式。

浏览一系列可用的格式并选择最好的一种。如果你幸运的话,这就是你真正想要的,而且sws_scale函数不必进行像素格式转换。 (此外,如果您不请求缩放或裁剪图片,则 sws_scale 应该认识到转换是无用的。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在libavcodec中设置解码像素格式? 的相关文章

随机推荐