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.

1010 lines
34KB

  1. /*
  2. * Intel MediaSDK QSV encoder utility functions
  3. *
  4. * copyright (c) 2013 Yukinori Yamazoe
  5. * copyright (c) 2015 Anton Khirnov
  6. *
  7. * This file is part of Libav.
  8. *
  9. * Libav is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * Libav is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with Libav; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include <string.h>
  24. #include <sys/types.h>
  25. #include <mfx/mfxvideo.h>
  26. #include "libavutil/common.h"
  27. #include "libavutil/mem.h"
  28. #include "libavutil/log.h"
  29. #include "libavutil/time.h"
  30. #include "libavutil/imgutils.h"
  31. #include "avcodec.h"
  32. #include "internal.h"
  33. #include "qsv.h"
  34. #include "qsv_internal.h"
  35. #include "qsvenc.h"
  36. static const struct {
  37. mfxU16 profile;
  38. const char *name;
  39. } profile_names[] = {
  40. { MFX_PROFILE_AVC_BASELINE, "baseline" },
  41. { MFX_PROFILE_AVC_MAIN, "main" },
  42. { MFX_PROFILE_AVC_EXTENDED, "extended" },
  43. { MFX_PROFILE_AVC_HIGH, "high" },
  44. #if QSV_VERSION_ATLEAST(1, 15)
  45. { MFX_PROFILE_AVC_HIGH_422, "high 422" },
  46. #endif
  47. #if QSV_VERSION_ATLEAST(1, 4)
  48. { MFX_PROFILE_AVC_CONSTRAINED_BASELINE, "constrained baseline" },
  49. { MFX_PROFILE_AVC_CONSTRAINED_HIGH, "constrained high" },
  50. { MFX_PROFILE_AVC_PROGRESSIVE_HIGH, "progressive high" },
  51. #endif
  52. { MFX_PROFILE_MPEG2_SIMPLE, "simple" },
  53. { MFX_PROFILE_MPEG2_MAIN, "main" },
  54. { MFX_PROFILE_MPEG2_HIGH, "high" },
  55. { MFX_PROFILE_VC1_SIMPLE, "simple" },
  56. { MFX_PROFILE_VC1_MAIN, "main" },
  57. { MFX_PROFILE_VC1_ADVANCED, "advanced" },
  58. #if QSV_VERSION_ATLEAST(1, 8)
  59. { MFX_PROFILE_HEVC_MAIN, "main" },
  60. { MFX_PROFILE_HEVC_MAIN10, "main10" },
  61. { MFX_PROFILE_HEVC_MAINSP, "mainsp" },
  62. #endif
  63. };
  64. static const char *print_profile(mfxU16 profile)
  65. {
  66. int i;
  67. for (i = 0; i < FF_ARRAY_ELEMS(profile_names); i++)
  68. if (profile == profile_names[i].profile)
  69. return profile_names[i].name;
  70. return "unknown";
  71. }
  72. static const struct {
  73. mfxU16 rc_mode;
  74. const char *name;
  75. } rc_names[] = {
  76. { MFX_RATECONTROL_CBR, "CBR" },
  77. { MFX_RATECONTROL_VBR, "VBR" },
  78. { MFX_RATECONTROL_CQP, "CQP" },
  79. { MFX_RATECONTROL_AVBR, "AVBR" },
  80. #if QSV_HAVE_LA
  81. { MFX_RATECONTROL_LA, "LA" },
  82. #endif
  83. #if QSV_HAVE_ICQ
  84. { MFX_RATECONTROL_ICQ, "ICQ" },
  85. { MFX_RATECONTROL_LA_ICQ, "LA_ICQ" },
  86. #endif
  87. #if QSV_HAVE_VCM
  88. { MFX_RATECONTROL_VCM, "VCM" },
  89. #endif
  90. #if QSV_VERSION_ATLEAST(1, 10)
  91. { MFX_RATECONTROL_LA_EXT, "LA_EXT" },
  92. #endif
  93. #if QSV_HAVE_LA_HRD
  94. { MFX_RATECONTROL_LA_HRD, "LA_HRD" },
  95. #endif
  96. #if QSV_HAVE_QVBR
  97. { MFX_RATECONTROL_QVBR, "QVBR" },
  98. #endif
  99. };
  100. static const char *print_ratecontrol(mfxU16 rc_mode)
  101. {
  102. int i;
  103. for (i = 0; i < FF_ARRAY_ELEMS(rc_names); i++)
  104. if (rc_mode == rc_names[i].rc_mode)
  105. return rc_names[i].name;
  106. return "unknown";
  107. }
  108. static const char *print_threestate(mfxU16 val)
  109. {
  110. if (val == MFX_CODINGOPTION_ON)
  111. return "ON";
  112. else if (val == MFX_CODINGOPTION_OFF)
  113. return "OFF";
  114. return "unknown";
  115. }
  116. static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
  117. mfxExtBuffer **coding_opts)
  118. {
  119. mfxInfoMFX *info = &q->param.mfx;
  120. mfxExtCodingOption *co = (mfxExtCodingOption*)coding_opts[0];
  121. #if QSV_HAVE_CO2
  122. mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[1];
  123. #endif
  124. #if QSV_HAVE_CO3
  125. mfxExtCodingOption3 *co3 = (mfxExtCodingOption3*)coding_opts[2];
  126. #endif
  127. av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
  128. print_profile(info->CodecProfile), info->CodecLevel);
  129. av_log(avctx, AV_LOG_VERBOSE, "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag: ",
  130. info->GopPicSize, info->GopRefDist);
  131. if (info->GopOptFlag & MFX_GOP_CLOSED)
  132. av_log(avctx, AV_LOG_VERBOSE, "closed ");
  133. if (info->GopOptFlag & MFX_GOP_STRICT)
  134. av_log(avctx, AV_LOG_VERBOSE, "strict ");
  135. av_log(avctx, AV_LOG_VERBOSE, "; IdrInterval: %"PRIu16"\n", info->IdrInterval);
  136. av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
  137. info->TargetUsage, print_ratecontrol(info->RateControlMethod));
  138. if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
  139. info->RateControlMethod == MFX_RATECONTROL_VBR
  140. #if QSV_HAVE_VCM
  141. || info->RateControlMethod == MFX_RATECONTROL_VCM
  142. #endif
  143. ) {
  144. av_log(avctx, AV_LOG_VERBOSE,
  145. "InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"\n",
  146. info->InitialDelayInKB, info->TargetKbps, info->MaxKbps);
  147. } else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
  148. av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
  149. info->QPI, info->QPP, info->QPB);
  150. } else if (info->RateControlMethod == MFX_RATECONTROL_AVBR) {
  151. av_log(avctx, AV_LOG_VERBOSE,
  152. "TargetKbps: %"PRIu16"; Accuracy: %"PRIu16"; Convergence: %"PRIu16"\n",
  153. info->TargetKbps, info->Accuracy, info->Convergence);
  154. }
  155. #if QSV_HAVE_LA
  156. else if (info->RateControlMethod == MFX_RATECONTROL_LA
  157. #if QSV_HAVE_LA_HRD
  158. || info->RateControlMethod == MFX_RATECONTROL_LA_HRD
  159. #endif
  160. ) {
  161. av_log(avctx, AV_LOG_VERBOSE,
  162. "TargetKbps: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
  163. info->TargetKbps, co2->LookAheadDepth);
  164. }
  165. #endif
  166. #if QSV_HAVE_ICQ
  167. else if (info->RateControlMethod == MFX_RATECONTROL_ICQ) {
  168. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
  169. } else if (info->RateControlMethod == MFX_RATECONTROL_LA_ICQ) {
  170. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
  171. info->ICQQuality, co2->LookAheadDepth);
  172. }
  173. #endif
  174. #if QSV_HAVE_QVBR
  175. else if (info->RateControlMethod == MFX_RATECONTROL_QVBR) {
  176. av_log(avctx, AV_LOG_VERBOSE, "QVBRQuality: %"PRIu16"\n",
  177. co3->QVBRQuality);
  178. }
  179. #endif
  180. av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
  181. info->NumSlice, info->NumRefFrame);
  182. av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
  183. print_threestate(co->RateDistortionOpt));
  184. #if QSV_HAVE_CO2
  185. av_log(avctx, AV_LOG_VERBOSE,
  186. "RecoveryPointSEI: %s IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
  187. print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
  188. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %"PRIu16"; ", co2->MaxFrameSize);
  189. #if QSV_HAVE_MAX_SLICE_SIZE
  190. av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %"PRIu16"; ", co2->MaxSliceSize);
  191. #endif
  192. av_log(avctx, AV_LOG_VERBOSE, "\n");
  193. av_log(avctx, AV_LOG_VERBOSE,
  194. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  195. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  196. print_threestate(co2->ExtBRC));
  197. #if QSV_HAVE_TRELLIS
  198. av_log(avctx, AV_LOG_VERBOSE, "Trellis: ");
  199. if (co2->Trellis & MFX_TRELLIS_OFF) {
  200. av_log(avctx, AV_LOG_VERBOSE, "off");
  201. } else if (!co2->Trellis) {
  202. av_log(avctx, AV_LOG_VERBOSE, "auto");
  203. } else {
  204. if (co2->Trellis & MFX_TRELLIS_I) av_log(avctx, AV_LOG_VERBOSE, "I");
  205. if (co2->Trellis & MFX_TRELLIS_P) av_log(avctx, AV_LOG_VERBOSE, "P");
  206. if (co2->Trellis & MFX_TRELLIS_B) av_log(avctx, AV_LOG_VERBOSE, "B");
  207. }
  208. av_log(avctx, AV_LOG_VERBOSE, "\n");
  209. #endif
  210. #if QSV_VERSION_ATLEAST(1, 8)
  211. av_log(avctx, AV_LOG_VERBOSE,
  212. "RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: ",
  213. print_threestate(co2->RepeatPPS), co2->NumMbPerSlice);
  214. switch (co2->LookAheadDS) {
  215. case MFX_LOOKAHEAD_DS_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  216. case MFX_LOOKAHEAD_DS_2x: av_log(avctx, AV_LOG_VERBOSE, "2x"); break;
  217. case MFX_LOOKAHEAD_DS_4x: av_log(avctx, AV_LOG_VERBOSE, "4x"); break;
  218. default: av_log(avctx, AV_LOG_VERBOSE, "unknown"); break;
  219. }
  220. av_log(avctx, AV_LOG_VERBOSE, "\n");
  221. av_log(avctx, AV_LOG_VERBOSE, "AdaptiveI: %s; AdaptiveB: %s; BRefType: ",
  222. print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB));
  223. switch (co2->BRefType) {
  224. case MFX_B_REF_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  225. case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "pyramid"); break;
  226. default: av_log(avctx, AV_LOG_VERBOSE, "auto"); break;
  227. }
  228. av_log(avctx, AV_LOG_VERBOSE, "\n");
  229. #endif
  230. #if QSV_VERSION_ATLEAST(1, 9)
  231. av_log(avctx, AV_LOG_VERBOSE,
  232. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  233. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  234. #endif
  235. #endif
  236. if (avctx->codec_id == AV_CODEC_ID_H264) {
  237. av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
  238. co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
  239. av_log(avctx, AV_LOG_VERBOSE,
  240. "NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
  241. print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
  242. print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
  243. }
  244. }
  245. static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
  246. {
  247. const char *rc_desc;
  248. mfxU16 rc_mode;
  249. int want_la = q->la_depth >= 0;
  250. int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  251. int want_vcm = q->vcm;
  252. if (want_la && !QSV_HAVE_LA) {
  253. av_log(avctx, AV_LOG_ERROR,
  254. "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
  255. return AVERROR(ENOSYS);
  256. }
  257. if (want_vcm && !QSV_HAVE_VCM) {
  258. av_log(avctx, AV_LOG_ERROR,
  259. "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
  260. return AVERROR(ENOSYS);
  261. }
  262. if (want_la + want_qscale + want_vcm > 1) {
  263. av_log(avctx, AV_LOG_ERROR,
  264. "More than one of: { constant qscale, lookahead, VCM } requested, "
  265. "only one of them can be used at a time.\n");
  266. return AVERROR(EINVAL);
  267. }
  268. if (want_qscale) {
  269. rc_mode = MFX_RATECONTROL_CQP;
  270. rc_desc = "constant quantization parameter (CQP)";
  271. }
  272. #if QSV_HAVE_VCM
  273. else if (want_vcm) {
  274. rc_mode = MFX_RATECONTROL_VCM;
  275. rc_desc = "video conferencing mode (VCM)";
  276. }
  277. #endif
  278. #if QSV_HAVE_LA
  279. else if (want_la) {
  280. rc_mode = MFX_RATECONTROL_LA;
  281. rc_desc = "VBR with lookahead (LA)";
  282. #if QSV_HAVE_ICQ
  283. if (avctx->global_quality > 0) {
  284. rc_mode = MFX_RATECONTROL_LA_ICQ;
  285. rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
  286. }
  287. #endif
  288. }
  289. #endif
  290. #if QSV_HAVE_ICQ
  291. else if (avctx->global_quality > 0) {
  292. rc_mode = MFX_RATECONTROL_ICQ;
  293. rc_desc = "intelligent constant quality (ICQ)";
  294. }
  295. #endif
  296. else if (avctx->rc_max_rate == avctx->bit_rate) {
  297. rc_mode = MFX_RATECONTROL_CBR;
  298. rc_desc = "constant bitrate (CBR)";
  299. } else if (!avctx->rc_max_rate) {
  300. rc_mode = MFX_RATECONTROL_AVBR;
  301. rc_desc = "average variable bitrate (AVBR)";
  302. } else {
  303. rc_mode = MFX_RATECONTROL_VBR;
  304. rc_desc = "variable bitrate (VBR)";
  305. }
  306. q->param.mfx.RateControlMethod = rc_mode;
  307. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
  308. return 0;
  309. }
  310. static int rc_supported(QSVEncContext *q)
  311. {
  312. mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
  313. mfxStatus ret;
  314. ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
  315. if (ret < 0 ||
  316. param_out.mfx.RateControlMethod != q->param.mfx.RateControlMethod)
  317. return 0;
  318. return 1;
  319. }
  320. static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  321. {
  322. float quant;
  323. int ret;
  324. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  325. if (ret < 0)
  326. return AVERROR_BUG;
  327. q->param.mfx.CodecId = ret;
  328. q->width_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  329. if (avctx->level > 0)
  330. q->param.mfx.CodecLevel = avctx->level;
  331. q->param.mfx.CodecProfile = q->profile;
  332. q->param.mfx.TargetUsage = q->preset;
  333. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  334. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  335. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  336. MFX_GOP_CLOSED : 0;
  337. q->param.mfx.IdrInterval = q->idr_interval;
  338. q->param.mfx.NumSlice = avctx->slices;
  339. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  340. q->param.mfx.EncodedOrder = 0;
  341. q->param.mfx.BufferSizeInKB = 0;
  342. q->param.mfx.FrameInfo.FourCC = MFX_FOURCC_NV12;
  343. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  344. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 32);
  345. q->param.mfx.FrameInfo.CropX = 0;
  346. q->param.mfx.FrameInfo.CropY = 0;
  347. q->param.mfx.FrameInfo.CropW = avctx->width;
  348. q->param.mfx.FrameInfo.CropH = avctx->height;
  349. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  350. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  351. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  352. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  353. q->param.mfx.FrameInfo.BitDepthLuma = 8;
  354. q->param.mfx.FrameInfo.BitDepthChroma = 8;
  355. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  356. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  357. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  358. } else {
  359. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  360. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  361. }
  362. ret = select_rc_mode(avctx, q);
  363. if (ret < 0)
  364. return ret;
  365. switch (q->param.mfx.RateControlMethod) {
  366. case MFX_RATECONTROL_CBR:
  367. case MFX_RATECONTROL_VBR:
  368. #if QSV_HAVE_VCM
  369. case MFX_RATECONTROL_VCM:
  370. #endif
  371. q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
  372. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  373. q->param.mfx.MaxKbps = avctx->rc_max_rate / 1000;
  374. break;
  375. case MFX_RATECONTROL_CQP:
  376. quant = avctx->global_quality / FF_QP2LAMBDA;
  377. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  378. q->param.mfx.QPP = av_clip(quant, 0, 51);
  379. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  380. break;
  381. case MFX_RATECONTROL_AVBR:
  382. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  383. q->param.mfx.Convergence = q->avbr_convergence;
  384. q->param.mfx.Accuracy = q->avbr_accuracy;
  385. break;
  386. #if QSV_HAVE_LA
  387. case MFX_RATECONTROL_LA:
  388. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  389. q->extco2.LookAheadDepth = q->la_depth;
  390. break;
  391. #if QSV_HAVE_ICQ
  392. case MFX_RATECONTROL_LA_ICQ:
  393. q->extco2.LookAheadDepth = q->la_depth;
  394. case MFX_RATECONTROL_ICQ:
  395. q->param.mfx.ICQQuality = avctx->global_quality;
  396. break;
  397. #endif
  398. #endif
  399. }
  400. // the HEVC encoder plugin currently fails if coding options
  401. // are provided
  402. if (avctx->codec_id != AV_CODEC_ID_HEVC) {
  403. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  404. q->extco.Header.BufferSz = sizeof(q->extco);
  405. q->extco.CAVLC = avctx->coder_type == FF_CODER_TYPE_VLC ?
  406. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  407. if (q->rdo >= 0)
  408. q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  409. if (avctx->codec_id == AV_CODEC_ID_H264) {
  410. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  411. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  412. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  413. if (q->single_sei_nal_unit >= 0)
  414. q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  415. if (q->recovery_point_sei >= 0)
  416. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  417. q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
  418. }
  419. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  420. #if QSV_HAVE_CO2
  421. if (avctx->codec_id == AV_CODEC_ID_H264) {
  422. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  423. q->extco2.Header.BufferSz = sizeof(q->extco2);
  424. if (q->int_ref_type >= 0)
  425. q->extco2.IntRefType = q->int_ref_type;
  426. if (q->int_ref_cycle_size >= 0)
  427. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  428. if (q->int_ref_qp_delta != INT16_MIN)
  429. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  430. if (q->bitrate_limit >= 0)
  431. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  432. if (q->mbbrc >= 0)
  433. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  434. if (q->extbrc >= 0)
  435. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  436. if (q->max_frame_size >= 0)
  437. q->extco2.MaxFrameSize = q->max_frame_size;
  438. #if QSV_HAVE_MAX_SLICE_SIZE
  439. if (q->max_slice_size >= 0)
  440. q->extco2.MaxSliceSize = q->max_slice_size;
  441. #endif
  442. #if QSV_HAVE_TRELLIS
  443. q->extco2.Trellis = q->trellis;
  444. #endif
  445. #if QSV_HAVE_BREF_TYPE
  446. if (avctx->b_frame_strategy >= 0)
  447. q->extco2.BRefType = avctx->b_frame_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  448. if (q->adaptive_i >= 0)
  449. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  450. if (q->adaptive_b >= 0)
  451. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  452. #endif
  453. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  454. }
  455. #endif
  456. }
  457. if (!rc_supported(q)) {
  458. av_log(avctx, AV_LOG_ERROR,
  459. "Selected ratecontrol mode is not supported by the QSV "
  460. "runtime. Choose a different mode.\n");
  461. return AVERROR(ENOSYS);
  462. }
  463. return 0;
  464. }
  465. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  466. {
  467. AVCPBProperties *cpb_props;
  468. uint8_t sps_buf[128];
  469. uint8_t pps_buf[128];
  470. mfxExtCodingOptionSPSPPS extradata = {
  471. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  472. .Header.BufferSz = sizeof(extradata),
  473. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  474. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  475. };
  476. mfxExtCodingOption co = {
  477. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  478. .Header.BufferSz = sizeof(co),
  479. };
  480. #if QSV_HAVE_CO2
  481. mfxExtCodingOption2 co2 = {
  482. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  483. .Header.BufferSz = sizeof(co2),
  484. };
  485. #endif
  486. #if QSV_HAVE_CO3
  487. mfxExtCodingOption3 co3 = {
  488. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  489. .Header.BufferSz = sizeof(co3),
  490. };
  491. #endif
  492. mfxExtBuffer *ext_buffers[] = {
  493. (mfxExtBuffer*)&extradata,
  494. (mfxExtBuffer*)&co,
  495. #if QSV_HAVE_CO2
  496. (mfxExtBuffer*)&co2,
  497. #endif
  498. #if QSV_HAVE_CO3
  499. (mfxExtBuffer*)&co3,
  500. #endif
  501. };
  502. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  503. int ret;
  504. q->param.ExtParam = ext_buffers;
  505. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  506. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  507. if (ret < 0)
  508. return ff_qsv_error(ret);
  509. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  510. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  511. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  512. return AVERROR_UNKNOWN;
  513. }
  514. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  515. AV_INPUT_BUFFER_PADDING_SIZE);
  516. if (!avctx->extradata)
  517. return AVERROR(ENOMEM);
  518. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  519. if (need_pps)
  520. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  521. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  522. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  523. cpb_props = ff_add_cpb_side_data(avctx);
  524. if (!cpb_props)
  525. return AVERROR(ENOMEM);
  526. cpb_props->max_bitrate = avctx->rc_max_rate;
  527. cpb_props->min_bitrate = avctx->rc_min_rate;
  528. cpb_props->avg_bitrate = avctx->bit_rate;
  529. cpb_props->buffer_size = avctx->rc_buffer_size;
  530. dump_video_param(avctx, q, ext_buffers + 1);
  531. return 0;
  532. }
  533. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  534. {
  535. AVQSVContext *qsv = avctx->hwaccel_context;
  536. mfxFrameSurface1 *surfaces;
  537. int nb_surfaces, i;
  538. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested + q->async_depth;
  539. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  540. if (!q->opaque_alloc_buf)
  541. return AVERROR(ENOMEM);
  542. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  543. if (!q->opaque_surfaces)
  544. return AVERROR(ENOMEM);
  545. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  546. for (i = 0; i < nb_surfaces; i++) {
  547. surfaces[i].Info = q->req.Info;
  548. q->opaque_surfaces[i] = surfaces + i;
  549. }
  550. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  551. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  552. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  553. q->opaque_alloc.In.NumSurface = nb_surfaces;
  554. q->opaque_alloc.In.Type = q->req.Type;
  555. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  556. qsv->nb_opaque_surfaces = nb_surfaces;
  557. qsv->opaque_surfaces = q->opaque_alloc_buf;
  558. qsv->opaque_alloc_type = q->req.Type;
  559. return 0;
  560. }
  561. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  562. {
  563. int opaque_alloc = 0;
  564. int ret;
  565. q->param.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  566. q->param.AsyncDepth = q->async_depth;
  567. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  568. (sizeof(AVPacket) + sizeof(mfxSyncPoint) + sizeof(mfxBitstream*)));
  569. if (!q->async_fifo)
  570. return AVERROR(ENOMEM);
  571. if (avctx->hwaccel_context) {
  572. AVQSVContext *qsv = avctx->hwaccel_context;
  573. q->session = qsv->session;
  574. q->param.IOPattern = qsv->iopattern;
  575. opaque_alloc = qsv->opaque_alloc;
  576. }
  577. if (!q->session) {
  578. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  579. q->load_plugins);
  580. if (ret < 0)
  581. return ret;
  582. q->session = q->internal_session;
  583. }
  584. ret = init_video_param(avctx, q);
  585. if (ret < 0)
  586. return ret;
  587. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  588. if (ret < 0) {
  589. av_log(avctx, AV_LOG_ERROR, "Error querying the encoding parameters\n");
  590. return ff_qsv_error(ret);
  591. }
  592. if (opaque_alloc) {
  593. ret = qsv_init_opaque_alloc(avctx, q);
  594. if (ret < 0)
  595. return ret;
  596. }
  597. if (avctx->hwaccel_context) {
  598. AVQSVContext *qsv = avctx->hwaccel_context;
  599. int i, j;
  600. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  601. sizeof(*q->extparam));
  602. if (!q->extparam)
  603. return AVERROR(ENOMEM);
  604. q->param.ExtParam = q->extparam;
  605. for (i = 0; i < qsv->nb_ext_buffers; i++)
  606. q->param.ExtParam[i] = qsv->ext_buffers[i];
  607. q->param.NumExtParam = qsv->nb_ext_buffers;
  608. for (i = 0; i < q->nb_extparam_internal; i++) {
  609. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  610. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  611. break;
  612. }
  613. if (j < qsv->nb_ext_buffers)
  614. continue;
  615. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  616. }
  617. } else {
  618. q->param.ExtParam = q->extparam_internal;
  619. q->param.NumExtParam = q->nb_extparam_internal;
  620. }
  621. ret = MFXVideoENCODE_Init(q->session, &q->param);
  622. if (ret < 0) {
  623. av_log(avctx, AV_LOG_ERROR, "Error initializing the encoder\n");
  624. return ff_qsv_error(ret);
  625. }
  626. ret = qsv_retrieve_enc_params(avctx, q);
  627. if (ret < 0) {
  628. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  629. return ret;
  630. }
  631. q->avctx = avctx;
  632. return 0;
  633. }
  634. static void clear_unused_frames(QSVEncContext *q)
  635. {
  636. QSVFrame *cur = q->work_frames;
  637. while (cur) {
  638. if (cur->surface && !cur->surface->Data.Locked) {
  639. cur->surface = NULL;
  640. av_frame_unref(cur->frame);
  641. }
  642. cur = cur->next;
  643. }
  644. }
  645. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  646. {
  647. QSVFrame *frame, **last;
  648. clear_unused_frames(q);
  649. frame = q->work_frames;
  650. last = &q->work_frames;
  651. while (frame) {
  652. if (!frame->surface) {
  653. *f = frame;
  654. return 0;
  655. }
  656. last = &frame->next;
  657. frame = frame->next;
  658. }
  659. frame = av_mallocz(sizeof(*frame));
  660. if (!frame)
  661. return AVERROR(ENOMEM);
  662. frame->frame = av_frame_alloc();
  663. if (!frame->frame) {
  664. av_freep(&frame);
  665. return AVERROR(ENOMEM);
  666. }
  667. *last = frame;
  668. *f = frame;
  669. return 0;
  670. }
  671. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  672. mfxFrameSurface1 **surface)
  673. {
  674. QSVFrame *qf;
  675. int ret;
  676. ret = get_free_frame(q, &qf);
  677. if (ret < 0)
  678. return ret;
  679. if (frame->format == AV_PIX_FMT_QSV) {
  680. ret = av_frame_ref(qf->frame, frame);
  681. if (ret < 0)
  682. return ret;
  683. qf->surface = (mfxFrameSurface1*)qf->frame->data[3];
  684. } else {
  685. /* make a copy if the input is not padded as libmfx requires */
  686. if (frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) {
  687. qf->frame->height = FFALIGN(frame->height, 32);
  688. qf->frame->width = FFALIGN(frame->width, q->width_align);
  689. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  690. if (ret < 0)
  691. return ret;
  692. qf->frame->height = frame->height;
  693. qf->frame->width = frame->width;
  694. ret = av_frame_copy(qf->frame, frame);
  695. if (ret < 0) {
  696. av_frame_unref(qf->frame);
  697. return ret;
  698. }
  699. } else {
  700. ret = av_frame_ref(qf->frame, frame);
  701. if (ret < 0)
  702. return ret;
  703. }
  704. qf->surface_internal.Info = q->param.mfx.FrameInfo;
  705. qf->surface_internal.Info.PicStruct =
  706. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  707. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  708. MFX_PICSTRUCT_FIELD_BFF;
  709. if (frame->repeat_pict == 1)
  710. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  711. else if (frame->repeat_pict == 2)
  712. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  713. else if (frame->repeat_pict == 4)
  714. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  715. qf->surface_internal.Data.PitchLow = qf->frame->linesize[0];
  716. qf->surface_internal.Data.Y = qf->frame->data[0];
  717. qf->surface_internal.Data.UV = qf->frame->data[1];
  718. qf->surface = &qf->surface_internal;
  719. }
  720. qf->surface->Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  721. *surface = qf->surface;
  722. return 0;
  723. }
  724. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  725. {
  726. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  727. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  728. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  729. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  730. av_log(avctx, AV_LOG_WARNING,
  731. "Interlaced coding is supported"
  732. " at Main/High Profile Level 2.1-4.1\n");
  733. }
  734. }
  735. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  736. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  737. {
  738. AVPacket new_pkt = { 0 };
  739. mfxBitstream *bs;
  740. mfxFrameSurface1 *surf = NULL;
  741. mfxSyncPoint sync = NULL;
  742. int ret;
  743. if (frame) {
  744. ret = submit_frame(q, frame, &surf);
  745. if (ret < 0) {
  746. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  747. return ret;
  748. }
  749. }
  750. ret = av_new_packet(&new_pkt, q->packet_size);
  751. if (ret < 0) {
  752. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  753. return ret;
  754. }
  755. bs = av_mallocz(sizeof(*bs));
  756. if (!bs) {
  757. av_packet_unref(&new_pkt);
  758. return AVERROR(ENOMEM);
  759. }
  760. bs->Data = new_pkt.data;
  761. bs->MaxLength = new_pkt.size;
  762. do {
  763. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, &sync);
  764. if (ret == MFX_WRN_DEVICE_BUSY)
  765. av_usleep(1);
  766. } while (ret > 0);
  767. if (ret < 0) {
  768. av_packet_unref(&new_pkt);
  769. av_freep(&bs);
  770. return (ret == MFX_ERR_MORE_DATA) ? 0 : ff_qsv_error(ret);
  771. }
  772. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  773. print_interlace_msg(avctx, q);
  774. if (sync) {
  775. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  776. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  777. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  778. } else {
  779. av_packet_unref(&new_pkt);
  780. av_freep(&bs);
  781. }
  782. if (!av_fifo_space(q->async_fifo) ||
  783. (!frame && av_fifo_size(q->async_fifo))) {
  784. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  785. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  786. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  787. MFXVideoCORE_SyncOperation(q->session, sync, 60000);
  788. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  789. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  790. new_pkt.size = bs->DataLength;
  791. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  792. bs->FrameType & MFX_FRAMETYPE_xIDR)
  793. new_pkt.flags |= AV_PKT_FLAG_KEY;
  794. #if FF_API_CODED_FRAME
  795. FF_DISABLE_DEPRECATION_WARNINGS
  796. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  797. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  798. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  799. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  800. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  801. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  802. FF_ENABLE_DEPRECATION_WARNINGS
  803. #endif
  804. av_freep(&bs);
  805. if (pkt->data) {
  806. if (pkt->size < new_pkt.size) {
  807. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  808. pkt->size, new_pkt.size);
  809. av_packet_unref(&new_pkt);
  810. return AVERROR(EINVAL);
  811. }
  812. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  813. pkt->size = new_pkt.size;
  814. ret = av_packet_copy_props(pkt, &new_pkt);
  815. av_packet_unref(&new_pkt);
  816. if (ret < 0)
  817. return ret;
  818. } else
  819. *pkt = new_pkt;
  820. *got_packet = 1;
  821. }
  822. return 0;
  823. }
  824. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  825. {
  826. QSVFrame *cur;
  827. if (q->session)
  828. MFXVideoENCODE_Close(q->session);
  829. if (q->internal_session)
  830. MFXClose(q->internal_session);
  831. q->session = NULL;
  832. q->internal_session = NULL;
  833. cur = q->work_frames;
  834. while (cur) {
  835. q->work_frames = cur->next;
  836. av_frame_free(&cur->frame);
  837. av_freep(&cur);
  838. cur = q->work_frames;
  839. }
  840. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  841. AVPacket pkt;
  842. mfxSyncPoint sync;
  843. mfxBitstream *bs;
  844. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  845. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  846. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  847. av_freep(&bs);
  848. av_packet_unref(&pkt);
  849. }
  850. av_fifo_free(q->async_fifo);
  851. q->async_fifo = NULL;
  852. av_freep(&q->opaque_surfaces);
  853. av_buffer_unref(&q->opaque_alloc_buf);
  854. av_freep(&q->extparam);
  855. return 0;
  856. }