From patchwork Fri Nov 3 09:57:16 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Thomas Siedel X-Patchwork-Id: 44490 Delivered-To: ffmpegpatchwork2@gmail.com Received: by 2002:a05:6a20:671c:b0:181:818d:5e7f with SMTP id q28csp429785pzh; Fri, 3 Nov 2023 02:58:02 -0700 (PDT) X-Google-Smtp-Source: AGHT+IHT7AMfplQMNqU/M0EQeCDalD8ucm4qnPudv2CFsqvtjrvG+hGl6uSQHlqVFZDE021v7otU X-Received: by 2002:a17:907:361:b0:9bf:2ddf:1bca with SMTP id rs1-20020a170907036100b009bf2ddf1bcamr5213659ejb.62.1699005482590; Fri, 03 Nov 2023 02:58:02 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1699005482; cv=none; d=google.com; s=arc-20160816; b=jY3US/jeM7aCOTnVhltIAh4CpfaCIfKJpCBqnGkh1ukzT+mFID4ezVwLQOTBQyT1Yb anXAHpYaBUSpPm6AL93x4h+gZtBuLCp8xCQEvMsFAVwwt0lGBNzaYYPEAOwB51bwS7M9 GyolIr10225bk9Rjp5sOS33LaHEPMgSzeQSa/t7aXIIKRCGIzXnSkdP7ooHUesI0gb2T 9djXsF7dArvYPiXT1c5pm5k5MoQ3dKKKKxNZLrNj4n1lP/FaMdrTHzsmqSze5PF1syqX zn0mMQP+0jCTK3Kjjl1l/Zn8W5rk3Av9GwkrQnVWqNH3oxl6o/5pMsP1rk5ED/6P8ik+ VVpg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=sender:errors-to:content-transfer-encoding:reply-to:list-subscribe :list-help:list-post:list-archive:list-unsubscribe:list-id :precedence:subject:mime-version:references:in-reply-to:message-id :date:to:from:dkim-signature:delivered-to; bh=sxvIyeZ0eUYF9yByq/EsPOnujwY+d4I+Al/ctbtD/Bk=; fh=YOA8vD9MJZuwZ71F/05pj6KdCjf6jQRmzLS+CATXUQk=; b=ZdlpM6uV/d9yh17FlA25YSj1QSLp6FCyE3WPK9NA+iZAx4wvvS1nZjt9MGHF5yBIbR LGk18e3SLiXe/DB3RpYfwcKFUfB+b42E0rTziZoDXexw9re1QDEIAGUoWsveSUY7JZbE l0mxfd+/0ntm8vPM0zpACWw0dfGb4B/BmzutsnwZs2J141nfxWhEKTWBf5h3CMggurlg ynQx5e0uXiwOolEhyfPzud0nz4QumJHHuk/stfuvgb0/UGtb8O1v9/DZE2IbbBDOOQ4Y ketxh240T5iYk4qRfwY4H1ER8jfK2pov66Y7+g7BEtgwrWUg3XzzSAS9hRi8Wu0M2oZZ UUQQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=neutral (body hash did not verify) header.i=@spin-digital-com.20230601.gappssmtp.com header.s=20230601 header.b=psr9whmj; spf=pass (google.com: domain of ffmpeg-devel-bounces@ffmpeg.org designates 79.124.17.100 as permitted sender) smtp.mailfrom=ffmpeg-devel-bounces@ffmpeg.org Return-Path: Received: from ffbox0-bg.mplayerhq.hu (ffbox0-bg.ffmpeg.org. [79.124.17.100]) by mx.google.com with ESMTP id dk4-20020a170907940400b0099db62aef8asi831737ejc.558.2023.11.03.02.58.02; Fri, 03 Nov 2023 02:58:02 -0700 (PDT) Received-SPF: pass (google.com: domain of ffmpeg-devel-bounces@ffmpeg.org designates 79.124.17.100 as permitted sender) client-ip=79.124.17.100; Authentication-Results: mx.google.com; dkim=neutral (body hash did not verify) header.i=@spin-digital-com.20230601.gappssmtp.com header.s=20230601 header.b=psr9whmj; spf=pass (google.com: domain of ffmpeg-devel-bounces@ffmpeg.org designates 79.124.17.100 as permitted sender) smtp.mailfrom=ffmpeg-devel-bounces@ffmpeg.org Received: from [127.0.1.1] (localhost [127.0.0.1]) by ffbox0-bg.mplayerhq.hu (Postfix) with ESMTP id 8458C68CD0C; Fri, 3 Nov 2023 11:57:49 +0200 (EET) X-Original-To: ffmpeg-devel@ffmpeg.org Delivered-To: ffmpeg-devel@ffmpeg.org Received: from mail-ed1-f47.google.com (mail-ed1-f47.google.com [209.85.208.47]) by ffbox0-bg.mplayerhq.hu (Postfix) with ESMTPS id 4020868CB7F for ; Fri, 3 Nov 2023 11:57:42 +0200 (EET) Received: by mail-ed1-f47.google.com with SMTP id 4fb4d7f45d1cf-53d8320f0easo2986707a12.3 for ; Fri, 03 Nov 2023 02:57:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=spin-digital-com.20230601.gappssmtp.com; s=20230601; t=1699005461; x=1699610261; darn=ffmpeg.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to; bh=Zq2J9IMw2i/B1GdHW/MZ/bHcw2teDueY/x6/63IbKxY=; b=psr9whmj6VKUwO/ycNEYyBdvZB/bJ9M3hV0G379hoJBYjjbh9eRheM9BViECNQ3b2X xnx5sEwkZ2dHmK9uZDGncGh47WeUShy3MBQs37KFXYcneT6GTCvDQ0mvr1eYJwdaxHUB LCucPaBCeJc5uHAieQIEbhyIgtrM5AfbOy8r3OzMNmVgU2TSSpMAVzsti614AOP6+9Yt YJMYvHdh68bY2/g3noTfBgbES/emLoTpOqVoIErjmwdbZSDHjiewRVQD6OpB9yuiVED9 8YLAksFQD505F9FXFJR4ZGPuwD2veTtjK8UjzkxQO3Q6DqxGOMXnQCOMV5pAs/5VaPu6 kcqA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1699005461; x=1699610261; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=Zq2J9IMw2i/B1GdHW/MZ/bHcw2teDueY/x6/63IbKxY=; b=wN7LIEBqUOpSChGQnQpWyxcRM3+j4slV1GaXRRV6C2ggOZu6kmArsIltXA2dVM8bFs 1nUVvF8UMr4M/IXz4T+fvlx/lMyW+IbXhf1xjZfryug5kjP/5IwilNYStIFW0PJhzzMS W6onJWcZnda2Ho/NtXpdNizf1sC2ERjSp22MVdoKgY48n2yAxBLo1uNNnuduGJwKDnJt XBeEqMz/JRWnEu9WjDDoF6c0HFGaDD9YpHGa1Bgdhi6vYswAGk6gPrbadxi5RapyCGkb FYjfX7SJNUCjk1yuyfbVGqHn/b6b8+xtnn7KucKJZOV7n2sguBL9vPlnhYEKStIy66Mc uXlQ== X-Gm-Message-State: AOJu0Yz9eeygZXDsnSaJasWkLUYZ9kFfbI7xkN7pB0DwCzwh8qmhNpcM riMJAsuanGoilOVvfb6z+V25MGqWx785IPzS6zY= X-Received: by 2002:a05:6402:1a39:b0:540:e598:a35f with SMTP id be25-20020a0564021a3900b00540e598a35fmr18195647edb.5.1699005460895; Fri, 03 Nov 2023 02:57:40 -0700 (PDT) Received: from thomas-win.localdomain ([213.138.44.237]) by smtp.gmail.com with ESMTPSA id s3-20020a50d483000000b00537963f692esm806214edi.0.2023.11.03.02.57.40 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 03 Nov 2023 02:57:40 -0700 (PDT) From: Thomas Siedel To: ffmpeg-devel@ffmpeg.org Date: Fri, 3 Nov 2023 10:57:16 +0100 Message-Id: <20231103095720.32426-2-thomas.ff@spin-digital.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20231103095720.32426-1-thomas.ff@spin-digital.com> References: <20231103095720.32426-1-thomas.ff@spin-digital.com> MIME-Version: 1.0 Subject: [FFmpeg-devel] [PATCH v1 1/5] avcodec: add external encoder libvvenc for H266/VVC X-BeenThere: ffmpeg-devel@ffmpeg.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: FFmpeg development discussions and patches List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: FFmpeg development discussions and patches Errors-To: ffmpeg-devel-bounces@ffmpeg.org Sender: "ffmpeg-devel" X-TUID: q55/g7z70+lO Add external encoder VVenC for H266/VVC encoding. Register new encoder libvvenc. Add libvvenc to wrap the vvenc interface. libvvenc implements encoder option: preset,qp,period,subjopt, vvenc-params,levelidc,tier. Enable encoder by adding --enable-libvvenc in configure step. Signed-off-by: Thomas Siedel --- configure | 5 + libavcodec/Makefile | 1 + libavcodec/allcodecs.c | 1 + libavcodec/libvvenc.c | 500 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 507 insertions(+) create mode 100644 libavcodec/libvvenc.c diff --git a/configure b/configure index 7afeebebcd..dab6427b41 100755 --- a/configure +++ b/configure @@ -286,6 +286,7 @@ External library support: --enable-libvorbis enable Vorbis en/decoding via libvorbis, native implementation exists [no] --enable-libvpx enable VP8 and VP9 de/encoding via libvpx [no] + --enable-libvvenc enable H.266/VVC encoding via vvenc [no] --enable-libwebp enable WebP encoding via libwebp [no] --enable-libx264 enable H.264 encoding via x264 [no] --enable-libx265 enable HEVC encoding via x265 [no] @@ -1900,6 +1901,7 @@ EXTERNAL_LIBRARY_LIST=" libvmaf libvorbis libvpx + libvvenc libwebp libxml2 libzimg @@ -3444,6 +3446,8 @@ libvpx_vp8_decoder_deps="libvpx" libvpx_vp8_encoder_deps="libvpx" libvpx_vp9_decoder_deps="libvpx" libvpx_vp9_encoder_deps="libvpx" +libvvenc_encoder_deps="libvvenc" +libvvenc_encoder_select="atsc_a53" libwebp_encoder_deps="libwebp" libwebp_anim_encoder_deps="libwebp" libx262_encoder_deps="libx262" @@ -6853,6 +6857,7 @@ enabled libvpx && { die "libvpx enabled but no supported decoders found" fi } +enabled libvvenc && require_pkg_config libvvenc "libvvenc >= 1.6.1" "vvenc/vvenc.h" vvenc_get_version enabled libwebp && { enabled libwebp_encoder && require_pkg_config libwebp "libwebp >= 0.2.0" webp/encode.h WebPGetEncoderVersion diff --git a/libavcodec/Makefile b/libavcodec/Makefile index ab7fba394a..b2bec7a2c2 100644 --- a/libavcodec/Makefile +++ b/libavcodec/Makefile @@ -1140,6 +1140,7 @@ OBJS-$(CONFIG_LIBVPX_VP8_DECODER) += libvpxdec.o OBJS-$(CONFIG_LIBVPX_VP8_ENCODER) += libvpxenc.o OBJS-$(CONFIG_LIBVPX_VP9_DECODER) += libvpxdec.o OBJS-$(CONFIG_LIBVPX_VP9_ENCODER) += libvpxenc.o +OBJS-$(CONFIG_LIBVVENC_ENCODER) += libvvenc.o OBJS-$(CONFIG_LIBWEBP_ENCODER) += libwebpenc_common.o libwebpenc.o OBJS-$(CONFIG_LIBWEBP_ANIM_ENCODER) += libwebpenc_common.o libwebpenc_animencoder.o OBJS-$(CONFIG_LIBX262_ENCODER) += libx264.o diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c index 5136a566f1..2e8cb1f8fd 100644 --- a/libavcodec/allcodecs.c +++ b/libavcodec/allcodecs.c @@ -805,6 +805,7 @@ extern const FFCodec ff_libvpx_vp8_encoder; extern const FFCodec ff_libvpx_vp8_decoder; extern FFCodec ff_libvpx_vp9_encoder; extern const FFCodec ff_libvpx_vp9_decoder; +extern const FFCodec ff_libvvenc_encoder; /* preferred over libwebp */ extern const FFCodec ff_libwebp_anim_encoder; extern const FFCodec ff_libwebp_encoder; diff --git a/libavcodec/libvvenc.c b/libavcodec/libvvenc.c new file mode 100644 index 0000000000..14cbecea4a --- /dev/null +++ b/libavcodec/libvvenc.c @@ -0,0 +1,500 @@ +/* + * H.266 encoding using the VVenC library + * + * Copyright (C) 2022, Thomas Siedel + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config_components.h" + +#include +#include +#include + +#include "avcodec.h" +#include "codec_internal.h" +#include "encode.h" +#include "internal.h" +#include "packet_internal.h" +#include "profiles.h" + +#include "libavutil/avutil.h" +#include "libavutil/pixdesc.h" +#include "libavutil/opt.h" +#include "libavutil/common.h" +#include "libavutil/imgutils.h" +#include "libavutil/frame.h" +#include "libavutil/log.h" + +typedef struct VVenCOptions { + int preset; // preset 0: faster 4: slower + int qp; // quantization parameter 0-63 + int subjectiveOptimization; // perceptually motivated QP adaptation, XPSNR based + int flag8bitCoding; // encode in 8bit instead of 10bit + int intraRefreshSec; // intra period/refresh in seconds + int levelIdc; // vvc level_idc + int tier; // vvc tier + AVDictionary *vvenc_opts; +} VVenCOptions; + +typedef struct VVenCContext { + AVClass *av_class; + VVenCOptions options; // encoder options + vvencEncoder *vvencEnc; + vvencAccessUnit *pAU; + bool encodeDone; +} VVenCContext; + + +static av_cold void ff_vvenc_log_callback(void *avctx, int level, + const char *fmt, va_list args) +{ + vfprintf(level == 1 ? stderr : stdout, fmt, args); +} + +static void ff_vvenc_internalLog(void *ctx, int level, const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + ff_vvenc_log_callback(ctx, level, fmt, args); + va_end(args); +} + +static av_cold int ff_vvenc_encode_init(AVCodecContext *avctx) +{ + int ret; + int framerate, qp, parse_ret; + VVenCContext *s; + vvenc_config params; + vvencPresetMode preset; + AVDictionaryEntry *en; + char statsfile[1024] = "vvenc-rcstats.json"; + + s = (VVenCContext *) avctx->priv_data; + qp = (vvencPresetMode) s->options.qp; + preset = (vvencPresetMode) s->options.preset; + + if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) { + av_log(avctx, AV_LOG_ERROR, + "ff_vvenc_encode_init::init() interlaced encoding not supported yet\n"); + return AVERROR_INVALIDDATA; + } + + vvenc_config_default(¶ms); + + // set desired encoding options + framerate = avctx->time_base.den / avctx->time_base.num; + vvenc_init_default(¶ms, avctx->width, avctx->height, framerate, + (qp >= 0) ? 0 : avctx->bit_rate, (qp < 0) ? 32 : qp, preset); + params.m_FrameRate = avctx->time_base.den; + params.m_FrameScale = avctx->time_base.num; + + params.m_verbosity = VVENC_VERBOSE; + if (av_log_get_level() >= AV_LOG_DEBUG) + params.m_verbosity = VVENC_DETAILS; + else if (av_log_get_level() >= AV_LOG_VERBOSE) + params.m_verbosity = VVENC_NOTICE; // output per picture info + else if (av_log_get_level() >= AV_LOG_INFO) + params.m_verbosity = VVENC_WARNING; // ffmpeg default ffmpeg loglevel + else + params.m_verbosity = VVENC_SILENT; + +FF_DISABLE_DEPRECATION_WARNINGS + +#if FF_API_TICKS_PER_FRAME + if (avctx->ticks_per_frame == 1) { +#endif + params.m_TicksPerSecond = -1; // auto mode for ticks per frame = 1 +#if FF_API_TICKS_PER_FRAME + } else { + params.m_TicksPerSecond = + ceil((avctx->time_base.den / (double) avctx->time_base.num) * + (double) avctx->ticks_per_frame); + } +#endif +FF_ENABLE_DEPRECATION_WARNINGS + + if (avctx->thread_count > 0) + params.m_numThreads = avctx->thread_count; + + // GOP settings (IDR/CRA) + if (avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) + params.m_DecodingRefreshType = VVENC_DRT_IDR; + + if (avctx->gop_size == 1) { + params.m_GOPSize = 1; + params.m_IntraPeriod = 1; + } else { + params.m_IntraPeriodSec = s->options.intraRefreshSec; + } + + params.m_usePerceptQPA = s->options.subjectiveOptimization; + params.m_level = (vvencLevel) s->options.levelIdc; + params.m_levelTier = (vvencTier) s->options.tier; + + params.m_AccessUnitDelimiter = true; + + params.m_internChromaFormat = VVENC_CHROMA_420; + params.m_inputBitDepth[0] = 10; + + if ( avctx->pix_fmt != AV_PIX_FMT_YUV420P10LE ){ + av_log(avctx, AV_LOG_ERROR, + "unsupported pixel format %s, currently only support for yuv420p10le\n", + av_get_pix_fmt_name(avctx->pix_fmt)); + return AVERROR(EINVAL); + } + + if ( s->options.flag8bitCoding ) { +#if VVENC_VERSION_MAJOR > 1 || (VVENC_VERSION_MAJOR == 1 && VVENC_VERSION_MINOR > 9) || (VVENC_VERSION_MAJOR == 1 && VVENC_VERSION_MINOR >= 9 && VVENC_VERSION_PATCH >= 1) + params.m_internalBitDepth[0] = 8; +#else + av_log(avctx, AV_LOG_ERROR, + "unsupported 8bit coding mode. 8bit coding needs at least vvenc version >= 1.9.1\n", + av_get_pix_fmt_name(avctx->pix_fmt)); + return AVERROR(EINVAL); +#endif + } + + if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED) + params.m_colourPrimaries = (int) avctx->color_primaries; + if (avctx->colorspace != AVCOL_SPC_UNSPECIFIED) + params.m_matrixCoefficients = (int) avctx->colorspace; + if (avctx->color_trc != AVCOL_TRC_UNSPECIFIED) { + params.m_transferCharacteristics = (int) avctx->color_trc; + + if (avctx->color_trc == AVCOL_TRC_SMPTE2084) + params.m_HdrMode = (avctx->color_primaries == AVCOL_PRI_BT2020) ? + VVENC_HDR_PQ_BT2020 : VVENC_HDR_PQ; + else if (avctx->color_trc == AVCOL_TRC_BT2020_10 + || avctx->color_trc == AVCOL_TRC_ARIB_STD_B67) + params.m_HdrMode = (avctx->color_trc == AVCOL_TRC_BT2020_10 || + avctx->color_primaries == AVCOL_PRI_BT2020 || + avctx->colorspace == AVCOL_SPC_BT2020_NCL || + avctx->colorspace == AVCOL_SPC_BT2020_CL) ? + VVENC_HDR_HLG_BT2020 : VVENC_HDR_HLG; + } + + if (params.m_HdrMode == VVENC_HDR_OFF + && (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED + || avctx->colorspace != AVCOL_SPC_UNSPECIFIED)) { + params.m_vuiParametersPresent = 1; + params.m_colourDescriptionPresent = true; + } + + params.m_RCNumPasses = 1; + en = NULL; + while ((en = av_dict_get(s->options.vvenc_opts, "", en, + AV_DICT_IGNORE_SUFFIX))) { + av_log(avctx, AV_LOG_DEBUG, "vvenc_set_param: '%s:%s'\n", en->key, + en->value); + parse_ret = vvenc_set_param(¶ms, en->key, en->value); + switch (parse_ret) { + case VVENC_PARAM_BAD_NAME: + av_log(avctx, AV_LOG_WARNING, "Unknown vvenc option: %s.\n", + en->key); + break; + case VVENC_PARAM_BAD_VALUE: + av_log(avctx, AV_LOG_WARNING, + "Invalid vvenc value for %s: %s.\n", en->key, en->value); + break; + default: + break; + } + + if (memcmp(en->key, "rcstatsfile", 11) == 0 || + memcmp(en->key, "RCStatsFile", 11) == 0) { + strncpy(statsfile, en->value, sizeof(statsfile) - 1); + statsfile[sizeof(statsfile) - 1] = '\0'; + } + } + + if (params.m_RCPass != -1 && params.m_RCNumPasses == 1) + params.m_RCNumPasses = 2; // enable 2pass mode + +#if VVENC_VERSION_MAJOR > 1 || (VVENC_VERSION_MAJOR == 1 && VVENC_VERSION_MINOR > 8) + if(avctx->rc_max_rate) { + if(!avctx->bit_rate) { + av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n"); + return AVERROR(EINVAL); + } + else + params.m_RCMaxBitrate = avctx->rc_max_rate; + } +#endif + + s->vvencEnc = vvenc_encoder_create(); + if (NULL == s->vvencEnc) { + av_log(avctx, AV_LOG_ERROR, "cannot create vvc encoder (vvenc)\n"); + return AVERROR(ENOMEM); + } + + vvenc_set_msg_callback(¶ms, s->vvencEnc, ff_vvenc_log_callback); + ret = vvenc_encoder_open(s->vvencEnc, ¶ms); + if (0 != ret) { + av_log(avctx, AV_LOG_ERROR, "cannot open vvc encoder (vvenc): %s\n", + vvenc_get_last_error(s->vvencEnc)); + vvenc_encoder_close(s->vvencEnc); + return AVERROR(EINVAL); + } + + vvenc_get_config(s->vvencEnc, ¶ms); // get the adapted config + + if (params.m_verbosity >= VVENC_INFO + && av_log_get_level() <= AV_LOG_INFO) { + ff_vvenc_internalLog(avctx, params.m_verbosity, "vvenc version: %s\n", + vvenc_get_version()); + ff_vvenc_internalLog(avctx, params.m_verbosity, "%s\n", + vvenc_get_config_as_string(¶ms, + params.m_verbosity)); + } else { + vvencMsgLevel loglvl = VVENC_INFO; + if (av_log_get_level() >= AV_LOG_DEBUG) + loglvl = VVENC_DETAILS; + else if (av_log_get_level() >= AV_LOG_VERBOSE) + loglvl = VVENC_VERBOSE; + + av_log(avctx, av_log_get_level(), "vvenc version: %s\n", + vvenc_get_version()); + av_log(avctx, av_log_get_level(), "%s\n", + vvenc_get_config_as_string(¶ms, loglvl )); + } + + if (params.m_RCNumPasses == 2) { + ret = vvenc_init_pass(s->vvencEnc, params.m_RCPass - 1, &statsfile[0]); + if (0 != ret) { + av_log(avctx, AV_LOG_ERROR, + "cannot init pass %d for vvc encoder (vvenc): %s\n", + params.m_RCPass, vvenc_get_last_error(s->vvencEnc)); + vvenc_encoder_close(s->vvencEnc); + return AVERROR(EINVAL); + } + } + + s->pAU = vvenc_accessUnit_alloc(); + vvenc_accessUnit_alloc_payload(s->pAU, avctx->width * avctx->height); + + if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) { + ret = vvenc_get_headers(s->vvencEnc, s->pAU); + if (0 != ret) { + av_log(avctx, AV_LOG_ERROR, + "cannot get headers (SPS,PPS) from vvc encoder(vvenc): %s\n", + vvenc_get_last_error(s->vvencEnc)); + vvenc_encoder_close(s->vvencEnc); + return AVERROR(EINVAL); + } + + if (s->pAU->payloadUsedSize <= 0) { + vvenc_encoder_close(s->vvencEnc); + return AVERROR_INVALIDDATA; + } + + avctx->extradata_size = s->pAU->payloadUsedSize; + avctx->extradata = + av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); + if (!avctx->extradata) { + av_log(avctx, AV_LOG_ERROR, + "Cannot allocate VVC header of size %d.\n", + avctx->extradata_size); + vvenc_encoder_close(s->vvencEnc); + return AVERROR(ENOMEM); + } + + memcpy(avctx->extradata, s->pAU->payload, avctx->extradata_size); + memset(avctx->extradata + avctx->extradata_size, 0, + AV_INPUT_BUFFER_PADDING_SIZE); + } + s->encodeDone = false; + return 0; +} + +static av_cold int ff_vvenc_encode_close(AVCodecContext * avctx) +{ + VVenCContext *s = (VVenCContext *) avctx->priv_data; + if (s->vvencEnc) { + if (av_log_get_level() >= AV_LOG_VERBOSE) + vvenc_print_summary(s->vvencEnc); + + if (0 != vvenc_encoder_close(s->vvencEnc)) { + av_log(avctx, AV_LOG_ERROR, "cannot close vvenc\n"); + return -1; + } + } + + vvenc_accessUnit_free(s->pAU, true); + + return 0; +} + +static av_cold int ff_vvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt, + const AVFrame *frame, int *got_packet) +{ + VVenCContext *s = (VVenCContext *) avctx->priv_data; + vvencYUVBuffer *pyuvbuf; + vvencYUVBuffer yuvbuf; + int pict_type; + int ret; + + pyuvbuf = NULL; + if (frame) { + if (avctx->pix_fmt == AV_PIX_FMT_YUV420P10LE) { + vvenc_YUVBuffer_default(&yuvbuf); + yuvbuf.planes[0].ptr = (int16_t *) frame->data[0]; + yuvbuf.planes[1].ptr = (int16_t *) frame->data[1]; + yuvbuf.planes[2].ptr = (int16_t *) frame->data[2]; + + yuvbuf.planes[0].width = frame->width; + yuvbuf.planes[0].height = frame->height; + yuvbuf.planes[0].stride = frame->linesize[0] >> 1; // stride is used in samples (16bit) in vvenc, ffmpeg uses stride in bytes + + yuvbuf.planes[1].width = frame->width >> 1; + yuvbuf.planes[1].height = frame->height >> 1; + yuvbuf.planes[1].stride = frame->linesize[1] >> 1; + + yuvbuf.planes[2].width = frame->width >> 1; + yuvbuf.planes[2].height = frame->height >> 1; + yuvbuf.planes[2].stride = frame->linesize[2] >> 1; + + yuvbuf.cts = frame->pts; + yuvbuf.ctsValid = true; + pyuvbuf = &yuvbuf; + } else { + av_log(avctx, AV_LOG_ERROR, + "unsupported input colorspace! input must be yuv420p10le"); + return AVERROR(EINVAL); + } + } + + if (!s->encodeDone) { + ret = vvenc_encode(s->vvencEnc, pyuvbuf, s->pAU, &s->encodeDone); + if (ret != 0) { + av_log(avctx, AV_LOG_ERROR, "error in vvenc::encode - ret:%d\n", + ret); + return AVERROR(EINVAL); + } + } else { + *got_packet = 0; + return 0; + } + + if (s->pAU->payloadUsedSize > 0) { + ret = ff_get_encode_buffer(avctx, pkt, s->pAU->payloadUsedSize, 0); + if (ret < 0) { + av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n"); + return ret; + } + + memcpy(pkt->data, s->pAU->payload, s->pAU->payloadUsedSize); + + if (s->pAU->ctsValid) + pkt->pts = s->pAU->cts; + if (s->pAU->dtsValid) + pkt->dts = s->pAU->dts; + pkt->flags |= AV_PKT_FLAG_KEY * s->pAU->rap; + + switch (s->pAU->sliceType) { + case VVENC_I_SLICE: + pict_type = AV_PICTURE_TYPE_I; + break; + case VVENC_P_SLICE: + pict_type = AV_PICTURE_TYPE_P; + break; + case VVENC_B_SLICE: + pict_type = AV_PICTURE_TYPE_B; + break; + default: + av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered.\n"); + return AVERROR_EXTERNAL; + } + + ff_side_data_set_encoder_stats(pkt, 0, NULL, 0, pict_type); + + *got_packet = 1; + + return 0; + } else { + *got_packet = 0; + return 0; + } + + return 0; +} + +static const enum AVPixelFormat pix_fmts_vvenc[] = { + AV_PIX_FMT_YUV420P10LE, + AV_PIX_FMT_NONE +}; + +#define OFFSET(x) offsetof(VVenCContext, x) +#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM +static const AVOption libvvenc_options[] = { + {"preset", "set encoding preset(0: faster - 4: slower", OFFSET( options.preset), AV_OPT_TYPE_INT, {.i64 = 2} , 0 , 4 , VE, "preset"}, + { "faster", "0", 0, AV_OPT_TYPE_CONST, {.i64 = VVENC_FASTER}, INT_MIN, INT_MAX, VE, "preset" }, + { "fast", "1", 0, AV_OPT_TYPE_CONST, {.i64 = VVENC_FAST}, INT_MIN, INT_MAX, VE, "preset" }, + { "medium", "2", 0, AV_OPT_TYPE_CONST, {.i64 = VVENC_MEDIUM}, INT_MIN, INT_MAX, VE, "preset" }, + { "slow", "3", 0, AV_OPT_TYPE_CONST, {.i64 = VVENC_SLOW}, INT_MIN, INT_MAX, VE, "preset" }, + { "slower", "4", 0, AV_OPT_TYPE_CONST, {.i64 = VVENC_SLOWER}, INT_MIN, INT_MAX, VE, "preset" }, + { "qp" , "set quantization", OFFSET(options.qp), AV_OPT_TYPE_INT, {.i64 = -1}, -1 , 63 ,VE, "qp_mode" }, + { "period" , "set (intra) refresh period in seconds", OFFSET(options.intraRefreshSec), AV_OPT_TYPE_INT, {.i64 = 1}, 1 , INT_MAX ,VE,"irefreshsec" }, + { "subjopt", "set subjective (perceptually motivated) optimization", OFFSET(options.subjectiveOptimization), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0 , 1, VE}, + { "bitdepth8", "set 8bit coding mode", OFFSET(options.flag8bitCoding), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0 , 1, VE}, + { "vvenc-params", "set the vvenc configuration using a :-separated list of key=value parameters", OFFSET(options.vvenc_opts), AV_OPT_TYPE_DICT, { 0 }, 0, 0, VE }, + { "levelidc", "vvc level_idc", OFFSET( options.levelIdc), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 105, VE, "levelidc"}, + { "0", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "1", "1" , 0, AV_OPT_TYPE_CONST, {.i64 = 16}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "2", "2" , 0, AV_OPT_TYPE_CONST, {.i64 = 32}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "2.1", "2.1" , 0, AV_OPT_TYPE_CONST, {.i64 = 35}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "3", "3" , 0, AV_OPT_TYPE_CONST, {.i64 = 48}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "3.1", "3.1" , 0, AV_OPT_TYPE_CONST, {.i64 = 51}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "4", "4" , 0, AV_OPT_TYPE_CONST, {.i64 = 64}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "4.1", "4.1" , 0, AV_OPT_TYPE_CONST, {.i64 = 67}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "5", "5" , 0, AV_OPT_TYPE_CONST, {.i64 = 80}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "5.1", "5.1" , 0, AV_OPT_TYPE_CONST, {.i64 = 83}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "5.2", "5.2" , 0, AV_OPT_TYPE_CONST, {.i64 = 86}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "6", "6" , 0, AV_OPT_TYPE_CONST, {.i64 = 96}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "6.1", "6.1" , 0, AV_OPT_TYPE_CONST, {.i64 = 99}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "6.2", "6.2" , 0, AV_OPT_TYPE_CONST, {.i64 = 102}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "6.3", "6.3" , 0, AV_OPT_TYPE_CONST, {.i64 = 105}, INT_MIN, INT_MAX, VE, "levelidc"}, + { "tier", "set vvc tier", OFFSET( options.tier), AV_OPT_TYPE_INT, {.i64 = 0}, 0 , 1 , VE, "tier"}, + { "main", "main", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, VE, "tier"}, + { "high", "high", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, INT_MIN, INT_MAX, VE, "tier"}, + {NULL} +}; + +static const AVClass class_libvvenc = { + .class_name = "libvvenc-vvc encoder", + .item_name = av_default_item_name, + .option = libvvenc_options, + .version = LIBAVUTIL_VERSION_INT, +}; + +FFCodec ff_libvvenc_encoder = { + .p.name = "libvvenc", + CODEC_LONG_NAME("H.266 / VVC Encoder VVenC"), + .p.type = AVMEDIA_TYPE_VIDEO, + .p.id = AV_CODEC_ID_VVC, + .p.capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_OTHER_THREADS, + .p.profiles = NULL_IF_CONFIG_SMALL(ff_vvc_profiles), + .p.priv_class = &class_libvvenc, + .p.wrapper_name = "libvvenc", + .priv_data_size = sizeof(VVenCContext), + .p.pix_fmts = pix_fmts_vvenc, + .init = ff_vvenc_encode_init, + FF_CODEC_ENCODE_CB(ff_vvenc_encode_frame), + .close = ff_vvenc_encode_close, + .caps_internal = FF_CODEC_CAP_AUTO_THREADS, +};