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
25 #include "libavutil/internal.h"
26 #include "libavutil/common.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
32 typedef struct libx265Context {
35 x265_encoder *encoder;
45 static int is_keyframe(NalUnitType naltype)
48 case NAL_UNIT_CODED_SLICE_BLA_W_LP:
49 case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
50 case NAL_UNIT_CODED_SLICE_BLA_N_LP:
51 case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
52 case NAL_UNIT_CODED_SLICE_IDR_N_LP:
53 case NAL_UNIT_CODED_SLICE_CRA:
60 static av_cold int libx265_encode_close(AVCodecContext *avctx)
62 libx265Context *ctx = avctx->priv_data;
64 av_frame_free(&avctx->coded_frame);
65 av_freep(&ctx->header);
67 x265_param_free(ctx->params);
70 x265_encoder_close(ctx->encoder);
75 static av_cold int libx265_encode_init(AVCodecContext *avctx)
77 libx265Context *ctx = avctx->priv_data;
85 if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL &&
86 !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_w &&
87 !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h) {
88 av_log(avctx, AV_LOG_ERROR,
89 "4:4:4 support is not fully defined for HEVC yet. "
90 "Set -strict experimental to encode anyway.\n");
91 return AVERROR(ENOSYS);
94 avctx->coded_frame = av_frame_alloc();
95 if (!avctx->coded_frame) {
96 av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
97 return AVERROR(ENOMEM);
100 ctx->params = x265_param_alloc();
102 av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
103 return AVERROR(ENOMEM);
106 if (x265_param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
107 av_log(avctx, AV_LOG_ERROR, "Invalid preset or tune.\n");
108 return AVERROR(EINVAL);
111 ctx->params->frameNumThreads = avctx->thread_count;
112 ctx->params->fpsNum = avctx->time_base.den;
113 ctx->params->fpsDenom = avctx->time_base.num * avctx->ticks_per_frame;
114 ctx->params->sourceWidth = avctx->width;
115 ctx->params->sourceHeight = avctx->height;
117 av_reduce(&sar_num, &sar_den,
118 avctx->sample_aspect_ratio.num,
119 avctx->sample_aspect_ratio.den, 4096);
120 ctx->params->bEnableVuiParametersPresentFlag = 1;
121 ctx->params->bEnableAspectRatioIdc = 1;
122 ctx->params->aspectRatioIdc = 255;
123 ctx->params->sarWidth = sar_num;
124 ctx->params->sarHeight = sar_den;
126 if (x265_max_bit_depth == 8)
127 ctx->params->internalBitDepth = 8;
128 else if (x265_max_bit_depth == 12)
129 ctx->params->internalBitDepth = 10;
131 switch (avctx->pix_fmt) {
132 case AV_PIX_FMT_YUV420P:
133 case AV_PIX_FMT_YUV420P10:
134 ctx->params->internalCsp = X265_CSP_I420;
136 case AV_PIX_FMT_YUV444P:
137 case AV_PIX_FMT_YUV444P10:
138 ctx->params->internalCsp = X265_CSP_I444;
142 if (avctx->bit_rate > 0) {
143 ctx->params->rc.bitrate = avctx->bit_rate / 1000;
144 ctx->params->rc.rateControlMode = X265_RC_ABR;
147 if (ctx->x265_opts) {
148 AVDictionary *dict = NULL;
149 AVDictionaryEntry *en = NULL;
151 if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
152 while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
153 int parse_ret = x265_param_parse(ctx->params, en->key, en->value);
156 case X265_PARAM_BAD_NAME:
157 av_log(avctx, AV_LOG_WARNING,
158 "Unknown option: %s.\n", en->key);
160 case X265_PARAM_BAD_VALUE:
161 av_log(avctx, AV_LOG_WARNING,
162 "Invalid value for %s: %s.\n", en->key, en->value);
172 ctx->encoder = x265_encoder_open(ctx->params);
174 av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
175 libx265_encode_close(avctx);
176 return AVERROR_INVALIDDATA;
179 ret = x265_encoder_headers(ctx->encoder, &nal, &nnal);
181 av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
182 libx265_encode_close(avctx);
183 return AVERROR_INVALIDDATA;
186 for (i = 0; i < nnal; i++)
187 ctx->header_size += nal[i].sizeBytes;
189 ctx->header = av_malloc(ctx->header_size);
191 av_log(avctx, AV_LOG_ERROR,
192 "Cannot allocate HEVC header of size %d.\n", ctx->header_size);
193 libx265_encode_close(avctx);
194 return AVERROR(ENOMEM);
198 for (i = 0; i < nnal; i++) {
199 memcpy(buf, nal[i].payload, nal[i].sizeBytes);
200 buf += nal[i].sizeBytes;
206 static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
207 const AVFrame *pic, int *got_packet)
209 libx265Context *ctx = avctx->priv_data;
210 x265_picture x265pic;
211 x265_picture x265pic_out = { { 0 } };
219 x265_picture_init(ctx->params, &x265pic);
222 for (i = 0; i < 3; i++) {
223 x265pic.planes[i] = pic->data[i];
224 x265pic.stride[i] = pic->linesize[i];
227 x265pic.pts = pic->pts;
228 x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
231 ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
232 pic ? &x265pic : NULL, &x265pic_out);
234 return AVERROR_UNKNOWN;
239 for (i = 0; i < nnal; i++)
240 payload += nal[i].sizeBytes;
242 payload += ctx->header_size;
244 ret = ff_alloc_packet(pkt, payload);
246 av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
252 memcpy(dst, ctx->header, ctx->header_size);
253 dst += ctx->header_size;
255 av_freep(&ctx->header);
256 ctx->header_size = 0;
259 for (i = 0; i < nnal; i++) {
260 memcpy(dst, nal[i].payload, nal[i].sizeBytes);
261 dst += nal[i].sizeBytes;
263 if (is_keyframe(nal[i].type))
264 pkt->flags |= AV_PKT_FLAG_KEY;
267 pkt->pts = x265pic_out.pts;
268 pkt->dts = x265pic_out.dts;
274 static const enum AVPixelFormat x265_csp_eight[] = {
280 static const enum AVPixelFormat x265_csp_twelve[] = {
283 AV_PIX_FMT_YUV420P10,
284 AV_PIX_FMT_YUV444P10,
288 static av_cold void libx265_encode_init_csp(AVCodec *codec)
290 if (x265_max_bit_depth == 8)
291 codec->pix_fmts = x265_csp_eight;
292 else if (x265_max_bit_depth == 12)
293 codec->pix_fmts = x265_csp_twelve;
296 #define OFFSET(x) offsetof(libx265Context, x)
297 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
298 static const AVOption options[] = {
299 { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
300 { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
301 { "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 },
305 static const AVClass class = {
306 .class_name = "libx265",
307 .item_name = av_default_item_name,
309 .version = LIBAVUTIL_VERSION_INT,
312 AVCodec ff_libx265_encoder = {
314 .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
315 .type = AVMEDIA_TYPE_VIDEO,
316 .id = AV_CODEC_ID_HEVC,
317 .init = libx265_encode_init,
318 .init_static_data = libx265_encode_init_csp,
319 .encode2 = libx265_encode_frame,
320 .close = libx265_encode_close,
321 .priv_data_size = sizeof(libx265Context),
322 .priv_class = &class,
323 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,