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.

1613 lines
56KB

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