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.

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