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.

340 lines
11KB

  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. av_log(avctx, AV_LOG_ERROR, "Invalid preset or tune.\n");
  87. return AVERROR(EINVAL);
  88. }
  89. ctx->params->frameNumThreads = avctx->thread_count;
  90. ctx->params->fpsNum = avctx->time_base.den;
  91. ctx->params->fpsDenom = avctx->time_base.num * avctx->ticks_per_frame;
  92. ctx->params->sourceWidth = avctx->width;
  93. ctx->params->sourceHeight = avctx->height;
  94. ctx->params->bEnablePsnr = !!(avctx->flags & CODEC_FLAG_PSNR);
  95. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  96. char sar[12];
  97. int sar_num, sar_den;
  98. av_reduce(&sar_num, &sar_den,
  99. avctx->sample_aspect_ratio.num,
  100. avctx->sample_aspect_ratio.den, 65535);
  101. snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);
  102. if (x265_param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {
  103. av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);
  104. return AVERROR_INVALIDDATA;
  105. }
  106. }
  107. switch (avctx->pix_fmt) {
  108. case AV_PIX_FMT_YUV420P:
  109. case AV_PIX_FMT_YUV420P10:
  110. ctx->params->internalCsp = X265_CSP_I420;
  111. break;
  112. case AV_PIX_FMT_YUV422P:
  113. case AV_PIX_FMT_YUV422P10:
  114. ctx->params->internalCsp = X265_CSP_I422;
  115. break;
  116. case AV_PIX_FMT_YUV444P:
  117. case AV_PIX_FMT_YUV444P10:
  118. ctx->params->internalCsp = X265_CSP_I444;
  119. break;
  120. }
  121. if (ctx->crf >= 0) {
  122. char crf[6];
  123. snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
  124. if (x265_param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
  125. av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
  126. return AVERROR(EINVAL);
  127. }
  128. } else if (avctx->bit_rate > 0) {
  129. ctx->params->rc.bitrate = avctx->bit_rate / 1000;
  130. ctx->params->rc.rateControlMode = X265_RC_ABR;
  131. }
  132. if (!(avctx->flags & CODEC_FLAG_GLOBAL_HEADER))
  133. ctx->params->bRepeatHeaders = 1;
  134. if (ctx->x265_opts) {
  135. AVDictionary *dict = NULL;
  136. AVDictionaryEntry *en = NULL;
  137. if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
  138. while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
  139. int parse_ret = x265_param_parse(ctx->params, en->key, en->value);
  140. switch (parse_ret) {
  141. case X265_PARAM_BAD_NAME:
  142. av_log(avctx, AV_LOG_WARNING,
  143. "Unknown option: %s.\n", en->key);
  144. break;
  145. case X265_PARAM_BAD_VALUE:
  146. av_log(avctx, AV_LOG_WARNING,
  147. "Invalid value for %s: %s.\n", en->key, en->value);
  148. break;
  149. default:
  150. break;
  151. }
  152. }
  153. av_dict_free(&dict);
  154. }
  155. }
  156. ctx->encoder = x265_encoder_open(ctx->params);
  157. if (!ctx->encoder) {
  158. av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
  159. libx265_encode_close(avctx);
  160. return AVERROR_INVALIDDATA;
  161. }
  162. if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
  163. x265_nal *nal;
  164. int nnal;
  165. avctx->extradata_size = x265_encoder_headers(ctx->encoder, &nal, &nnal);
  166. if (avctx->extradata_size <= 0) {
  167. av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
  168. libx265_encode_close(avctx);
  169. return AVERROR_INVALIDDATA;
  170. }
  171. avctx->extradata = av_malloc(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  172. if (!avctx->extradata) {
  173. av_log(avctx, AV_LOG_ERROR,
  174. "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);
  175. libx265_encode_close(avctx);
  176. return AVERROR(ENOMEM);
  177. }
  178. memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);
  179. }
  180. return 0;
  181. }
  182. static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  183. const AVFrame *pic, int *got_packet)
  184. {
  185. libx265Context *ctx = avctx->priv_data;
  186. x265_picture x265pic;
  187. x265_picture x265pic_out = { { 0 } };
  188. x265_nal *nal;
  189. uint8_t *dst;
  190. int payload = 0;
  191. int nnal;
  192. int ret;
  193. int i;
  194. x265_picture_init(ctx->params, &x265pic);
  195. if (pic) {
  196. for (i = 0; i < 3; i++) {
  197. x265pic.planes[i] = pic->data[i];
  198. x265pic.stride[i] = pic->linesize[i];
  199. }
  200. x265pic.pts = pic->pts;
  201. x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
  202. x265pic.sliceType = pic->pict_type == AV_PICTURE_TYPE_I ? X265_TYPE_I :
  203. pic->pict_type == AV_PICTURE_TYPE_P ? X265_TYPE_P :
  204. pic->pict_type == AV_PICTURE_TYPE_B ? X265_TYPE_B :
  205. X265_TYPE_AUTO;
  206. }
  207. ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
  208. pic ? &x265pic : NULL, &x265pic_out);
  209. if (ret < 0)
  210. return AVERROR_UNKNOWN;
  211. if (!nnal)
  212. return 0;
  213. for (i = 0; i < nnal; i++)
  214. payload += nal[i].sizeBytes;
  215. ret = ff_alloc_packet(pkt, payload);
  216. if (ret < 0) {
  217. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  218. return ret;
  219. }
  220. dst = pkt->data;
  221. for (i = 0; i < nnal; i++) {
  222. memcpy(dst, nal[i].payload, nal[i].sizeBytes);
  223. dst += nal[i].sizeBytes;
  224. if (is_keyframe(nal[i].type))
  225. pkt->flags |= AV_PKT_FLAG_KEY;
  226. }
  227. pkt->pts = x265pic_out.pts;
  228. pkt->dts = x265pic_out.dts;
  229. *got_packet = 1;
  230. return 0;
  231. }
  232. static const enum AVPixelFormat x265_csp_eight[] = {
  233. AV_PIX_FMT_YUV420P,
  234. AV_PIX_FMT_YUV422P,
  235. AV_PIX_FMT_YUV444P,
  236. AV_PIX_FMT_NONE
  237. };
  238. static const enum AVPixelFormat x265_csp_twelve[] = {
  239. AV_PIX_FMT_YUV420P,
  240. AV_PIX_FMT_YUV422P,
  241. AV_PIX_FMT_YUV444P,
  242. AV_PIX_FMT_YUV420P10,
  243. AV_PIX_FMT_YUV422P10,
  244. AV_PIX_FMT_YUV444P10,
  245. AV_PIX_FMT_NONE
  246. };
  247. static av_cold void libx265_encode_init_csp(AVCodec *codec)
  248. {
  249. if (x265_max_bit_depth == 8)
  250. codec->pix_fmts = x265_csp_eight;
  251. else if (x265_max_bit_depth == 12)
  252. codec->pix_fmts = x265_csp_twelve;
  253. }
  254. #define OFFSET(x) offsetof(libx265Context, x)
  255. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  256. static const AVOption options[] = {
  257. { "crf", "set the x265 crf", OFFSET(crf), AV_OPT_TYPE_FLOAT, { .dbl = -1 }, -1, FLT_MAX, VE },
  258. { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  259. { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  260. { "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 },
  261. { NULL }
  262. };
  263. static const AVClass class = {
  264. .class_name = "libx265",
  265. .item_name = av_default_item_name,
  266. .option = options,
  267. .version = LIBAVUTIL_VERSION_INT,
  268. };
  269. static const AVCodecDefault x265_defaults[] = {
  270. { "b", "0" },
  271. { NULL },
  272. };
  273. AVCodec ff_libx265_encoder = {
  274. .name = "libx265",
  275. .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
  276. .type = AVMEDIA_TYPE_VIDEO,
  277. .id = AV_CODEC_ID_HEVC,
  278. .init = libx265_encode_init,
  279. .init_static_data = libx265_encode_init_csp,
  280. .encode2 = libx265_encode_frame,
  281. .close = libx265_encode_close,
  282. .priv_data_size = sizeof(libx265Context),
  283. .priv_class = &class,
  284. .defaults = x265_defaults,
  285. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
  286. };