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.

1355 lines
47KB

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