You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

383 lines
12KB

  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. #if defined(_MSC_VER)
  23. #define X265_API_IMPORTS 1
  24. #endif
  25. #include <x265.h>
  26. #include <float.h>
  27. #include "libavutil/internal.h"
  28. #include "libavutil/common.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/pixdesc.h"
  31. #include "avcodec.h"
  32. #include "internal.h"
  33. typedef struct libx265Context {
  34. const AVClass *class;
  35. x265_encoder *encoder;
  36. x265_param *params;
  37. const x265_api *api;
  38. float crf;
  39. char *preset;
  40. char *tune;
  41. char *x265_opts;
  42. } libx265Context;
  43. static int is_keyframe(NalUnitType naltype)
  44. {
  45. switch (naltype) {
  46. case NAL_UNIT_CODED_SLICE_BLA_W_LP:
  47. case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
  48. case NAL_UNIT_CODED_SLICE_BLA_N_LP:
  49. case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
  50. case NAL_UNIT_CODED_SLICE_IDR_N_LP:
  51. case NAL_UNIT_CODED_SLICE_CRA:
  52. return 1;
  53. default:
  54. return 0;
  55. }
  56. }
  57. static av_cold int libx265_encode_close(AVCodecContext *avctx)
  58. {
  59. libx265Context *ctx = avctx->priv_data;
  60. ctx->api->param_free(ctx->params);
  61. if (ctx->encoder)
  62. ctx->api->encoder_close(ctx->encoder);
  63. return 0;
  64. }
  65. static av_cold int libx265_encode_init(AVCodecContext *avctx)
  66. {
  67. libx265Context *ctx = avctx->priv_data;
  68. ctx->api = x265_api_get(av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth);
  69. if (!ctx->api)
  70. ctx->api = x265_api_get(0);
  71. if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL &&
  72. !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_w) {
  73. av_log(avctx, AV_LOG_ERROR,
  74. "4:2:2 and 4:4:4 support is not fully defined for HEVC yet. "
  75. "Set -strict experimental to encode anyway.\n");
  76. return AVERROR(ENOSYS);
  77. }
  78. ctx->params = ctx->api->param_alloc();
  79. if (!ctx->params) {
  80. av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
  81. return AVERROR(ENOMEM);
  82. }
  83. if (ctx->api->param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
  84. int i;
  85. av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", ctx->preset, ctx->tune);
  86. av_log(avctx, AV_LOG_INFO, "Possible presets:");
  87. for (i = 0; x265_preset_names[i]; i++)
  88. av_log(avctx, AV_LOG_INFO, " %s", x265_preset_names[i]);
  89. av_log(avctx, AV_LOG_INFO, "\n");
  90. av_log(avctx, AV_LOG_INFO, "Possible tunes:");
  91. for (i = 0; x265_tune_names[i]; i++)
  92. av_log(avctx, AV_LOG_INFO, " %s", x265_tune_names[i]);
  93. av_log(avctx, AV_LOG_INFO, "\n");
  94. return AVERROR(EINVAL);
  95. }
  96. ctx->params->frameNumThreads = avctx->thread_count;
  97. ctx->params->fpsNum = avctx->time_base.den;
  98. ctx->params->fpsDenom = avctx->time_base.num * avctx->ticks_per_frame;
  99. ctx->params->sourceWidth = avctx->width;
  100. ctx->params->sourceHeight = avctx->height;
  101. ctx->params->bEnablePsnr = !!(avctx->flags & AV_CODEC_FLAG_PSNR);
  102. if ((avctx->color_primaries <= AVCOL_PRI_BT2020 &&
  103. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED) ||
  104. (avctx->color_trc <= AVCOL_TRC_BT2020_12 &&
  105. avctx->color_trc != AVCOL_TRC_UNSPECIFIED) ||
  106. (avctx->colorspace <= AVCOL_SPC_BT2020_CL &&
  107. avctx->colorspace != AVCOL_SPC_UNSPECIFIED)) {
  108. ctx->params->vui.bEnableVideoSignalTypePresentFlag = 1;
  109. ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
  110. // x265 validates the parameters internally
  111. ctx->params->vui.colorPrimaries = avctx->color_primaries;
  112. ctx->params->vui.transferCharacteristics = avctx->color_trc;
  113. ctx->params->vui.matrixCoeffs = avctx->colorspace;
  114. }
  115. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  116. char sar[12];
  117. int sar_num, sar_den;
  118. av_reduce(&sar_num, &sar_den,
  119. avctx->sample_aspect_ratio.num,
  120. avctx->sample_aspect_ratio.den, 65535);
  121. snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);
  122. if (ctx->api->param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {
  123. av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);
  124. return AVERROR_INVALIDDATA;
  125. }
  126. }
  127. switch (avctx->pix_fmt) {
  128. case AV_PIX_FMT_YUV420P:
  129. case AV_PIX_FMT_YUV420P10:
  130. ctx->params->internalCsp = X265_CSP_I420;
  131. break;
  132. case AV_PIX_FMT_YUV422P:
  133. case AV_PIX_FMT_YUV422P10:
  134. ctx->params->internalCsp = X265_CSP_I422;
  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. if (ctx->crf >= 0) {
  142. char crf[6];
  143. snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
  144. if (ctx->api->param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
  145. av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
  146. return AVERROR(EINVAL);
  147. }
  148. } else if (avctx->bit_rate > 0) {
  149. ctx->params->rc.bitrate = avctx->bit_rate / 1000;
  150. ctx->params->rc.rateControlMode = X265_RC_ABR;
  151. }
  152. if (!(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
  153. ctx->params->bRepeatHeaders = 1;
  154. if (ctx->x265_opts) {
  155. AVDictionary *dict = NULL;
  156. AVDictionaryEntry *en = NULL;
  157. if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
  158. while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
  159. int parse_ret = ctx->api->param_parse(ctx->params, en->key, en->value);
  160. switch (parse_ret) {
  161. case X265_PARAM_BAD_NAME:
  162. av_log(avctx, AV_LOG_WARNING,
  163. "Unknown option: %s.\n", en->key);
  164. break;
  165. case X265_PARAM_BAD_VALUE:
  166. av_log(avctx, AV_LOG_WARNING,
  167. "Invalid value for %s: %s.\n", en->key, en->value);
  168. break;
  169. default:
  170. break;
  171. }
  172. }
  173. av_dict_free(&dict);
  174. }
  175. }
  176. ctx->encoder = ctx->api->encoder_open(ctx->params);
  177. if (!ctx->encoder) {
  178. av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
  179. libx265_encode_close(avctx);
  180. return AVERROR_INVALIDDATA;
  181. }
  182. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  183. x265_nal *nal;
  184. int nnal;
  185. avctx->extradata_size = ctx->api->encoder_headers(ctx->encoder, &nal, &nnal);
  186. if (avctx->extradata_size <= 0) {
  187. av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
  188. libx265_encode_close(avctx);
  189. return AVERROR_INVALIDDATA;
  190. }
  191. avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  192. if (!avctx->extradata) {
  193. av_log(avctx, AV_LOG_ERROR,
  194. "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);
  195. libx265_encode_close(avctx);
  196. return AVERROR(ENOMEM);
  197. }
  198. memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);
  199. }
  200. return 0;
  201. }
  202. static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  203. const AVFrame *pic, int *got_packet)
  204. {
  205. libx265Context *ctx = avctx->priv_data;
  206. x265_picture x265pic;
  207. x265_picture x265pic_out = { 0 };
  208. x265_nal *nal;
  209. uint8_t *dst;
  210. int payload = 0;
  211. int nnal;
  212. int ret;
  213. int i;
  214. ctx->api->picture_init(ctx->params, &x265pic);
  215. if (pic) {
  216. for (i = 0; i < 3; i++) {
  217. x265pic.planes[i] = pic->data[i];
  218. x265pic.stride[i] = pic->linesize[i];
  219. }
  220. x265pic.pts = pic->pts;
  221. x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth;
  222. x265pic.sliceType = pic->pict_type == AV_PICTURE_TYPE_I ? X265_TYPE_I :
  223. pic->pict_type == AV_PICTURE_TYPE_P ? X265_TYPE_P :
  224. pic->pict_type == AV_PICTURE_TYPE_B ? X265_TYPE_B :
  225. X265_TYPE_AUTO;
  226. }
  227. ret = ctx->api->encoder_encode(ctx->encoder, &nal, &nnal,
  228. pic ? &x265pic : NULL, &x265pic_out);
  229. if (ret < 0)
  230. return AVERROR_UNKNOWN;
  231. if (!nnal)
  232. return 0;
  233. for (i = 0; i < nnal; i++)
  234. payload += nal[i].sizeBytes;
  235. ret = ff_alloc_packet(pkt, payload);
  236. if (ret < 0) {
  237. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  238. return ret;
  239. }
  240. dst = pkt->data;
  241. for (i = 0; i < nnal; i++) {
  242. memcpy(dst, nal[i].payload, nal[i].sizeBytes);
  243. dst += nal[i].sizeBytes;
  244. if (is_keyframe(nal[i].type))
  245. pkt->flags |= AV_PKT_FLAG_KEY;
  246. }
  247. pkt->pts = x265pic_out.pts;
  248. pkt->dts = x265pic_out.dts;
  249. #if FF_API_CODED_FRAME
  250. FF_DISABLE_DEPRECATION_WARNINGS
  251. switch (x265pic_out.sliceType) {
  252. case X265_TYPE_IDR:
  253. case X265_TYPE_I:
  254. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  255. break;
  256. case X265_TYPE_P:
  257. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  258. break;
  259. case X265_TYPE_B:
  260. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  261. break;
  262. }
  263. FF_ENABLE_DEPRECATION_WARNINGS
  264. #endif
  265. *got_packet = 1;
  266. return 0;
  267. }
  268. static const enum AVPixelFormat x265_csp_eight[] = {
  269. AV_PIX_FMT_YUV420P,
  270. AV_PIX_FMT_YUV422P,
  271. AV_PIX_FMT_YUV444P,
  272. AV_PIX_FMT_NONE
  273. };
  274. static const enum AVPixelFormat x265_csp_twelve[] = {
  275. AV_PIX_FMT_YUV420P,
  276. AV_PIX_FMT_YUV422P,
  277. AV_PIX_FMT_YUV444P,
  278. AV_PIX_FMT_YUV420P10,
  279. AV_PIX_FMT_YUV422P10,
  280. AV_PIX_FMT_YUV444P10,
  281. AV_PIX_FMT_NONE
  282. };
  283. static av_cold void libx265_encode_init_csp(AVCodec *codec)
  284. {
  285. if (x265_max_bit_depth == 8)
  286. codec->pix_fmts = x265_csp_eight;
  287. else if (x265_max_bit_depth == 12)
  288. codec->pix_fmts = x265_csp_twelve;
  289. }
  290. #define OFFSET(x) offsetof(libx265Context, x)
  291. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  292. static const AVOption options[] = {
  293. { "crf", "set the x265 crf", OFFSET(crf), AV_OPT_TYPE_FLOAT, { .dbl = -1 }, -1, FLT_MAX, VE },
  294. { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  295. { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  296. { "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 },
  297. { NULL }
  298. };
  299. static const AVClass class = {
  300. .class_name = "libx265",
  301. .item_name = av_default_item_name,
  302. .option = options,
  303. .version = LIBAVUTIL_VERSION_INT,
  304. };
  305. static const AVCodecDefault x265_defaults[] = {
  306. { "b", "0" },
  307. { NULL },
  308. };
  309. AVCodec ff_libx265_encoder = {
  310. .name = "libx265",
  311. .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
  312. .type = AVMEDIA_TYPE_VIDEO,
  313. .id = AV_CODEC_ID_HEVC,
  314. .init = libx265_encode_init,
  315. .init_static_data = libx265_encode_init_csp,
  316. .encode2 = libx265_encode_frame,
  317. .close = libx265_encode_close,
  318. .priv_data_size = sizeof(libx265Context),
  319. .priv_class = &class,
  320. .defaults = x265_defaults,
  321. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  322. };