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.

1295 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.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. 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. q->extco.AUDelimiter = q->aud ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  537. }
  538. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  539. #if QSV_HAVE_CO2
  540. if (avctx->codec_id == AV_CODEC_ID_H264) {
  541. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  542. q->extco2.Header.BufferSz = sizeof(q->extco2);
  543. if (q->int_ref_type >= 0)
  544. q->extco2.IntRefType = q->int_ref_type;
  545. if (q->int_ref_cycle_size >= 0)
  546. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  547. if (q->int_ref_qp_delta != INT16_MIN)
  548. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  549. if (q->bitrate_limit >= 0)
  550. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  551. if (q->mbbrc >= 0)
  552. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  553. if (q->extbrc >= 0)
  554. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  555. if (q->max_frame_size >= 0)
  556. q->extco2.MaxFrameSize = q->max_frame_size;
  557. #if QSV_HAVE_MAX_SLICE_SIZE
  558. if (q->max_slice_size >= 0)
  559. q->extco2.MaxSliceSize = q->max_slice_size;
  560. #endif
  561. #if QSV_HAVE_TRELLIS
  562. q->extco2.Trellis = q->trellis;
  563. #endif
  564. #if QSV_HAVE_LA_DS
  565. q->extco2.LookAheadDS = q->la_ds;
  566. #endif
  567. #if QSV_HAVE_BREF_TYPE
  568. #if FF_API_PRIVATE_OPT
  569. FF_DISABLE_DEPRECATION_WARNINGS
  570. if (avctx->b_frame_strategy >= 0)
  571. q->b_strategy = avctx->b_frame_strategy;
  572. FF_ENABLE_DEPRECATION_WARNINGS
  573. #endif
  574. if (q->b_strategy >= 0)
  575. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  576. if (q->adaptive_i >= 0)
  577. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  578. if (q->adaptive_b >= 0)
  579. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  580. #endif
  581. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  582. }
  583. #endif
  584. }
  585. if (!check_enc_param(avctx,q)) {
  586. av_log(avctx, AV_LOG_ERROR,
  587. "some encoding parameters are not supported by the QSV "
  588. "runtime. Please double check the input parameters.\n");
  589. return AVERROR(ENOSYS);
  590. }
  591. return 0;
  592. }
  593. static int qsv_retrieve_enc_jpeg_params(AVCodecContext *avctx, QSVEncContext *q)
  594. {
  595. int ret = 0;
  596. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  597. if (ret < 0)
  598. return ff_qsv_print_error(avctx, ret,
  599. "Error calling GetVideoParam");
  600. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  601. // for qsv mjpeg the return value maybe 0 so alloc the buffer
  602. if (q->packet_size == 0)
  603. q->packet_size = q->param.mfx.FrameInfo.Height * q->param.mfx.FrameInfo.Width * 4;
  604. return 0;
  605. }
  606. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  607. {
  608. AVCPBProperties *cpb_props;
  609. uint8_t sps_buf[128];
  610. uint8_t pps_buf[128];
  611. mfxExtCodingOptionSPSPPS extradata = {
  612. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  613. .Header.BufferSz = sizeof(extradata),
  614. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  615. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  616. };
  617. mfxExtCodingOption co = {
  618. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  619. .Header.BufferSz = sizeof(co),
  620. };
  621. #if QSV_HAVE_CO2
  622. mfxExtCodingOption2 co2 = {
  623. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  624. .Header.BufferSz = sizeof(co2),
  625. };
  626. #endif
  627. #if QSV_HAVE_CO3
  628. mfxExtCodingOption3 co3 = {
  629. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  630. .Header.BufferSz = sizeof(co3),
  631. };
  632. #endif
  633. mfxExtBuffer *ext_buffers[] = {
  634. (mfxExtBuffer*)&extradata,
  635. (mfxExtBuffer*)&co,
  636. #if QSV_HAVE_CO2
  637. (mfxExtBuffer*)&co2,
  638. #endif
  639. #if QSV_HAVE_CO3
  640. (mfxExtBuffer*)&co3,
  641. #endif
  642. };
  643. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  644. int ret;
  645. q->param.ExtParam = ext_buffers;
  646. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  647. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  648. if (ret < 0)
  649. return ff_qsv_print_error(avctx, ret,
  650. "Error calling GetVideoParam");
  651. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  652. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  653. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  654. return AVERROR_UNKNOWN;
  655. }
  656. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  657. AV_INPUT_BUFFER_PADDING_SIZE);
  658. if (!avctx->extradata)
  659. return AVERROR(ENOMEM);
  660. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  661. if (need_pps)
  662. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  663. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  664. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  665. cpb_props = ff_add_cpb_side_data(avctx);
  666. if (!cpb_props)
  667. return AVERROR(ENOMEM);
  668. cpb_props->max_bitrate = avctx->rc_max_rate;
  669. cpb_props->min_bitrate = avctx->rc_min_rate;
  670. cpb_props->avg_bitrate = avctx->bit_rate;
  671. cpb_props->buffer_size = avctx->rc_buffer_size;
  672. dump_video_param(avctx, q, ext_buffers + 1);
  673. return 0;
  674. }
  675. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  676. {
  677. AVQSVContext *qsv = avctx->hwaccel_context;
  678. mfxFrameSurface1 *surfaces;
  679. int nb_surfaces, i;
  680. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested + q->async_depth;
  681. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  682. if (!q->opaque_alloc_buf)
  683. return AVERROR(ENOMEM);
  684. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  685. if (!q->opaque_surfaces)
  686. return AVERROR(ENOMEM);
  687. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  688. for (i = 0; i < nb_surfaces; i++) {
  689. surfaces[i].Info = q->req.Info;
  690. q->opaque_surfaces[i] = surfaces + i;
  691. }
  692. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  693. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  694. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  695. q->opaque_alloc.In.NumSurface = nb_surfaces;
  696. q->opaque_alloc.In.Type = q->req.Type;
  697. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  698. qsv->nb_opaque_surfaces = nb_surfaces;
  699. qsv->opaque_surfaces = q->opaque_alloc_buf;
  700. qsv->opaque_alloc_type = q->req.Type;
  701. return 0;
  702. }
  703. static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
  704. {
  705. int ret;
  706. if (avctx->hwaccel_context) {
  707. AVQSVContext *qsv = avctx->hwaccel_context;
  708. q->session = qsv->session;
  709. } else if (avctx->hw_frames_ctx) {
  710. q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  711. if (!q->frames_ctx.hw_frames_ctx)
  712. return AVERROR(ENOMEM);
  713. ret = ff_qsv_init_session_frames(avctx, &q->internal_session,
  714. &q->frames_ctx, q->load_plugins,
  715. q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY);
  716. if (ret < 0) {
  717. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  718. return ret;
  719. }
  720. q->session = q->internal_session;
  721. } else if (avctx->hw_device_ctx) {
  722. ret = ff_qsv_init_session_device(avctx, &q->internal_session,
  723. avctx->hw_device_ctx, q->load_plugins);
  724. if (ret < 0)
  725. return ret;
  726. q->session = q->internal_session;
  727. } else {
  728. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  729. q->load_plugins);
  730. if (ret < 0)
  731. return ret;
  732. q->session = q->internal_session;
  733. }
  734. return 0;
  735. }
  736. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  737. {
  738. int iopattern = 0;
  739. int opaque_alloc = 0;
  740. int ret;
  741. q->param.AsyncDepth = q->async_depth;
  742. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  743. (sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*)));
  744. if (!q->async_fifo)
  745. return AVERROR(ENOMEM);
  746. if (avctx->hwaccel_context) {
  747. AVQSVContext *qsv = avctx->hwaccel_context;
  748. iopattern = qsv->iopattern;
  749. opaque_alloc = qsv->opaque_alloc;
  750. }
  751. if (avctx->hw_frames_ctx) {
  752. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  753. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  754. if (!iopattern) {
  755. if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
  756. iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
  757. else if (frames_hwctx->frame_type &
  758. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  759. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  760. }
  761. }
  762. if (!iopattern)
  763. iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  764. q->param.IOPattern = iopattern;
  765. ret = qsvenc_init_session(avctx, q);
  766. if (ret < 0)
  767. return ret;
  768. // in the mfxInfoMFX struct, JPEG is different from other codecs
  769. switch (avctx->codec_id) {
  770. case AV_CODEC_ID_MJPEG:
  771. ret = init_video_param_jpeg(avctx, q);
  772. break;
  773. default:
  774. ret = init_video_param(avctx, q);
  775. break;
  776. }
  777. if (ret < 0)
  778. return ret;
  779. ret = MFXVideoENCODE_Query(q->session, &q->param, &q->param);
  780. if (ret == MFX_WRN_PARTIAL_ACCELERATION) {
  781. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  782. } else if (ret < 0) {
  783. return ff_qsv_print_error(avctx, ret,
  784. "Error querying encoder params");
  785. }
  786. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  787. if (ret < 0)
  788. return ff_qsv_print_error(avctx, ret,
  789. "Error querying (IOSurf) the encoding parameters");
  790. if (opaque_alloc) {
  791. ret = qsv_init_opaque_alloc(avctx, q);
  792. if (ret < 0)
  793. return ret;
  794. }
  795. if (avctx->hwaccel_context) {
  796. AVQSVContext *qsv = avctx->hwaccel_context;
  797. int i, j;
  798. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  799. sizeof(*q->extparam));
  800. if (!q->extparam)
  801. return AVERROR(ENOMEM);
  802. q->param.ExtParam = q->extparam;
  803. for (i = 0; i < qsv->nb_ext_buffers; i++)
  804. q->param.ExtParam[i] = qsv->ext_buffers[i];
  805. q->param.NumExtParam = qsv->nb_ext_buffers;
  806. for (i = 0; i < q->nb_extparam_internal; i++) {
  807. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  808. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  809. break;
  810. }
  811. if (j < qsv->nb_ext_buffers)
  812. continue;
  813. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  814. }
  815. } else {
  816. q->param.ExtParam = q->extparam_internal;
  817. q->param.NumExtParam = q->nb_extparam_internal;
  818. }
  819. ret = MFXVideoENCODE_Init(q->session, &q->param);
  820. if (ret < 0)
  821. return ff_qsv_print_error(avctx, ret,
  822. "Error initializing the encoder");
  823. else if (ret > 0)
  824. ff_qsv_print_warning(avctx, ret,
  825. "Warning in encoder initialization");
  826. switch (avctx->codec_id) {
  827. case AV_CODEC_ID_MJPEG:
  828. ret = qsv_retrieve_enc_jpeg_params(avctx, q);
  829. break;
  830. default:
  831. ret = qsv_retrieve_enc_params(avctx, q);
  832. break;
  833. }
  834. if (ret < 0) {
  835. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  836. return ret;
  837. }
  838. q->avctx = avctx;
  839. return 0;
  840. }
  841. static void clear_unused_frames(QSVEncContext *q)
  842. {
  843. QSVFrame *cur = q->work_frames;
  844. while (cur) {
  845. if (cur->used && !cur->surface.Data.Locked) {
  846. av_frame_unref(cur->frame);
  847. cur->used = 0;
  848. }
  849. cur = cur->next;
  850. }
  851. }
  852. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  853. {
  854. QSVFrame *frame, **last;
  855. clear_unused_frames(q);
  856. frame = q->work_frames;
  857. last = &q->work_frames;
  858. while (frame) {
  859. if (!frame->used) {
  860. *f = frame;
  861. frame->used = 1;
  862. return 0;
  863. }
  864. last = &frame->next;
  865. frame = frame->next;
  866. }
  867. frame = av_mallocz(sizeof(*frame));
  868. if (!frame)
  869. return AVERROR(ENOMEM);
  870. frame->frame = av_frame_alloc();
  871. if (!frame->frame) {
  872. av_freep(&frame);
  873. return AVERROR(ENOMEM);
  874. }
  875. *last = frame;
  876. *f = frame;
  877. frame->used = 1;
  878. return 0;
  879. }
  880. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  881. mfxFrameSurface1 **surface)
  882. {
  883. QSVFrame *qf;
  884. int ret;
  885. ret = get_free_frame(q, &qf);
  886. if (ret < 0)
  887. return ret;
  888. if (frame->format == AV_PIX_FMT_QSV) {
  889. ret = av_frame_ref(qf->frame, frame);
  890. if (ret < 0)
  891. return ret;
  892. qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
  893. if (q->frames_ctx.mids) {
  894. ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
  895. if (ret < 0)
  896. return ret;
  897. qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
  898. }
  899. } else {
  900. /* make a copy if the input is not padded as libmfx requires */
  901. if (frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) {
  902. qf->frame->height = FFALIGN(frame->height, q->height_align);
  903. qf->frame->width = FFALIGN(frame->width, q->width_align);
  904. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  905. if (ret < 0)
  906. return ret;
  907. qf->frame->height = frame->height;
  908. qf->frame->width = frame->width;
  909. ret = av_frame_copy(qf->frame, frame);
  910. if (ret < 0) {
  911. av_frame_unref(qf->frame);
  912. return ret;
  913. }
  914. } else {
  915. ret = av_frame_ref(qf->frame, frame);
  916. if (ret < 0)
  917. return ret;
  918. }
  919. qf->surface.Info = q->param.mfx.FrameInfo;
  920. qf->surface.Info.PicStruct =
  921. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  922. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  923. MFX_PICSTRUCT_FIELD_BFF;
  924. if (frame->repeat_pict == 1)
  925. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  926. else if (frame->repeat_pict == 2)
  927. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  928. else if (frame->repeat_pict == 4)
  929. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  930. qf->surface.Data.PitchLow = qf->frame->linesize[0];
  931. qf->surface.Data.Y = qf->frame->data[0];
  932. qf->surface.Data.UV = qf->frame->data[1];
  933. }
  934. qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  935. *surface = &qf->surface;
  936. return 0;
  937. }
  938. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  939. {
  940. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  941. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  942. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  943. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  944. av_log(avctx, AV_LOG_WARNING,
  945. "Interlaced coding is supported"
  946. " at Main/High Profile Level 2.1-4.1\n");
  947. }
  948. }
  949. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  950. const AVFrame *frame)
  951. {
  952. AVPacket new_pkt = { 0 };
  953. mfxBitstream *bs;
  954. mfxFrameSurface1 *surf = NULL;
  955. mfxSyncPoint *sync = NULL;
  956. int ret;
  957. if (frame) {
  958. ret = submit_frame(q, frame, &surf);
  959. if (ret < 0) {
  960. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  961. return ret;
  962. }
  963. }
  964. ret = av_new_packet(&new_pkt, q->packet_size);
  965. if (ret < 0) {
  966. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  967. return ret;
  968. }
  969. bs = av_mallocz(sizeof(*bs));
  970. if (!bs) {
  971. av_packet_unref(&new_pkt);
  972. return AVERROR(ENOMEM);
  973. }
  974. bs->Data = new_pkt.data;
  975. bs->MaxLength = new_pkt.size;
  976. sync = av_mallocz(sizeof(*sync));
  977. if (!sync) {
  978. av_freep(&bs);
  979. av_packet_unref(&new_pkt);
  980. return AVERROR(ENOMEM);
  981. }
  982. do {
  983. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, sync);
  984. if (ret == MFX_WRN_DEVICE_BUSY)
  985. av_usleep(1);
  986. } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
  987. if (ret > 0)
  988. ff_qsv_print_warning(avctx, ret, "Warning during encoding");
  989. if (ret < 0) {
  990. av_packet_unref(&new_pkt);
  991. av_freep(&bs);
  992. av_freep(&sync);
  993. return (ret == MFX_ERR_MORE_DATA) ?
  994. 0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
  995. }
  996. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  997. print_interlace_msg(avctx, q);
  998. if (*sync) {
  999. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1000. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  1001. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  1002. } else {
  1003. av_freep(&sync);
  1004. av_packet_unref(&new_pkt);
  1005. av_freep(&bs);
  1006. }
  1007. return 0;
  1008. }
  1009. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  1010. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  1011. {
  1012. int ret;
  1013. ret = encode_frame(avctx, q, frame);
  1014. if (ret < 0)
  1015. return ret;
  1016. if (!av_fifo_space(q->async_fifo) ||
  1017. (!frame && av_fifo_size(q->async_fifo))) {
  1018. AVPacket new_pkt;
  1019. mfxBitstream *bs;
  1020. mfxSyncPoint *sync;
  1021. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1022. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1023. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1024. do {
  1025. ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
  1026. } while (ret == MFX_WRN_IN_EXECUTION);
  1027. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1028. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1029. new_pkt.size = bs->DataLength;
  1030. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  1031. bs->FrameType & MFX_FRAMETYPE_xIDR)
  1032. new_pkt.flags |= AV_PKT_FLAG_KEY;
  1033. #if FF_API_CODED_FRAME
  1034. FF_DISABLE_DEPRECATION_WARNINGS
  1035. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  1036. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  1037. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  1038. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  1039. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  1040. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  1041. FF_ENABLE_DEPRECATION_WARNINGS
  1042. #endif
  1043. av_freep(&bs);
  1044. av_freep(&sync);
  1045. if (pkt->data) {
  1046. if (pkt->size < new_pkt.size) {
  1047. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  1048. pkt->size, new_pkt.size);
  1049. av_packet_unref(&new_pkt);
  1050. return AVERROR(EINVAL);
  1051. }
  1052. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  1053. pkt->size = new_pkt.size;
  1054. ret = av_packet_copy_props(pkt, &new_pkt);
  1055. av_packet_unref(&new_pkt);
  1056. if (ret < 0)
  1057. return ret;
  1058. } else
  1059. *pkt = new_pkt;
  1060. *got_packet = 1;
  1061. }
  1062. return 0;
  1063. }
  1064. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  1065. {
  1066. QSVFrame *cur;
  1067. if (q->session)
  1068. MFXVideoENCODE_Close(q->session);
  1069. if (q->internal_session)
  1070. MFXClose(q->internal_session);
  1071. q->session = NULL;
  1072. q->internal_session = NULL;
  1073. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  1074. av_buffer_unref(&q->frames_ctx.mids_buf);
  1075. cur = q->work_frames;
  1076. while (cur) {
  1077. q->work_frames = cur->next;
  1078. av_frame_free(&cur->frame);
  1079. av_freep(&cur);
  1080. cur = q->work_frames;
  1081. }
  1082. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  1083. AVPacket pkt;
  1084. mfxSyncPoint *sync;
  1085. mfxBitstream *bs;
  1086. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  1087. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1088. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1089. av_freep(&sync);
  1090. av_freep(&bs);
  1091. av_packet_unref(&pkt);
  1092. }
  1093. av_fifo_free(q->async_fifo);
  1094. q->async_fifo = NULL;
  1095. av_freep(&q->opaque_surfaces);
  1096. av_buffer_unref(&q->opaque_alloc_buf);
  1097. av_freep(&q->extparam);
  1098. return 0;
  1099. }