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.

708 lines
24KB

  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. #include "packet_internal.h"
  34. typedef struct libx265Context {
  35. const AVClass *class;
  36. x265_encoder *encoder;
  37. x265_param *params;
  38. const x265_api *api;
  39. float crf;
  40. int cqp;
  41. int forced_idr;
  42. char *preset;
  43. char *tune;
  44. char *profile;
  45. AVDictionary *x265_opts;
  46. /**
  47. * If the encoder does not support ROI then warn the first time we
  48. * encounter a frame with ROI side data.
  49. */
  50. int roi_warned;
  51. } libx265Context;
  52. static int is_keyframe(NalUnitType naltype)
  53. {
  54. switch (naltype) {
  55. case NAL_UNIT_CODED_SLICE_BLA_W_LP:
  56. case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
  57. case NAL_UNIT_CODED_SLICE_BLA_N_LP:
  58. case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
  59. case NAL_UNIT_CODED_SLICE_IDR_N_LP:
  60. case NAL_UNIT_CODED_SLICE_CRA:
  61. return 1;
  62. default:
  63. return 0;
  64. }
  65. }
  66. static av_cold int libx265_encode_close(AVCodecContext *avctx)
  67. {
  68. libx265Context *ctx = avctx->priv_data;
  69. ctx->api->param_free(ctx->params);
  70. if (ctx->encoder)
  71. ctx->api->encoder_close(ctx->encoder);
  72. return 0;
  73. }
  74. static av_cold int libx265_param_parse_float(AVCodecContext *avctx,
  75. const char *key, float value)
  76. {
  77. libx265Context *ctx = avctx->priv_data;
  78. char buf[256];
  79. snprintf(buf, sizeof(buf), "%2.2f", value);
  80. if (ctx->api->param_parse(ctx->params, key, buf) == X265_PARAM_BAD_VALUE) {
  81. av_log(avctx, AV_LOG_ERROR, "Invalid value %2.2f for param \"%s\".\n", value, key);
  82. return AVERROR(EINVAL);
  83. }
  84. return 0;
  85. }
  86. static av_cold int libx265_param_parse_int(AVCodecContext *avctx,
  87. const char *key, int value)
  88. {
  89. libx265Context *ctx = avctx->priv_data;
  90. char buf[256];
  91. snprintf(buf, sizeof(buf), "%d", value);
  92. if (ctx->api->param_parse(ctx->params, key, buf) == X265_PARAM_BAD_VALUE) {
  93. av_log(avctx, AV_LOG_ERROR, "Invalid value %d for param \"%s\".\n", value, key);
  94. return AVERROR(EINVAL);
  95. }
  96. return 0;
  97. }
  98. static av_cold int libx265_encode_init(AVCodecContext *avctx)
  99. {
  100. libx265Context *ctx = avctx->priv_data;
  101. AVCPBProperties *cpb_props = NULL;
  102. int ret;
  103. ctx->api = x265_api_get(av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth);
  104. if (!ctx->api)
  105. ctx->api = x265_api_get(0);
  106. ctx->params = ctx->api->param_alloc();
  107. if (!ctx->params) {
  108. av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
  109. return AVERROR(ENOMEM);
  110. }
  111. if (ctx->api->param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
  112. int i;
  113. av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", ctx->preset, ctx->tune);
  114. av_log(avctx, AV_LOG_INFO, "Possible presets:");
  115. for (i = 0; x265_preset_names[i]; i++)
  116. av_log(avctx, AV_LOG_INFO, " %s", x265_preset_names[i]);
  117. av_log(avctx, AV_LOG_INFO, "\n");
  118. av_log(avctx, AV_LOG_INFO, "Possible tunes:");
  119. for (i = 0; x265_tune_names[i]; i++)
  120. av_log(avctx, AV_LOG_INFO, " %s", x265_tune_names[i]);
  121. av_log(avctx, AV_LOG_INFO, "\n");
  122. return AVERROR(EINVAL);
  123. }
  124. ctx->params->frameNumThreads = avctx->thread_count;
  125. if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  126. ctx->params->fpsNum = avctx->framerate.num;
  127. ctx->params->fpsDenom = avctx->framerate.den;
  128. } else {
  129. ctx->params->fpsNum = avctx->time_base.den;
  130. ctx->params->fpsDenom = avctx->time_base.num * avctx->ticks_per_frame;
  131. }
  132. ctx->params->sourceWidth = avctx->width;
  133. ctx->params->sourceHeight = avctx->height;
  134. ctx->params->bEnablePsnr = !!(avctx->flags & AV_CODEC_FLAG_PSNR);
  135. ctx->params->bOpenGOP = !(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
  136. /* Tune the CTU size based on input resolution. */
  137. if (ctx->params->sourceWidth < 64 || ctx->params->sourceHeight < 64)
  138. ctx->params->maxCUSize = 32;
  139. if (ctx->params->sourceWidth < 32 || ctx->params->sourceHeight < 32)
  140. ctx->params->maxCUSize = 16;
  141. if (ctx->params->sourceWidth < 16 || ctx->params->sourceHeight < 16) {
  142. av_log(avctx, AV_LOG_ERROR, "Image size is too small (%dx%d).\n",
  143. ctx->params->sourceWidth, ctx->params->sourceHeight);
  144. return AVERROR(EINVAL);
  145. }
  146. ctx->params->vui.bEnableVideoSignalTypePresentFlag = 1;
  147. ctx->params->vui.bEnableVideoFullRangeFlag = avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
  148. avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
  149. avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
  150. avctx->color_range == AVCOL_RANGE_JPEG;
  151. if ((avctx->color_primaries <= AVCOL_PRI_SMPTE432 &&
  152. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED) ||
  153. (avctx->color_trc <= AVCOL_TRC_ARIB_STD_B67 &&
  154. avctx->color_trc != AVCOL_TRC_UNSPECIFIED) ||
  155. (avctx->colorspace <= AVCOL_SPC_ICTCP &&
  156. avctx->colorspace != AVCOL_SPC_UNSPECIFIED)) {
  157. ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
  158. // x265 validates the parameters internally
  159. ctx->params->vui.colorPrimaries = avctx->color_primaries;
  160. ctx->params->vui.transferCharacteristics = avctx->color_trc;
  161. #if X265_BUILD >= 159
  162. if (avctx->color_trc == AVCOL_TRC_ARIB_STD_B67)
  163. ctx->params->preferredTransferCharacteristics = ctx->params->vui.transferCharacteristics;
  164. #endif
  165. ctx->params->vui.matrixCoeffs = avctx->colorspace;
  166. }
  167. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  168. char sar[12];
  169. int sar_num, sar_den;
  170. av_reduce(&sar_num, &sar_den,
  171. avctx->sample_aspect_ratio.num,
  172. avctx->sample_aspect_ratio.den, 65535);
  173. snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);
  174. if (ctx->api->param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {
  175. av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);
  176. return AVERROR_INVALIDDATA;
  177. }
  178. }
  179. switch (avctx->pix_fmt) {
  180. case AV_PIX_FMT_YUV420P:
  181. case AV_PIX_FMT_YUV420P10:
  182. case AV_PIX_FMT_YUV420P12:
  183. ctx->params->internalCsp = X265_CSP_I420;
  184. break;
  185. case AV_PIX_FMT_YUV422P:
  186. case AV_PIX_FMT_YUV422P10:
  187. case AV_PIX_FMT_YUV422P12:
  188. ctx->params->internalCsp = X265_CSP_I422;
  189. break;
  190. case AV_PIX_FMT_GBRP:
  191. case AV_PIX_FMT_GBRP10:
  192. case AV_PIX_FMT_GBRP12:
  193. ctx->params->vui.matrixCoeffs = AVCOL_SPC_RGB;
  194. ctx->params->vui.bEnableVideoSignalTypePresentFlag = 1;
  195. ctx->params->vui.bEnableColorDescriptionPresentFlag = 1;
  196. case AV_PIX_FMT_YUV444P:
  197. case AV_PIX_FMT_YUV444P10:
  198. case AV_PIX_FMT_YUV444P12:
  199. ctx->params->internalCsp = X265_CSP_I444;
  200. break;
  201. case AV_PIX_FMT_GRAY8:
  202. case AV_PIX_FMT_GRAY10:
  203. case AV_PIX_FMT_GRAY12:
  204. if (ctx->api->api_build_number < 85) {
  205. av_log(avctx, AV_LOG_ERROR,
  206. "libx265 version is %d, must be at least 85 for gray encoding.\n",
  207. ctx->api->api_build_number);
  208. return AVERROR_INVALIDDATA;
  209. }
  210. ctx->params->internalCsp = X265_CSP_I400;
  211. break;
  212. }
  213. if (ctx->crf >= 0) {
  214. char crf[6];
  215. snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
  216. if (ctx->api->param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
  217. av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
  218. return AVERROR(EINVAL);
  219. }
  220. } else if (avctx->bit_rate > 0) {
  221. ctx->params->rc.bitrate = avctx->bit_rate / 1000;
  222. ctx->params->rc.rateControlMode = X265_RC_ABR;
  223. } else if (ctx->cqp >= 0) {
  224. ret = libx265_param_parse_int(avctx, "qp", ctx->cqp);
  225. if (ret < 0)
  226. return ret;
  227. }
  228. #if X265_BUILD >= 89
  229. if (avctx->qmin >= 0) {
  230. ret = libx265_param_parse_int(avctx, "qpmin", avctx->qmin);
  231. if (ret < 0)
  232. return ret;
  233. }
  234. if (avctx->qmax >= 0) {
  235. ret = libx265_param_parse_int(avctx, "qpmax", avctx->qmax);
  236. if (ret < 0)
  237. return ret;
  238. }
  239. #endif
  240. if (avctx->max_qdiff >= 0) {
  241. ret = libx265_param_parse_int(avctx, "qpstep", avctx->max_qdiff);
  242. if (ret < 0)
  243. return ret;
  244. }
  245. if (avctx->qblur >= 0) {
  246. ret = libx265_param_parse_float(avctx, "qblur", avctx->qblur);
  247. if (ret < 0)
  248. return ret;
  249. }
  250. if (avctx->qcompress >= 0) {
  251. ret = libx265_param_parse_float(avctx, "qcomp", avctx->qcompress);
  252. if (ret < 0)
  253. return ret;
  254. }
  255. if (avctx->i_quant_factor >= 0) {
  256. ret = libx265_param_parse_float(avctx, "ipratio", avctx->i_quant_factor);
  257. if (ret < 0)
  258. return ret;
  259. }
  260. if (avctx->b_quant_factor >= 0) {
  261. ret = libx265_param_parse_float(avctx, "pbratio", avctx->b_quant_factor);
  262. if (ret < 0)
  263. return ret;
  264. }
  265. ctx->params->rc.vbvBufferSize = avctx->rc_buffer_size / 1000;
  266. ctx->params->rc.vbvMaxBitrate = avctx->rc_max_rate / 1000;
  267. cpb_props = ff_add_cpb_side_data(avctx);
  268. if (!cpb_props)
  269. return AVERROR(ENOMEM);
  270. cpb_props->buffer_size = ctx->params->rc.vbvBufferSize * 1000;
  271. cpb_props->max_bitrate = ctx->params->rc.vbvMaxBitrate * 1000LL;
  272. cpb_props->avg_bitrate = ctx->params->rc.bitrate * 1000LL;
  273. if (!(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
  274. ctx->params->bRepeatHeaders = 1;
  275. if (avctx->gop_size >= 0) {
  276. ret = libx265_param_parse_int(avctx, "keyint", avctx->gop_size);
  277. if (ret < 0)
  278. return ret;
  279. }
  280. if (avctx->keyint_min > 0) {
  281. ret = libx265_param_parse_int(avctx, "min-keyint", avctx->keyint_min);
  282. if (ret < 0)
  283. return ret;
  284. }
  285. if (avctx->max_b_frames >= 0) {
  286. ret = libx265_param_parse_int(avctx, "bframes", avctx->max_b_frames);
  287. if (ret < 0)
  288. return ret;
  289. }
  290. if (avctx->refs >= 0) {
  291. ret = libx265_param_parse_int(avctx, "ref", avctx->refs);
  292. if (ret < 0)
  293. return ret;
  294. }
  295. {
  296. AVDictionaryEntry *en = NULL;
  297. while ((en = av_dict_get(ctx->x265_opts, "", en, AV_DICT_IGNORE_SUFFIX))) {
  298. int parse_ret = ctx->api->param_parse(ctx->params, en->key, en->value);
  299. switch (parse_ret) {
  300. case X265_PARAM_BAD_NAME:
  301. av_log(avctx, AV_LOG_WARNING,
  302. "Unknown option: %s.\n", en->key);
  303. break;
  304. case X265_PARAM_BAD_VALUE:
  305. av_log(avctx, AV_LOG_WARNING,
  306. "Invalid value for %s: %s.\n", en->key, en->value);
  307. break;
  308. default:
  309. break;
  310. }
  311. }
  312. }
  313. if (ctx->params->rc.vbvBufferSize && avctx->rc_initial_buffer_occupancy > 1000 &&
  314. ctx->params->rc.vbvBufferInit == 0.9) {
  315. ctx->params->rc.vbvBufferInit = (float)avctx->rc_initial_buffer_occupancy / 1000;
  316. }
  317. if (ctx->profile) {
  318. if (ctx->api->param_apply_profile(ctx->params, ctx->profile) < 0) {
  319. int i;
  320. av_log(avctx, AV_LOG_ERROR, "Invalid or incompatible profile set: %s.\n", ctx->profile);
  321. av_log(avctx, AV_LOG_INFO, "Possible profiles:");
  322. for (i = 0; x265_profile_names[i]; i++)
  323. av_log(avctx, AV_LOG_INFO, " %s", x265_profile_names[i]);
  324. av_log(avctx, AV_LOG_INFO, "\n");
  325. return AVERROR(EINVAL);
  326. }
  327. }
  328. ctx->encoder = ctx->api->encoder_open(ctx->params);
  329. if (!ctx->encoder) {
  330. av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
  331. libx265_encode_close(avctx);
  332. return AVERROR_INVALIDDATA;
  333. }
  334. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  335. x265_nal *nal;
  336. int nnal;
  337. avctx->extradata_size = ctx->api->encoder_headers(ctx->encoder, &nal, &nnal);
  338. if (avctx->extradata_size <= 0) {
  339. av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
  340. libx265_encode_close(avctx);
  341. return AVERROR_INVALIDDATA;
  342. }
  343. avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  344. if (!avctx->extradata) {
  345. av_log(avctx, AV_LOG_ERROR,
  346. "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);
  347. libx265_encode_close(avctx);
  348. return AVERROR(ENOMEM);
  349. }
  350. memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);
  351. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  352. }
  353. return 0;
  354. }
  355. static av_cold int libx265_encode_set_roi(libx265Context *ctx, const AVFrame *frame, x265_picture* pic)
  356. {
  357. AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
  358. if (sd) {
  359. if (ctx->params->rc.aqMode == X265_AQ_NONE) {
  360. if (!ctx->roi_warned) {
  361. ctx->roi_warned = 1;
  362. av_log(ctx, AV_LOG_WARNING, "Adaptive quantization must be enabled to use ROI encoding, skipping ROI.\n");
  363. }
  364. } else {
  365. /* 8x8 block when qg-size is 8, 16*16 block otherwise. */
  366. int mb_size = (ctx->params->rc.qgSize == 8) ? 8 : 16;
  367. int mbx = (frame->width + mb_size - 1) / mb_size;
  368. int mby = (frame->height + mb_size - 1) / mb_size;
  369. int qp_range = 51 + 6 * (pic->bitDepth - 8);
  370. int nb_rois;
  371. const AVRegionOfInterest *roi;
  372. uint32_t roi_size;
  373. float *qoffsets; /* will be freed after encode is called. */
  374. roi = (const AVRegionOfInterest*)sd->data;
  375. roi_size = roi->self_size;
  376. if (!roi_size || sd->size % roi_size != 0) {
  377. av_log(ctx, AV_LOG_ERROR, "Invalid AVRegionOfInterest.self_size.\n");
  378. return AVERROR(EINVAL);
  379. }
  380. nb_rois = sd->size / roi_size;
  381. qoffsets = av_mallocz_array(mbx * mby, sizeof(*qoffsets));
  382. if (!qoffsets)
  383. return AVERROR(ENOMEM);
  384. // This list must be iterated in reverse because the first
  385. // region in the list applies when regions overlap.
  386. for (int i = nb_rois - 1; i >= 0; i--) {
  387. int startx, endx, starty, endy;
  388. float qoffset;
  389. roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
  390. starty = FFMIN(mby, roi->top / mb_size);
  391. endy = FFMIN(mby, (roi->bottom + mb_size - 1)/ mb_size);
  392. startx = FFMIN(mbx, roi->left / mb_size);
  393. endx = FFMIN(mbx, (roi->right + mb_size - 1)/ mb_size);
  394. if (roi->qoffset.den == 0) {
  395. av_free(qoffsets);
  396. av_log(ctx, AV_LOG_ERROR, "AVRegionOfInterest.qoffset.den must not be zero.\n");
  397. return AVERROR(EINVAL);
  398. }
  399. qoffset = roi->qoffset.num * 1.0f / roi->qoffset.den;
  400. qoffset = av_clipf(qoffset * qp_range, -qp_range, +qp_range);
  401. for (int y = starty; y < endy; y++)
  402. for (int x = startx; x < endx; x++)
  403. qoffsets[x + y*mbx] = qoffset;
  404. }
  405. pic->quantOffsets = qoffsets;
  406. }
  407. }
  408. return 0;
  409. }
  410. static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  411. const AVFrame *pic, int *got_packet)
  412. {
  413. libx265Context *ctx = avctx->priv_data;
  414. x265_picture x265pic;
  415. x265_picture x265pic_out = { 0 };
  416. x265_nal *nal;
  417. uint8_t *dst;
  418. int pict_type;
  419. int payload = 0;
  420. int nnal;
  421. int ret;
  422. int i;
  423. ctx->api->picture_init(ctx->params, &x265pic);
  424. if (pic) {
  425. for (i = 0; i < 3; i++) {
  426. x265pic.planes[i] = pic->data[i];
  427. x265pic.stride[i] = pic->linesize[i];
  428. }
  429. x265pic.pts = pic->pts;
  430. x265pic.bitDepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth;
  431. x265pic.sliceType = pic->pict_type == AV_PICTURE_TYPE_I ?
  432. (ctx->forced_idr ? X265_TYPE_IDR : X265_TYPE_I) :
  433. pic->pict_type == AV_PICTURE_TYPE_P ? X265_TYPE_P :
  434. pic->pict_type == AV_PICTURE_TYPE_B ? X265_TYPE_B :
  435. X265_TYPE_AUTO;
  436. ret = libx265_encode_set_roi(ctx, pic, &x265pic);
  437. if (ret < 0)
  438. return ret;
  439. if (pic->reordered_opaque) {
  440. x265pic.userData = av_malloc(sizeof(pic->reordered_opaque));
  441. if (!x265pic.userData) {
  442. av_freep(&x265pic.quantOffsets);
  443. return AVERROR(ENOMEM);
  444. }
  445. memcpy(x265pic.userData, &pic->reordered_opaque, sizeof(pic->reordered_opaque));
  446. }
  447. }
  448. ret = ctx->api->encoder_encode(ctx->encoder, &nal, &nnal,
  449. pic ? &x265pic : NULL, &x265pic_out);
  450. av_freep(&x265pic.quantOffsets);
  451. if (ret < 0)
  452. return AVERROR_EXTERNAL;
  453. if (!nnal)
  454. return 0;
  455. for (i = 0; i < nnal; i++)
  456. payload += nal[i].sizeBytes;
  457. ret = ff_alloc_packet2(avctx, pkt, payload, payload);
  458. if (ret < 0) {
  459. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  460. return ret;
  461. }
  462. dst = pkt->data;
  463. for (i = 0; i < nnal; i++) {
  464. memcpy(dst, nal[i].payload, nal[i].sizeBytes);
  465. dst += nal[i].sizeBytes;
  466. if (is_keyframe(nal[i].type))
  467. pkt->flags |= AV_PKT_FLAG_KEY;
  468. }
  469. pkt->pts = x265pic_out.pts;
  470. pkt->dts = x265pic_out.dts;
  471. switch (x265pic_out.sliceType) {
  472. case X265_TYPE_IDR:
  473. case X265_TYPE_I:
  474. pict_type = AV_PICTURE_TYPE_I;
  475. break;
  476. case X265_TYPE_P:
  477. pict_type = AV_PICTURE_TYPE_P;
  478. break;
  479. case X265_TYPE_B:
  480. case X265_TYPE_BREF:
  481. pict_type = AV_PICTURE_TYPE_B;
  482. break;
  483. default:
  484. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered.\n");
  485. return AVERROR_EXTERNAL;
  486. }
  487. #if FF_API_CODED_FRAME
  488. FF_DISABLE_DEPRECATION_WARNINGS
  489. avctx->coded_frame->pict_type = pict_type;
  490. FF_ENABLE_DEPRECATION_WARNINGS
  491. #endif
  492. #if X265_BUILD >= 130
  493. if (x265pic_out.sliceType == X265_TYPE_B)
  494. #else
  495. if (x265pic_out.frameData.sliceType == 'b')
  496. #endif
  497. pkt->flags |= AV_PKT_FLAG_DISPOSABLE;
  498. ff_side_data_set_encoder_stats(pkt, x265pic_out.frameData.qp * FF_QP2LAMBDA, NULL, 0, pict_type);
  499. if (x265pic_out.userData) {
  500. memcpy(&avctx->reordered_opaque, x265pic_out.userData, sizeof(avctx->reordered_opaque));
  501. av_freep(&x265pic_out.userData);
  502. } else
  503. avctx->reordered_opaque = 0;
  504. *got_packet = 1;
  505. return 0;
  506. }
  507. static const enum AVPixelFormat x265_csp_eight[] = {
  508. AV_PIX_FMT_YUV420P,
  509. AV_PIX_FMT_YUVJ420P,
  510. AV_PIX_FMT_YUV422P,
  511. AV_PIX_FMT_YUVJ422P,
  512. AV_PIX_FMT_YUV444P,
  513. AV_PIX_FMT_YUVJ444P,
  514. AV_PIX_FMT_GBRP,
  515. AV_PIX_FMT_GRAY8,
  516. AV_PIX_FMT_NONE
  517. };
  518. static const enum AVPixelFormat x265_csp_ten[] = {
  519. AV_PIX_FMT_YUV420P,
  520. AV_PIX_FMT_YUVJ420P,
  521. AV_PIX_FMT_YUV422P,
  522. AV_PIX_FMT_YUVJ422P,
  523. AV_PIX_FMT_YUV444P,
  524. AV_PIX_FMT_YUVJ444P,
  525. AV_PIX_FMT_GBRP,
  526. AV_PIX_FMT_YUV420P10,
  527. AV_PIX_FMT_YUV422P10,
  528. AV_PIX_FMT_YUV444P10,
  529. AV_PIX_FMT_GBRP10,
  530. AV_PIX_FMT_GRAY8,
  531. AV_PIX_FMT_GRAY10,
  532. AV_PIX_FMT_NONE
  533. };
  534. static const enum AVPixelFormat x265_csp_twelve[] = {
  535. AV_PIX_FMT_YUV420P,
  536. AV_PIX_FMT_YUVJ420P,
  537. AV_PIX_FMT_YUV422P,
  538. AV_PIX_FMT_YUVJ422P,
  539. AV_PIX_FMT_YUV444P,
  540. AV_PIX_FMT_YUVJ444P,
  541. AV_PIX_FMT_GBRP,
  542. AV_PIX_FMT_YUV420P10,
  543. AV_PIX_FMT_YUV422P10,
  544. AV_PIX_FMT_YUV444P10,
  545. AV_PIX_FMT_GBRP10,
  546. AV_PIX_FMT_YUV420P12,
  547. AV_PIX_FMT_YUV422P12,
  548. AV_PIX_FMT_YUV444P12,
  549. AV_PIX_FMT_GBRP12,
  550. AV_PIX_FMT_GRAY8,
  551. AV_PIX_FMT_GRAY10,
  552. AV_PIX_FMT_GRAY12,
  553. AV_PIX_FMT_NONE
  554. };
  555. static av_cold void libx265_encode_init_csp(AVCodec *codec)
  556. {
  557. if (x265_api_get(12))
  558. codec->pix_fmts = x265_csp_twelve;
  559. else if (x265_api_get(10))
  560. codec->pix_fmts = x265_csp_ten;
  561. else if (x265_api_get(8))
  562. codec->pix_fmts = x265_csp_eight;
  563. }
  564. #define OFFSET(x) offsetof(libx265Context, x)
  565. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  566. static const AVOption options[] = {
  567. { "crf", "set the x265 crf", OFFSET(crf), AV_OPT_TYPE_FLOAT, { .dbl = -1 }, -1, FLT_MAX, VE },
  568. { "qp", "set the x265 qp", OFFSET(cqp), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE },
  569. { "forced-idr", "if forcing keyframes, force them as IDR frames", OFFSET(forced_idr),AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  570. { "preset", "set the x265 preset", OFFSET(preset), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  571. { "tune", "set the x265 tune parameter", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  572. { "profile", "set the x265 profile", OFFSET(profile), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
  573. { "x265-params", "set the x265 configuration using a :-separated list of key=value parameters", OFFSET(x265_opts), AV_OPT_TYPE_DICT, { 0 }, 0, 0, VE },
  574. { NULL }
  575. };
  576. static const AVClass class = {
  577. .class_name = "libx265",
  578. .item_name = av_default_item_name,
  579. .option = options,
  580. .version = LIBAVUTIL_VERSION_INT,
  581. };
  582. static const AVCodecDefault x265_defaults[] = {
  583. { "b", "0" },
  584. { "bf", "-1" },
  585. { "g", "-1" },
  586. { "keyint_min", "-1" },
  587. { "refs", "-1" },
  588. { "qmin", "-1" },
  589. { "qmax", "-1" },
  590. { "qdiff", "-1" },
  591. { "qblur", "-1" },
  592. { "qcomp", "-1" },
  593. { "i_qfactor", "-1" },
  594. { "b_qfactor", "-1" },
  595. { NULL },
  596. };
  597. AVCodec ff_libx265_encoder = {
  598. .name = "libx265",
  599. .long_name = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
  600. .type = AVMEDIA_TYPE_VIDEO,
  601. .id = AV_CODEC_ID_HEVC,
  602. .init = libx265_encode_init,
  603. .init_static_data = libx265_encode_init_csp,
  604. .encode2 = libx265_encode_frame,
  605. .close = libx265_encode_close,
  606. .priv_data_size = sizeof(libx265Context),
  607. .priv_class = &class,
  608. .defaults = x265_defaults,
  609. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_OTHER_THREADS |
  610. AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
  611. .caps_internal = FF_CODEC_CAP_AUTO_THREADS,
  612. .wrapper_name = "libx265",
  613. };