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.

1649 lines
57KB

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