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.

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