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.

1542 lines
54KB

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