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.

425 lines
13KB

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