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.

1444 lines
50KB

  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. "BufferSizeInKB: %"PRIu16"; InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"\n",
  148. info->BufferSizeInKB, 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. av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
  244. info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
  245. }
  246. static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
  247. {
  248. const char *rc_desc;
  249. mfxU16 rc_mode;
  250. int want_la = q->look_ahead;
  251. int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  252. int want_vcm = q->vcm;
  253. if (want_la && !QSV_HAVE_LA) {
  254. av_log(avctx, AV_LOG_ERROR,
  255. "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
  256. return AVERROR(ENOSYS);
  257. }
  258. if (want_vcm && !QSV_HAVE_VCM) {
  259. av_log(avctx, AV_LOG_ERROR,
  260. "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
  261. return AVERROR(ENOSYS);
  262. }
  263. if (want_la + want_qscale + want_vcm > 1) {
  264. av_log(avctx, AV_LOG_ERROR,
  265. "More than one of: { constant qscale, lookahead, VCM } requested, "
  266. "only one of them can be used at a time.\n");
  267. return AVERROR(EINVAL);
  268. }
  269. if (!want_qscale && avctx->global_quality > 0 && !QSV_HAVE_ICQ){
  270. av_log(avctx, AV_LOG_ERROR,
  271. "ICQ ratecontrol mode requested, but is not supported by this SDK version\n");
  272. return AVERROR(ENOSYS);
  273. }
  274. if (want_qscale) {
  275. rc_mode = MFX_RATECONTROL_CQP;
  276. rc_desc = "constant quantization parameter (CQP)";
  277. }
  278. #if QSV_HAVE_VCM
  279. else if (want_vcm) {
  280. rc_mode = MFX_RATECONTROL_VCM;
  281. rc_desc = "video conferencing mode (VCM)";
  282. }
  283. #endif
  284. #if QSV_HAVE_LA
  285. else if (want_la) {
  286. rc_mode = MFX_RATECONTROL_LA;
  287. rc_desc = "VBR with lookahead (LA)";
  288. #if QSV_HAVE_ICQ
  289. if (avctx->global_quality > 0) {
  290. rc_mode = MFX_RATECONTROL_LA_ICQ;
  291. rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
  292. }
  293. #endif
  294. }
  295. #endif
  296. #if QSV_HAVE_ICQ
  297. else if (avctx->global_quality > 0) {
  298. rc_mode = MFX_RATECONTROL_ICQ;
  299. rc_desc = "intelligent constant quality (ICQ)";
  300. }
  301. #endif
  302. else if (avctx->rc_max_rate == avctx->bit_rate) {
  303. rc_mode = MFX_RATECONTROL_CBR;
  304. rc_desc = "constant bitrate (CBR)";
  305. }
  306. #if QSV_HAVE_AVBR
  307. else if (!avctx->rc_max_rate) {
  308. rc_mode = MFX_RATECONTROL_AVBR;
  309. rc_desc = "average variable bitrate (AVBR)";
  310. }
  311. #endif
  312. else {
  313. rc_mode = MFX_RATECONTROL_VBR;
  314. rc_desc = "variable bitrate (VBR)";
  315. }
  316. q->param.mfx.RateControlMethod = rc_mode;
  317. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
  318. return 0;
  319. }
  320. static int check_enc_param(AVCodecContext *avctx, QSVEncContext *q)
  321. {
  322. mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
  323. mfxStatus ret;
  324. #define UNMATCH(x) (param_out.mfx.x != q->param.mfx.x)
  325. ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
  326. if (ret < 0) {
  327. if (UNMATCH(CodecId))
  328. av_log(avctx, AV_LOG_ERROR, "Current codec type is unsupported\n");
  329. if (UNMATCH(CodecProfile))
  330. av_log(avctx, AV_LOG_ERROR, "Current profile is unsupported\n");
  331. if (UNMATCH(RateControlMethod))
  332. av_log(avctx, AV_LOG_ERROR, "Selected ratecontrol mode is unsupported\n");
  333. if (UNMATCH(LowPower))
  334. av_log(avctx, AV_LOG_ERROR, "Low power mode is unsupported\n");
  335. if (UNMATCH(FrameInfo.FrameRateExtN) || UNMATCH(FrameInfo.FrameRateExtD))
  336. av_log(avctx, AV_LOG_ERROR, "Current frame rate is unsupported\n");
  337. if (UNMATCH(FrameInfo.PicStruct))
  338. av_log(avctx, AV_LOG_ERROR, "Current picture structure is unsupported\n");
  339. if (UNMATCH(FrameInfo.Width) || UNMATCH(FrameInfo.Height))
  340. av_log(avctx, AV_LOG_ERROR, "Current resolution is unsupported\n");
  341. if (UNMATCH(FrameInfo.FourCC))
  342. av_log(avctx, AV_LOG_ERROR, "Current pixel format is unsupported\n");
  343. return 0;
  344. }
  345. return 1;
  346. }
  347. static int init_video_param_jpeg(AVCodecContext *avctx, QSVEncContext *q)
  348. {
  349. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  350. avctx->sw_pix_fmt : avctx->pix_fmt;
  351. const AVPixFmtDescriptor *desc;
  352. int ret;
  353. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  354. if (ret < 0)
  355. return AVERROR_BUG;
  356. q->param.mfx.CodecId = ret;
  357. if (avctx->level > 0)
  358. q->param.mfx.CodecLevel = avctx->level;
  359. q->param.mfx.CodecProfile = q->profile;
  360. desc = av_pix_fmt_desc_get(sw_format);
  361. if (!desc)
  362. return AVERROR_BUG;
  363. ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
  364. q->param.mfx.FrameInfo.CropX = 0;
  365. q->param.mfx.FrameInfo.CropY = 0;
  366. q->param.mfx.FrameInfo.CropW = avctx->width;
  367. q->param.mfx.FrameInfo.CropH = avctx->height;
  368. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  369. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  370. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  371. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  372. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  373. q->param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
  374. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, 16);
  375. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 16);
  376. if (avctx->hw_frames_ctx) {
  377. AVHWFramesContext *frames_ctx = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
  378. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  379. q->param.mfx.FrameInfo.Width = frames_hwctx->surfaces[0].Info.Width;
  380. q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
  381. }
  382. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  383. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  384. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  385. } else {
  386. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  387. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  388. }
  389. q->param.mfx.Interleaved = 1;
  390. q->param.mfx.Quality = av_clip(avctx->global_quality, 1, 100);
  391. q->param.mfx.RestartInterval = 0;
  392. return 0;
  393. }
  394. static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  395. {
  396. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  397. avctx->sw_pix_fmt : avctx->pix_fmt;
  398. const AVPixFmtDescriptor *desc;
  399. float quant;
  400. int ret;
  401. mfxVersion ver;
  402. ret = MFXQueryVersion(q->session,&ver);
  403. if (ret != MFX_ERR_NONE) {
  404. av_log(avctx, AV_LOG_ERROR, "Error getting the session handle\n");
  405. return AVERROR_UNKNOWN;
  406. }
  407. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  408. if (ret < 0)
  409. return AVERROR_BUG;
  410. q->param.mfx.CodecId = ret;
  411. if (avctx->level > 0)
  412. q->param.mfx.CodecLevel = avctx->level;
  413. if (avctx->compression_level == FF_COMPRESSION_DEFAULT) {
  414. avctx->compression_level = q->preset;
  415. } else if (avctx->compression_level >= 0) {
  416. if (avctx->compression_level > MFX_TARGETUSAGE_BEST_SPEED) {
  417. av_log(avctx, AV_LOG_WARNING, "Invalid compression level: "
  418. "valid range is 0-%d, using %d instead\n",
  419. MFX_TARGETUSAGE_BEST_SPEED, MFX_TARGETUSAGE_BEST_SPEED);
  420. avctx->compression_level = MFX_TARGETUSAGE_BEST_SPEED;
  421. }
  422. }
  423. q->param.mfx.CodecProfile = q->profile;
  424. q->param.mfx.TargetUsage = avctx->compression_level;
  425. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  426. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  427. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  428. MFX_GOP_CLOSED : 0;
  429. q->param.mfx.IdrInterval = q->idr_interval;
  430. q->param.mfx.NumSlice = avctx->slices;
  431. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  432. q->param.mfx.EncodedOrder = 0;
  433. q->param.mfx.BufferSizeInKB = 0;
  434. desc = av_pix_fmt_desc_get(sw_format);
  435. if (!desc)
  436. return AVERROR_BUG;
  437. ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
  438. q->param.mfx.FrameInfo.CropX = 0;
  439. q->param.mfx.FrameInfo.CropY = 0;
  440. q->param.mfx.FrameInfo.CropW = avctx->width;
  441. q->param.mfx.FrameInfo.CropH = avctx->height;
  442. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  443. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  444. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  445. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  446. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  447. q->param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
  448. // If the minor version is greater than or equal to 19,
  449. // then can use the same alignment settings as H.264 for HEVC
  450. q->width_align = (avctx->codec_id != AV_CODEC_ID_HEVC ||
  451. QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 19)) ? 16 : 32;
  452. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  453. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  454. // it is important that PicStruct be setup correctly from the
  455. // start--otherwise, encoding doesn't work and results in a bunch
  456. // of incompatible video parameter errors
  457. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
  458. // height alignment always must be 32 for interlaced video
  459. q->height_align = 32;
  460. } else {
  461. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  462. // for progressive video, the height should be aligned to 16 for
  463. // H.264. For HEVC, depending on the version of MFX, it should be
  464. // either 32 or 16. The lower number is better if possible.
  465. q->height_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  466. }
  467. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  468. if (avctx->hw_frames_ctx) {
  469. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  470. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  471. q->param.mfx.FrameInfo.Width = frames_hwctx->surfaces[0].Info.Width;
  472. q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
  473. }
  474. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  475. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  476. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  477. } else {
  478. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  479. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  480. }
  481. ret = select_rc_mode(avctx, q);
  482. if (ret < 0)
  483. return ret;
  484. switch (q->param.mfx.RateControlMethod) {
  485. case MFX_RATECONTROL_CBR:
  486. case MFX_RATECONTROL_VBR:
  487. #if QSV_HAVE_VCM
  488. case MFX_RATECONTROL_VCM:
  489. #endif
  490. q->param.mfx.BufferSizeInKB = avctx->rc_buffer_size / 8000;
  491. q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
  492. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  493. q->param.mfx.MaxKbps = avctx->rc_max_rate / 1000;
  494. break;
  495. case MFX_RATECONTROL_CQP:
  496. quant = avctx->global_quality / FF_QP2LAMBDA;
  497. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  498. q->param.mfx.QPP = av_clip(quant, 0, 51);
  499. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  500. break;
  501. #if QSV_HAVE_AVBR
  502. case MFX_RATECONTROL_AVBR:
  503. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  504. q->param.mfx.Convergence = q->avbr_convergence;
  505. q->param.mfx.Accuracy = q->avbr_accuracy;
  506. break;
  507. #endif
  508. #if QSV_HAVE_LA
  509. case MFX_RATECONTROL_LA:
  510. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  511. q->extco2.LookAheadDepth = q->look_ahead_depth;
  512. break;
  513. #if QSV_HAVE_ICQ
  514. case MFX_RATECONTROL_LA_ICQ:
  515. q->extco2.LookAheadDepth = q->look_ahead_depth;
  516. case MFX_RATECONTROL_ICQ:
  517. q->param.mfx.ICQQuality = avctx->global_quality;
  518. break;
  519. #endif
  520. #endif
  521. }
  522. // the HEVC encoder plugin currently fails if coding options
  523. // are provided
  524. if (avctx->codec_id != AV_CODEC_ID_HEVC) {
  525. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  526. q->extco.Header.BufferSz = sizeof(q->extco);
  527. q->extco.PicTimingSEI = q->pic_timing_sei ?
  528. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  529. if (q->rdo >= 0)
  530. q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  531. if (avctx->codec_id == AV_CODEC_ID_H264) {
  532. #if FF_API_CODER_TYPE
  533. FF_DISABLE_DEPRECATION_WARNINGS
  534. if (avctx->coder_type >= 0)
  535. q->cavlc = avctx->coder_type == FF_CODER_TYPE_VLC;
  536. FF_ENABLE_DEPRECATION_WARNINGS
  537. #endif
  538. q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
  539. : MFX_CODINGOPTION_UNKNOWN;
  540. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  541. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  542. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  543. if (q->single_sei_nal_unit >= 0)
  544. q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  545. if (q->recovery_point_sei >= 0)
  546. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  547. q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
  548. q->extco.AUDelimiter = q->aud ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  549. }
  550. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  551. if (avctx->codec_id == AV_CODEC_ID_H264) {
  552. #if QSV_HAVE_CO2
  553. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  554. q->extco2.Header.BufferSz = sizeof(q->extco2);
  555. if (q->int_ref_type >= 0)
  556. q->extco2.IntRefType = q->int_ref_type;
  557. if (q->int_ref_cycle_size >= 0)
  558. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  559. if (q->int_ref_qp_delta != INT16_MIN)
  560. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  561. if (q->bitrate_limit >= 0)
  562. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  563. if (q->mbbrc >= 0)
  564. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  565. if (q->extbrc >= 0)
  566. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  567. if (q->max_frame_size >= 0)
  568. q->extco2.MaxFrameSize = q->max_frame_size;
  569. #if QSV_HAVE_MAX_SLICE_SIZE
  570. if (q->max_slice_size >= 0)
  571. q->extco2.MaxSliceSize = q->max_slice_size;
  572. #endif
  573. #if QSV_HAVE_TRELLIS
  574. q->extco2.Trellis = q->trellis;
  575. #endif
  576. #if QSV_VERSION_ATLEAST(1, 8)
  577. q->extco2.LookAheadDS = q->look_ahead_downsampling;
  578. q->extco2.RepeatPPS = q->repeat_pps ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  579. #if FF_API_PRIVATE_OPT
  580. FF_DISABLE_DEPRECATION_WARNINGS
  581. if (avctx->b_frame_strategy >= 0)
  582. q->b_strategy = avctx->b_frame_strategy;
  583. FF_ENABLE_DEPRECATION_WARNINGS
  584. #endif
  585. if (q->b_strategy >= 0)
  586. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  587. if (q->adaptive_i >= 0)
  588. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  589. if (q->adaptive_b >= 0)
  590. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  591. #endif
  592. #if QSV_VERSION_ATLEAST(1, 9)
  593. if (avctx->qmin >= 0 && avctx->qmax >= 0 && avctx->qmin > avctx->qmax) {
  594. av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are set but invalid, please make sure min <= max\n");
  595. return AVERROR(EINVAL);
  596. }
  597. if (avctx->qmin >= 0) {
  598. q->extco2.MinQPI = avctx->qmin > 51 ? 51 : avctx->qmin;
  599. q->extco2.MinQPP = q->extco2.MinQPB = q->extco2.MinQPI;
  600. }
  601. if (avctx->qmax >= 0) {
  602. q->extco2.MaxQPI = avctx->qmax > 51 ? 51 : avctx->qmax;
  603. q->extco2.MaxQPP = q->extco2.MaxQPB = q->extco2.MaxQPI;
  604. }
  605. #endif
  606. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  607. #endif
  608. #if QSV_HAVE_MF
  609. if (QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 25)) {
  610. q->extmfp.Header.BufferId = MFX_EXTBUFF_MULTI_FRAME_PARAM;
  611. q->extmfp.Header.BufferSz = sizeof(q->extmfp);
  612. q->extmfp.MFMode = q->mfmode;
  613. av_log(avctx,AV_LOG_VERBOSE,"MFMode:%d\n", q->extmfp.MFMode);
  614. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extmfp;
  615. }
  616. #endif
  617. }
  618. }
  619. if (!check_enc_param(avctx,q)) {
  620. av_log(avctx, AV_LOG_ERROR,
  621. "some encoding parameters are not supported by the QSV "
  622. "runtime. Please double check the input parameters.\n");
  623. return AVERROR(ENOSYS);
  624. }
  625. return 0;
  626. }
  627. static int qsv_retrieve_enc_jpeg_params(AVCodecContext *avctx, QSVEncContext *q)
  628. {
  629. int ret = 0;
  630. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  631. if (ret < 0)
  632. return ff_qsv_print_error(avctx, ret,
  633. "Error calling GetVideoParam");
  634. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  635. // for qsv mjpeg the return value maybe 0 so alloc the buffer
  636. if (q->packet_size == 0)
  637. q->packet_size = q->param.mfx.FrameInfo.Height * q->param.mfx.FrameInfo.Width * 4;
  638. return 0;
  639. }
  640. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  641. {
  642. AVCPBProperties *cpb_props;
  643. uint8_t sps_buf[128];
  644. uint8_t pps_buf[128];
  645. mfxExtCodingOptionSPSPPS extradata = {
  646. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  647. .Header.BufferSz = sizeof(extradata),
  648. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  649. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  650. };
  651. mfxExtCodingOption co = {
  652. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  653. .Header.BufferSz = sizeof(co),
  654. };
  655. #if QSV_HAVE_CO2
  656. mfxExtCodingOption2 co2 = {
  657. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  658. .Header.BufferSz = sizeof(co2),
  659. };
  660. #endif
  661. mfxExtBuffer *ext_buffers[] = {
  662. (mfxExtBuffer*)&extradata,
  663. (mfxExtBuffer*)&co,
  664. #if QSV_HAVE_CO2
  665. (mfxExtBuffer*)&co2,
  666. #endif
  667. };
  668. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  669. int ret;
  670. q->param.ExtParam = ext_buffers;
  671. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  672. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  673. if (ret < 0)
  674. return ff_qsv_print_error(avctx, ret,
  675. "Error calling GetVideoParam");
  676. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  677. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  678. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  679. return AVERROR_UNKNOWN;
  680. }
  681. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  682. AV_INPUT_BUFFER_PADDING_SIZE);
  683. if (!avctx->extradata)
  684. return AVERROR(ENOMEM);
  685. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  686. if (need_pps)
  687. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  688. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  689. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  690. cpb_props = ff_add_cpb_side_data(avctx);
  691. if (!cpb_props)
  692. return AVERROR(ENOMEM);
  693. cpb_props->max_bitrate = avctx->rc_max_rate;
  694. cpb_props->min_bitrate = avctx->rc_min_rate;
  695. cpb_props->avg_bitrate = avctx->bit_rate;
  696. cpb_props->buffer_size = avctx->rc_buffer_size;
  697. dump_video_param(avctx, q, ext_buffers + 1);
  698. return 0;
  699. }
  700. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  701. {
  702. AVQSVContext *qsv = avctx->hwaccel_context;
  703. mfxFrameSurface1 *surfaces;
  704. int nb_surfaces, i;
  705. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested;
  706. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  707. if (!q->opaque_alloc_buf)
  708. return AVERROR(ENOMEM);
  709. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  710. if (!q->opaque_surfaces)
  711. return AVERROR(ENOMEM);
  712. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  713. for (i = 0; i < nb_surfaces; i++) {
  714. surfaces[i].Info = q->req.Info;
  715. q->opaque_surfaces[i] = surfaces + i;
  716. }
  717. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  718. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  719. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  720. q->opaque_alloc.In.NumSurface = nb_surfaces;
  721. q->opaque_alloc.In.Type = q->req.Type;
  722. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  723. qsv->nb_opaque_surfaces = nb_surfaces;
  724. qsv->opaque_surfaces = q->opaque_alloc_buf;
  725. qsv->opaque_alloc_type = q->req.Type;
  726. return 0;
  727. }
  728. static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
  729. {
  730. int ret;
  731. if (avctx->hwaccel_context) {
  732. AVQSVContext *qsv = avctx->hwaccel_context;
  733. q->session = qsv->session;
  734. } else if (avctx->hw_frames_ctx) {
  735. q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  736. if (!q->frames_ctx.hw_frames_ctx)
  737. return AVERROR(ENOMEM);
  738. ret = ff_qsv_init_session_frames(avctx, &q->internal_session,
  739. &q->frames_ctx, q->load_plugins,
  740. q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY);
  741. if (ret < 0) {
  742. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  743. return ret;
  744. }
  745. q->session = q->internal_session;
  746. } else if (avctx->hw_device_ctx) {
  747. ret = ff_qsv_init_session_device(avctx, &q->internal_session,
  748. avctx->hw_device_ctx, q->load_plugins);
  749. if (ret < 0)
  750. return ret;
  751. q->session = q->internal_session;
  752. } else {
  753. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  754. q->load_plugins);
  755. if (ret < 0)
  756. return ret;
  757. q->session = q->internal_session;
  758. }
  759. return 0;
  760. }
  761. static inline unsigned int qsv_fifo_item_size(void)
  762. {
  763. return sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*);
  764. }
  765. static inline unsigned int qsv_fifo_size(const AVFifoBuffer* fifo)
  766. {
  767. return av_fifo_size(fifo)/qsv_fifo_item_size();
  768. }
  769. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  770. {
  771. int iopattern = 0;
  772. int opaque_alloc = 0;
  773. int ret;
  774. q->param.AsyncDepth = q->async_depth;
  775. q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
  776. if (!q->async_fifo)
  777. return AVERROR(ENOMEM);
  778. if (avctx->hwaccel_context) {
  779. AVQSVContext *qsv = avctx->hwaccel_context;
  780. iopattern = qsv->iopattern;
  781. opaque_alloc = qsv->opaque_alloc;
  782. }
  783. if (avctx->hw_frames_ctx) {
  784. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  785. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  786. if (!iopattern) {
  787. if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
  788. iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
  789. else if (frames_hwctx->frame_type &
  790. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  791. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  792. }
  793. }
  794. if (!iopattern)
  795. iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  796. q->param.IOPattern = iopattern;
  797. ret = qsvenc_init_session(avctx, q);
  798. if (ret < 0)
  799. return ret;
  800. // in the mfxInfoMFX struct, JPEG is different from other codecs
  801. switch (avctx->codec_id) {
  802. case AV_CODEC_ID_MJPEG:
  803. ret = init_video_param_jpeg(avctx, q);
  804. break;
  805. default:
  806. ret = init_video_param(avctx, q);
  807. break;
  808. }
  809. if (ret < 0)
  810. return ret;
  811. ret = MFXVideoENCODE_Query(q->session, &q->param, &q->param);
  812. if (ret == MFX_WRN_PARTIAL_ACCELERATION) {
  813. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  814. } else if (ret < 0) {
  815. return ff_qsv_print_error(avctx, ret,
  816. "Error querying encoder params");
  817. }
  818. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  819. if (ret < 0)
  820. return ff_qsv_print_error(avctx, ret,
  821. "Error querying (IOSurf) the encoding parameters");
  822. if (opaque_alloc) {
  823. ret = qsv_init_opaque_alloc(avctx, q);
  824. if (ret < 0)
  825. return ret;
  826. }
  827. if (avctx->hwaccel_context) {
  828. AVQSVContext *qsv = avctx->hwaccel_context;
  829. int i, j;
  830. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  831. sizeof(*q->extparam));
  832. if (!q->extparam)
  833. return AVERROR(ENOMEM);
  834. q->param.ExtParam = q->extparam;
  835. for (i = 0; i < qsv->nb_ext_buffers; i++)
  836. q->param.ExtParam[i] = qsv->ext_buffers[i];
  837. q->param.NumExtParam = qsv->nb_ext_buffers;
  838. for (i = 0; i < q->nb_extparam_internal; i++) {
  839. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  840. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  841. break;
  842. }
  843. if (j < qsv->nb_ext_buffers)
  844. continue;
  845. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  846. }
  847. } else {
  848. q->param.ExtParam = q->extparam_internal;
  849. q->param.NumExtParam = q->nb_extparam_internal;
  850. }
  851. ret = MFXVideoENCODE_Init(q->session, &q->param);
  852. if (ret < 0)
  853. return ff_qsv_print_error(avctx, ret,
  854. "Error initializing the encoder");
  855. else if (ret > 0)
  856. ff_qsv_print_warning(avctx, ret,
  857. "Warning in encoder initialization");
  858. switch (avctx->codec_id) {
  859. case AV_CODEC_ID_MJPEG:
  860. ret = qsv_retrieve_enc_jpeg_params(avctx, q);
  861. break;
  862. default:
  863. ret = qsv_retrieve_enc_params(avctx, q);
  864. break;
  865. }
  866. if (ret < 0) {
  867. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  868. return ret;
  869. }
  870. q->avctx = avctx;
  871. return 0;
  872. }
  873. static void free_encoder_ctrl_payloads(mfxEncodeCtrl* enc_ctrl)
  874. {
  875. if (enc_ctrl) {
  876. int i;
  877. for (i = 0; i < enc_ctrl->NumPayload && i < QSV_MAX_ENC_PAYLOAD; i++) {
  878. av_free(enc_ctrl->Payload[i]);
  879. }
  880. enc_ctrl->NumPayload = 0;
  881. }
  882. }
  883. static void clear_unused_frames(QSVEncContext *q)
  884. {
  885. QSVFrame *cur = q->work_frames;
  886. while (cur) {
  887. if (cur->used && !cur->surface.Data.Locked) {
  888. free_encoder_ctrl_payloads(&cur->enc_ctrl);
  889. if (cur->frame->format == AV_PIX_FMT_QSV) {
  890. av_frame_unref(cur->frame);
  891. }
  892. cur->used = 0;
  893. }
  894. cur = cur->next;
  895. }
  896. }
  897. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  898. {
  899. QSVFrame *frame, **last;
  900. clear_unused_frames(q);
  901. frame = q->work_frames;
  902. last = &q->work_frames;
  903. while (frame) {
  904. if (!frame->used) {
  905. *f = frame;
  906. frame->used = 1;
  907. return 0;
  908. }
  909. last = &frame->next;
  910. frame = frame->next;
  911. }
  912. frame = av_mallocz(sizeof(*frame));
  913. if (!frame)
  914. return AVERROR(ENOMEM);
  915. frame->frame = av_frame_alloc();
  916. if (!frame->frame) {
  917. av_freep(&frame);
  918. return AVERROR(ENOMEM);
  919. }
  920. frame->enc_ctrl.Payload = av_mallocz(sizeof(mfxPayload*) * QSV_MAX_ENC_PAYLOAD);
  921. if (!frame->enc_ctrl.Payload) {
  922. av_freep(&frame);
  923. return AVERROR(ENOMEM);
  924. }
  925. *last = frame;
  926. *f = frame;
  927. frame->used = 1;
  928. return 0;
  929. }
  930. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  931. QSVFrame **new_frame)
  932. {
  933. QSVFrame *qf;
  934. int ret;
  935. ret = get_free_frame(q, &qf);
  936. if (ret < 0)
  937. return ret;
  938. if (frame->format == AV_PIX_FMT_QSV) {
  939. ret = av_frame_ref(qf->frame, frame);
  940. if (ret < 0)
  941. return ret;
  942. qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
  943. if (q->frames_ctx.mids) {
  944. ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
  945. if (ret < 0)
  946. return ret;
  947. qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
  948. }
  949. } else {
  950. /* make a copy if the input is not padded as libmfx requires */
  951. /* and to make allocation continious for data[0]/data[1] */
  952. if ((frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) ||
  953. (frame->data[1] - frame->data[0] != frame->linesize[0] * FFALIGN(qf->frame->height, q->height_align))) {
  954. qf->frame->height = FFALIGN(frame->height, q->height_align);
  955. qf->frame->width = FFALIGN(frame->width, q->width_align);
  956. qf->frame->format = frame->format;
  957. if (!qf->frame->data[0]) {
  958. ret = av_frame_get_buffer(qf->frame, q->width_align);
  959. if (ret < 0)
  960. return ret;
  961. }
  962. qf->frame->height = frame->height;
  963. qf->frame->width = frame->width;
  964. ret = av_frame_copy(qf->frame, frame);
  965. if (ret < 0) {
  966. av_frame_unref(qf->frame);
  967. return ret;
  968. }
  969. } else {
  970. ret = av_frame_ref(qf->frame, frame);
  971. if (ret < 0)
  972. return ret;
  973. }
  974. qf->surface.Info = q->param.mfx.FrameInfo;
  975. qf->surface.Info.PicStruct =
  976. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  977. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  978. MFX_PICSTRUCT_FIELD_BFF;
  979. if (frame->repeat_pict == 1)
  980. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  981. else if (frame->repeat_pict == 2)
  982. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  983. else if (frame->repeat_pict == 4)
  984. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  985. qf->surface.Data.PitchLow = qf->frame->linesize[0];
  986. qf->surface.Data.Y = qf->frame->data[0];
  987. qf->surface.Data.UV = qf->frame->data[1];
  988. }
  989. qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  990. *new_frame = qf;
  991. return 0;
  992. }
  993. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  994. {
  995. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  996. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  997. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  998. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  999. av_log(avctx, AV_LOG_WARNING,
  1000. "Interlaced coding is supported"
  1001. " at Main/High Profile Level 2.2-4.0\n");
  1002. }
  1003. }
  1004. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  1005. const AVFrame *frame)
  1006. {
  1007. AVPacket new_pkt = { 0 };
  1008. mfxBitstream *bs;
  1009. #if QSV_VERSION_ATLEAST(1, 26)
  1010. mfxExtAVCEncodedFrameInfo *enc_info;
  1011. mfxExtBuffer **enc_buf;
  1012. #endif
  1013. mfxFrameSurface1 *surf = NULL;
  1014. mfxSyncPoint *sync = NULL;
  1015. QSVFrame *qsv_frame = NULL;
  1016. mfxEncodeCtrl* enc_ctrl = NULL;
  1017. int ret;
  1018. if (frame) {
  1019. ret = submit_frame(q, frame, &qsv_frame);
  1020. if (ret < 0) {
  1021. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  1022. return ret;
  1023. }
  1024. }
  1025. if (qsv_frame) {
  1026. surf = &qsv_frame->surface;
  1027. enc_ctrl = &qsv_frame->enc_ctrl;
  1028. memset(enc_ctrl, 0, sizeof(mfxEncodeCtrl));
  1029. if (frame->pict_type == AV_PICTURE_TYPE_I) {
  1030. enc_ctrl->FrameType = MFX_FRAMETYPE_I | MFX_FRAMETYPE_REF;
  1031. if (q->forced_idr)
  1032. enc_ctrl->FrameType |= MFX_FRAMETYPE_IDR;
  1033. }
  1034. }
  1035. ret = av_new_packet(&new_pkt, q->packet_size);
  1036. if (ret < 0) {
  1037. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  1038. return ret;
  1039. }
  1040. bs = av_mallocz(sizeof(*bs));
  1041. if (!bs) {
  1042. av_packet_unref(&new_pkt);
  1043. return AVERROR(ENOMEM);
  1044. }
  1045. bs->Data = new_pkt.data;
  1046. bs->MaxLength = new_pkt.size;
  1047. #if QSV_VERSION_ATLEAST(1, 26)
  1048. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1049. enc_info = av_mallocz(sizeof(*enc_info));
  1050. if (!enc_info)
  1051. return AVERROR(ENOMEM);
  1052. enc_info->Header.BufferId = MFX_EXTBUFF_ENCODED_FRAME_INFO;
  1053. enc_info->Header.BufferSz = sizeof (*enc_info);
  1054. bs->NumExtParam = 1;
  1055. enc_buf = av_mallocz(sizeof(mfxExtBuffer *));
  1056. if (!enc_buf)
  1057. return AVERROR(ENOMEM);
  1058. enc_buf[0] = (mfxExtBuffer *)enc_info;
  1059. bs->ExtParam = enc_buf;
  1060. }
  1061. #endif
  1062. if (q->set_encode_ctrl_cb) {
  1063. q->set_encode_ctrl_cb(avctx, frame, &qsv_frame->enc_ctrl);
  1064. }
  1065. sync = av_mallocz(sizeof(*sync));
  1066. if (!sync) {
  1067. av_freep(&bs);
  1068. #if QSV_VERSION_ATLEAST(1, 26)
  1069. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1070. av_freep(&enc_info);
  1071. av_freep(&enc_buf);
  1072. }
  1073. #endif
  1074. av_packet_unref(&new_pkt);
  1075. return AVERROR(ENOMEM);
  1076. }
  1077. do {
  1078. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, bs, sync);
  1079. if (ret == MFX_WRN_DEVICE_BUSY)
  1080. av_usleep(500);
  1081. } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
  1082. if (ret > 0)
  1083. ff_qsv_print_warning(avctx, ret, "Warning during encoding");
  1084. if (ret < 0) {
  1085. av_packet_unref(&new_pkt);
  1086. av_freep(&bs);
  1087. #if QSV_VERSION_ATLEAST(1, 26)
  1088. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1089. av_freep(&enc_info);
  1090. av_freep(&enc_buf);
  1091. }
  1092. #endif
  1093. av_freep(&sync);
  1094. return (ret == MFX_ERR_MORE_DATA) ?
  1095. 0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
  1096. }
  1097. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  1098. print_interlace_msg(avctx, q);
  1099. if (*sync) {
  1100. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1101. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  1102. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  1103. } else {
  1104. av_freep(&sync);
  1105. av_packet_unref(&new_pkt);
  1106. av_freep(&bs);
  1107. #if QSV_VERSION_ATLEAST(1, 26)
  1108. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1109. av_freep(&enc_info);
  1110. av_freep(&enc_buf);
  1111. }
  1112. #endif
  1113. }
  1114. return 0;
  1115. }
  1116. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  1117. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  1118. {
  1119. int ret;
  1120. ret = encode_frame(avctx, q, frame);
  1121. if (ret < 0)
  1122. return ret;
  1123. if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
  1124. (!frame && av_fifo_size(q->async_fifo))) {
  1125. AVPacket new_pkt;
  1126. mfxBitstream *bs;
  1127. mfxSyncPoint *sync;
  1128. #if QSV_VERSION_ATLEAST(1, 26)
  1129. mfxExtAVCEncodedFrameInfo *enc_info;
  1130. mfxExtBuffer **enc_buf;
  1131. #endif
  1132. enum AVPictureType pict_type;
  1133. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  1134. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1135. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1136. do {
  1137. ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
  1138. } while (ret == MFX_WRN_IN_EXECUTION);
  1139. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1140. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  1141. new_pkt.size = bs->DataLength;
  1142. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  1143. bs->FrameType & MFX_FRAMETYPE_xIDR)
  1144. new_pkt.flags |= AV_PKT_FLAG_KEY;
  1145. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  1146. pict_type = AV_PICTURE_TYPE_I;
  1147. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  1148. pict_type = AV_PICTURE_TYPE_P;
  1149. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  1150. pict_type = AV_PICTURE_TYPE_B;
  1151. else if (bs->FrameType == MFX_FRAMETYPE_UNKNOWN) {
  1152. pict_type = AV_PICTURE_TYPE_NONE;
  1153. av_log(avctx, AV_LOG_WARNING, "Unkown FrameType, set pict_type to AV_PICTURE_TYPE_NONE.\n");
  1154. } else {
  1155. av_log(avctx, AV_LOG_ERROR, "Invalid FrameType:%d.\n", bs->FrameType);
  1156. return AVERROR_INVALIDDATA;
  1157. }
  1158. #if FF_API_CODED_FRAME
  1159. FF_DISABLE_DEPRECATION_WARNINGS
  1160. avctx->coded_frame->pict_type = pict_type;
  1161. FF_ENABLE_DEPRECATION_WARNINGS
  1162. #endif
  1163. #if QSV_VERSION_ATLEAST(1, 26)
  1164. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1165. enc_buf = bs->ExtParam;
  1166. enc_info = (mfxExtAVCEncodedFrameInfo *)(*bs->ExtParam);
  1167. ff_side_data_set_encoder_stats(&new_pkt,
  1168. enc_info->QP * FF_QP2LAMBDA, NULL, 0, pict_type);
  1169. av_freep(&enc_info);
  1170. av_freep(&enc_buf);
  1171. }
  1172. #endif
  1173. av_freep(&bs);
  1174. av_freep(&sync);
  1175. if (pkt->data) {
  1176. if (pkt->size < new_pkt.size) {
  1177. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  1178. pkt->size, new_pkt.size);
  1179. av_packet_unref(&new_pkt);
  1180. return AVERROR(EINVAL);
  1181. }
  1182. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  1183. pkt->size = new_pkt.size;
  1184. ret = av_packet_copy_props(pkt, &new_pkt);
  1185. av_packet_unref(&new_pkt);
  1186. if (ret < 0)
  1187. return ret;
  1188. } else
  1189. *pkt = new_pkt;
  1190. *got_packet = 1;
  1191. }
  1192. return 0;
  1193. }
  1194. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  1195. {
  1196. QSVFrame *cur;
  1197. if (q->session)
  1198. MFXVideoENCODE_Close(q->session);
  1199. if (q->internal_session)
  1200. MFXClose(q->internal_session);
  1201. q->session = NULL;
  1202. q->internal_session = NULL;
  1203. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  1204. av_buffer_unref(&q->frames_ctx.mids_buf);
  1205. cur = q->work_frames;
  1206. while (cur) {
  1207. q->work_frames = cur->next;
  1208. av_frame_free(&cur->frame);
  1209. av_free(cur->enc_ctrl.Payload);
  1210. av_freep(&cur);
  1211. cur = q->work_frames;
  1212. }
  1213. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  1214. AVPacket pkt;
  1215. mfxSyncPoint *sync;
  1216. mfxBitstream *bs;
  1217. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  1218. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  1219. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  1220. av_freep(&sync);
  1221. av_freep(&bs);
  1222. av_packet_unref(&pkt);
  1223. }
  1224. av_fifo_free(q->async_fifo);
  1225. q->async_fifo = NULL;
  1226. av_freep(&q->opaque_surfaces);
  1227. av_buffer_unref(&q->opaque_alloc_buf);
  1228. av_freep(&q->extparam);
  1229. return 0;
  1230. }