]> git.sesse.net Git - ffmpeg/blob - libavcodec/libx265.c
Merge commit 'c513fcd7d235aa4cef45a6c3125bd4dcc03bf276'
[ffmpeg] / libavcodec / libx265.c
1 /*
2  * libx265 encoder
3  *
4  * Copyright (c) 2013-2014 Derek Buitenhuis
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #if defined(_MSC_VER)
24 #define X265_API_IMPORTS 1
25 #endif
26
27 #include <x265.h>
28 #include <float.h>
29
30 #include "libavutil/internal.h"
31 #include "libavutil/common.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/pixdesc.h"
34 #include "avcodec.h"
35 #include "internal.h"
36
37 typedef struct libx265Context {
38     const AVClass *class;
39
40     x265_encoder *encoder;
41     x265_param   *params;
42     const x265_api *api;
43
44     float crf;
45     int   forced_idr;
46     char *preset;
47     char *tune;
48     char *profile;
49     char *x265_opts;
50 } libx265Context;
51
52 static int is_keyframe(NalUnitType naltype)
53 {
54     switch (naltype) {
55     case NAL_UNIT_CODED_SLICE_BLA_W_LP:
56     case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
57     case NAL_UNIT_CODED_SLICE_BLA_N_LP:
58     case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
59     case NAL_UNIT_CODED_SLICE_IDR_N_LP:
60     case NAL_UNIT_CODED_SLICE_CRA:
61         return 1;
62     default:
63         return 0;
64     }
65 }
66
67 static av_cold int libx265_encode_close(AVCodecContext *avctx)
68 {
69     libx265Context *ctx = avctx->priv_data;
70
71     ctx->api->param_free(ctx->params);
72
73     if (ctx->encoder)
74         ctx->api->encoder_close(ctx->encoder);
75
76     return 0;
77 }
78
79 static av_cold int libx265_encode_init(AVCodecContext *avctx)
80 {
81     libx265Context *ctx = avctx->priv_data;
82     AVCPBProperties *cpb_props = NULL;
83
84     ctx->api = x265_api_get(av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth);
85     if (!ctx->api)
86         ctx->api = x265_api_get(0);
87
88     ctx->params = ctx->api->param_alloc();
89     if (!ctx->params) {
90         av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
91         return AVERROR(ENOMEM);
92     }
93
94     if (ctx->api->param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
95         int i;
96
97         av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", ctx->preset, ctx->tune);
98         av_log(avctx, AV_LOG_INFO, "Possible presets:");
99         for (i = 0; x265_preset_names[i]; i++)
100             av_log(avctx, AV_LOG_INFO, " %s", x265_preset_names[i]);
101
102         av_log(avctx, AV_LOG_INFO, "\n");
103         av_log(avctx, AV_LOG_INFO, "Possible tunes:");
104         for (i = 0; x265_tune_names[i]; i++)
105             av_log(avctx, AV_LOG_INFO, " %s", x265_tune_names[i]);
106
107         av_log(avctx, AV_LOG_INFO, "\n");
108
109         return AVERROR(EINVAL);
110     }
111
112     ctx->params->frameNumThreads = avctx->thread_count;
113     ctx->params->fpsNum          = avctx->time_base.den;
114     ctx->params->fpsDenom        = avctx->time_base.num * avctx->ticks_per_frame;
115     ctx->params->sourceWidth     = avctx->width;
116     ctx->params->sourceHeight    = avctx->height;
117     ctx->params->bEnablePsnr     = !!(avctx->flags & AV_CODEC_FLAG_PSNR);
118     ctx->params->bOpenGOP        = !(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
119
120     /* Tune the CTU size based on input resolution. */
121     if (ctx->params->sourceWidth < 64 || ctx->params->sourceHeight < 64)
122         ctx->params->maxCUSize = 32;
123     if (ctx->params->sourceWidth < 32 || ctx->params->sourceHeight < 32)
124         ctx->params->maxCUSize = 16;
125     if (ctx->params->sourceWidth < 16 || ctx->params->sourceHeight < 16) {
126         av_log(avctx, AV_LOG_ERROR, "Image size is too small (%dx%d).\n",
127                ctx->params->sourceWidth, ctx->params->sourceHeight);
128         return AVERROR(EINVAL);
129     }
130
131     if ((avctx->color_primaries <= AVCOL_PRI_SMPTE432 &&
132          avctx->color_primaries != AVCOL_PRI_UNSPECIFIED) ||
133         (avctx->color_trc <= AVCOL_TRC_ARIB_STD_B67 &&
134          avctx->color_trc != AVCOL_TRC_UNSPECIFIED) ||
135         (avctx->colorspace <= AVCOL_SPC_ICTCP &&
136          avctx->colorspace != AVCOL_SPC_UNSPECIFIED)) {
137
138         ctx->params->vui.bEnableVideoSignalTypePresentFlag  = 1;
139         ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
140
141         // x265 validates the parameters internally
142         ctx->params->vui.colorPrimaries          = avctx->color_primaries;
143         ctx->params->vui.transferCharacteristics = avctx->color_trc;
144         ctx->params->vui.matrixCoeffs            = avctx->colorspace;
145     }
146
147     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
148         char sar[12];
149         int sar_num, sar_den;
150
151         av_reduce(&sar_num, &sar_den,
152                   avctx->sample_aspect_ratio.num,
153                   avctx->sample_aspect_ratio.den, 65535);
154         snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);
155         if (ctx->api->param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {
156             av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);
157             return AVERROR_INVALIDDATA;
158         }
159     }
160
161     switch (avctx->pix_fmt) {
162     case AV_PIX_FMT_YUV420P:
163     case AV_PIX_FMT_YUV420P10:
164     case AV_PIX_FMT_YUV420P12:
165         ctx->params->internalCsp = X265_CSP_I420;
166         break;
167     case AV_PIX_FMT_YUV422P:
168     case AV_PIX_FMT_YUV422P10:
169     case AV_PIX_FMT_YUV422P12:
170         ctx->params->internalCsp = X265_CSP_I422;
171         break;
172     case AV_PIX_FMT_GBRP:
173     case AV_PIX_FMT_GBRP10:
174     case AV_PIX_FMT_GBRP12:
175         ctx->params->vui.matrixCoeffs = AVCOL_SPC_RGB;
176         ctx->params->vui.bEnableVideoSignalTypePresentFlag  = 1;
177         ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
178     case AV_PIX_FMT_YUV444P:
179     case AV_PIX_FMT_YUV444P10:
180     case AV_PIX_FMT_YUV444P12:
181         ctx->params->internalCsp = X265_CSP_I444;
182         break;
183     case AV_PIX_FMT_GRAY8:
184     case AV_PIX_FMT_GRAY10:
185     case AV_PIX_FMT_GRAY12:
186         if (ctx->api->api_build_number < 85) {
187             av_log(avctx, AV_LOG_ERROR,
188                    "libx265 version is %d, must be at least 85 for gray encoding.\n",
189                    ctx->api->api_build_number);
190             return AVERROR_INVALIDDATA;
191         }
192         ctx->params->internalCsp = X265_CSP_I400;
193         break;
194     }
195
196     if (ctx->crf >= 0) {
197         char crf[6];
198
199         snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
200         if (ctx->api->param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
201             av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
202             return AVERROR(EINVAL);
203         }
204     } else if (avctx->bit_rate > 0) {
205         ctx->params->rc.bitrate         = avctx->bit_rate / 1000;
206         ctx->params->rc.rateControlMode = X265_RC_ABR;
207     }
208
209     ctx->params->rc.vbvBufferSize = avctx->rc_buffer_size / 1000;
210     ctx->params->rc.vbvMaxBitrate = avctx->rc_max_rate    / 1000;
211
212     cpb_props = ff_add_cpb_side_data(avctx);
213     if (!cpb_props)
214         return AVERROR(ENOMEM);
215     cpb_props->buffer_size = ctx->params->rc.vbvBufferSize * 1000;
216     cpb_props->max_bitrate = ctx->params->rc.vbvMaxBitrate * 1000;
217     cpb_props->avg_bitrate = ctx->params->rc.bitrate       * 1000;
218
219     if (!(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
220         ctx->params->bRepeatHeaders = 1;
221
222     if (ctx->x265_opts) {
223         AVDictionary *dict    = NULL;
224         AVDictionaryEntry *en = NULL;
225
226         if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
227             while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
228                 int parse_ret = ctx->api->param_parse(ctx->params, en->key, en->value);
229
230                 switch (parse_ret) {
231                 case X265_PARAM_BAD_NAME:
232                     av_log(avctx, AV_LOG_WARNING,
233                           "Unknown option: %s.\n", en->key);
234                     break;
235                 case X265_PARAM_BAD_VALUE:
236                     av_log(avctx, AV_LOG_WARNING,
237                           "Invalid value for %s: %s.\n", en->key, en->value);
238                     break;
239                 default:
240                     break;
241                 }
242             }
243             av_dict_free(&dict);
244         }
245     }
246
247     if (ctx->params->rc.vbvBufferSize && avctx->rc_initial_buffer_occupancy > 1000 &&
248         ctx->params->rc.vbvBufferInit == 0.9) {
249         ctx->params->rc.vbvBufferInit = (float)avctx->rc_initial_buffer_occupancy / 1000;
250     }
251
252     if (ctx->profile) {
253         if (ctx->api->param_apply_profile(ctx->params, ctx->profile) < 0) {
254             int i;
255             av_log(avctx, AV_LOG_ERROR, "Invalid or incompatible profile set: %s.\n", ctx->profile);
256             av_log(avctx, AV_LOG_INFO, "Possible profiles:");
257             for (i = 0; x265_profile_names[i]; i++)
258                 av_log(avctx, AV_LOG_INFO, " %s", x265_profile_names[i]);
259             av_log(avctx, AV_LOG_INFO, "\n");
260             return AVERROR(EINVAL);
261         }
262     }
263
264     ctx->encoder = ctx->api->encoder_open(ctx->params);
265     if (!ctx->encoder) {
266         av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
267         libx265_encode_close(avctx);
268         return AVERROR_INVALIDDATA;
269     }
270
271     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
272         x265_nal *nal;
273         int nnal;
274
275         avctx->extradata_size = ctx->api->encoder_headers(ctx->encoder, &nal, &nnal);
276         if (avctx->extradata_size <= 0) {
277             av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
278             libx265_encode_close(avctx);
279             return AVERROR_INVALIDDATA;
280         }
281
282         avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
283         if (!avctx->extradata) {
284             av_log(avctx, AV_LOG_ERROR,
285                    "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);
286             libx265_encode_close(avctx);
287             return AVERROR(ENOMEM);
288         }
289
290         memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);
291     }
292
293     return 0;
294 }
295
296 static av_cold int libx265_encode_set_roi(libx265Context *ctx, const AVFrame *frame, x265_picture* pic)
297 {
298     AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
299     if (sd) {
300         if (ctx->params->rc.aqMode == X265_AQ_NONE) {
301             av_log(ctx, AV_LOG_WARNING, "Adaptive quantization must be enabled to use ROI encoding, skipping ROI.\n");
302         } else {
303             /* 8x8 block when qg-size is 8, 16*16 block otherwise. */
304             int mb_size = (ctx->params->rc.qgSize == 8) ? 8 : 16;
305             int mbx = (frame->width + mb_size - 1) / mb_size;
306             int mby = (frame->height + mb_size - 1) / mb_size;
307             int nb_rois;
308             AVRegionOfInterest *roi;
309             float *qoffsets;         /* will be freed after encode is called. */
310             qoffsets = av_mallocz_array(mbx * mby, sizeof(*qoffsets));
311             if (!qoffsets)
312                 return AVERROR(ENOMEM);
313
314             nb_rois = sd->size / sizeof(AVRegionOfInterest);
315             roi = (AVRegionOfInterest*)sd->data;
316             for (int count = 0; count < nb_rois; count++) {
317                 int starty = FFMIN(mby, roi->top / mb_size);
318                 int endy   = FFMIN(mby, (roi->bottom + mb_size - 1)/ mb_size);
319                 int startx = FFMIN(mbx, roi->left / mb_size);
320                 int endx   = FFMIN(mbx, (roi->right + mb_size - 1)/ mb_size);
321                 float qoffset;
322
323                 if (roi->self_size == 0) {
324                     av_free(qoffsets);
325                     av_log(ctx, AV_LOG_ERROR, "AVRegionOfInterest.self_size must be set to sizeof(AVRegionOfInterest).\n");
326                     return AVERROR(EINVAL);
327                 }
328
329                 if (roi->qoffset.den == 0) {
330                     av_free(qoffsets);
331                     av_log(ctx, AV_LOG_ERROR, "AVRegionOfInterest.qoffset.den must not be zero.\n");
332                     return AVERROR(EINVAL);
333                 }
334                 qoffset = roi->qoffset.num * 1.0f / roi->qoffset.den;
335                 qoffset = av_clipf(qoffset, -1.0f, 1.0f);
336
337                 /* qp range of x265 is from 0 to 51, just choose 25 as the scale value,
338                  * so the range of final qoffset is [-25.0, 25.0].
339                  */
340                 qoffset = qoffset * 25;
341
342                 for (int y = starty; y < endy; y++)
343                     for (int x = startx; x < endx; x++)
344                         qoffsets[x + y*mbx] = qoffset;
345
346                 roi = (AVRegionOfInterest*)((char*)roi + roi->self_size);
347             }
348
349             pic->quantOffsets = qoffsets;
350         }
351     }
352     return 0;
353 }
354
355 static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
356                                 const AVFrame *pic, int *got_packet)
357 {
358     libx265Context *ctx = avctx->priv_data;
359     x265_picture x265pic;
360     x265_picture x265pic_out = { 0 };
361     x265_nal *nal;
362     uint8_t *dst;
363     int payload = 0;
364     int nnal;
365     int ret;
366     int i;
367
368     ctx->api->picture_init(ctx->params, &x265pic);
369
370     if (pic) {
371         for (i = 0; i < 3; i++) {
372            x265pic.planes[i] = pic->data[i];
373            x265pic.stride[i] = pic->linesize[i];
374         }
375
376         x265pic.pts      = pic->pts;
377         x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth;
378
379         x265pic.sliceType = pic->pict_type == AV_PICTURE_TYPE_I ?
380                                               (ctx->forced_idr ? X265_TYPE_IDR : X265_TYPE_I) :
381                             pic->pict_type == AV_PICTURE_TYPE_P ? X265_TYPE_P :
382                             pic->pict_type == AV_PICTURE_TYPE_B ? X265_TYPE_B :
383                             X265_TYPE_AUTO;
384
385         ret = libx265_encode_set_roi(ctx, pic, &x265pic);
386         if (ret < 0)
387             return ret;
388     }
389
390     ret = ctx->api->encoder_encode(ctx->encoder, &nal, &nnal,
391                                    pic ? &x265pic : NULL, &x265pic_out);
392
393     av_freep(&x265pic.quantOffsets);
394
395     if (ret < 0)
396         return AVERROR_EXTERNAL;
397
398     if (!nnal)
399         return 0;
400
401     for (i = 0; i < nnal; i++)
402         payload += nal[i].sizeBytes;
403
404     ret = ff_alloc_packet2(avctx, pkt, payload, payload);
405     if (ret < 0) {
406         av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
407         return ret;
408     }
409     dst = pkt->data;
410
411     for (i = 0; i < nnal; i++) {
412         memcpy(dst, nal[i].payload, nal[i].sizeBytes);
413         dst += nal[i].sizeBytes;
414
415         if (is_keyframe(nal[i].type))
416             pkt->flags |= AV_PKT_FLAG_KEY;
417     }
418
419     pkt->pts = x265pic_out.pts;
420     pkt->dts = x265pic_out.dts;
421
422 #if FF_API_CODED_FRAME
423 FF_DISABLE_DEPRECATION_WARNINGS
424     switch (x265pic_out.sliceType) {
425     case X265_TYPE_IDR:
426     case X265_TYPE_I:
427         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
428         break;
429     case X265_TYPE_P:
430         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
431         break;
432     case X265_TYPE_B:
433         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
434         break;
435     }
436 FF_ENABLE_DEPRECATION_WARNINGS
437 #endif
438
439 #if X265_BUILD >= 130
440     if (x265pic_out.sliceType == X265_TYPE_B)
441 #else
442     if (x265pic_out.frameData.sliceType == 'b')
443 #endif
444         pkt->flags |= AV_PKT_FLAG_DISPOSABLE;
445
446     *got_packet = 1;
447     return 0;
448 }
449
450 static const enum AVPixelFormat x265_csp_eight[] = {
451     AV_PIX_FMT_YUV420P,
452     AV_PIX_FMT_YUV422P,
453     AV_PIX_FMT_YUV444P,
454     AV_PIX_FMT_GBRP,
455     AV_PIX_FMT_GRAY8,
456     AV_PIX_FMT_NONE
457 };
458
459 static const enum AVPixelFormat x265_csp_ten[] = {
460     AV_PIX_FMT_YUV420P,
461     AV_PIX_FMT_YUV422P,
462     AV_PIX_FMT_YUV444P,
463     AV_PIX_FMT_GBRP,
464     AV_PIX_FMT_YUV420P10,
465     AV_PIX_FMT_YUV422P10,
466     AV_PIX_FMT_YUV444P10,
467     AV_PIX_FMT_GBRP10,
468     AV_PIX_FMT_GRAY8,
469     AV_PIX_FMT_GRAY10,
470     AV_PIX_FMT_NONE
471 };
472
473 static const enum AVPixelFormat x265_csp_twelve[] = {
474     AV_PIX_FMT_YUV420P,
475     AV_PIX_FMT_YUV422P,
476     AV_PIX_FMT_YUV444P,
477     AV_PIX_FMT_GBRP,
478     AV_PIX_FMT_YUV420P10,
479     AV_PIX_FMT_YUV422P10,
480     AV_PIX_FMT_YUV444P10,
481     AV_PIX_FMT_GBRP10,
482     AV_PIX_FMT_YUV420P12,
483     AV_PIX_FMT_YUV422P12,
484     AV_PIX_FMT_YUV444P12,
485     AV_PIX_FMT_GBRP12,
486     AV_PIX_FMT_GRAY8,
487     AV_PIX_FMT_GRAY10,
488     AV_PIX_FMT_GRAY12,
489     AV_PIX_FMT_NONE
490 };
491
492 static av_cold void libx265_encode_init_csp(AVCodec *codec)
493 {
494     if (x265_api_get(12))
495         codec->pix_fmts = x265_csp_twelve;
496     else if (x265_api_get(10))
497         codec->pix_fmts = x265_csp_ten;
498     else if (x265_api_get(8))
499         codec->pix_fmts = x265_csp_eight;
500 }
501
502 #define OFFSET(x) offsetof(libx265Context, x)
503 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
504 static const AVOption options[] = {
505     { "crf",         "set the x265 crf",                                                            OFFSET(crf),       AV_OPT_TYPE_FLOAT,  { .dbl = -1 }, -1, FLT_MAX, VE },
506     { "forced-idr",  "if forcing keyframes, force them as IDR frames",                              OFFSET(forced_idr),AV_OPT_TYPE_BOOL,   { .i64 =  0 },  0,       1, VE },
507     { "preset",      "set the x265 preset",                                                         OFFSET(preset),    AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
508     { "tune",        "set the x265 tune parameter",                                                 OFFSET(tune),      AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
509     { "profile",     "set the x265 profile",                                                        OFFSET(profile),   AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
510     { "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 },
511     { NULL }
512 };
513
514 static const AVClass class = {
515     .class_name = "libx265",
516     .item_name  = av_default_item_name,
517     .option     = options,
518     .version    = LIBAVUTIL_VERSION_INT,
519 };
520
521 static const AVCodecDefault x265_defaults[] = {
522     { "b", "0" },
523     { NULL },
524 };
525
526 AVCodec ff_libx265_encoder = {
527     .name             = "libx265",
528     .long_name        = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
529     .type             = AVMEDIA_TYPE_VIDEO,
530     .id               = AV_CODEC_ID_HEVC,
531     .init             = libx265_encode_init,
532     .init_static_data = libx265_encode_init_csp,
533     .encode2          = libx265_encode_frame,
534     .close            = libx265_encode_close,
535     .priv_data_size   = sizeof(libx265Context),
536     .priv_class       = &class,
537     .defaults         = x265_defaults,
538     .capabilities     = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
539     .wrapper_name     = "libx265",
540 };