Add libx265 encoder
[libav.git] / libavcodec / libx265.c
CommitLineData
50ea9315
DB
1/*
2 * libx265 encoder
3 *
4 * Copyright (c) 2013-2014 Derek Buitenhuis
5 *
6 * This file is part of Libav.
7 *
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.
12 *
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.
17 *
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
21 */
22
23#include <x265.h>
24
25#include "libavutil/internal.h"
26#include "libavutil/common.h"
27#include "libavutil/opt.h"
28#include "libavutil/pixdesc.h"
29#include "avcodec.h"
30#include "internal.h"
31
32typedef struct libx265Context {
33 const AVClass *class;
34
35 x265_encoder *encoder;
36 x265_param *params;
37 uint8_t *header;
38 int header_size;
39
40 char *preset;
41 char *tune;
42 char *x265_opts;
43} libx265Context;
44
45static int is_keyframe(NalUnitType naltype)
46{
47 switch (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:
54 return 1;
55 default:
56 return 0;
57 }
58}
59
60static av_cold int libx265_encode_close(AVCodecContext *avctx)
61{
62 libx265Context *ctx = avctx->priv_data;
63
64 av_frame_free(&avctx->coded_frame);
65 av_freep(&ctx->header);
66
67 x265_param_free(ctx->params);
68
69 if (ctx->encoder)
70 x265_encoder_close(ctx->encoder);
71
72 return 0;
73}
74
75static av_cold int libx265_encode_init(AVCodecContext *avctx)
76{
77 libx265Context *ctx = avctx->priv_data;
78 x265_nal *nal;
79 uint8_t *buf;
80 int nnal;
81 int ret;
82 int i;
83
84 avctx->coded_frame = av_frame_alloc();
85 if (!avctx->coded_frame) {
86 av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
87 return AVERROR(ENOMEM);
88 }
89
90 ctx->params = x265_param_alloc();
91 if (!ctx->params) {
92 av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
93 return AVERROR(ENOMEM);
94 }
95
96 x265_param_default(ctx->params);
97 if (x265_param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
98 av_log(avctx, AV_LOG_ERROR, "Invalid preset or tune.\n");
99 return AVERROR(EINVAL);
100 }
101
102 ctx->params->frameNumThreads = avctx->thread_count;
103 ctx->params->frameRate = (int) (avctx->time_base.den / avctx->time_base.num);
104 ctx->params->sourceWidth = avctx->width;
105 ctx->params->sourceHeight = avctx->height;
106 ctx->params->inputBitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
107
108 if (avctx->bit_rate > 0) {
109 ctx->params->rc.bitrate = avctx->bit_rate / 1000;
110 ctx->params->rc.rateControlMode = X265_RC_ABR;
111 }
112
113 if (ctx->x265_opts) {
114 AVDictionary *dict = NULL;
115 AVDictionaryEntry *en = NULL;
116
117 if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
118 while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
119 int parse_ret = x265_param_parse(ctx->params, en->key, en->value);
120
121 switch (parse_ret) {
122 case X265_PARAM_BAD_NAME:
123 av_log(avctx, AV_LOG_WARNING,
124 "Unknown option: %s.\n", en->key);
125 break;
126 case X265_PARAM_BAD_VALUE:
127 av_log(avctx, AV_LOG_WARNING,
128 "Invalid value for %s: %s.\n", en->key, en->value);
129 break;
130 default:
131 break;
132 }
133 }
134 av_dict_free(&dict);
135 }
136 }
137
138 ctx->encoder = x265_encoder_open(ctx->params);
139 if (!ctx->encoder) {
140 av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
141 libx265_encode_close(avctx);
142 return AVERROR_INVALIDDATA;
143 }
144
145 ret = x265_encoder_headers(ctx->encoder, &nal, &nnal);
146 if (ret < 0) {
147 av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
148 libx265_encode_close(avctx);
149 return AVERROR_INVALIDDATA;
150 }
151
152 for (i = 0; i < nnal; i++)
153 ctx->header_size += nal[i].sizeBytes;
154
155 ctx->header = av_malloc(ctx->header_size);
156 if (!ctx->header) {
157 av_log(avctx, AV_LOG_ERROR,
158 "Cannot allocate HEVC header of size %d.\n", ctx->header_size);
159 libx265_encode_close(avctx);
160 return AVERROR(ENOMEM);
161 }
162
163 buf = ctx->header;
164 for (i = 0; i < nnal; i++) {
165 memcpy(buf, nal[i].payload, nal[i].sizeBytes);
166 buf += nal[i].sizeBytes;
167 }
168
169 return 0;
170}
171
172static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
173 const AVFrame *pic, int *got_packet)
174{
175 libx265Context *ctx = avctx->priv_data;
176 x265_picture x265pic;
177 x265_picture x265pic_out = { { 0 } };
178 x265_nal *nal;
179 uint8_t *dst;
180 int payload = 0;
181 int nnal;
182 int ret;
183 int i;
184
185 if (pic) {
186 for (i = 0; i < 3; i++) {
187 x265pic.planes[i] = pic->data[i];
188 x265pic.stride[i] = pic->linesize[i];
189 }
190
191 x265pic.pts = pic->pts;
192 }
193
194 ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
195 pic ? &x265pic : NULL, &x265pic_out);
196 if (ret < 0)
197 return AVERROR_UNKNOWN;
198
199 if (!nnal)
200 return 0;
201
202 for (i = 0; i < nnal; i++)
203 payload += nal[i].sizeBytes;
204
205 payload += ctx->header_size;
206
207 ret = ff_alloc_packet(pkt, payload);
208 if (ret < 0) {
209 av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
210 return ret;
211 }
212 dst = pkt->data;
213
214 if (ctx->header) {
215 memcpy(dst, ctx->header, ctx->header_size);
216 dst += ctx->header_size;
217
218 av_freep(&ctx->header);
219 ctx->header_size = 0;
220 }
221
222 for (i = 0; i < nnal; i++) {
223 memcpy(dst, nal[i].payload, nal[i].sizeBytes);
224 dst += nal[i].sizeBytes;
225
226 if (is_keyframe(nal[i].type))
227 pkt->flags |= AV_PKT_FLAG_KEY;
228 }
229
230 pkt->pts = x265pic_out.pts;
231 pkt->dts = x265pic_out.dts;
232
233 *got_packet = 1;
234 return 0;
235}
236
237static const enum AVPixelFormat x265_csp_eight[] = {
238 AV_PIX_FMT_YUV420P,
239 AV_PIX_FMT_NONE
240};
241
242static const enum AVPixelFormat x265_csp_twelve[] = {
243 AV_PIX_FMT_YUV420P,
244 AV_PIX_FMT_YUV420P10,
245 AV_PIX_FMT_NONE
246};
247
248static av_cold void libx265_encode_init_csp(AVCodec *codec)
249{
250 if (x265_max_bit_depth == 8)
251 codec->pix_fmts = x265_csp_eight;
252 else if (x265_max_bit_depth == 12)
253 codec->pix_fmts = x265_csp_twelve;
254}
255
256#define OFFSET(x) offsetof(libx265Context, x)
257#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
258static const AVOption options[] = {
259 { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
260 { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
261 { "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 },
262 { NULL }
263};
264
265static const AVClass class = {
266 .class_name = "libx265",
267 .item_name = av_default_item_name,
268 .option = options,
269 .version = LIBAVUTIL_VERSION_INT,
270};
271
272AVCodec ff_libx265_encoder = {
273 .name = "libx265",
274 .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
275 .type = AVMEDIA_TYPE_VIDEO,
276 .id = AV_CODEC_ID_HEVC,
277 .init = libx265_encode_init,
278 .init_static_data = libx265_encode_init_csp,
279 .encode2 = libx265_encode_frame,
280 .close = libx265_encode_close,
281 .priv_data_size = sizeof(libx265Context),
282 .priv_class = &class,
283 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
284};