首页 > 解决方案 > 使用 libavcodec 编码 h264 时如何限制 CPU 使用率?

问题描述

我将原始图像编码为 h264 视频,并在调用之前设置我的编码器参数avocdec_open2()

void set_codec_params(AVFormatContext *&fctx, AVCodecContext *&codec_ctx,
                      double width, double height, int fps) {
  const AVRational dst_fps = {fps, 1};

  codec_ctx->codec_tag = 0;
  codec_ctx->bit_rate = target_bitrate;
  codec_ctx->thread_count = 1; // <----- does nothing
  codec_ctx->codec_id = AV_CODEC_ID_H264;
  codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
  codec_ctx->width = width;
  codec_ctx->height = height;
  codec_ctx->gop_size = 12;
  codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
  codec_ctx->framerate = dst_fps;
  codec_ctx->time_base = av_inv_q(dst_fps);
  if (fctx->oformat->flags & AVFMT_GLOBALHEADER) {
    codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  }
}

我这样设置配置文件参数

  AVDictionary *codec_options = nullptr;
  av_dict_set(&codec_options, "profile", "high", 0);
  av_dict_set(&codec_options, "preset", "ultrafast", 0);
  av_dict_set(&codec_options, "tune", "zerolatency", 0);

无论我做什么,在编码过程中所有内核都会被最大化,但我想将其限制为一定数量的线程。thread_count结构成员似乎被忽略了。

一般来说,可以采取哪些步骤来限制用于编码的线程数?某些设置是否与用​​户定义的线程数冲突?

标签: cffmpegencodinglibavlibavcodec

解决方案


我将假设您使用 x264 作为 h264 编码器。

AVCodecContex是所有现有编解码器的通用结构。因此,如果所选编码器不支持,设置某些属性将无效。然而,调整线程数是大多数编码器应该支持的设置。尽管如此,某些设置仍将被忽略或覆盖。在这种情况下,您需要使用以下方法设置它们AVDictionary

av_dict_set(&codec_options, "threads", "1", 0);

推荐阅读