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.

446 lines
14KB

  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. #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. int forced_idr;
  40. char *preset;
  41. char *tune;
  42. char *profile;
  43. char *x265_opts;
  44. } libx265Context;
  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. static av_cold int libx265_encode_close(AVCodecContext *avctx)
  60. {
  61. libx265Context *ctx = avctx->priv_data;
  62. ctx->api->param_free(ctx->params);
  63. if (ctx->encoder)
  64. ctx->api->encoder_close(ctx->encoder);
  65. return 0;
  66. }
  67. static av_cold int libx265_encode_init(AVCodecContext *avctx)
  68. {
  69. libx265Context *ctx = avctx->priv_data;
  70. ctx->api = x265_api_get(av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth);
  71. if (!ctx->api)
  72. ctx->api = x265_api_get(0);
  73. ctx->params = ctx->api->param_alloc();
  74. if (!ctx->params) {
  75. av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
  76. return AVERROR(ENOMEM);
  77. }
  78. if (ctx->api->param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
  79. int i;
  80. av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", ctx->preset, ctx->tune);
  81. av_log(avctx, AV_LOG_INFO, "Possible presets:");
  82. for (i = 0; x265_preset_names[i]; i++)
  83. av_log(avctx, AV_LOG_INFO, " %s", x265_preset_names[i]);
  84. av_log(avctx, AV_LOG_INFO, "\n");
  85. av_log(avctx, AV_LOG_INFO, "Possible tunes:");
  86. for (i = 0; x265_tune_names[i]; i++)
  87. av_log(avctx, AV_LOG_INFO, " %s", x265_tune_names[i]);
  88. av_log(avctx, AV_LOG_INFO, "\n");
  89. return AVERROR(EINVAL);
  90. }
  91. ctx->params->frameNumThreads = avctx->thread_count;
  92. ctx->params->fpsNum = avctx->time_base.den;
  93. ctx->params->fpsDenom = avctx->time_base.num * avctx->ticks_per_frame;
  94. ctx->params->sourceWidth = avctx->width;
  95. ctx->params->sourceHeight = avctx->height;
  96. ctx->params->bEnablePsnr = !!(avctx->flags & AV_CODEC_FLAG_PSNR);
  97. if ((avctx->color_primaries <= AVCOL_PRI_BT2020 &&
  98. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED) ||
  99. (avctx->color_trc <= AVCOL_TRC_BT2020_12 &&
  100. avctx->color_trc != AVCOL_TRC_UNSPECIFIED) ||
  101. (avctx->colorspace <= AVCOL_SPC_BT2020_CL &&
  102. avctx->colorspace != AVCOL_SPC_UNSPECIFIED)) {
  103. ctx->params->vui.bEnableVideoSignalTypePresentFlag = 1;
  104. ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
  105. // x265 validates the parameters internally
  106. ctx->params->vui.colorPrimaries = avctx->color_primaries;
  107. ctx->params->vui.transferCharacteristics = avctx->color_trc;
  108. ctx->params->vui.matrixCoeffs = avctx->colorspace;
  109. }
  110. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  111. char sar[12];
  112. int sar_num, sar_den;
  113. av_reduce(&sar_num, &sar_den,
  114. avctx->sample_aspect_ratio.num,
  115. avctx->sample_aspect_ratio.den, 65535);
  116. snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);
  117. if (ctx->api->param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {
  118. av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);
  119. return AVERROR_INVALIDDATA;
  120. }
  121. }
  122. switch (avctx->pix_fmt) {
  123. case AV_PIX_FMT_YUV420P:
  124. case AV_PIX_FMT_YUV420P10:
  125. case AV_PIX_FMT_YUV420P12:
  126. ctx->params->internalCsp = X265_CSP_I420;
  127. break;
  128. case AV_PIX_FMT_YUV422P:
  129. case AV_PIX_FMT_YUV422P10:
  130. case AV_PIX_FMT_YUV422P12:
  131. ctx->params->internalCsp = X265_CSP_I422;
  132. break;
  133. case AV_PIX_FMT_GBRP:
  134. case AV_PIX_FMT_GBRP10:
  135. case AV_PIX_FMT_GBRP12:
  136. ctx->params->vui.matrixCoeffs = AVCOL_SPC_RGB;
  137. ctx->params->vui.bEnableVideoSignalTypePresentFlag = 1;
  138. ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
  139. case AV_PIX_FMT_YUV444P:
  140. case AV_PIX_FMT_YUV444P10:
  141. case AV_PIX_FMT_YUV444P12:
  142. ctx->params->internalCsp = X265_CSP_I444;
  143. break;
  144. case AV_PIX_FMT_GRAY8:
  145. case AV_PIX_FMT_GRAY10:
  146. case AV_PIX_FMT_GRAY12:
  147. if (ctx->api->api_build_number < 85) {
  148. av_log(avctx, AV_LOG_ERROR,
  149. "libx265 version is %d, must be at least 85 for gray encoding.\n",
  150. ctx->api->api_build_number);
  151. return AVERROR_INVALIDDATA;
  152. }
  153. ctx->params->internalCsp = X265_CSP_I400;
  154. break;
  155. }
  156. if (ctx->crf >= 0) {
  157. char crf[6];
  158. snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
  159. if (ctx->api->param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
  160. av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
  161. return AVERROR(EINVAL);
  162. }
  163. } else if (avctx->bit_rate > 0) {
  164. ctx->params->rc.bitrate = avctx->bit_rate / 1000;
  165. ctx->params->rc.rateControlMode = X265_RC_ABR;
  166. }
  167. if (!(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
  168. ctx->params->bRepeatHeaders = 1;
  169. if (ctx->x265_opts) {
  170. AVDictionary *dict = NULL;
  171. AVDictionaryEntry *en = NULL;
  172. if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
  173. while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
  174. int parse_ret = ctx->api->param_parse(ctx->params, en->key, en->value);
  175. switch (parse_ret) {
  176. case X265_PARAM_BAD_NAME:
  177. av_log(avctx, AV_LOG_WARNING,
  178. "Unknown option: %s.\n", en->key);
  179. break;
  180. case X265_PARAM_BAD_VALUE:
  181. av_log(avctx, AV_LOG_WARNING,
  182. "Invalid value for %s: %s.\n", en->key, en->value);
  183. break;
  184. default:
  185. break;
  186. }
  187. }
  188. av_dict_free(&dict);
  189. }
  190. }
  191. if (ctx->profile) {
  192. if (ctx->api->param_apply_profile(ctx->params, ctx->profile) < 0) {
  193. int i;
  194. av_log(avctx, AV_LOG_ERROR, "Invalid or incompatible profile set: %s.\n", ctx->profile);
  195. av_log(avctx, AV_LOG_INFO, "Possible profiles:");
  196. for (i = 0; x265_profile_names[i]; i++)
  197. av_log(avctx, AV_LOG_INFO, " %s", x265_profile_names[i]);
  198. av_log(avctx, AV_LOG_INFO, "\n");
  199. return AVERROR(EINVAL);
  200. }
  201. }
  202. ctx->encoder = ctx->api->encoder_open(ctx->params);
  203. if (!ctx->encoder) {
  204. av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
  205. libx265_encode_close(avctx);
  206. return AVERROR_INVALIDDATA;
  207. }
  208. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  209. x265_nal *nal;
  210. int nnal;
  211. avctx->extradata_size = ctx->api->encoder_headers(ctx->encoder, &nal, &nnal);
  212. if (avctx->extradata_size <= 0) {
  213. av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
  214. libx265_encode_close(avctx);
  215. return AVERROR_INVALIDDATA;
  216. }
  217. avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  218. if (!avctx->extradata) {
  219. av_log(avctx, AV_LOG_ERROR,
  220. "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);
  221. libx265_encode_close(avctx);
  222. return AVERROR(ENOMEM);
  223. }
  224. memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);
  225. }
  226. return 0;
  227. }
  228. static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  229. const AVFrame *pic, int *got_packet)
  230. {
  231. libx265Context *ctx = avctx->priv_data;
  232. x265_picture x265pic;
  233. x265_picture x265pic_out = { 0 };
  234. x265_nal *nal;
  235. uint8_t *dst;
  236. int payload = 0;
  237. int nnal;
  238. int ret;
  239. int i;
  240. ctx->api->picture_init(ctx->params, &x265pic);
  241. if (pic) {
  242. for (i = 0; i < 3; i++) {
  243. x265pic.planes[i] = pic->data[i];
  244. x265pic.stride[i] = pic->linesize[i];
  245. }
  246. x265pic.pts = pic->pts;
  247. x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth;
  248. x265pic.sliceType = pic->pict_type == AV_PICTURE_TYPE_I ?
  249. (ctx->forced_idr ? X265_TYPE_IDR : X265_TYPE_I) :
  250. pic->pict_type == AV_PICTURE_TYPE_P ? X265_TYPE_P :
  251. pic->pict_type == AV_PICTURE_TYPE_B ? X265_TYPE_B :
  252. X265_TYPE_AUTO;
  253. }
  254. ret = ctx->api->encoder_encode(ctx->encoder, &nal, &nnal,
  255. pic ? &x265pic : NULL, &x265pic_out);
  256. if (ret < 0)
  257. return AVERROR_EXTERNAL;
  258. if (!nnal)
  259. return 0;
  260. for (i = 0; i < nnal; i++)
  261. payload += nal[i].sizeBytes;
  262. ret = ff_alloc_packet2(avctx, pkt, payload, payload);
  263. if (ret < 0) {
  264. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  265. return ret;
  266. }
  267. dst = pkt->data;
  268. for (i = 0; i < nnal; i++) {
  269. memcpy(dst, nal[i].payload, nal[i].sizeBytes);
  270. dst += nal[i].sizeBytes;
  271. if (is_keyframe(nal[i].type))
  272. pkt->flags |= AV_PKT_FLAG_KEY;
  273. }
  274. pkt->pts = x265pic_out.pts;
  275. pkt->dts = x265pic_out.dts;
  276. #if FF_API_CODED_FRAME
  277. FF_DISABLE_DEPRECATION_WARNINGS
  278. switch (x265pic_out.sliceType) {
  279. case X265_TYPE_IDR:
  280. case X265_TYPE_I:
  281. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  282. break;
  283. case X265_TYPE_P:
  284. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  285. break;
  286. case X265_TYPE_B:
  287. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  288. break;
  289. }
  290. FF_ENABLE_DEPRECATION_WARNINGS
  291. #endif
  292. #if X265_BUILD >= 130
  293. if (x265pic_out.sliceType == X265_TYPE_B)
  294. #else
  295. if (x265pic_out.frameData.sliceType == 'b')
  296. #endif
  297. pkt->flags |= AV_PKT_FLAG_DISPOSABLE;
  298. *got_packet = 1;
  299. return 0;
  300. }
  301. static const enum AVPixelFormat x265_csp_eight[] = {
  302. AV_PIX_FMT_YUV420P,
  303. AV_PIX_FMT_YUV422P,
  304. AV_PIX_FMT_YUV444P,
  305. AV_PIX_FMT_GBRP,
  306. AV_PIX_FMT_GRAY8,
  307. AV_PIX_FMT_NONE
  308. };
  309. static const enum AVPixelFormat x265_csp_ten[] = {
  310. AV_PIX_FMT_YUV420P,
  311. AV_PIX_FMT_YUV422P,
  312. AV_PIX_FMT_YUV444P,
  313. AV_PIX_FMT_GBRP,
  314. AV_PIX_FMT_YUV420P10,
  315. AV_PIX_FMT_YUV422P10,
  316. AV_PIX_FMT_YUV444P10,
  317. AV_PIX_FMT_GBRP10,
  318. AV_PIX_FMT_GRAY8,
  319. AV_PIX_FMT_GRAY10,
  320. AV_PIX_FMT_NONE
  321. };
  322. static const enum AVPixelFormat x265_csp_twelve[] = {
  323. AV_PIX_FMT_YUV420P,
  324. AV_PIX_FMT_YUV422P,
  325. AV_PIX_FMT_YUV444P,
  326. AV_PIX_FMT_GBRP,
  327. AV_PIX_FMT_YUV420P10,
  328. AV_PIX_FMT_YUV422P10,
  329. AV_PIX_FMT_YUV444P10,
  330. AV_PIX_FMT_GBRP10,
  331. AV_PIX_FMT_YUV420P12,
  332. AV_PIX_FMT_YUV422P12,
  333. AV_PIX_FMT_YUV444P12,
  334. AV_PIX_FMT_GBRP12,
  335. AV_PIX_FMT_GRAY8,
  336. AV_PIX_FMT_GRAY10,
  337. AV_PIX_FMT_GRAY12,
  338. AV_PIX_FMT_NONE
  339. };
  340. static av_cold void libx265_encode_init_csp(AVCodec *codec)
  341. {
  342. if (x265_api_get(12))
  343. codec->pix_fmts = x265_csp_twelve;
  344. else if (x265_api_get(10))
  345. codec->pix_fmts = x265_csp_ten;
  346. else if (x265_api_get(8))
  347. codec->pix_fmts = x265_csp_eight;
  348. }
  349. #define OFFSET(x) offsetof(libx265Context, x)
  350. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  351. static const AVOption options[] = {
  352. { "crf", "set the x265 crf", OFFSET(crf), AV_OPT_TYPE_FLOAT, { .dbl = -1 }, -1, FLT_MAX, VE },
  353. { "forced-idr", "if forcing keyframes, force them as IDR frames", OFFSET(forced_idr),AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  354. { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  355. { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  356. { "profile", "set the x265 profile", OFFSET(profile), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  357. { "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 },
  358. { NULL }
  359. };
  360. static const AVClass class = {
  361. .class_name = "libx265",
  362. .item_name = av_default_item_name,
  363. .option = options,
  364. .version = LIBAVUTIL_VERSION_INT,
  365. };
  366. static const AVCodecDefault x265_defaults[] = {
  367. { "b", "0" },
  368. { NULL },
  369. };
  370. AVCodec ff_libx265_encoder = {
  371. .name = "libx265",
  372. .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
  373. .type = AVMEDIA_TYPE_VIDEO,
  374. .id = AV_CODEC_ID_HEVC,
  375. .init = libx265_encode_init,
  376. .init_static_data = libx265_encode_init_csp,
  377. .encode2 = libx265_encode_frame,
  378. .close = libx265_encode_close,
  379. .priv_data_size = sizeof(libx265Context),
  380. .priv_class = &class,
  381. .defaults = x265_defaults,
  382. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  383. };