]> git.sesse.net Git - ffmpeg/blob - libavcodec/libx265.c
libx265: Support 4:4:4
[ffmpeg] / libavcodec / libx265.c
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
32 typedef 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
45 static 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
60 static 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
75 static 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     if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL &&
85         !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_w &&
86         !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h) {
87         av_log(avctx, AV_LOG_ERROR,
88                "4:4:4 support is not fully defined for HEVC yet. "
89                "Set -strict experimental to encode anyway.\n");
90         return AVERROR(ENOSYS);
91     }
92
93     avctx->coded_frame = av_frame_alloc();
94     if (!avctx->coded_frame) {
95         av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
96         return AVERROR(ENOMEM);
97     }
98
99     ctx->params = x265_param_alloc();
100     if (!ctx->params) {
101         av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
102         return AVERROR(ENOMEM);
103     }
104
105     if (x265_param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
106         av_log(avctx, AV_LOG_ERROR, "Invalid preset or tune.\n");
107         return AVERROR(EINVAL);
108     }
109
110     ctx->params->frameNumThreads = avctx->thread_count;
111     ctx->params->fpsNum          = avctx->time_base.den;
112     ctx->params->fpsDenom        = avctx->time_base.num * avctx->ticks_per_frame;
113     ctx->params->sourceWidth     = avctx->width;
114     ctx->params->sourceHeight    = avctx->height;
115
116     if (x265_max_bit_depth == 8)
117         ctx->params->internalBitDepth = 8;
118     else if (x265_max_bit_depth == 12)
119         ctx->params->internalBitDepth = 10;
120
121     switch (avctx->pix_fmt) {
122     case AV_PIX_FMT_YUV420P:
123     case AV_PIX_FMT_YUV420P10:
124         ctx->params->internalCsp = X265_CSP_I420;
125         break;
126     case AV_PIX_FMT_YUV444P:
127     case AV_PIX_FMT_YUV444P10:
128         ctx->params->internalCsp = X265_CSP_I444;
129         break;
130     }
131
132     if (avctx->bit_rate > 0) {
133         ctx->params->rc.bitrate         = avctx->bit_rate / 1000;
134         ctx->params->rc.rateControlMode = X265_RC_ABR;
135     }
136
137     if (ctx->x265_opts) {
138         AVDictionary *dict    = NULL;
139         AVDictionaryEntry *en = NULL;
140
141         if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
142             while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
143                 int parse_ret = x265_param_parse(ctx->params, en->key, en->value);
144
145                 switch (parse_ret) {
146                 case X265_PARAM_BAD_NAME:
147                     av_log(avctx, AV_LOG_WARNING,
148                           "Unknown option: %s.\n", en->key);
149                     break;
150                 case X265_PARAM_BAD_VALUE:
151                     av_log(avctx, AV_LOG_WARNING,
152                           "Invalid value for %s: %s.\n", en->key, en->value);
153                     break;
154                 default:
155                     break;
156                 }
157             }
158             av_dict_free(&dict);
159         }
160     }
161
162     ctx->encoder = x265_encoder_open(ctx->params);
163     if (!ctx->encoder) {
164         av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
165         libx265_encode_close(avctx);
166         return AVERROR_INVALIDDATA;
167     }
168
169     ret = x265_encoder_headers(ctx->encoder, &nal, &nnal);
170     if (ret < 0) {
171         av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
172         libx265_encode_close(avctx);
173         return AVERROR_INVALIDDATA;
174     }
175
176     for (i = 0; i < nnal; i++)
177         ctx->header_size += nal[i].sizeBytes;
178
179     ctx->header = av_malloc(ctx->header_size);
180     if (!ctx->header) {
181         av_log(avctx, AV_LOG_ERROR,
182                "Cannot allocate HEVC header of size %d.\n", ctx->header_size);
183         libx265_encode_close(avctx);
184         return AVERROR(ENOMEM);
185     }
186
187     buf = ctx->header;
188     for (i = 0; i < nnal; i++) {
189         memcpy(buf, nal[i].payload, nal[i].sizeBytes);
190         buf += nal[i].sizeBytes;
191     }
192
193     return 0;
194 }
195
196 static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
197                                 const AVFrame *pic, int *got_packet)
198 {
199     libx265Context *ctx = avctx->priv_data;
200     x265_picture x265pic;
201     x265_picture x265pic_out = { { 0 } };
202     x265_nal *nal;
203     uint8_t *dst;
204     int payload = 0;
205     int nnal;
206     int ret;
207     int i;
208
209     x265_picture_init(ctx->params, &x265pic);
210
211     if (pic) {
212         for (i = 0; i < 3; i++) {
213            x265pic.planes[i] = pic->data[i];
214            x265pic.stride[i] = pic->linesize[i];
215         }
216
217         x265pic.pts      = pic->pts;
218         x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
219     }
220
221     ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
222                               pic ? &x265pic : NULL, &x265pic_out);
223     if (ret < 0)
224         return AVERROR_UNKNOWN;
225
226     if (!nnal)
227         return 0;
228
229     for (i = 0; i < nnal; i++)
230         payload += nal[i].sizeBytes;
231
232     payload += ctx->header_size;
233
234     ret = ff_alloc_packet(pkt, payload);
235     if (ret < 0) {
236         av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
237         return ret;
238     }
239     dst = pkt->data;
240
241     if (ctx->header) {
242         memcpy(dst, ctx->header, ctx->header_size);
243         dst += ctx->header_size;
244
245         av_freep(&ctx->header);
246         ctx->header_size = 0;
247     }
248
249     for (i = 0; i < nnal; i++) {
250         memcpy(dst, nal[i].payload, nal[i].sizeBytes);
251         dst += nal[i].sizeBytes;
252
253         if (is_keyframe(nal[i].type))
254             pkt->flags |= AV_PKT_FLAG_KEY;
255     }
256
257     pkt->pts = x265pic_out.pts;
258     pkt->dts = x265pic_out.dts;
259
260     *got_packet = 1;
261     return 0;
262 }
263
264 static const enum AVPixelFormat x265_csp_eight[] = {
265     AV_PIX_FMT_YUV420P,
266     AV_PIX_FMT_YUV444P,
267     AV_PIX_FMT_NONE
268 };
269
270 static const enum AVPixelFormat x265_csp_twelve[] = {
271     AV_PIX_FMT_YUV420P,
272     AV_PIX_FMT_YUV444P,
273     AV_PIX_FMT_YUV420P10,
274     AV_PIX_FMT_YUV444P10,
275     AV_PIX_FMT_NONE
276 };
277
278 static av_cold void libx265_encode_init_csp(AVCodec *codec)
279 {
280     if (x265_max_bit_depth == 8)
281         codec->pix_fmts = x265_csp_eight;
282     else if (x265_max_bit_depth == 12)
283         codec->pix_fmts = x265_csp_twelve;
284 }
285
286 #define OFFSET(x) offsetof(libx265Context, x)
287 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
288 static const AVOption options[] = {
289     { "preset",      "set the x265 preset",                                                         OFFSET(preset),    AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
290     { "tune",        "set the x265 tune parameter",                                                 OFFSET(tune),      AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
291     { "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 },
292     { NULL }
293 };
294
295 static const AVClass class = {
296     .class_name = "libx265",
297     .item_name  = av_default_item_name,
298     .option     = options,
299     .version    = LIBAVUTIL_VERSION_INT,
300 };
301
302 AVCodec ff_libx265_encoder = {
303     .name             = "libx265",
304     .long_name        = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
305     .type             = AVMEDIA_TYPE_VIDEO,
306     .id               = AV_CODEC_ID_HEVC,
307     .init             = libx265_encode_init,
308     .init_static_data = libx265_encode_init_csp,
309     .encode2          = libx265_encode_frame,
310     .close            = libx265_encode_close,
311     .priv_data_size   = sizeof(libx265Context),
312     .priv_class       = &class,
313     .capabilities     = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
314 };