25#include <EbSvtAv1ErrorCodes.h>
26#include <EbSvtAv1Enc.h>
27#include <EbSvtAv1Metadata.h>
47typedef enum eos_status {
85 { EB_ErrorNone, 0,
"success" },
86 { EB_ErrorInsufficientResources,
AVERROR(ENOMEM),
"insufficient resources" },
87 { EB_ErrorUndefined,
AVERROR(EINVAL),
"undefined error" },
88 { EB_ErrorInvalidComponent,
AVERROR(EINVAL),
"invalid component" },
89 { EB_ErrorBadParameter,
AVERROR(EINVAL),
"bad parameter" },
90 { EB_ErrorDestroyThreadFailed,
AVERROR_EXTERNAL,
"failed to destroy thread" },
91 { EB_ErrorSemaphoreUnresponsive,
AVERROR_EXTERNAL,
"semaphore unresponsive" },
92 { EB_ErrorDestroySemaphoreFailed,
AVERROR_EXTERNAL,
"failed to destroy semaphore"},
96 { EB_NoErrorEmptyQueue,
AVERROR(EAGAIN),
"empty queue" },
110 *
desc =
"unknown error";
115 const char *error_string)
127 const size_t luma_size = config->source_width * config->source_height *
128 (config->encoder_bit_depth > 8 ? 2 : 1);
130 EbSvtIOFormat *in_data;
132 svt_enc->
raw_size = luma_size * 3 / 2;
140 if (!svt_enc->
in_buf->p_buffer)
153 const struct EbSvtAv1ChromaPoints *
const points[] = {
159 for (
int i = 0;
i < 3;
i++) {
160 const struct EbSvtAv1ChromaPoints *
dst = points[
i];
188 EbSvtAv1EncConfiguration *param)
219#if !SVT_AV1_CHECK_VERSION(3, 0, 0)
229 "Input dimensions %dx%d are smaller than the minimum 64x64 "
230 "supported by SVT-AV1 < 3.0.0.\n",
238 param->enc_mode = svt_enc->
enc_mode;
241 param->target_bit_rate = avctx->
bit_rate;
243 param->rate_control_mode = 1;
245 param->rate_control_mode = 2;
247 param->max_qp_allowed = avctx->
qmax;
248 param->min_qp_allowed = avctx->
qmin;
252 param->maximum_buffer_size_ms =
256 if (svt_enc->
crf > 0) {
257 param->qp = svt_enc->
crf;
258 param->rate_control_mode = 0;
259 }
else if (svt_enc->
qp > 0) {
260 param->qp = svt_enc->
qp;
261 param->rate_control_mode = 0;
262#if SVT_AV1_CHECK_VERSION(4, 0, 0)
265 param->enable_adaptive_quantization = 0;
270 param->color_primaries = (
enum EbColorPrimaries)avctx->
color_primaries;
273 param->transfer_characteristics = (
enum EbTransferCharacteristics)avctx->
color_trc;
280#if SVT_AV1_CHECK_VERSION(1, 0, 0)
287 param->chroma_sample_position = EB_CSP_VERTICAL;
290 param->chroma_sample_position = EB_CSP_COLOCATED;
297 "Specified chroma sample location %s is unsupported "
298 "on the AV1 bit stream level. Usage of a container that "
299 "allows passing this information - such as Matroska - "
308 param->profile = avctx->
profile;
311 param->level = avctx->
level;
319 param->intra_period_length = avctx->
gop_size - 1;
321#if SVT_AV1_CHECK_VERSION(1, 1, 0)
331 param->force_key_frames = 1;
347#if SVT_AV1_CHECK_VERSION(0, 9, 1)
349 EbErrorType ret = svt_av1_enc_parse_parameter(param, en->key, en->value);
350 if (ret != EB_ErrorNone) {
352 av_log(avctx,
level,
"Error parsing option %s: %s.\n", en->key, en->value);
360 av_log(avctx,
level,
"svt-params needs libavcodec to be compiled with SVT-AV1 "
361 "headers >= 0.9.1.\n");
393 param->rc_stats_buffer.buf = svt_enc->
stats_buf;
394 param->rc_stats_buffer.sz = stats_sz;
403 param->source_width = avctx->
width;
404 param->source_height = avctx->
height;
406 param->encoder_bit_depth =
desc->comp[0].depth;
408 if (
desc->log2_chroma_w == 1 &&
desc->log2_chroma_h == 1)
409 param->encoder_color_format = EB_YUV420;
410 else if (
desc->log2_chroma_w == 1 &&
desc->log2_chroma_h == 0)
411 param->encoder_color_format = EB_YUV422;
412 else if (!
desc->log2_chroma_w && !
desc->log2_chroma_h)
413 param->encoder_color_format = EB_YUV444;
419 if ((param->encoder_color_format == EB_YUV422 || param->encoder_bit_depth > 10)
423 }
else if (param->encoder_color_format == EB_YUV444 && param->profile !=
AV_PROFILE_AV1_HIGH) {
428 avctx->
bit_rate = param->rate_control_mode > 0 ?
429 param->target_bit_rate : 0;
448 EbBufferHeaderType *header_ptr)
450 EbSvtIOFormat *in_data = (EbSvtIOFormat *)header_ptr->p_buffer;
451 ptrdiff_t linesizes[4];
453 int bytes_shift = param->encoder_bit_depth > 8 ? 1 : 0;
456 for (
int i = 0;
i < 4;
i++)
457 linesizes[
i] =
frame->linesize[
i];
465 for (
int i = 0;
i < 4;
i++) {
471 in_data->luma =
frame->data[0];
472 in_data->cb =
frame->data[1];
473 in_data->cr =
frame->data[2];
480 svt_metadata_array_free(&header_ptr->metadata);
493#if SVT_AV1_CHECK_VERSION(3, 0, 0)
498 if (svt_ret != EB_ErrorNone) {
499 return svt_print_error(avctx, svt_ret,
"Error initializing encoder handle");
509 if (svt_ret != EB_ErrorNone) {
510 return svt_print_error(avctx, svt_ret,
"Error setting encoder parameters");
513 svt_ret = svt_av1_enc_init(svt_enc->
svt_handle);
514 if (svt_ret != EB_ErrorNone) {
524 EbBufferHeaderType *headerPtr =
NULL;
526 svt_ret = svt_av1_enc_stream_header(svt_enc->
svt_handle, &headerPtr);
527 if (svt_ret != EB_ErrorNone) {
528 return svt_print_error(avctx, svt_ret,
"Error building stream header");
535 "Cannot allocate AV1 header of size %d.\n", avctx->
extradata_size);
541 svt_ret = svt_av1_enc_stream_header_release(headerPtr);
542 if (svt_ret != EB_ErrorNone) {
557 EbBufferHeaderType *headerPtr = svt_enc->
in_buf;
563 EbBufferHeaderType headerPtrLast;
568 memset(&headerPtrLast, 0,
sizeof(headerPtrLast));
569 headerPtrLast.pic_type = EB_AV1_INVALID_PICTURE;
570 headerPtrLast.flags = EB_BUFFERFLAG_EOS;
572 svt_av1_enc_send_picture(svt_enc->
svt_handle, &headerPtrLast);
581 headerPtr->flags = 0;
582 headerPtr->p_app_private =
NULL;
583 headerPtr->pts =
frame->pts;
585 switch (
frame->pict_type) {
587 headerPtr->pic_type = EB_AV1_KEY_PICTURE;
591 headerPtr->pic_type = EB_AV1_INVALID_PICTURE;
596 headerPtr->pic_type = EB_AV1_KEY_PICTURE;
606 ret = svt_add_metadata(headerPtr, EB_AV1_METADATA_TYPE_ITUT_T35, t35,
size);
612 "without AV_FRAME_DATA_DOVI_METADATA\n");
617 svt_ret = svt_av1_enc_send_picture(svt_enc->
svt_handle, headerPtr);
618 if (svt_ret != EB_ErrorNone)
619 return svt_print_error(avctx, svt_ret,
"Error sending a frame to encoder");
627 const int max_frames = 8;
630 if (filled_len > svt_enc->
raw_size * max_frames) {
651 EbBufferHeaderType *headerPtr;
672 if (svt_ret == EB_NoErrorEmptyQueue)
674 else if (svt_ret != EB_ErrorNone)
675 return svt_print_error(avctx, svt_ret,
"Error getting an output packet from encoder");
677#if SVT_AV1_CHECK_VERSION(2, 0, 0)
678 if (headerPtr->flags & EB_BUFFERFLAG_EOS) {
680 SvtAv1FixedBuf first_pass_stats = { 0 };
681 EbErrorType svt_ret_stats;
684 svt_ret_stats = svt_av1_enc_get_stream_info(
686 SVT_AV1_STREAM_INFO_FIRST_PASS_STATS_OUT,
689 if (svt_ret_stats != EB_ErrorNone) {
691 "Failed to get first pass stats\n");
692 svt_av1_enc_release_out_buffer(&headerPtr);
696 if (first_pass_stats.sz > 0 && first_pass_stats.buf) {
701 "Failed to allocate stats output buffer\n");
702 svt_av1_enc_release_out_buffer(&headerPtr);
707 first_pass_stats.buf, first_pass_stats.sz);
710 "First pass stats: %"PRIu64
" bytes, encoded to %d bytes\n",
711 first_pass_stats.sz, b64_size);
716 svt_av1_enc_release_out_buffer(&headerPtr);
724 svt_av1_enc_release_out_buffer(&headerPtr);
730 memcpy(
pkt->data, headerPtr->p_buffer, headerPtr->n_filled_len);
733 pkt->size = headerPtr->n_filled_len;
734 pkt->pts = headerPtr->pts;
735 pkt->dts = headerPtr->dts;
738 switch (headerPtr->pic_type) {
739 case EB_AV1_KEY_PICTURE:
742 case EB_AV1_INTRA_ONLY_PICTURE:
745 case EB_AV1_INVALID_PICTURE:
753 if (headerPtr->pic_type == EB_AV1_NON_REF_PICTURE)
756#if !(SVT_AV1_CHECK_VERSION(2, 0, 0))
757 if (headerPtr->flags & EB_BUFFERFLAG_EOS)
763 svt_av1_enc_release_out_buffer(&headerPtr);
774 svt_av1_enc_deinit_handle(svt_enc->
svt_handle);
778 svt_metadata_array_free(&svt_enc->
in_buf->metadata);
790#define OFFSET(x) offsetof(SvtContext, x)
791#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
793 {
"preset",
"Encoding preset",
798#define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
799 { .i64 = value }, 0, 0, VE, .unit = "avctx.level"
800 {
LEVEL(
"2.0", 20) },
801 {
LEVEL(
"2.1", 21) },
802 {
LEVEL(
"2.2", 22) },
803 {
LEVEL(
"2.3", 23) },
804 {
LEVEL(
"3.0", 30) },
805 {
LEVEL(
"3.1", 31) },
806 {
LEVEL(
"3.2", 32) },
807 {
LEVEL(
"3.3", 33) },
808 {
LEVEL(
"4.0", 40) },
809 {
LEVEL(
"4.1", 41) },
810 {
LEVEL(
"4.2", 42) },
811 {
LEVEL(
"4.3", 43) },
812 {
LEVEL(
"5.0", 50) },
813 {
LEVEL(
"5.1", 51) },
814 {
LEVEL(
"5.2", 52) },
815 {
LEVEL(
"5.3", 53) },
816 {
LEVEL(
"6.0", 60) },
817 {
LEVEL(
"6.1", 61) },
818 {
LEVEL(
"6.2", 62) },
819 {
LEVEL(
"6.3", 63) },
820 {
LEVEL(
"7.0", 70) },
821 {
LEVEL(
"7.1", 71) },
822 {
LEVEL(
"7.2", 72) },
823 {
LEVEL(
"7.3", 73) },
826 {
"crf",
"Constant Rate Factor value",
OFFSET(crf),
828 {
"qp",
"Initial Quantizer level value",
OFFSET(qp),
830 {
"svtav1-params",
"Set the SVT-AV1 configuration using a :-separated list of key=value parameters",
OFFSET(svtav1_opts),
AV_OPT_TYPE_DICT, { 0 }, 0, 0,
VE },
847 {
"flags",
"+cgop" },
855 .p.name =
"libsvtav1",
868 .p.priv_class = &
class,
870 .p.wrapper_name =
"libsvtav1",
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
const FFCodec ff_libsvtav1_encoder
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Libavcodec external API header.
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#define i(width, name, range_min, range_max)
#define CODEC_PIXFMTS(...)
#define FF_CODEC_CAP_NOT_INIT_THREADSAFE
The codec is not known to be init-threadsafe (i.e.
#define FF_CODEC_RECEIVE_PACKET_CB(func)
#define CODEC_LONG_NAME(str)
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
#define FF_CODEC_CAP_AUTO_THREADS
Codec handles avctx->thread_count == 0 (auto) internally.
common internal and external API header
#define AV_CEIL_RSHIFT(a, b)
#define AV_PROFILE_AV1_HIGH
#define AV_PROFILE_UNKNOWN
#define AV_EF_EXPLODE
abort decoding on minor error detection
#define AV_PROFILE_AV1_PROFESSIONAL
void ff_dovi_ctx_unref(DOVIContext *s)
Completely reset a DOVIContext, preserving only logctx.
#define FF_DOVI_AUTOMATIC
Enable tri-state.
int ff_dovi_rpu_generate(DOVIContext *s, const AVDOVIMetadata *metadata, int flags, uint8_t **out_rpu, int *out_size)
Synthesize a Dolby Vision RPU reflecting the current state.
@ FF_DOVI_WRAP_T35
wrap inside T.35+EMDF
int ff_dovi_configure(DOVIContext *s, AVCodecContext *avctx)
Variant of ff_dovi_configure_from_codedpar which infers the codec parameters from an AVCodecContext.
int ff_encode_get_frame(AVCodecContext *avctx, AVFrame *frame)
Called by encoders to get the next frame for encoding.
AVCPBProperties * ff_encode_add_cpb_side_data(AVCodecContext *avctx)
Add a CPB properties side data to an encoding context.
int ff_encode_add_stats_side_data(AVPacket *pkt, int quality, const int64_t error[], int error_count, enum AVPictureType pict_type)
reference-counted frame API
static const uint8_t frame_size[4]
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
@ AV_OPT_TYPE_INT
Underlying C type is int.
@ AV_OPT_TYPE_DICT
Underlying C type is AVDictionary*.
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
#define AV_CODEC_CAP_OTHER_THREADS
Codec supports multithreading through a method other than slice- or frame-level multithreading.
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
#define AV_CODEC_FLAG_CLOSED_GOP
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
#define AV_PKT_FLAG_DISPOSABLE
Flag is used to indicate packets that contain frames that can be discarded by the decoder.
char * av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size)
Encode data to base64 and null-terminate.
#define AV_BASE64_DECODE_SIZE(x)
Calculate the output size in bytes needed to decode a base64 string with length x to a data buffer.
#define AV_BASE64_SIZE(x)
Calculate the output size needed to base64-encode x bytes to a null-terminated string.
int av_base64_decode(uint8_t *out, const char *in_str, int out_size)
Decode a base64-encoded string.
void av_buffer_pool_uninit(AVBufferPool **ppool)
Mark the pool as being available for freeing.
AVBufferPool * av_buffer_pool_init(size_t size, AVBufferRef *(*alloc)(size_t size))
Allocate and initialize a buffer pool.
AVBufferRef * av_buffer_pool_get(AVBufferPool *pool)
Allocate a new AVBuffer, reusing an old buffer from the pool when available.
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
#define AVERROR_EXTERNAL
Generic error in an external library.
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
#define AVERROR_EOF
End of file.
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
static const AVFrameSideData * av_frame_side_data_get(AVFrameSideData *const *sd, const int nb_sd, enum AVFrameSideDataType type)
Wrapper around av_frame_side_data_get_c() to workaround the limitation that for any type T the conver...
@ AV_FRAME_DATA_DOVI_METADATA
Parsed Dolby Vision metadata, suitable for passing to a software implementation.
@ AV_FRAME_DATA_CONTENT_LIGHT_LEVEL
Content light level (based on CTA-861.3).
@ AV_FRAME_DATA_MASTERING_DISPLAY_METADATA
Mastering display metadata associated with a video frame.
#define AV_LOG_WARNING
Something somehow does not look correct.
#define AV_LOG_VERBOSE
Detailed information.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
const char * av_default_item_name(void *ptr)
Return the context name.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
int av_image_fill_plane_sizes(size_t sizes[4], enum AVPixelFormat pix_fmt, int height, const ptrdiff_t linesizes[4])
Fill plane sizes for an image with pixel format pix_fmt and height height.
@ AV_PICTURE_TYPE_I
Intra.
@ AV_PICTURE_TYPE_NONE
Undefined.
@ AV_PICTURE_TYPE_P
Predicted.
#define LIBAVUTIL_VERSION_INT
static const int sizes[][2]
Macro definitions for various function/variable attributes.
static const FFCodecDefault eb_enc_defaults[]
static int config_enc_params(EbSvtAv1EncConfiguration *param, AVCodecContext *avctx)
static int eb_send_frame(AVCodecContext *avctx, const AVFrame *frame)
static int svt_print_error(void *log_ctx, EbErrorType err, const char *error_string)
static int alloc_buffer(EbSvtAv1EncConfiguration *config, SvtContext *svt_enc)
static AVBufferRef * get_output_ref(AVCodecContext *avctx, SvtContext *svt_enc, int filled_len)
static void handle_mdcv(struct EbSvtAv1MasteringDisplayInfo *dst, const AVMasteringDisplayMetadata *mdcv)
static int svt_map_error(EbErrorType eb_err, const char **desc)
static int eb_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
static av_cold int eb_enc_init(AVCodecContext *avctx)
#define LEVEL(name, value)
static void handle_side_data(AVCodecContext *avctx, EbSvtAv1EncConfiguration *param)
static int read_in_data(EbSvtAv1EncConfiguration *param, const AVFrame *frame, EbBufferHeaderType *header_ptr)
static av_cold int eb_enc_close(AVCodecContext *avctx)
static const struct @322326316233131355250374050203261141371005313331 svt_errors[]
Memory handling functions.
const char * av_chroma_location_name(enum AVChromaLocation location)
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
#define AV_PIX_FMT_FLAG_RGB
The pixel format contains RGB-like data (as opposed to YUV/grayscale).
@ AVCHROMA_LOC_TOPLEFT
ITU-R 601, SMPTE 274M 296M S314M(DV 4:1:1), mpeg2 4:2:2.
@ AVCHROMA_LOC_LEFT
MPEG-2/4 4:2:0, H.264 default for 4:2:0.
@ AVCHROMA_LOC_UNSPECIFIED
#define AV_PIX_FMT_YUV420P10
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
@ AVCOL_RANGE_UNSPECIFIED
@ AVCOL_RANGE_JPEG
Full range content.
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
@ AVCOL_SPC_RGB
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1
#define FF_AV1_PROFILE_OPTS
#define FF_ARRAY_ELEMS(a)
A reference to a data buffer.
This structure describes the bitrate properties of an encoded bitstream.
int64_t avg_bitrate
Average bitrate of the stream, in bits per second.
int64_t max_bitrate
Maximum bitrate of the stream, in bits per second.
int64_t buffer_size
The size of the buffer to which the ratecontrol is applied, in bits.
Describe the class of an AVClass context structure.
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
main external API structure.
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
int width
picture width / height.
char * stats_out
pass1 encoding statistics output buffer
int rc_buffer_size
decoder bitstream buffer size
enum AVColorRange color_range
MPEG vs JPEG YUV range.
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
int qmin
minimum quantizer
char * stats_in
pass2 encoding statistics input buffer Concatenated stuff from stats_out of pass1 should be placed he...
int level
Encoding level descriptor.
int64_t bit_rate
the average bitrate
enum AVColorSpace colorspace
YUV colorspace type.
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
int64_t rc_max_rate
maximum bitrate
int qmax
maximum quantizer
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
int flags
AV_CODEC_FLAG_*.
AVFrameSideData ** decoded_side_data
Array containing static side data, such as HDR10 CLL / MDCV structures.
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
int err_recognition
Error recognition; may misdetect some more or less valid parts as errors.
Content light level needed by to transmit HDR over HDMI (CTA-861.3).
unsigned MaxFALL
Max average light level per frame (cd/m^2).
unsigned MaxCLL
Max content light level (cd/m^2).
Structure to hold side data for an AVFrame.
This structure describes decoded (raw) audio or video data.
This structure stores compressed data.
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Rational number (pair of numerator and denominator).
AVDOVIDecoderConfigurationRecord cfg
Currently active dolby vision configuration, or {0} for none.
EbComponentType * svt_handle
EbBufferHeaderType * in_buf
EbSvtAv1EncConfiguration enc_params
AVDictionary * svtav1_opts
static int ref[MAX_W *MAX_W]