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.

1034 lines
35KB

  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 FF_API_PRIVATE_OPT
  447. FF_DISABLE_DEPRECATION_WARNINGS
  448. if (avctx->b_frame_strategy >= 0)
  449. q->b_strategy = avctx->b_frame_strategy;
  450. FF_ENABLE_DEPRECATION_WARNINGS
  451. #endif
  452. if (q->extco2.b_strategy >= 0)
  453. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  454. if (q->adaptive_i >= 0)
  455. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  456. if (q->adaptive_b >= 0)
  457. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  458. #endif
  459. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  460. }
  461. #endif
  462. }
  463. if (!rc_supported(q)) {
  464. av_log(avctx, AV_LOG_ERROR,
  465. "Selected ratecontrol mode is not supported by the QSV "
  466. "runtime. Choose a different mode.\n");
  467. return AVERROR(ENOSYS);
  468. }
  469. return 0;
  470. }
  471. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  472. {
  473. AVCPBProperties *cpb_props;
  474. uint8_t sps_buf[128];
  475. uint8_t pps_buf[128];
  476. mfxExtCodingOptionSPSPPS extradata = {
  477. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  478. .Header.BufferSz = sizeof(extradata),
  479. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  480. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  481. };
  482. mfxExtCodingOption co = {
  483. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  484. .Header.BufferSz = sizeof(co),
  485. };
  486. #if QSV_HAVE_CO2
  487. mfxExtCodingOption2 co2 = {
  488. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  489. .Header.BufferSz = sizeof(co2),
  490. };
  491. #endif
  492. #if QSV_HAVE_CO3
  493. mfxExtCodingOption3 co3 = {
  494. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  495. .Header.BufferSz = sizeof(co3),
  496. };
  497. #endif
  498. mfxExtBuffer *ext_buffers[] = {
  499. (mfxExtBuffer*)&extradata,
  500. (mfxExtBuffer*)&co,
  501. #if QSV_HAVE_CO2
  502. (mfxExtBuffer*)&co2,
  503. #endif
  504. #if QSV_HAVE_CO3
  505. (mfxExtBuffer*)&co3,
  506. #endif
  507. };
  508. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  509. int ret;
  510. q->param.ExtParam = ext_buffers;
  511. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  512. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  513. if (ret < 0)
  514. return ff_qsv_error(ret);
  515. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  516. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  517. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  518. return AVERROR_UNKNOWN;
  519. }
  520. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  521. AV_INPUT_BUFFER_PADDING_SIZE);
  522. if (!avctx->extradata)
  523. return AVERROR(ENOMEM);
  524. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  525. if (need_pps)
  526. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  527. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  528. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  529. cpb_props = ff_add_cpb_side_data(avctx);
  530. if (!cpb_props)
  531. return AVERROR(ENOMEM);
  532. cpb_props->max_bitrate = avctx->rc_max_rate;
  533. cpb_props->min_bitrate = avctx->rc_min_rate;
  534. cpb_props->avg_bitrate = avctx->bit_rate;
  535. cpb_props->buffer_size = avctx->rc_buffer_size;
  536. dump_video_param(avctx, q, ext_buffers + 1);
  537. return 0;
  538. }
  539. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  540. {
  541. AVQSVContext *qsv = avctx->hwaccel_context;
  542. mfxFrameSurface1 *surfaces;
  543. int nb_surfaces, i;
  544. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested + q->async_depth;
  545. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  546. if (!q->opaque_alloc_buf)
  547. return AVERROR(ENOMEM);
  548. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  549. if (!q->opaque_surfaces)
  550. return AVERROR(ENOMEM);
  551. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  552. for (i = 0; i < nb_surfaces; i++) {
  553. surfaces[i].Info = q->req.Info;
  554. q->opaque_surfaces[i] = surfaces + i;
  555. }
  556. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  557. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  558. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  559. q->opaque_alloc.In.NumSurface = nb_surfaces;
  560. q->opaque_alloc.In.Type = q->req.Type;
  561. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  562. qsv->nb_opaque_surfaces = nb_surfaces;
  563. qsv->opaque_surfaces = q->opaque_alloc_buf;
  564. qsv->opaque_alloc_type = q->req.Type;
  565. return 0;
  566. }
  567. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  568. {
  569. int opaque_alloc = 0;
  570. int ret;
  571. q->param.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  572. q->param.AsyncDepth = q->async_depth;
  573. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  574. (sizeof(AVPacket) + sizeof(mfxSyncPoint) + sizeof(mfxBitstream*)));
  575. if (!q->async_fifo)
  576. return AVERROR(ENOMEM);
  577. if (avctx->hwaccel_context) {
  578. AVQSVContext *qsv = avctx->hwaccel_context;
  579. q->session = qsv->session;
  580. q->param.IOPattern = qsv->iopattern;
  581. opaque_alloc = qsv->opaque_alloc;
  582. }
  583. if (!q->session) {
  584. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  585. q->load_plugins);
  586. if (ret < 0)
  587. return ret;
  588. q->session = q->internal_session;
  589. }
  590. ret = init_video_param(avctx, q);
  591. if (ret < 0)
  592. return ret;
  593. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  594. if (ret < 0) {
  595. av_log(avctx, AV_LOG_ERROR, "Error querying the encoding parameters\n");
  596. return ff_qsv_error(ret);
  597. }
  598. if (opaque_alloc) {
  599. ret = qsv_init_opaque_alloc(avctx, q);
  600. if (ret < 0)
  601. return ret;
  602. }
  603. if (avctx->hwaccel_context) {
  604. AVQSVContext *qsv = avctx->hwaccel_context;
  605. int i, j;
  606. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  607. sizeof(*q->extparam));
  608. if (!q->extparam)
  609. return AVERROR(ENOMEM);
  610. q->param.ExtParam = q->extparam;
  611. for (i = 0; i < qsv->nb_ext_buffers; i++)
  612. q->param.ExtParam[i] = qsv->ext_buffers[i];
  613. q->param.NumExtParam = qsv->nb_ext_buffers;
  614. for (i = 0; i < q->nb_extparam_internal; i++) {
  615. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  616. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  617. break;
  618. }
  619. if (j < qsv->nb_ext_buffers)
  620. continue;
  621. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  622. }
  623. } else {
  624. q->param.ExtParam = q->extparam_internal;
  625. q->param.NumExtParam = q->nb_extparam_internal;
  626. }
  627. ret = MFXVideoENCODE_Init(q->session, &q->param);
  628. if (ret < 0) {
  629. av_log(avctx, AV_LOG_ERROR, "Error initializing the encoder\n");
  630. return ff_qsv_error(ret);
  631. }
  632. ret = qsv_retrieve_enc_params(avctx, q);
  633. if (ret < 0) {
  634. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  635. return ret;
  636. }
  637. q->avctx = avctx;
  638. return 0;
  639. }
  640. static void clear_unused_frames(QSVEncContext *q)
  641. {
  642. QSVFrame *cur = q->work_frames;
  643. while (cur) {
  644. if (cur->surface && !cur->surface->Data.Locked) {
  645. cur->surface = NULL;
  646. av_frame_unref(cur->frame);
  647. }
  648. cur = cur->next;
  649. }
  650. }
  651. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  652. {
  653. QSVFrame *frame, **last;
  654. clear_unused_frames(q);
  655. frame = q->work_frames;
  656. last = &q->work_frames;
  657. while (frame) {
  658. if (!frame->surface) {
  659. *f = frame;
  660. return 0;
  661. }
  662. last = &frame->next;
  663. frame = frame->next;
  664. }
  665. frame = av_mallocz(sizeof(*frame));
  666. if (!frame)
  667. return AVERROR(ENOMEM);
  668. frame->frame = av_frame_alloc();
  669. if (!frame->frame) {
  670. av_freep(&frame);
  671. return AVERROR(ENOMEM);
  672. }
  673. *last = frame;
  674. *f = frame;
  675. return 0;
  676. }
  677. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  678. mfxFrameSurface1 **surface)
  679. {
  680. QSVFrame *qf;
  681. int ret;
  682. ret = get_free_frame(q, &qf);
  683. if (ret < 0)
  684. return ret;
  685. if (frame->format == AV_PIX_FMT_QSV) {
  686. ret = av_frame_ref(qf->frame, frame);
  687. if (ret < 0)
  688. return ret;
  689. qf->surface = (mfxFrameSurface1*)qf->frame->data[3];
  690. } else {
  691. /* make a copy if the input is not padded as libmfx requires */
  692. if (frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) {
  693. qf->frame->height = FFALIGN(frame->height, 32);
  694. qf->frame->width = FFALIGN(frame->width, q->width_align);
  695. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  696. if (ret < 0)
  697. return ret;
  698. qf->frame->height = frame->height;
  699. qf->frame->width = frame->width;
  700. ret = av_frame_copy(qf->frame, frame);
  701. if (ret < 0) {
  702. av_frame_unref(qf->frame);
  703. return ret;
  704. }
  705. } else {
  706. ret = av_frame_ref(qf->frame, frame);
  707. if (ret < 0)
  708. return ret;
  709. }
  710. qf->surface_internal.Info = q->param.mfx.FrameInfo;
  711. qf->surface_internal.Info.PicStruct =
  712. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  713. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  714. MFX_PICSTRUCT_FIELD_BFF;
  715. if (frame->repeat_pict == 1)
  716. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  717. else if (frame->repeat_pict == 2)
  718. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  719. else if (frame->repeat_pict == 4)
  720. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  721. qf->surface_internal.Data.PitchLow = qf->frame->linesize[0];
  722. qf->surface_internal.Data.Y = qf->frame->data[0];
  723. qf->surface_internal.Data.UV = qf->frame->data[1];
  724. qf->surface = &qf->surface_internal;
  725. }
  726. qf->surface->Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  727. *surface = qf->surface;
  728. return 0;
  729. }
  730. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  731. {
  732. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  733. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  734. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  735. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  736. av_log(avctx, AV_LOG_WARNING,
  737. "Interlaced coding is supported"
  738. " at Main/High Profile Level 2.1-4.1\n");
  739. }
  740. }
  741. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  742. const AVFrame *frame)
  743. {
  744. AVPacket new_pkt = { 0 };
  745. mfxBitstream *bs;
  746. mfxFrameSurface1 *surf = NULL;
  747. mfxSyncPoint sync = NULL;
  748. int ret;
  749. if (frame) {
  750. ret = submit_frame(q, frame, &surf);
  751. if (ret < 0) {
  752. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  753. return ret;
  754. }
  755. }
  756. ret = av_new_packet(&new_pkt, q->packet_size);
  757. if (ret < 0) {
  758. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  759. return ret;
  760. }
  761. bs = av_mallocz(sizeof(*bs));
  762. if (!bs) {
  763. av_packet_unref(&new_pkt);
  764. return AVERROR(ENOMEM);
  765. }
  766. bs->Data = new_pkt.data;
  767. bs->MaxLength = new_pkt.size;
  768. do {
  769. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, &sync);
  770. if (ret == MFX_WRN_DEVICE_BUSY)
  771. av_usleep(1);
  772. } while (ret > 0);
  773. if (ret < 0) {
  774. av_packet_unref(&new_pkt);
  775. av_freep(&bs);
  776. return (ret == MFX_ERR_MORE_DATA) ? 0 : ff_qsv_error(ret);
  777. }
  778. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  779. print_interlace_msg(avctx, q);
  780. if (sync) {
  781. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  782. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  783. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  784. } else {
  785. av_packet_unref(&new_pkt);
  786. av_freep(&bs);
  787. }
  788. return 0;
  789. }
  790. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  791. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  792. {
  793. int ret;
  794. ret = encode_frame(avctx, q, frame);
  795. if (ret < 0)
  796. return ret;
  797. if (!av_fifo_space(q->async_fifo) ||
  798. (!frame && av_fifo_size(q->async_fifo))) {
  799. AVPacket new_pkt;
  800. mfxBitstream *bs;
  801. mfxSyncPoint sync;
  802. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  803. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  804. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  805. do {
  806. ret = MFXVideoCORE_SyncOperation(q->session, sync, 1000);
  807. } while (ret == MFX_WRN_IN_EXECUTION);
  808. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  809. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  810. new_pkt.size = bs->DataLength;
  811. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  812. bs->FrameType & MFX_FRAMETYPE_xIDR)
  813. new_pkt.flags |= AV_PKT_FLAG_KEY;
  814. #if FF_API_CODED_FRAME
  815. FF_DISABLE_DEPRECATION_WARNINGS
  816. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  817. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  818. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  819. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  820. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  821. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  822. FF_ENABLE_DEPRECATION_WARNINGS
  823. #endif
  824. av_freep(&bs);
  825. if (pkt->data) {
  826. if (pkt->size < new_pkt.size) {
  827. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  828. pkt->size, new_pkt.size);
  829. av_packet_unref(&new_pkt);
  830. return AVERROR(EINVAL);
  831. }
  832. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  833. pkt->size = new_pkt.size;
  834. ret = av_packet_copy_props(pkt, &new_pkt);
  835. av_packet_unref(&new_pkt);
  836. if (ret < 0)
  837. return ret;
  838. } else
  839. *pkt = new_pkt;
  840. *got_packet = 1;
  841. }
  842. return 0;
  843. }
  844. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  845. {
  846. QSVFrame *cur;
  847. if (q->session)
  848. MFXVideoENCODE_Close(q->session);
  849. if (q->internal_session)
  850. MFXClose(q->internal_session);
  851. q->session = NULL;
  852. q->internal_session = NULL;
  853. cur = q->work_frames;
  854. while (cur) {
  855. q->work_frames = cur->next;
  856. av_frame_free(&cur->frame);
  857. av_freep(&cur);
  858. cur = q->work_frames;
  859. }
  860. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  861. AVPacket pkt;
  862. mfxSyncPoint sync;
  863. mfxBitstream *bs;
  864. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  865. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  866. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  867. av_freep(&bs);
  868. av_packet_unref(&pkt);
  869. }
  870. av_fifo_free(q->async_fifo);
  871. q->async_fifo = NULL;
  872. av_freep(&q->opaque_surfaces);
  873. av_buffer_unref(&q->opaque_alloc_buf);
  874. av_freep(&q->extparam);
  875. return 0;
  876. }