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.

1323 lines
45KB

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