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.

1497 lines
52KB

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