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.

1294 lines
44KB

  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
  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. "InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"\n",
  150. 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.FrameRateExtN))
  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. q->param.mfx.CodecProfile = q->profile;
  414. q->param.mfx.TargetUsage = q->preset;
  415. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  416. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  417. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  418. MFX_GOP_CLOSED : 0;
  419. q->param.mfx.IdrInterval = q->idr_interval;
  420. q->param.mfx.NumSlice = avctx->slices;
  421. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  422. q->param.mfx.EncodedOrder = 0;
  423. q->param.mfx.BufferSizeInKB = 0;
  424. desc = av_pix_fmt_desc_get(sw_format);
  425. if (!desc)
  426. return AVERROR_BUG;
  427. ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
  428. q->param.mfx.FrameInfo.CropX = 0;
  429. q->param.mfx.FrameInfo.CropY = 0;
  430. q->param.mfx.FrameInfo.CropW = avctx->width;
  431. q->param.mfx.FrameInfo.CropH = avctx->height;
  432. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  433. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  434. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  435. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  436. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  437. q->param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
  438. // TODO: detect version of MFX--if the minor version is greater than
  439. // or equal to 19, then can use the same alignment settings as H.264
  440. // for HEVC
  441. q->width_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  442. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  443. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  444. // it is important that PicStruct be setup correctly from the
  445. // start--otherwise, encoding doesn't work and results in a bunch
  446. // of incompatible video parameter errors
  447. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
  448. // height alignment always must be 32 for interlaced video
  449. q->height_align = 32;
  450. } else {
  451. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  452. // for progressive video, the height should be aligned to 16 for
  453. // H.264. For HEVC, depending on the version of MFX, it should be
  454. // either 32 or 16. The lower number is better if possible.
  455. q->height_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  456. }
  457. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  458. if (avctx->hw_frames_ctx) {
  459. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  460. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  461. q->param.mfx.FrameInfo.Width = frames_hwctx->surfaces[0].Info.Width;
  462. q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
  463. }
  464. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  465. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  466. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  467. } else {
  468. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  469. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  470. }
  471. ret = select_rc_mode(avctx, q);
  472. if (ret < 0)
  473. return ret;
  474. switch (q->param.mfx.RateControlMethod) {
  475. case MFX_RATECONTROL_CBR:
  476. case MFX_RATECONTROL_VBR:
  477. #if QSV_HAVE_VCM
  478. case MFX_RATECONTROL_VCM:
  479. #endif
  480. q->param.mfx.BufferSizeInKB = avctx->rc_buffer_size / 8000;
  481. q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
  482. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  483. q->param.mfx.MaxKbps = avctx->rc_max_rate / 1000;
  484. break;
  485. case MFX_RATECONTROL_CQP:
  486. quant = avctx->global_quality / FF_QP2LAMBDA;
  487. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  488. q->param.mfx.QPP = av_clip(quant, 0, 51);
  489. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  490. break;
  491. #if QSV_HAVE_AVBR
  492. case MFX_RATECONTROL_AVBR:
  493. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  494. q->param.mfx.Convergence = q->avbr_convergence;
  495. q->param.mfx.Accuracy = q->avbr_accuracy;
  496. break;
  497. #endif
  498. #if QSV_HAVE_LA
  499. case MFX_RATECONTROL_LA:
  500. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  501. q->extco2.LookAheadDepth = q->la_depth;
  502. break;
  503. #if QSV_HAVE_ICQ
  504. case MFX_RATECONTROL_LA_ICQ:
  505. q->extco2.LookAheadDepth = q->la_depth;
  506. case MFX_RATECONTROL_ICQ:
  507. q->param.mfx.ICQQuality = avctx->global_quality;
  508. break;
  509. #endif
  510. #endif
  511. }
  512. // the HEVC encoder plugin currently fails if coding options
  513. // are provided
  514. if (avctx->codec_id != AV_CODEC_ID_HEVC) {
  515. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  516. q->extco.Header.BufferSz = sizeof(q->extco);
  517. if (q->rdo >= 0)
  518. q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  519. if (avctx->codec_id == AV_CODEC_ID_H264) {
  520. #if FF_API_CODER_TYPE
  521. FF_DISABLE_DEPRECATION_WARNINGS
  522. if (avctx->coder_type >= 0)
  523. q->cavlc = avctx->coder_type == FF_CODER_TYPE_VLC;
  524. FF_ENABLE_DEPRECATION_WARNINGS
  525. #endif
  526. q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
  527. : MFX_CODINGOPTION_UNKNOWN;
  528. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  529. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  530. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  531. if (q->single_sei_nal_unit >= 0)
  532. q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  533. if (q->recovery_point_sei >= 0)
  534. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  535. q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
  536. }
  537. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  538. #if QSV_HAVE_CO2
  539. if (avctx->codec_id == AV_CODEC_ID_H264) {
  540. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  541. q->extco2.Header.BufferSz = sizeof(q->extco2);
  542. if (q->int_ref_type >= 0)
  543. q->extco2.IntRefType = q->int_ref_type;
  544. if (q->int_ref_cycle_size >= 0)
  545. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  546. if (q->int_ref_qp_delta != INT16_MIN)
  547. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  548. if (q->bitrate_limit >= 0)
  549. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  550. if (q->mbbrc >= 0)
  551. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  552. if (q->extbrc >= 0)
  553. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  554. if (q->max_frame_size >= 0)
  555. q->extco2.MaxFrameSize = q->max_frame_size;
  556. #if QSV_HAVE_MAX_SLICE_SIZE
  557. if (q->max_slice_size >= 0)
  558. q->extco2.MaxSliceSize = q->max_slice_size;
  559. #endif
  560. #if QSV_HAVE_TRELLIS
  561. q->extco2.Trellis = q->trellis;
  562. #endif
  563. #if QSV_HAVE_LA_DS
  564. q->extco2.LookAheadDS = q->la_ds;
  565. #endif
  566. #if QSV_HAVE_BREF_TYPE
  567. #if FF_API_PRIVATE_OPT
  568. FF_DISABLE_DEPRECATION_WARNINGS
  569. if (avctx->b_frame_strategy >= 0)
  570. q->b_strategy = avctx->b_frame_strategy;
  571. FF_ENABLE_DEPRECATION_WARNINGS
  572. #endif
  573. if (q->b_strategy >= 0)
  574. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  575. if (q->adaptive_i >= 0)
  576. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  577. if (q->adaptive_b >= 0)
  578. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  579. #endif
  580. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  581. }
  582. #endif
  583. }
  584. if (!check_enc_param(avctx,q)) {
  585. av_log(avctx, AV_LOG_ERROR,
  586. "some encoding parameters are not supported by the QSV "
  587. "runtime. Please double check the input parameters.\n");
  588. return AVERROR(ENOSYS);
  589. }
  590. return 0;
  591. }
  592. static int qsv_retrieve_enc_jpeg_params(AVCodecContext *avctx, QSVEncContext *q)
  593. {
  594. int ret = 0;
  595. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  596. if (ret < 0)
  597. return ff_qsv_print_error(avctx, ret,
  598. "Error calling GetVideoParam");
  599. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  600. // for qsv mjpeg the return value maybe 0 so alloc the buffer
  601. if (q->packet_size == 0)
  602. q->packet_size = q->param.mfx.FrameInfo.Height * q->param.mfx.FrameInfo.Width * 4;
  603. return 0;
  604. }
  605. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  606. {
  607. AVCPBProperties *cpb_props;
  608. uint8_t sps_buf[128];
  609. uint8_t pps_buf[128];
  610. mfxExtCodingOptionSPSPPS extradata = {
  611. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  612. .Header.BufferSz = sizeof(extradata),
  613. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  614. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  615. };
  616. mfxExtCodingOption co = {
  617. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  618. .Header.BufferSz = sizeof(co),
  619. };
  620. #if QSV_HAVE_CO2
  621. mfxExtCodingOption2 co2 = {
  622. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  623. .Header.BufferSz = sizeof(co2),
  624. };
  625. #endif
  626. #if QSV_HAVE_CO3
  627. mfxExtCodingOption3 co3 = {
  628. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  629. .Header.BufferSz = sizeof(co3),
  630. };
  631. #endif
  632. mfxExtBuffer *ext_buffers[] = {
  633. (mfxExtBuffer*)&extradata,
  634. (mfxExtBuffer*)&co,
  635. #if QSV_HAVE_CO2
  636. (mfxExtBuffer*)&co2,
  637. #endif
  638. #if QSV_HAVE_CO3
  639. (mfxExtBuffer*)&co3,
  640. #endif
  641. };
  642. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  643. int ret;
  644. q->param.ExtParam = ext_buffers;
  645. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  646. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  647. if (ret < 0)
  648. return ff_qsv_print_error(avctx, ret,
  649. "Error calling GetVideoParam");
  650. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  651. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  652. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  653. return AVERROR_UNKNOWN;
  654. }
  655. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  656. AV_INPUT_BUFFER_PADDING_SIZE);
  657. if (!avctx->extradata)
  658. return AVERROR(ENOMEM);
  659. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  660. if (need_pps)
  661. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  662. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  663. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  664. cpb_props = ff_add_cpb_side_data(avctx);
  665. if (!cpb_props)
  666. return AVERROR(ENOMEM);
  667. cpb_props->max_bitrate = avctx->rc_max_rate;
  668. cpb_props->min_bitrate = avctx->rc_min_rate;
  669. cpb_props->avg_bitrate = avctx->bit_rate;
  670. cpb_props->buffer_size = avctx->rc_buffer_size;
  671. dump_video_param(avctx, q, ext_buffers + 1);
  672. return 0;
  673. }
  674. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  675. {
  676. AVQSVContext *qsv = avctx->hwaccel_context;
  677. mfxFrameSurface1 *surfaces;
  678. int nb_surfaces, i;
  679. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested + q->async_depth;
  680. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  681. if (!q->opaque_alloc_buf)
  682. return AVERROR(ENOMEM);
  683. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  684. if (!q->opaque_surfaces)
  685. return AVERROR(ENOMEM);
  686. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  687. for (i = 0; i < nb_surfaces; i++) {
  688. surfaces[i].Info = q->req.Info;
  689. q->opaque_surfaces[i] = surfaces + i;
  690. }
  691. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  692. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  693. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  694. q->opaque_alloc.In.NumSurface = nb_surfaces;
  695. q->opaque_alloc.In.Type = q->req.Type;
  696. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  697. qsv->nb_opaque_surfaces = nb_surfaces;
  698. qsv->opaque_surfaces = q->opaque_alloc_buf;
  699. qsv->opaque_alloc_type = q->req.Type;
  700. return 0;
  701. }
  702. static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
  703. {
  704. int ret;
  705. if (avctx->hwaccel_context) {
  706. AVQSVContext *qsv = avctx->hwaccel_context;
  707. q->session = qsv->session;
  708. } else if (avctx->hw_frames_ctx) {
  709. q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  710. if (!q->frames_ctx.hw_frames_ctx)
  711. return AVERROR(ENOMEM);
  712. ret = ff_qsv_init_session_frames(avctx, &q->internal_session,
  713. &q->frames_ctx, q->load_plugins,
  714. q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY);
  715. if (ret < 0) {
  716. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  717. return ret;
  718. }
  719. q->session = q->internal_session;
  720. } else if (avctx->hw_device_ctx) {
  721. ret = ff_qsv_init_session_device(avctx, &q->internal_session,
  722. avctx->hw_device_ctx, q->load_plugins);
  723. if (ret < 0)
  724. return ret;
  725. q->session = q->internal_session;
  726. } else {
  727. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  728. q->load_plugins);
  729. if (ret < 0)
  730. return ret;
  731. q->session = q->internal_session;
  732. }
  733. return 0;
  734. }
  735. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  736. {
  737. int iopattern = 0;
  738. int opaque_alloc = 0;
  739. int ret;
  740. q->param.AsyncDepth = q->async_depth;
  741. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  742. (sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*)));
  743. if (!q->async_fifo)
  744. return AVERROR(ENOMEM);
  745. if (avctx->hwaccel_context) {
  746. AVQSVContext *qsv = avctx->hwaccel_context;
  747. iopattern = qsv->iopattern;
  748. opaque_alloc = qsv->opaque_alloc;
  749. }
  750. if (avctx->hw_frames_ctx) {
  751. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  752. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  753. if (!iopattern) {
  754. if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
  755. iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
  756. else if (frames_hwctx->frame_type &
  757. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  758. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  759. }
  760. }
  761. if (!iopattern)
  762. iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  763. q->param.IOPattern = iopattern;
  764. ret = qsvenc_init_session(avctx, q);
  765. if (ret < 0)
  766. return ret;
  767. // in the mfxInfoMFX struct, JPEG is different from other codecs
  768. switch (avctx->codec_id) {
  769. case AV_CODEC_ID_MJPEG:
  770. ret = init_video_param_jpeg(avctx, q);
  771. break;
  772. default:
  773. ret = init_video_param(avctx, q);
  774. break;
  775. }
  776. if (ret < 0)
  777. return ret;
  778. ret = MFXVideoENCODE_Query(q->session, &q->param, &q->param);
  779. if (ret == MFX_WRN_PARTIAL_ACCELERATION) {
  780. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  781. } else if (ret < 0) {
  782. return ff_qsv_print_error(avctx, ret,
  783. "Error querying encoder params");
  784. }
  785. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  786. if (ret < 0)
  787. return ff_qsv_print_error(avctx, ret,
  788. "Error querying (IOSurf) the encoding parameters");
  789. if (opaque_alloc) {
  790. ret = qsv_init_opaque_alloc(avctx, q);
  791. if (ret < 0)
  792. return ret;
  793. }
  794. if (avctx->hwaccel_context) {
  795. AVQSVContext *qsv = avctx->hwaccel_context;
  796. int i, j;
  797. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  798. sizeof(*q->extparam));
  799. if (!q->extparam)
  800. return AVERROR(ENOMEM);
  801. q->param.ExtParam = q->extparam;
  802. for (i = 0; i < qsv->nb_ext_buffers; i++)
  803. q->param.ExtParam[i] = qsv->ext_buffers[i];
  804. q->param.NumExtParam = qsv->nb_ext_buffers;
  805. for (i = 0; i < q->nb_extparam_internal; i++) {
  806. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  807. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  808. break;
  809. }
  810. if (j < qsv->nb_ext_buffers)
  811. continue;
  812. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  813. }
  814. } else {
  815. q->param.ExtParam = q->extparam_internal;
  816. q->param.NumExtParam = q->nb_extparam_internal;
  817. }
  818. ret = MFXVideoENCODE_Init(q->session, &q->param);
  819. if (ret < 0)
  820. return ff_qsv_print_error(avctx, ret,
  821. "Error initializing the encoder");
  822. else if (ret > 0)
  823. ff_qsv_print_warning(avctx, ret,
  824. "Warning in encoder initialization");
  825. switch (avctx->codec_id) {
  826. case AV_CODEC_ID_MJPEG:
  827. ret = qsv_retrieve_enc_jpeg_params(avctx, q);
  828. break;
  829. default:
  830. ret = qsv_retrieve_enc_params(avctx, q);
  831. break;
  832. }
  833. if (ret < 0) {
  834. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  835. return ret;
  836. }
  837. q->avctx = avctx;
  838. return 0;
  839. }
  840. static void clear_unused_frames(QSVEncContext *q)
  841. {
  842. QSVFrame *cur = q->work_frames;
  843. while (cur) {
  844. if (cur->used && !cur->surface.Data.Locked) {
  845. av_frame_unref(cur->frame);
  846. cur->used = 0;
  847. }
  848. cur = cur->next;
  849. }
  850. }
  851. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  852. {
  853. QSVFrame *frame, **last;
  854. clear_unused_frames(q);
  855. frame = q->work_frames;
  856. last = &q->work_frames;
  857. while (frame) {
  858. if (!frame->used) {
  859. *f = frame;
  860. frame->used = 1;
  861. return 0;
  862. }
  863. last = &frame->next;
  864. frame = frame->next;
  865. }
  866. frame = av_mallocz(sizeof(*frame));
  867. if (!frame)
  868. return AVERROR(ENOMEM);
  869. frame->frame = av_frame_alloc();
  870. if (!frame->frame) {
  871. av_freep(&frame);
  872. return AVERROR(ENOMEM);
  873. }
  874. *last = frame;
  875. *f = frame;
  876. frame->used = 1;
  877. return 0;
  878. }
  879. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  880. mfxFrameSurface1 **surface)
  881. {
  882. QSVFrame *qf;
  883. int ret;
  884. ret = get_free_frame(q, &qf);
  885. if (ret < 0)
  886. return ret;
  887. if (frame->format == AV_PIX_FMT_QSV) {
  888. ret = av_frame_ref(qf->frame, frame);
  889. if (ret < 0)
  890. return ret;
  891. qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
  892. if (q->frames_ctx.mids) {
  893. ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
  894. if (ret < 0)
  895. return ret;
  896. qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
  897. }
  898. } else {
  899. /* make a copy if the input is not padded as libmfx requires */
  900. if (frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) {
  901. qf->frame->height = FFALIGN(frame->height, q->height_align);
  902. qf->frame->width = FFALIGN(frame->width, q->width_align);
  903. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  904. if (ret < 0)
  905. return ret;
  906. qf->frame->height = frame->height;
  907. qf->frame->width = frame->width;
  908. ret = av_frame_copy(qf->frame, frame);
  909. if (ret < 0) {
  910. av_frame_unref(qf->frame);
  911. return ret;
  912. }
  913. } else {
  914. ret = av_frame_ref(qf->frame, frame);
  915. if (ret < 0)
  916. return ret;
  917. }
  918. qf->surface.Info = q->param.mfx.FrameInfo;
  919. qf->surface.Info.PicStruct =
  920. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  921. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  922. MFX_PICSTRUCT_FIELD_BFF;
  923. if (frame->repeat_pict == 1)
  924. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  925. else if (frame->repeat_pict == 2)
  926. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  927. else if (frame->repeat_pict == 4)
  928. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  929. qf->surface.Data.PitchLow = qf->frame->linesize[0];
  930. qf->surface.Data.Y = qf->frame->data[0];
  931. qf->surface.Data.UV = qf->frame->data[1];
  932. }
  933. qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  934. *surface = &qf->surface;
  935. return 0;
  936. }
  937. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  938. {
  939. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  940. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  941. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  942. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  943. av_log(avctx, AV_LOG_WARNING,
  944. "Interlaced coding is supported"
  945. " at Main/High Profile Level 2.1-4.1\n");
  946. }
  947. }
  948. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  949. const AVFrame *frame)
  950. {
  951. AVPacket new_pkt = { 0 };
  952. mfxBitstream *bs;
  953. mfxFrameSurface1 *surf = NULL;
  954. mfxSyncPoint *sync = NULL;
  955. int ret;
  956. if (frame) {
  957. ret = submit_frame(q, frame, &surf);
  958. if (ret < 0) {
  959. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  960. return ret;
  961. }
  962. }
  963. ret = av_new_packet(&new_pkt, q->packet_size);
  964. if (ret < 0) {
  965. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  966. return ret;
  967. }
  968. bs = av_mallocz(sizeof(*bs));
  969. if (!bs) {
  970. av_packet_unref(&new_pkt);
  971. return AVERROR(ENOMEM);
  972. }
  973. bs->Data = new_pkt.data;
  974. bs->MaxLength = new_pkt.size;
  975. sync = av_mallocz(sizeof(*sync));
  976. if (!sync) {
  977. av_freep(&bs);
  978. av_packet_unref(&new_pkt);
  979. return AVERROR(ENOMEM);
  980. }
  981. do {
  982. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, sync);
  983. if (ret == MFX_WRN_DEVICE_BUSY)
  984. av_usleep(1);
  985. } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
  986. if (ret > 0)
  987. ff_qsv_print_warning(avctx, ret, "Warning during encoding");
  988. if (ret < 0) {
  989. av_packet_unref(&new_pkt);
  990. av_freep(&bs);
  991. av_freep(&sync);
  992. return (ret == MFX_ERR_MORE_DATA) ?
  993. 0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
  994. }
  995. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  996. print_interlace_msg(avctx, q);
  997. if (*sync) {
  998. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  999. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  1000. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  1001. } else {
  1002. av_freep(&sync);
  1003. av_packet_unref(&new_pkt);
  1004. av_freep(&bs);
  1005. }
  1006. return 0;
  1007. }
  1008. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  1009. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  1010. {
  1011. int ret;
  1012. ret = encode_frame(avctx, q, frame);
  1013. if (ret < 0)
  1014. return ret;
  1015. if (!av_fifo_space(q->async_fifo) ||
  1016. (!frame && av_fifo_size(q->async_fifo))) {
  1017. AVPacket new_pkt;
  1018. mfxBitstream *bs;
  1019. mfxSyncPoint *sync;
  1020. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1021. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1022. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1023. do {
  1024. ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
  1025. } while (ret == MFX_WRN_IN_EXECUTION);
  1026. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1027. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1028. new_pkt.size = bs->DataLength;
  1029. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  1030. bs->FrameType & MFX_FRAMETYPE_xIDR)
  1031. new_pkt.flags |= AV_PKT_FLAG_KEY;
  1032. #if FF_API_CODED_FRAME
  1033. FF_DISABLE_DEPRECATION_WARNINGS
  1034. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  1035. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  1036. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  1037. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  1038. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  1039. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  1040. FF_ENABLE_DEPRECATION_WARNINGS
  1041. #endif
  1042. av_freep(&bs);
  1043. av_freep(&sync);
  1044. if (pkt->data) {
  1045. if (pkt->size < new_pkt.size) {
  1046. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  1047. pkt->size, new_pkt.size);
  1048. av_packet_unref(&new_pkt);
  1049. return AVERROR(EINVAL);
  1050. }
  1051. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  1052. pkt->size = new_pkt.size;
  1053. ret = av_packet_copy_props(pkt, &new_pkt);
  1054. av_packet_unref(&new_pkt);
  1055. if (ret < 0)
  1056. return ret;
  1057. } else
  1058. *pkt = new_pkt;
  1059. *got_packet = 1;
  1060. }
  1061. return 0;
  1062. }
  1063. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  1064. {
  1065. QSVFrame *cur;
  1066. if (q->session)
  1067. MFXVideoENCODE_Close(q->session);
  1068. if (q->internal_session)
  1069. MFXClose(q->internal_session);
  1070. q->session = NULL;
  1071. q->internal_session = NULL;
  1072. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  1073. av_buffer_unref(&q->frames_ctx.mids_buf);
  1074. cur = q->work_frames;
  1075. while (cur) {
  1076. q->work_frames = cur->next;
  1077. av_frame_free(&cur->frame);
  1078. av_freep(&cur);
  1079. cur = q->work_frames;
  1080. }
  1081. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  1082. AVPacket pkt;
  1083. mfxSyncPoint *sync;
  1084. mfxBitstream *bs;
  1085. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  1086. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1087. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1088. av_freep(&sync);
  1089. av_freep(&bs);
  1090. av_packet_unref(&pkt);
  1091. }
  1092. av_fifo_free(q->async_fifo);
  1093. q->async_fifo = NULL;
  1094. av_freep(&q->opaque_surfaces);
  1095. av_buffer_unref(&q->opaque_alloc_buf);
  1096. av_freep(&q->extparam);
  1097. return 0;
  1098. }