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.

320 lines
9.7KB

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