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