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.

1260 lines
43KB

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