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.

1664 lines
58KB

  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 FFmpeg.
  8. *
  9. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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/hwcontext.h"
  28. #include "libavutil/hwcontext_qsv.h"
  29. #include "libavutil/mem.h"
  30. #include "libavutil/log.h"
  31. #include "libavutil/time.h"
  32. #include "libavutil/imgutils.h"
  33. #include "libavcodec/bytestream.h"
  34. #include "avcodec.h"
  35. #include "internal.h"
  36. #include "packet_internal.h"
  37. #include "qsv.h"
  38. #include "qsv_internal.h"
  39. #include "qsvenc.h"
  40. static const struct {
  41. mfxU16 profile;
  42. const char *name;
  43. } profile_names[] = {
  44. { MFX_PROFILE_AVC_BASELINE, "baseline" },
  45. { MFX_PROFILE_AVC_MAIN, "main" },
  46. { MFX_PROFILE_AVC_EXTENDED, "extended" },
  47. { MFX_PROFILE_AVC_HIGH, "high" },
  48. #if QSV_VERSION_ATLEAST(1, 15)
  49. { MFX_PROFILE_AVC_HIGH_422, "high 422" },
  50. #endif
  51. #if QSV_VERSION_ATLEAST(1, 4)
  52. { MFX_PROFILE_AVC_CONSTRAINED_BASELINE, "constrained baseline" },
  53. { MFX_PROFILE_AVC_CONSTRAINED_HIGH, "constrained high" },
  54. { MFX_PROFILE_AVC_PROGRESSIVE_HIGH, "progressive high" },
  55. #endif
  56. { MFX_PROFILE_MPEG2_SIMPLE, "simple" },
  57. { MFX_PROFILE_MPEG2_MAIN, "main" },
  58. { MFX_PROFILE_MPEG2_HIGH, "high" },
  59. { MFX_PROFILE_VC1_SIMPLE, "simple" },
  60. { MFX_PROFILE_VC1_MAIN, "main" },
  61. { MFX_PROFILE_VC1_ADVANCED, "advanced" },
  62. #if QSV_VERSION_ATLEAST(1, 8)
  63. { MFX_PROFILE_HEVC_MAIN, "main" },
  64. { MFX_PROFILE_HEVC_MAIN10, "main10" },
  65. { MFX_PROFILE_HEVC_MAINSP, "mainsp" },
  66. { MFX_PROFILE_HEVC_REXT, "rext" },
  67. #endif
  68. };
  69. static const char *print_profile(mfxU16 profile)
  70. {
  71. int i;
  72. for (i = 0; i < FF_ARRAY_ELEMS(profile_names); i++)
  73. if (profile == profile_names[i].profile)
  74. return profile_names[i].name;
  75. return "unknown";
  76. }
  77. static const struct {
  78. mfxU16 rc_mode;
  79. const char *name;
  80. } rc_names[] = {
  81. { MFX_RATECONTROL_CBR, "CBR" },
  82. { MFX_RATECONTROL_VBR, "VBR" },
  83. { MFX_RATECONTROL_CQP, "CQP" },
  84. #if QSV_HAVE_AVBR
  85. { MFX_RATECONTROL_AVBR, "AVBR" },
  86. #endif
  87. #if QSV_HAVE_LA
  88. { MFX_RATECONTROL_LA, "LA" },
  89. #endif
  90. #if QSV_HAVE_ICQ
  91. { MFX_RATECONTROL_ICQ, "ICQ" },
  92. { MFX_RATECONTROL_LA_ICQ, "LA_ICQ" },
  93. #endif
  94. #if QSV_HAVE_VCM
  95. { MFX_RATECONTROL_VCM, "VCM" },
  96. #endif
  97. #if QSV_VERSION_ATLEAST(1, 10)
  98. { MFX_RATECONTROL_LA_EXT, "LA_EXT" },
  99. #endif
  100. #if QSV_HAVE_LA_HRD
  101. { MFX_RATECONTROL_LA_HRD, "LA_HRD" },
  102. #endif
  103. #if QSV_HAVE_QVBR
  104. { MFX_RATECONTROL_QVBR, "QVBR" },
  105. #endif
  106. };
  107. static const char *print_ratecontrol(mfxU16 rc_mode)
  108. {
  109. int i;
  110. for (i = 0; i < FF_ARRAY_ELEMS(rc_names); i++)
  111. if (rc_mode == rc_names[i].rc_mode)
  112. return rc_names[i].name;
  113. return "unknown";
  114. }
  115. static const char *print_threestate(mfxU16 val)
  116. {
  117. if (val == MFX_CODINGOPTION_ON)
  118. return "ON";
  119. else if (val == MFX_CODINGOPTION_OFF)
  120. return "OFF";
  121. return "unknown";
  122. }
  123. static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
  124. mfxExtBuffer **coding_opts)
  125. {
  126. mfxInfoMFX *info = &q->param.mfx;
  127. mfxExtCodingOption *co = (mfxExtCodingOption*)coding_opts[0];
  128. #if QSV_HAVE_CO2
  129. mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[1];
  130. #endif
  131. #if QSV_HAVE_CO3
  132. mfxExtCodingOption3 *co3 = (mfxExtCodingOption3*)coding_opts[2];
  133. #endif
  134. #if QSV_HAVE_EXT_HEVC_TILES
  135. mfxExtHEVCTiles *exthevctiles = (mfxExtHEVCTiles *)coding_opts[3 + QSV_HAVE_CO_VPS];
  136. #endif
  137. av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
  138. print_profile(info->CodecProfile), info->CodecLevel);
  139. av_log(avctx, AV_LOG_VERBOSE, "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag: ",
  140. info->GopPicSize, info->GopRefDist);
  141. if (info->GopOptFlag & MFX_GOP_CLOSED)
  142. av_log(avctx, AV_LOG_VERBOSE, "closed ");
  143. if (info->GopOptFlag & MFX_GOP_STRICT)
  144. av_log(avctx, AV_LOG_VERBOSE, "strict ");
  145. av_log(avctx, AV_LOG_VERBOSE, "; IdrInterval: %"PRIu16"\n", info->IdrInterval);
  146. av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
  147. info->TargetUsage, print_ratecontrol(info->RateControlMethod));
  148. if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
  149. info->RateControlMethod == MFX_RATECONTROL_VBR
  150. #if QSV_HAVE_VCM
  151. || info->RateControlMethod == MFX_RATECONTROL_VCM
  152. #endif
  153. ) {
  154. av_log(avctx, AV_LOG_VERBOSE,
  155. "BufferSizeInKB: %"PRIu16"; InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  156. info->BufferSizeInKB, info->InitialDelayInKB, info->TargetKbps, info->MaxKbps, info->BRCParamMultiplier);
  157. } else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
  158. av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
  159. info->QPI, info->QPP, info->QPB);
  160. }
  161. #if QSV_HAVE_AVBR
  162. else if (info->RateControlMethod == MFX_RATECONTROL_AVBR) {
  163. av_log(avctx, AV_LOG_VERBOSE,
  164. "TargetKbps: %"PRIu16"; Accuracy: %"PRIu16"; Convergence: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  165. info->TargetKbps, info->Accuracy, info->Convergence, info->BRCParamMultiplier);
  166. }
  167. #endif
  168. #if QSV_HAVE_LA
  169. else if (info->RateControlMethod == MFX_RATECONTROL_LA
  170. #if QSV_HAVE_LA_HRD
  171. || info->RateControlMethod == MFX_RATECONTROL_LA_HRD
  172. #endif
  173. ) {
  174. av_log(avctx, AV_LOG_VERBOSE,
  175. "TargetKbps: %"PRIu16"; LookAheadDepth: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  176. info->TargetKbps, co2->LookAheadDepth, info->BRCParamMultiplier);
  177. }
  178. #endif
  179. #if QSV_HAVE_ICQ
  180. else if (info->RateControlMethod == MFX_RATECONTROL_ICQ) {
  181. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
  182. } else if (info->RateControlMethod == MFX_RATECONTROL_LA_ICQ) {
  183. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
  184. info->ICQQuality, co2->LookAheadDepth);
  185. }
  186. #endif
  187. #if QSV_HAVE_QVBR
  188. else if (info->RateControlMethod == MFX_RATECONTROL_QVBR) {
  189. av_log(avctx, AV_LOG_VERBOSE, "QVBRQuality: %"PRIu16"\n",
  190. co3->QVBRQuality);
  191. }
  192. #endif
  193. av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
  194. info->NumSlice, info->NumRefFrame);
  195. av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
  196. print_threestate(co->RateDistortionOpt));
  197. #if QSV_HAVE_EXT_HEVC_TILES
  198. if (avctx->codec_id == AV_CODEC_ID_HEVC)
  199. av_log(avctx, AV_LOG_VERBOSE, "NumTileColumns: %"PRIu16"; NumTileRows: %"PRIu16"\n",
  200. exthevctiles->NumTileColumns, exthevctiles->NumTileRows);
  201. #endif
  202. #if QSV_HAVE_CO2
  203. av_log(avctx, AV_LOG_VERBOSE,
  204. "RecoveryPointSEI: %s IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
  205. print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
  206. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %d; ", co2->MaxFrameSize);
  207. #if QSV_HAVE_MAX_SLICE_SIZE
  208. av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %d; ", co2->MaxSliceSize);
  209. #endif
  210. av_log(avctx, AV_LOG_VERBOSE, "\n");
  211. av_log(avctx, AV_LOG_VERBOSE,
  212. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  213. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  214. print_threestate(co2->ExtBRC));
  215. #if QSV_HAVE_TRELLIS
  216. av_log(avctx, AV_LOG_VERBOSE, "Trellis: ");
  217. if (co2->Trellis & MFX_TRELLIS_OFF) {
  218. av_log(avctx, AV_LOG_VERBOSE, "off");
  219. } else if (!co2->Trellis) {
  220. av_log(avctx, AV_LOG_VERBOSE, "auto");
  221. } else {
  222. if (co2->Trellis & MFX_TRELLIS_I) av_log(avctx, AV_LOG_VERBOSE, "I");
  223. if (co2->Trellis & MFX_TRELLIS_P) av_log(avctx, AV_LOG_VERBOSE, "P");
  224. if (co2->Trellis & MFX_TRELLIS_B) av_log(avctx, AV_LOG_VERBOSE, "B");
  225. }
  226. av_log(avctx, AV_LOG_VERBOSE, "\n");
  227. #endif
  228. #if QSV_HAVE_VDENC
  229. av_log(avctx, AV_LOG_VERBOSE, "VDENC: %s\n", print_threestate(info->LowPower));
  230. #endif
  231. #if QSV_VERSION_ATLEAST(1, 8)
  232. av_log(avctx, AV_LOG_VERBOSE,
  233. "RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: ",
  234. print_threestate(co2->RepeatPPS), co2->NumMbPerSlice);
  235. switch (co2->LookAheadDS) {
  236. case MFX_LOOKAHEAD_DS_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  237. case MFX_LOOKAHEAD_DS_2x: av_log(avctx, AV_LOG_VERBOSE, "2x"); break;
  238. case MFX_LOOKAHEAD_DS_4x: av_log(avctx, AV_LOG_VERBOSE, "4x"); break;
  239. default: av_log(avctx, AV_LOG_VERBOSE, "unknown"); break;
  240. }
  241. av_log(avctx, AV_LOG_VERBOSE, "\n");
  242. av_log(avctx, AV_LOG_VERBOSE, "AdaptiveI: %s; AdaptiveB: %s; BRefType: ",
  243. print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB));
  244. switch (co2->BRefType) {
  245. case MFX_B_REF_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  246. case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "pyramid"); break;
  247. default: av_log(avctx, AV_LOG_VERBOSE, "auto"); break;
  248. }
  249. av_log(avctx, AV_LOG_VERBOSE, "\n");
  250. #endif
  251. #if QSV_VERSION_ATLEAST(1, 9)
  252. av_log(avctx, AV_LOG_VERBOSE,
  253. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  254. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  255. #endif
  256. #endif
  257. #if QSV_HAVE_GPB
  258. if (avctx->codec_id == AV_CODEC_ID_HEVC)
  259. av_log(avctx, AV_LOG_VERBOSE,"GPB: %s\n", print_threestate(co3->GPB));
  260. #endif
  261. if (avctx->codec_id == AV_CODEC_ID_H264) {
  262. av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
  263. co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
  264. av_log(avctx, AV_LOG_VERBOSE,
  265. "NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
  266. print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
  267. print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
  268. }
  269. av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
  270. info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
  271. }
  272. static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
  273. {
  274. const char *rc_desc;
  275. mfxU16 rc_mode;
  276. int want_la = q->look_ahead;
  277. int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  278. int want_vcm = q->vcm;
  279. if (want_la && !QSV_HAVE_LA) {
  280. av_log(avctx, AV_LOG_ERROR,
  281. "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
  282. return AVERROR(ENOSYS);
  283. }
  284. if (want_vcm && !QSV_HAVE_VCM) {
  285. av_log(avctx, AV_LOG_ERROR,
  286. "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
  287. return AVERROR(ENOSYS);
  288. }
  289. if (want_la + want_qscale + want_vcm > 1) {
  290. av_log(avctx, AV_LOG_ERROR,
  291. "More than one of: { constant qscale, lookahead, VCM } requested, "
  292. "only one of them can be used at a time.\n");
  293. return AVERROR(EINVAL);
  294. }
  295. if (!want_qscale && avctx->global_quality > 0 && !QSV_HAVE_ICQ){
  296. av_log(avctx, AV_LOG_ERROR,
  297. "ICQ ratecontrol mode requested, but is not supported by this SDK version\n");
  298. return AVERROR(ENOSYS);
  299. }
  300. if (want_qscale) {
  301. rc_mode = MFX_RATECONTROL_CQP;
  302. rc_desc = "constant quantization parameter (CQP)";
  303. }
  304. #if QSV_HAVE_VCM
  305. else if (want_vcm) {
  306. rc_mode = MFX_RATECONTROL_VCM;
  307. rc_desc = "video conferencing mode (VCM)";
  308. }
  309. #endif
  310. #if QSV_HAVE_LA
  311. else if (want_la) {
  312. rc_mode = MFX_RATECONTROL_LA;
  313. rc_desc = "VBR with lookahead (LA)";
  314. #if QSV_HAVE_ICQ
  315. if (avctx->global_quality > 0) {
  316. rc_mode = MFX_RATECONTROL_LA_ICQ;
  317. rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
  318. }
  319. #endif
  320. }
  321. #endif
  322. #if QSV_HAVE_ICQ
  323. else if (avctx->global_quality > 0 && !avctx->rc_max_rate) {
  324. rc_mode = MFX_RATECONTROL_ICQ;
  325. rc_desc = "intelligent constant quality (ICQ)";
  326. }
  327. #endif
  328. else if (avctx->rc_max_rate == avctx->bit_rate) {
  329. rc_mode = MFX_RATECONTROL_CBR;
  330. rc_desc = "constant bitrate (CBR)";
  331. }
  332. #if QSV_HAVE_AVBR
  333. else if (!avctx->rc_max_rate) {
  334. rc_mode = MFX_RATECONTROL_AVBR;
  335. rc_desc = "average variable bitrate (AVBR)";
  336. }
  337. #endif
  338. #if QSV_HAVE_QVBR
  339. else if (avctx->global_quality > 0) {
  340. rc_mode = MFX_RATECONTROL_QVBR;
  341. rc_desc = "constant quality with VBR algorithm (QVBR)";
  342. }
  343. #endif
  344. else {
  345. rc_mode = MFX_RATECONTROL_VBR;
  346. rc_desc = "variable bitrate (VBR)";
  347. }
  348. q->param.mfx.RateControlMethod = rc_mode;
  349. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
  350. return 0;
  351. }
  352. static int check_enc_param(AVCodecContext *avctx, QSVEncContext *q)
  353. {
  354. mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
  355. mfxStatus ret;
  356. #define UNMATCH(x) (param_out.mfx.x != q->param.mfx.x)
  357. ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
  358. if (ret < 0) {
  359. if (UNMATCH(CodecId))
  360. av_log(avctx, AV_LOG_ERROR, "Current codec type is unsupported\n");
  361. if (UNMATCH(CodecProfile))
  362. av_log(avctx, AV_LOG_ERROR, "Current profile is unsupported\n");
  363. if (UNMATCH(RateControlMethod))
  364. av_log(avctx, AV_LOG_ERROR, "Selected ratecontrol mode is unsupported\n");
  365. if (UNMATCH(LowPower))
  366. av_log(avctx, AV_LOG_ERROR, "Low power mode is unsupported\n");
  367. if (UNMATCH(FrameInfo.FrameRateExtN) || UNMATCH(FrameInfo.FrameRateExtD))
  368. av_log(avctx, AV_LOG_ERROR, "Current frame rate is unsupported\n");
  369. if (UNMATCH(FrameInfo.PicStruct))
  370. av_log(avctx, AV_LOG_ERROR, "Current picture structure is unsupported\n");
  371. if (UNMATCH(FrameInfo.Width) || UNMATCH(FrameInfo.Height))
  372. av_log(avctx, AV_LOG_ERROR, "Current resolution is unsupported\n");
  373. if (UNMATCH(FrameInfo.FourCC))
  374. av_log(avctx, AV_LOG_ERROR, "Current pixel format is unsupported\n");
  375. return 0;
  376. }
  377. return 1;
  378. }
  379. static int init_video_param_jpeg(AVCodecContext *avctx, QSVEncContext *q)
  380. {
  381. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  382. avctx->sw_pix_fmt : avctx->pix_fmt;
  383. const AVPixFmtDescriptor *desc;
  384. int ret;
  385. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  386. if (ret < 0)
  387. return AVERROR_BUG;
  388. q->param.mfx.CodecId = ret;
  389. if (avctx->level > 0)
  390. q->param.mfx.CodecLevel = avctx->level;
  391. q->param.mfx.CodecProfile = q->profile;
  392. desc = av_pix_fmt_desc_get(sw_format);
  393. if (!desc)
  394. return AVERROR_BUG;
  395. ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
  396. q->param.mfx.FrameInfo.CropX = 0;
  397. q->param.mfx.FrameInfo.CropY = 0;
  398. q->param.mfx.FrameInfo.CropW = avctx->width;
  399. q->param.mfx.FrameInfo.CropH = avctx->height;
  400. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  401. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  402. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  403. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  404. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  405. q->param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
  406. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, 16);
  407. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 16);
  408. if (avctx->hw_frames_ctx) {
  409. AVHWFramesContext *frames_ctx = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
  410. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  411. q->param.mfx.FrameInfo.Width = frames_hwctx->surfaces[0].Info.Width;
  412. q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
  413. }
  414. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  415. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  416. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  417. } else {
  418. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  419. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  420. }
  421. q->param.mfx.Interleaved = 1;
  422. q->param.mfx.Quality = av_clip(avctx->global_quality, 1, 100);
  423. q->param.mfx.RestartInterval = 0;
  424. q->width_align = 16;
  425. q->height_align = 16;
  426. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  427. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  428. return 0;
  429. }
  430. static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  431. {
  432. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  433. avctx->sw_pix_fmt : avctx->pix_fmt;
  434. const AVPixFmtDescriptor *desc;
  435. float quant;
  436. int target_bitrate_kbps, max_bitrate_kbps, brc_param_multiplier;
  437. int buffer_size_in_kilobytes, initial_delay_in_kilobytes;
  438. int ret;
  439. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  440. if (ret < 0)
  441. return AVERROR_BUG;
  442. q->param.mfx.CodecId = ret;
  443. if (avctx->level > 0)
  444. q->param.mfx.CodecLevel = avctx->level;
  445. if (avctx->compression_level == FF_COMPRESSION_DEFAULT) {
  446. avctx->compression_level = q->preset;
  447. } else if (avctx->compression_level >= 0) {
  448. if (avctx->compression_level > MFX_TARGETUSAGE_BEST_SPEED) {
  449. av_log(avctx, AV_LOG_WARNING, "Invalid compression level: "
  450. "valid range is 0-%d, using %d instead\n",
  451. MFX_TARGETUSAGE_BEST_SPEED, MFX_TARGETUSAGE_BEST_SPEED);
  452. avctx->compression_level = MFX_TARGETUSAGE_BEST_SPEED;
  453. }
  454. }
  455. if (q->low_power) {
  456. #if QSV_HAVE_VDENC
  457. q->param.mfx.LowPower = MFX_CODINGOPTION_ON;
  458. #else
  459. av_log(avctx, AV_LOG_WARNING, "The low_power option is "
  460. "not supported with this MSDK version.\n");
  461. q->low_power = 0;
  462. q->param.mfx.LowPower = MFX_CODINGOPTION_OFF;
  463. #endif
  464. } else
  465. q->param.mfx.LowPower = MFX_CODINGOPTION_OFF;
  466. q->param.mfx.CodecProfile = q->profile;
  467. q->param.mfx.TargetUsage = avctx->compression_level;
  468. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  469. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  470. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  471. MFX_GOP_CLOSED : 0;
  472. q->param.mfx.IdrInterval = q->idr_interval;
  473. q->param.mfx.NumSlice = avctx->slices;
  474. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  475. q->param.mfx.EncodedOrder = 0;
  476. q->param.mfx.BufferSizeInKB = 0;
  477. desc = av_pix_fmt_desc_get(sw_format);
  478. if (!desc)
  479. return AVERROR_BUG;
  480. ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
  481. q->param.mfx.FrameInfo.CropX = 0;
  482. q->param.mfx.FrameInfo.CropY = 0;
  483. q->param.mfx.FrameInfo.CropW = avctx->width;
  484. q->param.mfx.FrameInfo.CropH = avctx->height;
  485. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  486. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  487. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420 +
  488. !desc->log2_chroma_w + !desc->log2_chroma_h;
  489. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  490. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  491. q->param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
  492. // If the minor version is greater than or equal to 19,
  493. // then can use the same alignment settings as H.264 for HEVC
  494. q->width_align = (avctx->codec_id != AV_CODEC_ID_HEVC ||
  495. QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 19)) ? 16 : 32;
  496. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  497. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  498. // it is important that PicStruct be setup correctly from the
  499. // start--otherwise, encoding doesn't work and results in a bunch
  500. // of incompatible video parameter errors
  501. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
  502. // height alignment always must be 32 for interlaced video
  503. q->height_align = 32;
  504. } else {
  505. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  506. // for progressive video, the height should be aligned to 16 for
  507. // H.264. For HEVC, depending on the version of MFX, it should be
  508. // either 32 or 16. The lower number is better if possible.
  509. q->height_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  510. }
  511. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  512. if (avctx->hw_frames_ctx) {
  513. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  514. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  515. q->param.mfx.FrameInfo.Width = frames_hwctx->surfaces[0].Info.Width;
  516. q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
  517. }
  518. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  519. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  520. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  521. } else {
  522. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  523. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  524. }
  525. ret = select_rc_mode(avctx, q);
  526. if (ret < 0)
  527. return ret;
  528. //libmfx BRC parameters are 16 bits thus maybe overflow, then BRCParamMultiplier is needed
  529. buffer_size_in_kilobytes = avctx->rc_buffer_size / 8000;
  530. initial_delay_in_kilobytes = avctx->rc_initial_buffer_occupancy / 8000;
  531. target_bitrate_kbps = avctx->bit_rate / 1000;
  532. max_bitrate_kbps = avctx->rc_max_rate / 1000;
  533. brc_param_multiplier = (FFMAX(FFMAX3(target_bitrate_kbps, max_bitrate_kbps, buffer_size_in_kilobytes),
  534. initial_delay_in_kilobytes) + 0x10000) / 0x10000;
  535. switch (q->param.mfx.RateControlMethod) {
  536. case MFX_RATECONTROL_CBR:
  537. case MFX_RATECONTROL_VBR:
  538. #if QSV_HAVE_VCM
  539. case MFX_RATECONTROL_VCM:
  540. #endif
  541. #if QSV_HAVE_QVBR
  542. case MFX_RATECONTROL_QVBR:
  543. #endif
  544. q->param.mfx.BufferSizeInKB = buffer_size_in_kilobytes / brc_param_multiplier;
  545. q->param.mfx.InitialDelayInKB = initial_delay_in_kilobytes / brc_param_multiplier;
  546. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  547. q->param.mfx.MaxKbps = max_bitrate_kbps / brc_param_multiplier;
  548. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  549. #if QSV_HAVE_QVBR
  550. if (q->param.mfx.RateControlMethod == MFX_RATECONTROL_QVBR)
  551. q->extco3.QVBRQuality = av_clip(avctx->global_quality, 0, 51);
  552. #endif
  553. break;
  554. case MFX_RATECONTROL_CQP:
  555. quant = avctx->global_quality / FF_QP2LAMBDA;
  556. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  557. q->param.mfx.QPP = av_clip(quant, 0, 51);
  558. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  559. break;
  560. #if QSV_HAVE_AVBR
  561. case MFX_RATECONTROL_AVBR:
  562. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  563. q->param.mfx.Convergence = q->avbr_convergence;
  564. q->param.mfx.Accuracy = q->avbr_accuracy;
  565. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  566. break;
  567. #endif
  568. #if QSV_HAVE_LA
  569. case MFX_RATECONTROL_LA:
  570. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  571. q->extco2.LookAheadDepth = q->look_ahead_depth;
  572. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  573. break;
  574. #if QSV_HAVE_ICQ
  575. case MFX_RATECONTROL_LA_ICQ:
  576. q->extco2.LookAheadDepth = q->look_ahead_depth;
  577. case MFX_RATECONTROL_ICQ:
  578. q->param.mfx.ICQQuality = avctx->global_quality;
  579. break;
  580. #endif
  581. #endif
  582. }
  583. // The HEVC encoder plugin currently fails with some old libmfx version if coding options
  584. // are provided. Can't find the extract libmfx version which fixed it, just enable it from
  585. // V1.28 in order to keep compatibility security.
  586. if (((avctx->codec_id != AV_CODEC_ID_HEVC) || QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 28))
  587. && (avctx->codec_id != AV_CODEC_ID_VP9)) {
  588. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  589. q->extco.Header.BufferSz = sizeof(q->extco);
  590. q->extco.PicTimingSEI = q->pic_timing_sei ?
  591. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  592. if (q->rdo >= 0)
  593. q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  594. if (avctx->codec_id == AV_CODEC_ID_H264) {
  595. #if FF_API_CODER_TYPE
  596. FF_DISABLE_DEPRECATION_WARNINGS
  597. if (avctx->coder_type >= 0)
  598. q->cavlc = avctx->coder_type == FF_CODER_TYPE_VLC;
  599. FF_ENABLE_DEPRECATION_WARNINGS
  600. #endif
  601. q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
  602. : MFX_CODINGOPTION_UNKNOWN;
  603. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  604. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  605. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  606. if (q->single_sei_nal_unit >= 0)
  607. q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  608. if (q->recovery_point_sei >= 0)
  609. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  610. q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
  611. q->extco.AUDelimiter = q->aud ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  612. }
  613. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  614. #if QSV_HAVE_CO2
  615. if (avctx->codec_id == AV_CODEC_ID_H264) {
  616. if (q->int_ref_type >= 0)
  617. q->extco2.IntRefType = q->int_ref_type;
  618. if (q->int_ref_cycle_size >= 0)
  619. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  620. if (q->int_ref_qp_delta != INT16_MIN)
  621. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  622. if (q->bitrate_limit >= 0)
  623. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  624. if (q->mbbrc >= 0)
  625. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  626. if (q->max_frame_size >= 0)
  627. q->extco2.MaxFrameSize = q->max_frame_size;
  628. #if QSV_HAVE_MAX_SLICE_SIZE
  629. if (q->max_slice_size >= 0)
  630. q->extco2.MaxSliceSize = q->max_slice_size;
  631. #endif
  632. #if QSV_HAVE_TRELLIS
  633. if (avctx->trellis >= 0)
  634. q->extco2.Trellis = (avctx->trellis == 0) ? MFX_TRELLIS_OFF : (MFX_TRELLIS_I | MFX_TRELLIS_P | MFX_TRELLIS_B);
  635. else
  636. q->extco2.Trellis = MFX_TRELLIS_UNKNOWN;
  637. #endif
  638. #if QSV_VERSION_ATLEAST(1, 8)
  639. q->extco2.LookAheadDS = q->look_ahead_downsampling;
  640. q->extco2.RepeatPPS = q->repeat_pps ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  641. #if FF_API_PRIVATE_OPT
  642. FF_DISABLE_DEPRECATION_WARNINGS
  643. if (avctx->b_frame_strategy >= 0)
  644. q->b_strategy = avctx->b_frame_strategy;
  645. FF_ENABLE_DEPRECATION_WARNINGS
  646. #endif
  647. if (q->b_strategy >= 0)
  648. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  649. if (q->adaptive_i >= 0)
  650. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  651. if (q->adaptive_b >= 0)
  652. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  653. #endif
  654. }
  655. if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) {
  656. if (q->extbrc >= 0)
  657. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  658. #if QSV_VERSION_ATLEAST(1, 9)
  659. if (avctx->qmin >= 0 && avctx->qmax >= 0 && avctx->qmin > avctx->qmax) {
  660. av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are set but invalid, please make sure min <= max\n");
  661. return AVERROR(EINVAL);
  662. }
  663. if (avctx->qmin >= 0) {
  664. q->extco2.MinQPI = avctx->qmin > 51 ? 51 : avctx->qmin;
  665. q->extco2.MinQPP = q->extco2.MinQPB = q->extco2.MinQPI;
  666. }
  667. if (avctx->qmax >= 0) {
  668. q->extco2.MaxQPI = avctx->qmax > 51 ? 51 : avctx->qmax;
  669. q->extco2.MaxQPP = q->extco2.MaxQPB = q->extco2.MaxQPI;
  670. }
  671. #endif
  672. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  673. q->extco2.Header.BufferSz = sizeof(q->extco2);
  674. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  675. }
  676. #endif
  677. if (avctx->codec_id == AV_CODEC_ID_H264) {
  678. #if QSV_HAVE_MF
  679. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 25)) {
  680. q->extmfp.Header.BufferId = MFX_EXTBUFF_MULTI_FRAME_PARAM;
  681. q->extmfp.Header.BufferSz = sizeof(q->extmfp);
  682. q->extmfp.MFMode = q->mfmode;
  683. av_log(avctx,AV_LOG_VERBOSE,"MFMode:%d\n", q->extmfp.MFMode);
  684. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extmfp;
  685. }
  686. #endif
  687. }
  688. #if QSV_HAVE_CO3
  689. q->extco3.Header.BufferId = MFX_EXTBUFF_CODING_OPTION3;
  690. q->extco3.Header.BufferSz = sizeof(q->extco3);
  691. #if QSV_HAVE_GPB
  692. if (avctx->codec_id == AV_CODEC_ID_HEVC)
  693. q->extco3.GPB = q->gpb ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  694. #endif
  695. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco3;
  696. #endif
  697. }
  698. #if QSV_HAVE_EXT_VP9_PARAM
  699. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  700. q->extvp9param.Header.BufferId = MFX_EXTBUFF_VP9_PARAM;
  701. q->extvp9param.Header.BufferSz = sizeof(q->extvp9param);
  702. q->extvp9param.WriteIVFHeaders = MFX_CODINGOPTION_OFF;
  703. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extvp9param;
  704. }
  705. #endif
  706. #if QSV_HAVE_EXT_HEVC_TILES
  707. if (avctx->codec_id == AV_CODEC_ID_HEVC) {
  708. q->exthevctiles.Header.BufferId = MFX_EXTBUFF_HEVC_TILES;
  709. q->exthevctiles.Header.BufferSz = sizeof(q->exthevctiles);
  710. q->exthevctiles.NumTileColumns = q->tile_cols;
  711. q->exthevctiles.NumTileRows = q->tile_rows;
  712. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->exthevctiles;
  713. }
  714. #endif
  715. if (!check_enc_param(avctx,q)) {
  716. av_log(avctx, AV_LOG_ERROR,
  717. "some encoding parameters are not supported by the QSV "
  718. "runtime. Please double check the input parameters.\n");
  719. return AVERROR(ENOSYS);
  720. }
  721. return 0;
  722. }
  723. static int qsv_retrieve_enc_jpeg_params(AVCodecContext *avctx, QSVEncContext *q)
  724. {
  725. int ret = 0;
  726. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  727. if (ret < 0)
  728. return ff_qsv_print_error(avctx, ret,
  729. "Error calling GetVideoParam");
  730. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  731. // for qsv mjpeg the return value maybe 0 so alloc the buffer
  732. if (q->packet_size == 0)
  733. q->packet_size = q->param.mfx.FrameInfo.Height * q->param.mfx.FrameInfo.Width * 4;
  734. return 0;
  735. }
  736. static int qsv_retrieve_enc_vp9_params(AVCodecContext *avctx, QSVEncContext *q)
  737. {
  738. int ret = 0;
  739. #if QSV_HAVE_EXT_VP9_PARAM
  740. mfxExtVP9Param vp9_extend_buf = {
  741. .Header.BufferId = MFX_EXTBUFF_VP9_PARAM,
  742. .Header.BufferSz = sizeof(vp9_extend_buf),
  743. };
  744. #endif
  745. #if QSV_HAVE_CO2
  746. mfxExtCodingOption2 co2 = {
  747. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  748. .Header.BufferSz = sizeof(co2),
  749. };
  750. #endif
  751. #if QSV_HAVE_CO3
  752. mfxExtCodingOption3 co3 = {
  753. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  754. .Header.BufferSz = sizeof(co3),
  755. };
  756. #endif
  757. mfxExtBuffer *ext_buffers[] = {
  758. #if QSV_HAVE_EXT_VP9_PARAM
  759. (mfxExtBuffer*)&vp9_extend_buf,
  760. #endif
  761. #if QSV_HAVE_CO2
  762. (mfxExtBuffer*)&co2,
  763. #endif
  764. #if QSV_HAVE_CO3
  765. (mfxExtBuffer*)&co3,
  766. #endif
  767. };
  768. q->param.ExtParam = ext_buffers;
  769. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  770. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  771. if (ret < 0)
  772. return ff_qsv_print_error(avctx, ret,
  773. "Error calling GetVideoParam");
  774. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  775. return 0;
  776. }
  777. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  778. {
  779. AVCPBProperties *cpb_props;
  780. uint8_t sps_buf[128];
  781. uint8_t pps_buf[128];
  782. mfxExtCodingOptionSPSPPS extradata = {
  783. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  784. .Header.BufferSz = sizeof(extradata),
  785. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  786. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  787. };
  788. mfxExtCodingOption co = {
  789. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  790. .Header.BufferSz = sizeof(co),
  791. };
  792. #if QSV_HAVE_CO2
  793. mfxExtCodingOption2 co2 = {
  794. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  795. .Header.BufferSz = sizeof(co2),
  796. };
  797. #endif
  798. #if QSV_HAVE_CO3
  799. mfxExtCodingOption3 co3 = {
  800. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  801. .Header.BufferSz = sizeof(co3),
  802. };
  803. #endif
  804. #if QSV_HAVE_CO_VPS
  805. uint8_t vps_buf[128];
  806. mfxExtCodingOptionVPS extradata_vps = {
  807. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_VPS,
  808. .Header.BufferSz = sizeof(extradata_vps),
  809. .VPSBuffer = vps_buf,
  810. .VPSBufSize = sizeof(vps_buf),
  811. };
  812. #endif
  813. #if QSV_HAVE_EXT_HEVC_TILES
  814. mfxExtHEVCTiles hevc_tile_buf = {
  815. .Header.BufferId = MFX_EXTBUFF_HEVC_TILES,
  816. .Header.BufferSz = sizeof(hevc_tile_buf),
  817. };
  818. #endif
  819. mfxExtBuffer *ext_buffers[2 + QSV_HAVE_CO2 + QSV_HAVE_CO3 + QSV_HAVE_CO_VPS + QSV_HAVE_EXT_HEVC_TILES];
  820. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  821. int ret, ext_buf_num = 0, extradata_offset = 0;
  822. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&extradata;
  823. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co;
  824. #if QSV_HAVE_CO2
  825. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co2;
  826. #endif
  827. #if QSV_HAVE_CO3
  828. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co3;
  829. #endif
  830. #if QSV_HAVE_CO_VPS
  831. q->hevc_vps = ((avctx->codec_id == AV_CODEC_ID_HEVC) && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 17));
  832. if (q->hevc_vps)
  833. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&extradata_vps;
  834. #endif
  835. #if QSV_HAVE_EXT_HEVC_TILES
  836. if (avctx->codec_id == AV_CODEC_ID_HEVC)
  837. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&hevc_tile_buf;
  838. #endif
  839. q->param.ExtParam = ext_buffers;
  840. q->param.NumExtParam = ext_buf_num;
  841. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  842. if (ret < 0)
  843. return ff_qsv_print_error(avctx, ret,
  844. "Error calling GetVideoParam");
  845. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  846. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)
  847. #if QSV_HAVE_CO_VPS
  848. || (q->hevc_vps && !extradata_vps.VPSBufSize)
  849. #endif
  850. ) {
  851. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  852. return AVERROR_UNKNOWN;
  853. }
  854. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  855. #if QSV_HAVE_CO_VPS
  856. avctx->extradata_size += q->hevc_vps * extradata_vps.VPSBufSize;
  857. #endif
  858. avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  859. if (!avctx->extradata)
  860. return AVERROR(ENOMEM);
  861. #if QSV_HAVE_CO_VPS
  862. if (q->hevc_vps) {
  863. memcpy(avctx->extradata, vps_buf, extradata_vps.VPSBufSize);
  864. extradata_offset += extradata_vps.VPSBufSize;
  865. }
  866. #endif
  867. memcpy(avctx->extradata + extradata_offset, sps_buf, extradata.SPSBufSize);
  868. extradata_offset += extradata.SPSBufSize;
  869. if (need_pps) {
  870. memcpy(avctx->extradata + extradata_offset, pps_buf, extradata.PPSBufSize);
  871. extradata_offset += extradata.PPSBufSize;
  872. }
  873. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  874. cpb_props = ff_add_cpb_side_data(avctx);
  875. if (!cpb_props)
  876. return AVERROR(ENOMEM);
  877. cpb_props->max_bitrate = avctx->rc_max_rate;
  878. cpb_props->min_bitrate = avctx->rc_min_rate;
  879. cpb_props->avg_bitrate = avctx->bit_rate;
  880. cpb_props->buffer_size = avctx->rc_buffer_size;
  881. dump_video_param(avctx, q, ext_buffers + 1);
  882. return 0;
  883. }
  884. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  885. {
  886. AVQSVContext *qsv = avctx->hwaccel_context;
  887. mfxFrameSurface1 *surfaces;
  888. int nb_surfaces, i;
  889. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested;
  890. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  891. if (!q->opaque_alloc_buf)
  892. return AVERROR(ENOMEM);
  893. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  894. if (!q->opaque_surfaces)
  895. return AVERROR(ENOMEM);
  896. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  897. for (i = 0; i < nb_surfaces; i++) {
  898. surfaces[i].Info = q->req.Info;
  899. q->opaque_surfaces[i] = surfaces + i;
  900. }
  901. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  902. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  903. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  904. q->opaque_alloc.In.NumSurface = nb_surfaces;
  905. q->opaque_alloc.In.Type = q->req.Type;
  906. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  907. qsv->nb_opaque_surfaces = nb_surfaces;
  908. qsv->opaque_surfaces = q->opaque_alloc_buf;
  909. qsv->opaque_alloc_type = q->req.Type;
  910. return 0;
  911. }
  912. static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
  913. {
  914. int ret;
  915. if (avctx->hwaccel_context) {
  916. AVQSVContext *qsv = avctx->hwaccel_context;
  917. q->session = qsv->session;
  918. } else if (avctx->hw_frames_ctx) {
  919. q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  920. if (!q->frames_ctx.hw_frames_ctx)
  921. return AVERROR(ENOMEM);
  922. ret = ff_qsv_init_session_frames(avctx, &q->internal_qs.session,
  923. &q->frames_ctx, q->load_plugins,
  924. q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY,
  925. MFX_GPUCOPY_OFF);
  926. if (ret < 0) {
  927. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  928. return ret;
  929. }
  930. q->session = q->internal_qs.session;
  931. } else if (avctx->hw_device_ctx) {
  932. ret = ff_qsv_init_session_device(avctx, &q->internal_qs.session,
  933. avctx->hw_device_ctx, q->load_plugins,
  934. MFX_GPUCOPY_OFF);
  935. if (ret < 0)
  936. return ret;
  937. q->session = q->internal_qs.session;
  938. } else {
  939. ret = ff_qsv_init_internal_session(avctx, &q->internal_qs,
  940. q->load_plugins, MFX_GPUCOPY_OFF);
  941. if (ret < 0)
  942. return ret;
  943. q->session = q->internal_qs.session;
  944. }
  945. return 0;
  946. }
  947. static inline unsigned int qsv_fifo_item_size(void)
  948. {
  949. return sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*);
  950. }
  951. static inline unsigned int qsv_fifo_size(const AVFifoBuffer* fifo)
  952. {
  953. return av_fifo_size(fifo)/qsv_fifo_item_size();
  954. }
  955. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  956. {
  957. int iopattern = 0;
  958. int opaque_alloc = 0;
  959. int ret;
  960. q->param.AsyncDepth = q->async_depth;
  961. q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
  962. if (!q->async_fifo)
  963. return AVERROR(ENOMEM);
  964. if (avctx->hwaccel_context) {
  965. AVQSVContext *qsv = avctx->hwaccel_context;
  966. iopattern = qsv->iopattern;
  967. opaque_alloc = qsv->opaque_alloc;
  968. }
  969. if (avctx->hw_frames_ctx) {
  970. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  971. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  972. if (!iopattern) {
  973. if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
  974. iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
  975. else if (frames_hwctx->frame_type &
  976. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  977. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  978. }
  979. }
  980. if (!iopattern)
  981. iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  982. q->param.IOPattern = iopattern;
  983. ret = qsvenc_init_session(avctx, q);
  984. if (ret < 0)
  985. return ret;
  986. ret = MFXQueryVersion(q->session,&q->ver);
  987. if (ret < 0) {
  988. return ff_qsv_print_error(avctx, ret,
  989. "Error querying mfx version");
  990. }
  991. // in the mfxInfoMFX struct, JPEG is different from other codecs
  992. switch (avctx->codec_id) {
  993. case AV_CODEC_ID_MJPEG:
  994. ret = init_video_param_jpeg(avctx, q);
  995. break;
  996. default:
  997. ret = init_video_param(avctx, q);
  998. break;
  999. }
  1000. if (ret < 0)
  1001. return ret;
  1002. if (avctx->hwaccel_context) {
  1003. AVQSVContext *qsv = avctx->hwaccel_context;
  1004. int i, j;
  1005. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  1006. sizeof(*q->extparam));
  1007. if (!q->extparam)
  1008. return AVERROR(ENOMEM);
  1009. q->param.ExtParam = q->extparam;
  1010. for (i = 0; i < qsv->nb_ext_buffers; i++)
  1011. q->param.ExtParam[i] = qsv->ext_buffers[i];
  1012. q->param.NumExtParam = qsv->nb_ext_buffers;
  1013. for (i = 0; i < q->nb_extparam_internal; i++) {
  1014. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  1015. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  1016. break;
  1017. }
  1018. if (j < qsv->nb_ext_buffers)
  1019. continue;
  1020. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  1021. }
  1022. } else {
  1023. q->param.ExtParam = q->extparam_internal;
  1024. q->param.NumExtParam = q->nb_extparam_internal;
  1025. }
  1026. ret = MFXVideoENCODE_Query(q->session, &q->param, &q->param);
  1027. if (ret == MFX_WRN_PARTIAL_ACCELERATION) {
  1028. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  1029. } else if (ret < 0) {
  1030. return ff_qsv_print_error(avctx, ret,
  1031. "Error querying encoder params");
  1032. }
  1033. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  1034. if (ret < 0)
  1035. return ff_qsv_print_error(avctx, ret,
  1036. "Error querying (IOSurf) the encoding parameters");
  1037. if (opaque_alloc) {
  1038. ret = qsv_init_opaque_alloc(avctx, q);
  1039. if (ret < 0)
  1040. return ret;
  1041. }
  1042. ret = MFXVideoENCODE_Init(q->session, &q->param);
  1043. if (ret < 0)
  1044. return ff_qsv_print_error(avctx, ret,
  1045. "Error initializing the encoder");
  1046. else if (ret > 0)
  1047. ff_qsv_print_warning(avctx, ret,
  1048. "Warning in encoder initialization");
  1049. switch (avctx->codec_id) {
  1050. case AV_CODEC_ID_MJPEG:
  1051. ret = qsv_retrieve_enc_jpeg_params(avctx, q);
  1052. break;
  1053. case AV_CODEC_ID_VP9:
  1054. ret = qsv_retrieve_enc_vp9_params(avctx, q);
  1055. break;
  1056. default:
  1057. ret = qsv_retrieve_enc_params(avctx, q);
  1058. break;
  1059. }
  1060. if (ret < 0) {
  1061. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  1062. return ret;
  1063. }
  1064. q->avctx = avctx;
  1065. return 0;
  1066. }
  1067. static void free_encoder_ctrl_payloads(mfxEncodeCtrl* enc_ctrl)
  1068. {
  1069. if (enc_ctrl) {
  1070. int i;
  1071. for (i = 0; i < enc_ctrl->NumPayload && i < QSV_MAX_ENC_PAYLOAD; i++) {
  1072. av_free(enc_ctrl->Payload[i]);
  1073. }
  1074. enc_ctrl->NumPayload = 0;
  1075. }
  1076. }
  1077. static void clear_unused_frames(QSVEncContext *q)
  1078. {
  1079. QSVFrame *cur = q->work_frames;
  1080. while (cur) {
  1081. if (cur->used && !cur->surface.Data.Locked) {
  1082. free_encoder_ctrl_payloads(&cur->enc_ctrl);
  1083. if (cur->frame->format == AV_PIX_FMT_QSV) {
  1084. av_frame_unref(cur->frame);
  1085. }
  1086. cur->used = 0;
  1087. }
  1088. cur = cur->next;
  1089. }
  1090. }
  1091. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  1092. {
  1093. QSVFrame *frame, **last;
  1094. clear_unused_frames(q);
  1095. frame = q->work_frames;
  1096. last = &q->work_frames;
  1097. while (frame) {
  1098. if (!frame->used) {
  1099. *f = frame;
  1100. frame->used = 1;
  1101. return 0;
  1102. }
  1103. last = &frame->next;
  1104. frame = frame->next;
  1105. }
  1106. frame = av_mallocz(sizeof(*frame));
  1107. if (!frame)
  1108. return AVERROR(ENOMEM);
  1109. frame->frame = av_frame_alloc();
  1110. if (!frame->frame) {
  1111. av_freep(&frame);
  1112. return AVERROR(ENOMEM);
  1113. }
  1114. frame->enc_ctrl.Payload = av_mallocz(sizeof(mfxPayload*) * QSV_MAX_ENC_PAYLOAD);
  1115. if (!frame->enc_ctrl.Payload) {
  1116. av_freep(&frame);
  1117. return AVERROR(ENOMEM);
  1118. }
  1119. *last = frame;
  1120. *f = frame;
  1121. frame->used = 1;
  1122. return 0;
  1123. }
  1124. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  1125. QSVFrame **new_frame)
  1126. {
  1127. QSVFrame *qf;
  1128. int ret;
  1129. ret = get_free_frame(q, &qf);
  1130. if (ret < 0)
  1131. return ret;
  1132. if (frame->format == AV_PIX_FMT_QSV) {
  1133. ret = av_frame_ref(qf->frame, frame);
  1134. if (ret < 0)
  1135. return ret;
  1136. qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
  1137. if (q->frames_ctx.mids) {
  1138. ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
  1139. if (ret < 0)
  1140. return ret;
  1141. qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
  1142. }
  1143. } else {
  1144. /* make a copy if the input is not padded as libmfx requires */
  1145. /* and to make allocation continious for data[0]/data[1] */
  1146. if ((frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) ||
  1147. (frame->data[1] - frame->data[0] != frame->linesize[0] * FFALIGN(qf->frame->height, q->height_align))) {
  1148. qf->frame->height = FFALIGN(frame->height, q->height_align);
  1149. qf->frame->width = FFALIGN(frame->width, q->width_align);
  1150. qf->frame->format = frame->format;
  1151. if (!qf->frame->data[0]) {
  1152. ret = av_frame_get_buffer(qf->frame, q->width_align);
  1153. if (ret < 0)
  1154. return ret;
  1155. }
  1156. qf->frame->height = frame->height;
  1157. qf->frame->width = frame->width;
  1158. ret = av_frame_copy(qf->frame, frame);
  1159. if (ret < 0) {
  1160. av_frame_unref(qf->frame);
  1161. return ret;
  1162. }
  1163. } else {
  1164. ret = av_frame_ref(qf->frame, frame);
  1165. if (ret < 0)
  1166. return ret;
  1167. }
  1168. qf->surface.Info = q->param.mfx.FrameInfo;
  1169. qf->surface.Info.PicStruct =
  1170. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  1171. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  1172. MFX_PICSTRUCT_FIELD_BFF;
  1173. if (frame->repeat_pict == 1)
  1174. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  1175. else if (frame->repeat_pict == 2)
  1176. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  1177. else if (frame->repeat_pict == 4)
  1178. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  1179. qf->surface.Data.PitchLow = qf->frame->linesize[0];
  1180. qf->surface.Data.Y = qf->frame->data[0];
  1181. qf->surface.Data.UV = qf->frame->data[1];
  1182. }
  1183. qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  1184. *new_frame = qf;
  1185. return 0;
  1186. }
  1187. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  1188. {
  1189. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  1190. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  1191. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  1192. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  1193. av_log(avctx, AV_LOG_WARNING,
  1194. "Interlaced coding is supported"
  1195. " at Main/High Profile Level 2.2-4.0\n");
  1196. }
  1197. }
  1198. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  1199. const AVFrame *frame)
  1200. {
  1201. AVPacket new_pkt = { 0 };
  1202. mfxBitstream *bs;
  1203. #if QSV_VERSION_ATLEAST(1, 26)
  1204. mfxExtAVCEncodedFrameInfo *enc_info;
  1205. mfxExtBuffer **enc_buf;
  1206. #endif
  1207. mfxFrameSurface1 *surf = NULL;
  1208. mfxSyncPoint *sync = NULL;
  1209. QSVFrame *qsv_frame = NULL;
  1210. mfxEncodeCtrl* enc_ctrl = NULL;
  1211. int ret;
  1212. if (frame) {
  1213. ret = submit_frame(q, frame, &qsv_frame);
  1214. if (ret < 0) {
  1215. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  1216. return ret;
  1217. }
  1218. }
  1219. if (qsv_frame) {
  1220. surf = &qsv_frame->surface;
  1221. enc_ctrl = &qsv_frame->enc_ctrl;
  1222. if (frame->pict_type == AV_PICTURE_TYPE_I) {
  1223. enc_ctrl->FrameType = MFX_FRAMETYPE_I | MFX_FRAMETYPE_REF;
  1224. if (q->forced_idr)
  1225. enc_ctrl->FrameType |= MFX_FRAMETYPE_IDR;
  1226. }
  1227. }
  1228. ret = av_new_packet(&new_pkt, q->packet_size);
  1229. if (ret < 0) {
  1230. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  1231. return ret;
  1232. }
  1233. bs = av_mallocz(sizeof(*bs));
  1234. if (!bs) {
  1235. av_packet_unref(&new_pkt);
  1236. return AVERROR(ENOMEM);
  1237. }
  1238. bs->Data = new_pkt.data;
  1239. bs->MaxLength = new_pkt.size;
  1240. #if QSV_VERSION_ATLEAST(1, 26)
  1241. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1242. enc_info = av_mallocz(sizeof(*enc_info));
  1243. if (!enc_info)
  1244. return AVERROR(ENOMEM);
  1245. enc_info->Header.BufferId = MFX_EXTBUFF_ENCODED_FRAME_INFO;
  1246. enc_info->Header.BufferSz = sizeof (*enc_info);
  1247. bs->NumExtParam = 1;
  1248. enc_buf = av_mallocz(sizeof(mfxExtBuffer *));
  1249. if (!enc_buf)
  1250. return AVERROR(ENOMEM);
  1251. enc_buf[0] = (mfxExtBuffer *)enc_info;
  1252. bs->ExtParam = enc_buf;
  1253. }
  1254. #endif
  1255. if (q->set_encode_ctrl_cb) {
  1256. q->set_encode_ctrl_cb(avctx, frame, &qsv_frame->enc_ctrl);
  1257. }
  1258. sync = av_mallocz(sizeof(*sync));
  1259. if (!sync) {
  1260. av_freep(&bs);
  1261. #if QSV_VERSION_ATLEAST(1, 26)
  1262. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1263. av_freep(&enc_info);
  1264. av_freep(&enc_buf);
  1265. }
  1266. #endif
  1267. av_packet_unref(&new_pkt);
  1268. return AVERROR(ENOMEM);
  1269. }
  1270. do {
  1271. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, bs, sync);
  1272. if (ret == MFX_WRN_DEVICE_BUSY)
  1273. av_usleep(500);
  1274. } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
  1275. if (ret > 0)
  1276. ff_qsv_print_warning(avctx, ret, "Warning during encoding");
  1277. if (ret < 0) {
  1278. av_packet_unref(&new_pkt);
  1279. av_freep(&bs);
  1280. #if QSV_VERSION_ATLEAST(1, 26)
  1281. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1282. av_freep(&enc_info);
  1283. av_freep(&enc_buf);
  1284. }
  1285. #endif
  1286. av_freep(&sync);
  1287. return (ret == MFX_ERR_MORE_DATA) ?
  1288. 0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
  1289. }
  1290. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  1291. print_interlace_msg(avctx, q);
  1292. if (*sync) {
  1293. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1294. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  1295. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  1296. } else {
  1297. av_freep(&sync);
  1298. av_packet_unref(&new_pkt);
  1299. av_freep(&bs);
  1300. #if QSV_VERSION_ATLEAST(1, 26)
  1301. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1302. av_freep(&enc_info);
  1303. av_freep(&enc_buf);
  1304. }
  1305. #endif
  1306. }
  1307. return 0;
  1308. }
  1309. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  1310. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  1311. {
  1312. int ret;
  1313. ret = encode_frame(avctx, q, frame);
  1314. if (ret < 0)
  1315. return ret;
  1316. if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
  1317. (!frame && av_fifo_size(q->async_fifo))) {
  1318. AVPacket new_pkt;
  1319. mfxBitstream *bs;
  1320. mfxSyncPoint *sync;
  1321. #if QSV_VERSION_ATLEAST(1, 26)
  1322. mfxExtAVCEncodedFrameInfo *enc_info;
  1323. mfxExtBuffer **enc_buf;
  1324. #endif
  1325. enum AVPictureType pict_type;
  1326. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1327. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1328. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1329. do {
  1330. ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
  1331. } while (ret == MFX_WRN_IN_EXECUTION);
  1332. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1333. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1334. new_pkt.size = bs->DataLength;
  1335. if (bs->FrameType & MFX_FRAMETYPE_IDR || bs->FrameType & MFX_FRAMETYPE_xIDR) {
  1336. new_pkt.flags |= AV_PKT_FLAG_KEY;
  1337. pict_type = AV_PICTURE_TYPE_I;
  1338. } else if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  1339. pict_type = AV_PICTURE_TYPE_I;
  1340. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  1341. pict_type = AV_PICTURE_TYPE_P;
  1342. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  1343. pict_type = AV_PICTURE_TYPE_B;
  1344. else if (bs->FrameType == MFX_FRAMETYPE_UNKNOWN) {
  1345. pict_type = AV_PICTURE_TYPE_NONE;
  1346. av_log(avctx, AV_LOG_WARNING, "Unknown FrameType, set pict_type to AV_PICTURE_TYPE_NONE.\n");
  1347. } else {
  1348. av_log(avctx, AV_LOG_ERROR, "Invalid FrameType:%d.\n", bs->FrameType);
  1349. return AVERROR_INVALIDDATA;
  1350. }
  1351. #if FF_API_CODED_FRAME
  1352. FF_DISABLE_DEPRECATION_WARNINGS
  1353. avctx->coded_frame->pict_type = pict_type;
  1354. FF_ENABLE_DEPRECATION_WARNINGS
  1355. #endif
  1356. #if QSV_VERSION_ATLEAST(1, 26)
  1357. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1358. enc_buf = bs->ExtParam;
  1359. enc_info = (mfxExtAVCEncodedFrameInfo *)(*bs->ExtParam);
  1360. ff_side_data_set_encoder_stats(&new_pkt,
  1361. enc_info->QP * FF_QP2LAMBDA, NULL, 0, pict_type);
  1362. av_freep(&enc_info);
  1363. av_freep(&enc_buf);
  1364. }
  1365. #endif
  1366. av_freep(&bs);
  1367. av_freep(&sync);
  1368. if (pkt->data) {
  1369. if (pkt->size < new_pkt.size) {
  1370. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  1371. pkt->size, new_pkt.size);
  1372. av_packet_unref(&new_pkt);
  1373. return AVERROR(EINVAL);
  1374. }
  1375. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  1376. pkt->size = new_pkt.size;
  1377. ret = av_packet_copy_props(pkt, &new_pkt);
  1378. av_packet_unref(&new_pkt);
  1379. if (ret < 0)
  1380. return ret;
  1381. } else
  1382. *pkt = new_pkt;
  1383. *got_packet = 1;
  1384. }
  1385. return 0;
  1386. }
  1387. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  1388. {
  1389. QSVFrame *cur;
  1390. if (q->session)
  1391. MFXVideoENCODE_Close(q->session);
  1392. q->session = NULL;
  1393. ff_qsv_close_internal_session(&q->internal_qs);
  1394. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  1395. av_buffer_unref(&q->frames_ctx.mids_buf);
  1396. cur = q->work_frames;
  1397. while (cur) {
  1398. q->work_frames = cur->next;
  1399. av_frame_free(&cur->frame);
  1400. av_free(cur->enc_ctrl.Payload);
  1401. av_freep(&cur);
  1402. cur = q->work_frames;
  1403. }
  1404. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  1405. AVPacket pkt;
  1406. mfxSyncPoint *sync;
  1407. mfxBitstream *bs;
  1408. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  1409. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1410. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1411. av_freep(&sync);
  1412. av_freep(&bs);
  1413. av_packet_unref(&pkt);
  1414. }
  1415. av_fifo_free(q->async_fifo);
  1416. q->async_fifo = NULL;
  1417. av_freep(&q->opaque_surfaces);
  1418. av_buffer_unref(&q->opaque_alloc_buf);
  1419. av_freep(&q->extparam);
  1420. return 0;
  1421. }
  1422. const AVCodecHWConfigInternal *const ff_qsv_enc_hw_configs[] = {
  1423. HW_CONFIG_ENCODER_FRAMES(QSV, QSV),
  1424. HW_CONFIG_ENCODER_DEVICE(NV12, QSV),
  1425. HW_CONFIG_ENCODER_DEVICE(P010, QSV),
  1426. NULL,
  1427. };