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.

1106 lines
37KB

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