]> git.sesse.net Git - ffmpeg/blob - libavcodec/libx265.c
libx265: Support SAR
[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 sar_num, sar_den;
81     int nnal;
82     int ret;
83     int i;
84
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);
92     }
93
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);
98     }
99
100     ctx->params = x265_param_alloc();
101     if (!ctx->params) {
102         av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
103         return AVERROR(ENOMEM);
104     }
105
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);
109     }
110
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;
116
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;
125
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;
130
131     switch (avctx->pix_fmt) {
132     case AV_PIX_FMT_YUV420P:
133     case AV_PIX_FMT_YUV420P10:
134         ctx->params->internalCsp = X265_CSP_I420;
135         break;
136     case AV_PIX_FMT_YUV444P:
137     case AV_PIX_FMT_YUV444P10:
138         ctx->params->internalCsp = X265_CSP_I444;
139         break;
140     }
141
142     if (avctx->bit_rate > 0) {
143         ctx->params->rc.bitrate         = avctx->bit_rate / 1000;
144         ctx->params->rc.rateControlMode = X265_RC_ABR;
145     }
146
147     if (ctx->x265_opts) {
148         AVDictionary *dict    = NULL;
149         AVDictionaryEntry *en = NULL;
150
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);
154
155                 switch (parse_ret) {
156                 case X265_PARAM_BAD_NAME:
157                     av_log(avctx, AV_LOG_WARNING,
158                           "Unknown option: %s.\n", en->key);
159                     break;
160                 case X265_PARAM_BAD_VALUE:
161                     av_log(avctx, AV_LOG_WARNING,
162                           "Invalid value for %s: %s.\n", en->key, en->value);
163                     break;
164                 default:
165                     break;
166                 }
167             }
168             av_dict_free(&dict);
169         }
170     }
171
172     ctx->encoder = x265_encoder_open(ctx->params);
173     if (!ctx->encoder) {
174         av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
175         libx265_encode_close(avctx);
176         return AVERROR_INVALIDDATA;
177     }
178
179     ret = x265_encoder_headers(ctx->encoder, &nal, &nnal);
180     if (ret < 0) {
181         av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
182         libx265_encode_close(avctx);
183         return AVERROR_INVALIDDATA;
184     }
185
186     for (i = 0; i < nnal; i++)
187         ctx->header_size += nal[i].sizeBytes;
188
189     ctx->header = av_malloc(ctx->header_size);
190     if (!ctx->header) {
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);
195     }
196
197     buf = ctx->header;
198     for (i = 0; i < nnal; i++) {
199         memcpy(buf, nal[i].payload, nal[i].sizeBytes);
200         buf += nal[i].sizeBytes;
201     }
202
203     return 0;
204 }
205
206 static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
207                                 const AVFrame *pic, int *got_packet)
208 {
209     libx265Context *ctx = avctx->priv_data;
210     x265_picture x265pic;
211     x265_picture x265pic_out = { { 0 } };
212     x265_nal *nal;
213     uint8_t *dst;
214     int payload = 0;
215     int nnal;
216     int ret;
217     int i;
218
219     x265_picture_init(ctx->params, &x265pic);
220
221     if (pic) {
222         for (i = 0; i < 3; i++) {
223            x265pic.planes[i] = pic->data[i];
224            x265pic.stride[i] = pic->linesize[i];
225         }
226
227         x265pic.pts      = pic->pts;
228         x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
229     }
230
231     ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
232                               pic ? &x265pic : NULL, &x265pic_out);
233     if (ret < 0)
234         return AVERROR_UNKNOWN;
235
236     if (!nnal)
237         return 0;
238
239     for (i = 0; i < nnal; i++)
240         payload += nal[i].sizeBytes;
241
242     payload += ctx->header_size;
243
244     ret = ff_alloc_packet(pkt, payload);
245     if (ret < 0) {
246         av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
247         return ret;
248     }
249     dst = pkt->data;
250
251     if (ctx->header) {
252         memcpy(dst, ctx->header, ctx->header_size);
253         dst += ctx->header_size;
254
255         av_freep(&ctx->header);
256         ctx->header_size = 0;
257     }
258
259     for (i = 0; i < nnal; i++) {
260         memcpy(dst, nal[i].payload, nal[i].sizeBytes);
261         dst += nal[i].sizeBytes;
262
263         if (is_keyframe(nal[i].type))
264             pkt->flags |= AV_PKT_FLAG_KEY;
265     }
266
267     pkt->pts = x265pic_out.pts;
268     pkt->dts = x265pic_out.dts;
269
270     *got_packet = 1;
271     return 0;
272 }
273
274 static const enum AVPixelFormat x265_csp_eight[] = {
275     AV_PIX_FMT_YUV420P,
276     AV_PIX_FMT_YUV444P,
277     AV_PIX_FMT_NONE
278 };
279
280 static const enum AVPixelFormat x265_csp_twelve[] = {
281     AV_PIX_FMT_YUV420P,
282     AV_PIX_FMT_YUV444P,
283     AV_PIX_FMT_YUV420P10,
284     AV_PIX_FMT_YUV444P10,
285     AV_PIX_FMT_NONE
286 };
287
288 static av_cold void libx265_encode_init_csp(AVCodec *codec)
289 {
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;
294 }
295
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 },
302     { NULL }
303 };
304
305 static const AVClass class = {
306     .class_name = "libx265",
307     .item_name  = av_default_item_name,
308     .option     = options,
309     .version    = LIBAVUTIL_VERSION_INT,
310 };
311
312 AVCodec ff_libx265_encoder = {
313     .name             = "libx265",
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,
324 };