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.

332 lines
9.8KB

  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. #include <x265.h>
  23. #include "libavutil/internal.h"
  24. #include "libavutil/common.h"
  25. #include "libavutil/opt.h"
  26. #include "libavutil/pixdesc.h"
  27. #include "avcodec.h"
  28. #include "internal.h"
  29. #if defined(_MSC_VER)
  30. #define X265_API_IMPORTS 1
  31. #endif
  32. typedef struct libx265Context {
  33. const AVClass *class;
  34. x265_encoder *encoder;
  35. x265_param *params;
  36. uint8_t *header;
  37. int header_size;
  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. av_freep(&ctx->header);
  61. x265_param_free(ctx->params);
  62. if (ctx->encoder)
  63. x265_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. x265_nal *nal;
  70. int sar_num, sar_den;
  71. int nnal;
  72. int ret;
  73. int i;
  74. if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL &&
  75. !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_w &&
  76. !av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h) {
  77. av_log(avctx, AV_LOG_ERROR,
  78. "4:4:4 support is not fully defined for HEVC yet. "
  79. "Set -strict experimental to encode anyway.\n");
  80. return AVERROR(ENOSYS);
  81. }
  82. avctx->coded_frame = av_frame_alloc();
  83. if (!avctx->coded_frame) {
  84. av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
  85. return AVERROR(ENOMEM);
  86. }
  87. ctx->params = x265_param_alloc();
  88. if (!ctx->params) {
  89. av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
  90. return AVERROR(ENOMEM);
  91. }
  92. if (x265_param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
  93. av_log(avctx, AV_LOG_ERROR, "Invalid preset or tune.\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. av_reduce(&sar_num, &sar_den,
  102. avctx->sample_aspect_ratio.num,
  103. avctx->sample_aspect_ratio.den, 4096);
  104. ctx->params->vui.bEnableVuiParametersPresentFlag = 1;
  105. ctx->params->vui.bEnableAspectRatioIdc = 1;
  106. ctx->params->vui.aspectRatioIdc = 255;
  107. ctx->params->vui.sarWidth = sar_num;
  108. ctx->params->vui.sarHeight = sar_den;
  109. if (x265_max_bit_depth == 8)
  110. ctx->params->internalBitDepth = 8;
  111. else if (x265_max_bit_depth == 12)
  112. ctx->params->internalBitDepth = 10;
  113. switch (avctx->pix_fmt) {
  114. case AV_PIX_FMT_YUV420P:
  115. case AV_PIX_FMT_YUV420P10:
  116. ctx->params->internalCsp = X265_CSP_I420;
  117. break;
  118. case AV_PIX_FMT_YUV444P:
  119. case AV_PIX_FMT_YUV444P10:
  120. ctx->params->internalCsp = X265_CSP_I444;
  121. break;
  122. }
  123. if (avctx->bit_rate > 0) {
  124. ctx->params->rc.bitrate = avctx->bit_rate / 1000;
  125. ctx->params->rc.rateControlMode = X265_RC_ABR;
  126. }
  127. if (ctx->x265_opts) {
  128. AVDictionary *dict = NULL;
  129. AVDictionaryEntry *en = NULL;
  130. if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
  131. while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
  132. int parse_ret = x265_param_parse(ctx->params, en->key, en->value);
  133. switch (parse_ret) {
  134. case X265_PARAM_BAD_NAME:
  135. av_log(avctx, AV_LOG_WARNING,
  136. "Unknown option: %s.\n", en->key);
  137. break;
  138. case X265_PARAM_BAD_VALUE:
  139. av_log(avctx, AV_LOG_WARNING,
  140. "Invalid value for %s: %s.\n", en->key, en->value);
  141. break;
  142. default:
  143. break;
  144. }
  145. }
  146. av_dict_free(&dict);
  147. }
  148. }
  149. ctx->encoder = x265_encoder_open(ctx->params);
  150. if (!ctx->encoder) {
  151. av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
  152. libx265_encode_close(avctx);
  153. return AVERROR_INVALIDDATA;
  154. }
  155. ret = x265_encoder_headers(ctx->encoder, &nal, &nnal);
  156. if (ret < 0) {
  157. av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
  158. libx265_encode_close(avctx);
  159. return AVERROR_INVALIDDATA;
  160. }
  161. for (i = 0; i < nnal; i++)
  162. ctx->header_size += nal[i].sizeBytes;
  163. ctx->header = av_malloc(ctx->header_size + FF_INPUT_BUFFER_PADDING_SIZE);
  164. if (!ctx->header) {
  165. av_log(avctx, AV_LOG_ERROR,
  166. "Cannot allocate HEVC header of size %d.\n", ctx->header_size);
  167. libx265_encode_close(avctx);
  168. return AVERROR(ENOMEM);
  169. }
  170. memcpy(ctx->header, nal[0].payload, ctx->header_size);
  171. if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
  172. avctx->extradata_size = ctx->header_size;
  173. avctx->extradata = ctx->header;
  174. ctx->header_size = 0;
  175. ctx->header = NULL;
  176. }
  177. return 0;
  178. }
  179. static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  180. const AVFrame *pic, int *got_packet)
  181. {
  182. libx265Context *ctx = avctx->priv_data;
  183. x265_picture x265pic;
  184. x265_picture x265pic_out = { { 0 } };
  185. x265_nal *nal;
  186. uint8_t *dst;
  187. int payload = 0;
  188. int nnal;
  189. int ret;
  190. int i;
  191. x265_picture_init(ctx->params, &x265pic);
  192. if (pic) {
  193. for (i = 0; i < 3; i++) {
  194. x265pic.planes[i] = pic->data[i];
  195. x265pic.stride[i] = pic->linesize[i];
  196. }
  197. x265pic.pts = pic->pts;
  198. x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
  199. }
  200. ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
  201. pic ? &x265pic : NULL, &x265pic_out);
  202. if (ret < 0)
  203. return AVERROR_UNKNOWN;
  204. if (!nnal)
  205. return 0;
  206. for (i = 0; i < nnal; i++)
  207. payload += nal[i].sizeBytes;
  208. payload += ctx->header_size;
  209. ret = ff_alloc_packet(pkt, payload);
  210. if (ret < 0) {
  211. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  212. return ret;
  213. }
  214. dst = pkt->data;
  215. if (ctx->header) {
  216. memcpy(dst, ctx->header, ctx->header_size);
  217. dst += ctx->header_size;
  218. av_freep(&ctx->header);
  219. ctx->header_size = 0;
  220. }
  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_YUV444P,
  235. AV_PIX_FMT_NONE
  236. };
  237. static const enum AVPixelFormat x265_csp_twelve[] = {
  238. AV_PIX_FMT_YUV420P,
  239. AV_PIX_FMT_YUV444P,
  240. AV_PIX_FMT_YUV420P10,
  241. AV_PIX_FMT_YUV444P10,
  242. AV_PIX_FMT_NONE
  243. };
  244. static av_cold void libx265_encode_init_csp(AVCodec *codec)
  245. {
  246. if (x265_max_bit_depth == 8)
  247. codec->pix_fmts = x265_csp_eight;
  248. else if (x265_max_bit_depth == 12)
  249. codec->pix_fmts = x265_csp_twelve;
  250. }
  251. #define OFFSET(x) offsetof(libx265Context, x)
  252. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  253. static const AVOption options[] = {
  254. { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  255. { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  256. { "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 },
  257. { NULL }
  258. };
  259. static const AVClass class = {
  260. .class_name = "libx265",
  261. .item_name = av_default_item_name,
  262. .option = options,
  263. .version = LIBAVUTIL_VERSION_INT,
  264. };
  265. AVCodec ff_libx265_encoder = {
  266. .name = "libx265",
  267. .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
  268. .type = AVMEDIA_TYPE_VIDEO,
  269. .id = AV_CODEC_ID_HEVC,
  270. .init = libx265_encode_init,
  271. .init_static_data = libx265_encode_init_csp,
  272. .encode2 = libx265_encode_frame,
  273. .close = libx265_encode_close,
  274. .priv_data_size = sizeof(libx265Context),
  275. .priv_class = &class,
  276. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
  277. };