4 * Copyright (c) 2013-2014 Derek Buitenhuis
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #define X265_API_IMPORTS 1
30 #include "libavutil/internal.h"
31 #include "libavutil/common.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/pixdesc.h"
37 typedef struct libx265Context
{
40 x265_encoder
*encoder
;
51 static int is_keyframe(NalUnitType naltype
)
54 case NAL_UNIT_CODED_SLICE_BLA_W_LP
:
55 case NAL_UNIT_CODED_SLICE_BLA_W_RADL
:
56 case NAL_UNIT_CODED_SLICE_BLA_N_LP
:
57 case NAL_UNIT_CODED_SLICE_IDR_W_RADL
:
58 case NAL_UNIT_CODED_SLICE_IDR_N_LP
:
59 case NAL_UNIT_CODED_SLICE_CRA
:
66 static av_cold
int libx265_encode_close(AVCodecContext
*avctx
)
68 libx265Context
*ctx
= avctx
->priv_data
;
70 ctx
->api
->param_free(ctx
->params
);
73 ctx
->api
->encoder_close(ctx
->encoder
);
78 static av_cold
int libx265_encode_init(AVCodecContext
*avctx
)
80 libx265Context
*ctx
= avctx
->priv_data
;
82 ctx
->api
= x265_api_get(av_pix_fmt_desc_get(avctx
->pix_fmt
)->comp
[0].depth
);
84 ctx
->api
= x265_api_get(0);
86 if (avctx
->strict_std_compliance
> FF_COMPLIANCE_EXPERIMENTAL
&&
87 !av_pix_fmt_desc_get(avctx
->pix_fmt
)->log2_chroma_w
) {
88 av_log(avctx
, AV_LOG_ERROR
,
89 "4:2:2 and 4:4:4 support is not fully defined for HEVC yet. "
90 "Set -strict experimental to encode anyway.\n");
91 return AVERROR(ENOSYS
);
94 ctx
->params
= ctx
->api
->param_alloc();
96 av_log(avctx
, AV_LOG_ERROR
, "Could not allocate x265 param structure.\n");
97 return AVERROR(ENOMEM
);
100 if (ctx
->api
->param_default_preset(ctx
->params
, ctx
->preset
, ctx
->tune
) < 0) {
103 av_log(avctx
, AV_LOG_ERROR
, "Error setting preset/tune %s/%s.\n", ctx
->preset
, ctx
->tune
);
104 av_log(avctx
, AV_LOG_INFO
, "Possible presets:");
105 for (i
= 0; x265_preset_names
[i
]; i
++)
106 av_log(avctx
, AV_LOG_INFO
, " %s", x265_preset_names
[i
]);
108 av_log(avctx
, AV_LOG_INFO
, "\n");
109 av_log(avctx
, AV_LOG_INFO
, "Possible tunes:");
110 for (i
= 0; x265_tune_names
[i
]; i
++)
111 av_log(avctx
, AV_LOG_INFO
, " %s", x265_tune_names
[i
]);
113 av_log(avctx
, AV_LOG_INFO
, "\n");
115 return AVERROR(EINVAL
);
118 ctx
->params
->frameNumThreads
= avctx
->thread_count
;
119 ctx
->params
->fpsNum
= avctx
->time_base
.den
;
120 ctx
->params
->fpsDenom
= avctx
->time_base
.num
* avctx
->ticks_per_frame
;
121 ctx
->params
->sourceWidth
= avctx
->width
;
122 ctx
->params
->sourceHeight
= avctx
->height
;
123 ctx
->params
->bEnablePsnr
= !!(avctx
->flags
& AV_CODEC_FLAG_PSNR
);
125 /* Tune the CTU size based on input resolution. */
126 if (ctx
->params
->sourceWidth
< 64 || ctx
->params
->sourceHeight
< 64)
127 ctx
->params
->maxCUSize
= 32;
128 if (ctx
->params
->sourceWidth
< 32 || ctx
->params
->sourceHeight
< 32)
129 ctx
->params
->maxCUSize
= 16;
130 if (ctx
->params
->sourceWidth
< 16 || ctx
->params
->sourceHeight
< 16) {
131 av_log(avctx
, AV_LOG_ERROR
, "Image size is too small (%dx%d).\n",
132 ctx
->params
->sourceWidth
, ctx
->params
->sourceHeight
);
133 return AVERROR(EINVAL
);
136 if ((avctx
->color_primaries
<= AVCOL_PRI_BT2020
&&
137 avctx
->color_primaries
!= AVCOL_PRI_UNSPECIFIED
) ||
138 (avctx
->color_trc
<= AVCOL_TRC_BT2020_12
&&
139 avctx
->color_trc
!= AVCOL_TRC_UNSPECIFIED
) ||
140 (avctx
->colorspace
<= AVCOL_SPC_BT2020_CL
&&
141 avctx
->colorspace
!= AVCOL_SPC_UNSPECIFIED
)) {
143 ctx
->params
->vui
.bEnableVideoSignalTypePresentFlag
= 1;
144 ctx
->params
->vui
.bEnableColorDescriptionPresentFlag
= 1;
146 // x265 validates the parameters internally
147 ctx
->params
->vui
.colorPrimaries
= avctx
->color_primaries
;
148 ctx
->params
->vui
.transferCharacteristics
= avctx
->color_trc
;
149 ctx
->params
->vui
.matrixCoeffs
= avctx
->colorspace
;
152 if (avctx
->sample_aspect_ratio
.num
> 0 && avctx
->sample_aspect_ratio
.den
> 0) {
154 int sar_num
, sar_den
;
156 av_reduce(&sar_num
, &sar_den
,
157 avctx
->sample_aspect_ratio
.num
,
158 avctx
->sample_aspect_ratio
.den
, 65535);
159 snprintf(sar
, sizeof(sar
), "%d:%d", sar_num
, sar_den
);
160 if (ctx
->api
->param_parse(ctx
->params
, "sar", sar
) == X265_PARAM_BAD_VALUE
) {
161 av_log(avctx
, AV_LOG_ERROR
, "Invalid SAR: %d:%d.\n", sar_num
, sar_den
);
162 return AVERROR_INVALIDDATA
;
166 switch (avctx
->pix_fmt
) {
167 case AV_PIX_FMT_YUV420P
:
168 case AV_PIX_FMT_YUV420P10
:
169 ctx
->params
->internalCsp
= X265_CSP_I420
;
171 case AV_PIX_FMT_YUV422P
:
172 case AV_PIX_FMT_YUV422P10
:
173 ctx
->params
->internalCsp
= X265_CSP_I422
;
175 case AV_PIX_FMT_YUV444P
:
176 case AV_PIX_FMT_YUV444P10
:
177 ctx
->params
->internalCsp
= X265_CSP_I444
;
184 snprintf(crf
, sizeof(crf
), "%2.2f", ctx
->crf
);
185 if (ctx
->api
->param_parse(ctx
->params
, "crf", crf
) == X265_PARAM_BAD_VALUE
) {
186 av_log(avctx
, AV_LOG_ERROR
, "Invalid crf: %2.2f.\n", ctx
->crf
);
187 return AVERROR(EINVAL
);
189 } else if (avctx
->bit_rate
> 0) {
190 ctx
->params
->rc
.bitrate
= avctx
->bit_rate
/ 1000;
191 ctx
->params
->rc
.rateControlMode
= X265_RC_ABR
;
194 if (!(avctx
->flags
& AV_CODEC_FLAG_GLOBAL_HEADER
))
195 ctx
->params
->bRepeatHeaders
= 1;
197 if (ctx
->x265_opts
) {
198 AVDictionary
*dict
= NULL
;
199 AVDictionaryEntry
*en
= NULL
;
201 if (!av_dict_parse_string(&dict
, ctx
->x265_opts
, "=", ":", 0)) {
202 while ((en
= av_dict_get(dict
, "", en
, AV_DICT_IGNORE_SUFFIX
))) {
203 int parse_ret
= ctx
->api
->param_parse(ctx
->params
, en
->key
, en
->value
);
206 case X265_PARAM_BAD_NAME
:
207 av_log(avctx
, AV_LOG_WARNING
,
208 "Unknown option: %s.\n", en
->key
);
210 case X265_PARAM_BAD_VALUE
:
211 av_log(avctx
, AV_LOG_WARNING
,
212 "Invalid value for %s: %s.\n", en
->key
, en
->value
);
222 ctx
->encoder
= ctx
->api
->encoder_open(ctx
->params
);
224 av_log(avctx
, AV_LOG_ERROR
, "Cannot open libx265 encoder.\n");
225 libx265_encode_close(avctx
);
226 return AVERROR_INVALIDDATA
;
229 if (avctx
->flags
& AV_CODEC_FLAG_GLOBAL_HEADER
) {
233 avctx
->extradata_size
= ctx
->api
->encoder_headers(ctx
->encoder
, &nal
, &nnal
);
234 if (avctx
->extradata_size
<= 0) {
235 av_log(avctx
, AV_LOG_ERROR
, "Cannot encode headers.\n");
236 libx265_encode_close(avctx
);
237 return AVERROR_INVALIDDATA
;
240 avctx
->extradata
= av_malloc(avctx
->extradata_size
+ AV_INPUT_BUFFER_PADDING_SIZE
);
241 if (!avctx
->extradata
) {
242 av_log(avctx
, AV_LOG_ERROR
,
243 "Cannot allocate HEVC header of size %d.\n", avctx
->extradata_size
);
244 libx265_encode_close(avctx
);
245 return AVERROR(ENOMEM
);
248 memcpy(avctx
->extradata
, nal
[0].payload
, avctx
->extradata_size
);
254 static int libx265_encode_frame(AVCodecContext
*avctx
, AVPacket
*pkt
,
255 const AVFrame
*pic
, int *got_packet
)
257 libx265Context
*ctx
= avctx
->priv_data
;
258 x265_picture x265pic
;
259 x265_picture x265pic_out
= { 0 };
267 ctx
->api
->picture_init(ctx
->params
, &x265pic
);
270 for (i
= 0; i
< 3; i
++) {
271 x265pic
.planes
[i
] = pic
->data
[i
];
272 x265pic
.stride
[i
] = pic
->linesize
[i
];
275 x265pic
.pts
= pic
->pts
;
276 x265pic
.bitDepth
= av_pix_fmt_desc_get(avctx
->pix_fmt
)->comp
[0].depth
;
278 x265pic
.sliceType
= pic
->pict_type
== AV_PICTURE_TYPE_I
?
279 (ctx
->forced_idr
? X265_TYPE_IDR
: X265_TYPE_I
) :
280 pic
->pict_type
== AV_PICTURE_TYPE_P
? X265_TYPE_P
:
281 pic
->pict_type
== AV_PICTURE_TYPE_B
? X265_TYPE_B
:
285 ret
= ctx
->api
->encoder_encode(ctx
->encoder
, &nal
, &nnal
,
286 pic
? &x265pic
: NULL
, &x265pic_out
);
288 return AVERROR_UNKNOWN
;
293 for (i
= 0; i
< nnal
; i
++)
294 payload
+= nal
[i
].sizeBytes
;
296 ret
= ff_alloc_packet(pkt
, payload
);
298 av_log(avctx
, AV_LOG_ERROR
, "Error getting output packet.\n");
303 for (i
= 0; i
< nnal
; i
++) {
304 memcpy(dst
, nal
[i
].payload
, nal
[i
].sizeBytes
);
305 dst
+= nal
[i
].sizeBytes
;
307 if (is_keyframe(nal
[i
].type
))
308 pkt
->flags
|= AV_PKT_FLAG_KEY
;
311 pkt
->pts
= x265pic_out
.pts
;
312 pkt
->dts
= x265pic_out
.dts
;
314 #if FF_API_CODED_FRAME
315 FF_DISABLE_DEPRECATION_WARNINGS
316 switch (x265pic_out
.sliceType
) {
319 avctx
->coded_frame
->pict_type
= AV_PICTURE_TYPE_I
;
322 avctx
->coded_frame
->pict_type
= AV_PICTURE_TYPE_P
;
325 avctx
->coded_frame
->pict_type
= AV_PICTURE_TYPE_B
;
328 FF_ENABLE_DEPRECATION_WARNINGS
335 static const enum AVPixelFormat x265_csp_eight
[] = {
342 static const enum AVPixelFormat x265_csp_twelve
[] = {
346 AV_PIX_FMT_YUV420P10
,
347 AV_PIX_FMT_YUV422P10
,
348 AV_PIX_FMT_YUV444P10
,
352 static av_cold
void libx265_encode_init_csp(AVCodec
*codec
)
354 if (x265_max_bit_depth
== 8)
355 codec
->pix_fmts
= x265_csp_eight
;
356 else if (x265_max_bit_depth
== 12)
357 codec
->pix_fmts
= x265_csp_twelve
;
360 #define OFFSET(x) offsetof(libx265Context, x)
361 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
362 static const AVOption options
[] = {
363 { "crf", "set the x265 crf", OFFSET(crf
), AV_OPT_TYPE_FLOAT
, { .dbl
= -1 }, -1, FLT_MAX
, VE
},
364 { "forced-idr", "if forcing keyframes, force them as IDR frames", OFFSET(forced_idr
),AV_OPT_TYPE_INT
, { .i64
= 0 }, 0, 1, VE
},
365 { "preset", "set the x265 preset", OFFSET(preset
), AV_OPT_TYPE_STRING
, { 0 }, 0, 0, VE
},
366 { "tune", "set the x265 tune parameter", OFFSET(tune
), AV_OPT_TYPE_STRING
, { 0 }, 0, 0, VE
},
367 { "x265-params", "set the x265 configuration using a :-separated list of key=value parameters", OFFSET(x265_opts
), AV_OPT_TYPE_STRING
, { 0 }, 0, 0, VE
},
371 static const AVClass
class = {
372 .class_name
= "libx265",
373 .item_name
= av_default_item_name
,
375 .version
= LIBAVUTIL_VERSION_INT
,
378 static const AVCodecDefault x265_defaults
[] = {
383 AVCodec ff_libx265_encoder
= {
385 .long_name
= NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
386 .type
= AVMEDIA_TYPE_VIDEO
,
387 .id
= AV_CODEC_ID_HEVC
,
388 .init
= libx265_encode_init
,
389 .init_static_data
= libx265_encode_init_csp
,
390 .encode2
= libx265_encode_frame
,
391 .close
= libx265_encode_close
,
392 .priv_data_size
= sizeof(libx265Context
),
393 .priv_class
= &class,
394 .defaults
= x265_defaults
,
395 .capabilities
= AV_CODEC_CAP_DELAY
| AV_CODEC_CAP_AUTO_THREADS
,
396 .wrapper_name
= "libx265",