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.

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