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.

989 lines
33KB

  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/mem.h"
  28. #include "libavutil/log.h"
  29. #include "libavutil/time.h"
  30. #include "libavutil/imgutils.h"
  31. #include "avcodec.h"
  32. #include "internal.h"
  33. #include "qsv.h"
  34. #include "qsv_internal.h"
  35. #include "qsvenc.h"
  36. static const struct {
  37. mfxU16 profile;
  38. const char *name;
  39. } profile_names[] = {
  40. { MFX_PROFILE_AVC_BASELINE, "baseline" },
  41. { MFX_PROFILE_AVC_MAIN, "main" },
  42. { MFX_PROFILE_AVC_EXTENDED, "extended" },
  43. { MFX_PROFILE_AVC_HIGH, "high" },
  44. #if QSV_VERSION_ATLEAST(1, 15)
  45. { MFX_PROFILE_AVC_HIGH_422, "high 422" },
  46. #endif
  47. #if QSV_VERSION_ATLEAST(1, 4)
  48. { MFX_PROFILE_AVC_CONSTRAINED_BASELINE, "constrained baseline" },
  49. { MFX_PROFILE_AVC_CONSTRAINED_HIGH, "constrained high" },
  50. { MFX_PROFILE_AVC_PROGRESSIVE_HIGH, "progressive high" },
  51. #endif
  52. { MFX_PROFILE_MPEG2_SIMPLE, "simple" },
  53. { MFX_PROFILE_MPEG2_MAIN, "main" },
  54. { MFX_PROFILE_MPEG2_HIGH, "high" },
  55. { MFX_PROFILE_VC1_SIMPLE, "simple" },
  56. { MFX_PROFILE_VC1_MAIN, "main" },
  57. { MFX_PROFILE_VC1_ADVANCED, "advanced" },
  58. #if QSV_VERSION_ATLEAST(1, 8)
  59. { MFX_PROFILE_HEVC_MAIN, "main" },
  60. { MFX_PROFILE_HEVC_MAIN10, "main10" },
  61. { MFX_PROFILE_HEVC_MAINSP, "mainsp" },
  62. #endif
  63. };
  64. static const char *print_profile(mfxU16 profile)
  65. {
  66. int i;
  67. for (i = 0; i < FF_ARRAY_ELEMS(profile_names); i++)
  68. if (profile == profile_names[i].profile)
  69. return profile_names[i].name;
  70. return "unknown";
  71. }
  72. static const struct {
  73. mfxU16 rc_mode;
  74. const char *name;
  75. } rc_names[] = {
  76. { MFX_RATECONTROL_CBR, "CBR" },
  77. { MFX_RATECONTROL_VBR, "VBR" },
  78. { MFX_RATECONTROL_CQP, "CQP" },
  79. { MFX_RATECONTROL_AVBR, "AVBR" },
  80. #if QSV_HAVE_LA
  81. { MFX_RATECONTROL_LA, "LA" },
  82. #endif
  83. #if QSV_HAVE_ICQ
  84. { MFX_RATECONTROL_ICQ, "ICQ" },
  85. { MFX_RATECONTROL_LA_ICQ, "LA_ICQ" },
  86. #endif
  87. #if QSV_HAVE_VCM
  88. { MFX_RATECONTROL_VCM, "VCM" },
  89. #endif
  90. #if QSV_VERSION_ATLEAST(1, 10)
  91. { MFX_RATECONTROL_LA_EXT, "LA_EXT" },
  92. #endif
  93. #if QSV_HAVE_LA_HRD
  94. { MFX_RATECONTROL_LA_HRD, "LA_HRD" },
  95. #endif
  96. #if QSV_HAVE_QVBR
  97. { MFX_RATECONTROL_QVBR, "QVBR" },
  98. #endif
  99. };
  100. static const char *print_ratecontrol(mfxU16 rc_mode)
  101. {
  102. int i;
  103. for (i = 0; i < FF_ARRAY_ELEMS(rc_names); i++)
  104. if (rc_mode == rc_names[i].rc_mode)
  105. return rc_names[i].name;
  106. return "unknown";
  107. }
  108. static const char *print_threestate(mfxU16 val)
  109. {
  110. if (val == MFX_CODINGOPTION_ON)
  111. return "ON";
  112. else if (val == MFX_CODINGOPTION_OFF)
  113. return "OFF";
  114. return "unknown";
  115. }
  116. static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
  117. mfxExtBuffer **coding_opts)
  118. {
  119. mfxInfoMFX *info = &q->param.mfx;
  120. mfxExtCodingOption *co = (mfxExtCodingOption*)coding_opts[0];
  121. #if QSV_HAVE_CO2
  122. mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[1];
  123. #endif
  124. #if QSV_HAVE_CO3
  125. mfxExtCodingOption3 *co3 = (mfxExtCodingOption3*)coding_opts[2];
  126. #endif
  127. av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
  128. print_profile(info->CodecProfile), info->CodecLevel);
  129. av_log(avctx, AV_LOG_VERBOSE, "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag: ",
  130. info->GopPicSize, info->GopRefDist);
  131. if (info->GopOptFlag & MFX_GOP_CLOSED)
  132. av_log(avctx, AV_LOG_VERBOSE, "closed ");
  133. if (info->GopOptFlag & MFX_GOP_STRICT)
  134. av_log(avctx, AV_LOG_VERBOSE, "strict ");
  135. av_log(avctx, AV_LOG_VERBOSE, "; IdrInterval: %"PRIu16"\n", info->IdrInterval);
  136. av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
  137. info->TargetUsage, print_ratecontrol(info->RateControlMethod));
  138. if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
  139. info->RateControlMethod == MFX_RATECONTROL_VBR
  140. #if QSV_HAVE_VCM
  141. || info->RateControlMethod == MFX_RATECONTROL_VCM
  142. #endif
  143. ) {
  144. av_log(avctx, AV_LOG_VERBOSE,
  145. "InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"\n",
  146. info->InitialDelayInKB, info->TargetKbps, info->MaxKbps);
  147. } else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
  148. av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
  149. info->QPI, info->QPP, info->QPB);
  150. } else if (info->RateControlMethod == MFX_RATECONTROL_AVBR) {
  151. av_log(avctx, AV_LOG_VERBOSE,
  152. "TargetKbps: %"PRIu16"; Accuracy: %"PRIu16"; Convergence: %"PRIu16"\n",
  153. info->TargetKbps, info->Accuracy, info->Convergence);
  154. }
  155. #if QSV_HAVE_LA
  156. else if (info->RateControlMethod == MFX_RATECONTROL_LA
  157. #if QSV_HAVE_LA_HRD
  158. || info->RateControlMethod == MFX_RATECONTROL_LA_HRD
  159. #endif
  160. ) {
  161. av_log(avctx, AV_LOG_VERBOSE,
  162. "TargetKbps: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
  163. info->TargetKbps, co2->LookAheadDepth);
  164. }
  165. #endif
  166. #if QSV_HAVE_ICQ
  167. else if (info->RateControlMethod == MFX_RATECONTROL_ICQ) {
  168. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
  169. } else if (info->RateControlMethod == MFX_RATECONTROL_LA_ICQ) {
  170. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
  171. info->ICQQuality, co2->LookAheadDepth);
  172. }
  173. #endif
  174. #if QSV_HAVE_QVBR
  175. else if (info->RateControlMethod == MFX_RATECONTROL_QVBR) {
  176. av_log(avctx, AV_LOG_VERBOSE, "QVBRQuality: %"PRIu16"\n",
  177. co3->QVBRQuality);
  178. }
  179. #endif
  180. av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
  181. info->NumSlice, info->NumRefFrame);
  182. av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
  183. print_threestate(co->RateDistortionOpt));
  184. #if QSV_HAVE_CO2
  185. av_log(avctx, AV_LOG_VERBOSE,
  186. "RecoveryPointSEI: %s IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
  187. print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
  188. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %"PRIu16"; ", co2->MaxFrameSize);
  189. #if QSV_VERSION_ATLEAST(1, 9)
  190. av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %"PRIu16"; ", co2->MaxSliceSize);
  191. #endif
  192. av_log(avctx, AV_LOG_VERBOSE, "\n");
  193. av_log(avctx, AV_LOG_VERBOSE,
  194. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  195. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  196. print_threestate(co2->ExtBRC));
  197. #if QSV_HAVE_TRELLIS
  198. av_log(avctx, AV_LOG_VERBOSE, "Trellis: ");
  199. if (co2->Trellis & MFX_TRELLIS_OFF) {
  200. av_log(avctx, AV_LOG_VERBOSE, "off");
  201. } else if (!co2->Trellis) {
  202. av_log(avctx, AV_LOG_VERBOSE, "auto");
  203. } else {
  204. if (co2->Trellis & MFX_TRELLIS_I) av_log(avctx, AV_LOG_VERBOSE, "I");
  205. if (co2->Trellis & MFX_TRELLIS_P) av_log(avctx, AV_LOG_VERBOSE, "P");
  206. if (co2->Trellis & MFX_TRELLIS_B) av_log(avctx, AV_LOG_VERBOSE, "B");
  207. }
  208. av_log(avctx, AV_LOG_VERBOSE, "\n");
  209. #endif
  210. #if QSV_VERSION_ATLEAST(1, 8)
  211. av_log(avctx, AV_LOG_VERBOSE,
  212. "RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: ",
  213. print_threestate(co2->RepeatPPS), co2->NumMbPerSlice);
  214. switch (co2->LookAheadDS) {
  215. case MFX_LOOKAHEAD_DS_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  216. case MFX_LOOKAHEAD_DS_2x: av_log(avctx, AV_LOG_VERBOSE, "2x"); break;
  217. case MFX_LOOKAHEAD_DS_4x: av_log(avctx, AV_LOG_VERBOSE, "4x"); break;
  218. default: av_log(avctx, AV_LOG_VERBOSE, "unknown"); break;
  219. }
  220. av_log(avctx, AV_LOG_VERBOSE, "\n");
  221. av_log(avctx, AV_LOG_VERBOSE, "AdaptiveI: %s; AdaptiveB: %s; BRefType: ",
  222. print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB));
  223. switch (co2->BRefType) {
  224. case MFX_B_REF_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  225. case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "pyramid"); break;
  226. default: av_log(avctx, AV_LOG_VERBOSE, "auto"); break;
  227. }
  228. av_log(avctx, AV_LOG_VERBOSE, "\n");
  229. #endif
  230. #if QSV_VERSION_ATLEAST(1, 9)
  231. av_log(avctx, AV_LOG_VERBOSE,
  232. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  233. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  234. #endif
  235. #endif
  236. if (avctx->codec_id == AV_CODEC_ID_H264) {
  237. av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
  238. co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
  239. av_log(avctx, AV_LOG_VERBOSE,
  240. "NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
  241. print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
  242. print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
  243. }
  244. }
  245. static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
  246. {
  247. const char *rc_desc;
  248. mfxU16 rc_mode;
  249. int want_la = q->look_ahead;
  250. int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  251. int want_vcm = q->vcm;
  252. if (want_la && !QSV_HAVE_LA) {
  253. av_log(avctx, AV_LOG_ERROR,
  254. "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
  255. return AVERROR(ENOSYS);
  256. }
  257. if (want_vcm && !QSV_HAVE_VCM) {
  258. av_log(avctx, AV_LOG_ERROR,
  259. "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
  260. return AVERROR(ENOSYS);
  261. }
  262. if (want_la + want_qscale + want_vcm > 1) {
  263. av_log(avctx, AV_LOG_ERROR,
  264. "More than one of: { constant qscale, lookahead, VCM } requested, "
  265. "only one of them can be used at a time.\n");
  266. return AVERROR(EINVAL);
  267. }
  268. if (want_qscale) {
  269. rc_mode = MFX_RATECONTROL_CQP;
  270. rc_desc = "constant quantization parameter (CQP)";
  271. }
  272. #if QSV_HAVE_VCM
  273. else if (want_vcm) {
  274. rc_mode = MFX_RATECONTROL_VCM;
  275. rc_desc = "video conferencing mode (VCM)";
  276. }
  277. #endif
  278. #if QSV_HAVE_LA
  279. else if (want_la) {
  280. rc_mode = MFX_RATECONTROL_LA;
  281. rc_desc = "VBR with lookahead (LA)";
  282. #if QSV_HAVE_ICQ
  283. if (avctx->global_quality > 0) {
  284. rc_mode = MFX_RATECONTROL_LA_ICQ;
  285. rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
  286. }
  287. #endif
  288. }
  289. #endif
  290. #if QSV_HAVE_ICQ
  291. else if (avctx->global_quality > 0) {
  292. rc_mode = MFX_RATECONTROL_ICQ;
  293. rc_desc = "intelligent constant quality (ICQ)";
  294. }
  295. #endif
  296. else if (avctx->rc_max_rate == avctx->bit_rate) {
  297. rc_mode = MFX_RATECONTROL_CBR;
  298. rc_desc = "constant bitrate (CBR)";
  299. } else if (!avctx->rc_max_rate) {
  300. rc_mode = MFX_RATECONTROL_AVBR;
  301. rc_desc = "average variable bitrate (AVBR)";
  302. } else {
  303. rc_mode = MFX_RATECONTROL_VBR;
  304. rc_desc = "variable bitrate (VBR)";
  305. }
  306. q->param.mfx.RateControlMethod = rc_mode;
  307. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
  308. return 0;
  309. }
  310. static int rc_supported(QSVEncContext *q)
  311. {
  312. mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
  313. mfxStatus ret;
  314. ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
  315. if (ret < 0 ||
  316. param_out.mfx.RateControlMethod != q->param.mfx.RateControlMethod)
  317. return 0;
  318. return 1;
  319. }
  320. static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  321. {
  322. float quant;
  323. int ret;
  324. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  325. if (ret < 0)
  326. return AVERROR_BUG;
  327. q->param.mfx.CodecId = ret;
  328. q->width_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  329. if (avctx->level > 0)
  330. q->param.mfx.CodecLevel = avctx->level;
  331. q->param.mfx.CodecProfile = q->profile;
  332. q->param.mfx.TargetUsage = q->preset;
  333. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  334. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  335. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  336. MFX_GOP_CLOSED : 0;
  337. q->param.mfx.IdrInterval = q->idr_interval;
  338. q->param.mfx.NumSlice = avctx->slices;
  339. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  340. q->param.mfx.EncodedOrder = 0;
  341. q->param.mfx.BufferSizeInKB = 0;
  342. q->param.mfx.FrameInfo.FourCC = MFX_FOURCC_NV12;
  343. q->param.mfx.FrameInfo.CropX = 0;
  344. q->param.mfx.FrameInfo.CropY = 0;
  345. q->param.mfx.FrameInfo.CropW = avctx->width;
  346. q->param.mfx.FrameInfo.CropH = avctx->height;
  347. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  348. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  349. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  350. q->param.mfx.FrameInfo.BitDepthLuma = 8;
  351. q->param.mfx.FrameInfo.BitDepthChroma = 8;
  352. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  353. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  354. /* A true field layout (TFF or BFF) is not important here,
  355. it will specified later during frame encoding. But it is important
  356. to specify is frame progressive or not because allowed heigh alignment
  357. does depend by this.
  358. */
  359. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
  360. q->height_align = 32;
  361. } else {
  362. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  363. q->height_align = 16;
  364. }
  365. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  366. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  367. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  368. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  369. } else {
  370. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  371. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  372. }
  373. ret = select_rc_mode(avctx, q);
  374. if (ret < 0)
  375. return ret;
  376. switch (q->param.mfx.RateControlMethod) {
  377. case MFX_RATECONTROL_CBR:
  378. case MFX_RATECONTROL_VBR:
  379. #if QSV_HAVE_VCM
  380. case MFX_RATECONTROL_VCM:
  381. #endif
  382. q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
  383. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  384. q->param.mfx.MaxKbps = avctx->rc_max_rate / 1000;
  385. break;
  386. case MFX_RATECONTROL_CQP:
  387. quant = avctx->global_quality / FF_QP2LAMBDA;
  388. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  389. q->param.mfx.QPP = av_clip(quant, 0, 51);
  390. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  391. break;
  392. case MFX_RATECONTROL_AVBR:
  393. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  394. q->param.mfx.Convergence = q->avbr_convergence;
  395. q->param.mfx.Accuracy = q->avbr_accuracy;
  396. break;
  397. #if QSV_HAVE_LA
  398. case MFX_RATECONTROL_LA:
  399. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  400. q->extco2.LookAheadDepth = q->look_ahead_depth;
  401. break;
  402. #if QSV_HAVE_ICQ
  403. case MFX_RATECONTROL_LA_ICQ:
  404. q->extco2.LookAheadDepth = q->look_ahead_depth;
  405. case MFX_RATECONTROL_ICQ:
  406. q->param.mfx.ICQQuality = avctx->global_quality;
  407. break;
  408. #endif
  409. #endif
  410. }
  411. // the HEVC encoder plugin currently fails if coding options
  412. // are provided
  413. if (avctx->codec_id != AV_CODEC_ID_HEVC) {
  414. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  415. q->extco.Header.BufferSz = sizeof(q->extco);
  416. q->extco.CAVLC = avctx->coder_type == FF_CODER_TYPE_VLC ?
  417. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  418. q->extco.PicTimingSEI = q->pic_timing_sei ?
  419. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  420. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  421. #if QSV_HAVE_CO2
  422. if (avctx->codec_id == AV_CODEC_ID_H264) {
  423. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  424. q->extco2.Header.BufferSz = sizeof(q->extco2);
  425. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  426. #if QSV_VERSION_ATLEAST(1,8)
  427. q->extco2.LookAheadDS = q->look_ahead_downsampling;
  428. #endif
  429. }
  430. #endif
  431. }
  432. if (!rc_supported(q)) {
  433. av_log(avctx, AV_LOG_ERROR,
  434. "Selected ratecontrol mode is not supported by the QSV "
  435. "runtime. Choose a different mode.\n");
  436. return AVERROR(ENOSYS);
  437. }
  438. return 0;
  439. }
  440. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  441. {
  442. uint8_t sps_buf[128];
  443. uint8_t pps_buf[128];
  444. mfxExtCodingOptionSPSPPS extradata = {
  445. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  446. .Header.BufferSz = sizeof(extradata),
  447. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  448. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  449. };
  450. mfxExtCodingOption co = {
  451. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  452. .Header.BufferSz = sizeof(co),
  453. };
  454. #if QSV_HAVE_CO2
  455. mfxExtCodingOption2 co2 = {
  456. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  457. .Header.BufferSz = sizeof(co2),
  458. };
  459. #endif
  460. #if QSV_HAVE_CO3
  461. mfxExtCodingOption3 co3 = {
  462. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  463. .Header.BufferSz = sizeof(co3),
  464. };
  465. #endif
  466. mfxExtBuffer *ext_buffers[] = {
  467. (mfxExtBuffer*)&extradata,
  468. (mfxExtBuffer*)&co,
  469. #if QSV_HAVE_CO2
  470. (mfxExtBuffer*)&co2,
  471. #endif
  472. #if QSV_HAVE_CO3
  473. (mfxExtBuffer*)&co3,
  474. #endif
  475. };
  476. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  477. int ret;
  478. q->param.ExtParam = ext_buffers;
  479. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  480. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  481. if (ret < 0)
  482. return ff_qsv_error(ret);
  483. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  484. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  485. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  486. return AVERROR_UNKNOWN;
  487. }
  488. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  489. AV_INPUT_BUFFER_PADDING_SIZE);
  490. if (!avctx->extradata)
  491. return AVERROR(ENOMEM);
  492. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  493. if (need_pps)
  494. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  495. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  496. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  497. dump_video_param(avctx, q, ext_buffers + 1);
  498. return 0;
  499. }
  500. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  501. {
  502. AVQSVContext *qsv = avctx->hwaccel_context;
  503. mfxFrameSurface1 *surfaces;
  504. int nb_surfaces, i;
  505. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested + q->async_depth;
  506. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  507. if (!q->opaque_alloc_buf)
  508. return AVERROR(ENOMEM);
  509. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  510. if (!q->opaque_surfaces)
  511. return AVERROR(ENOMEM);
  512. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  513. for (i = 0; i < nb_surfaces; i++) {
  514. surfaces[i].Info = q->req.Info;
  515. q->opaque_surfaces[i] = surfaces + i;
  516. }
  517. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  518. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  519. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  520. q->opaque_alloc.In.NumSurface = nb_surfaces;
  521. q->opaque_alloc.In.Type = q->req.Type;
  522. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  523. qsv->nb_opaque_surfaces = nb_surfaces;
  524. qsv->opaque_surfaces = q->opaque_alloc_buf;
  525. qsv->opaque_alloc_type = q->req.Type;
  526. return 0;
  527. }
  528. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  529. {
  530. int opaque_alloc = 0;
  531. int ret;
  532. q->param.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  533. q->param.AsyncDepth = q->async_depth;
  534. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  535. (sizeof(AVPacket) + sizeof(mfxSyncPoint) + sizeof(mfxBitstream*)));
  536. if (!q->async_fifo)
  537. return AVERROR(ENOMEM);
  538. if (avctx->hwaccel_context) {
  539. AVQSVContext *qsv = avctx->hwaccel_context;
  540. q->session = qsv->session;
  541. q->param.IOPattern = qsv->iopattern;
  542. opaque_alloc = qsv->opaque_alloc;
  543. }
  544. if (!q->session) {
  545. ret = ff_qsv_init_internal_session(avctx, &q->internal_qs,
  546. q->load_plugins);
  547. if (ret < 0)
  548. return ret;
  549. q->session = q->internal_qs.session;
  550. }
  551. ret = init_video_param(avctx, q);
  552. if (ret < 0)
  553. return ret;
  554. ret = MFXVideoENCODE_Query(q->session, &q->param,&q->param);
  555. if (MFX_WRN_PARTIAL_ACCELERATION==ret) {
  556. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  557. } else if (ret < 0) {
  558. av_log(avctx, AV_LOG_ERROR, "Error %d querying encoder params\n", ret);
  559. return ff_qsv_error(ret);
  560. }
  561. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  562. if (ret < 0) {
  563. av_log(avctx, AV_LOG_ERROR, "Error querying the encoding parameters\n");
  564. return ff_qsv_error(ret);
  565. }
  566. if (opaque_alloc) {
  567. ret = qsv_init_opaque_alloc(avctx, q);
  568. if (ret < 0)
  569. return ret;
  570. }
  571. if (avctx->hwaccel_context) {
  572. AVQSVContext *qsv = avctx->hwaccel_context;
  573. int i, j;
  574. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  575. sizeof(*q->extparam));
  576. if (!q->extparam)
  577. return AVERROR(ENOMEM);
  578. q->param.ExtParam = q->extparam;
  579. for (i = 0; i < qsv->nb_ext_buffers; i++)
  580. q->param.ExtParam[i] = qsv->ext_buffers[i];
  581. q->param.NumExtParam = qsv->nb_ext_buffers;
  582. for (i = 0; i < q->nb_extparam_internal; i++) {
  583. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  584. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  585. break;
  586. }
  587. if (j < qsv->nb_ext_buffers)
  588. continue;
  589. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  590. }
  591. } else {
  592. q->param.ExtParam = q->extparam_internal;
  593. q->param.NumExtParam = q->nb_extparam_internal;
  594. }
  595. ret = MFXVideoENCODE_Init(q->session, &q->param);
  596. if (MFX_WRN_PARTIAL_ACCELERATION==ret) {
  597. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  598. } else if (ret < 0) {
  599. av_log(avctx, AV_LOG_ERROR, "Error initializing the encoder\n");
  600. return ff_qsv_error(ret);
  601. }
  602. ret = qsv_retrieve_enc_params(avctx, q);
  603. if (ret < 0) {
  604. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  605. return ret;
  606. }
  607. q->avctx = avctx;
  608. return 0;
  609. }
  610. static void clear_unused_frames(QSVEncContext *q)
  611. {
  612. QSVFrame *cur = q->work_frames;
  613. while (cur) {
  614. if (cur->surface && !cur->surface->Data.Locked) {
  615. cur->surface = NULL;
  616. av_frame_unref(cur->frame);
  617. }
  618. cur = cur->next;
  619. }
  620. }
  621. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  622. {
  623. QSVFrame *frame, **last;
  624. clear_unused_frames(q);
  625. frame = q->work_frames;
  626. last = &q->work_frames;
  627. while (frame) {
  628. if (!frame->surface) {
  629. *f = frame;
  630. return 0;
  631. }
  632. last = &frame->next;
  633. frame = frame->next;
  634. }
  635. frame = av_mallocz(sizeof(*frame));
  636. if (!frame)
  637. return AVERROR(ENOMEM);
  638. frame->frame = av_frame_alloc();
  639. if (!frame->frame) {
  640. av_freep(&frame);
  641. return AVERROR(ENOMEM);
  642. }
  643. *last = frame;
  644. *f = frame;
  645. return 0;
  646. }
  647. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  648. mfxFrameSurface1 **surface)
  649. {
  650. QSVFrame *qf;
  651. int ret;
  652. ret = get_free_frame(q, &qf);
  653. if (ret < 0)
  654. return ret;
  655. if (frame->format == AV_PIX_FMT_QSV) {
  656. ret = av_frame_ref(qf->frame, frame);
  657. if (ret < 0)
  658. return ret;
  659. qf->surface = (mfxFrameSurface1*)qf->frame->data[3];
  660. } else {
  661. /* make a copy if the input is not padded as libmfx requires */
  662. if ( frame->height & (q->height_align - 1) ||
  663. frame->linesize[0] & (q->width_align - 1)) {
  664. qf->frame->height = FFALIGN(frame->height, q->height_align);
  665. qf->frame->width = FFALIGN(frame->width, q->width_align);
  666. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  667. if (ret < 0)
  668. return ret;
  669. qf->frame->height = frame->height;
  670. qf->frame->width = frame->width;
  671. ret = av_frame_copy(qf->frame, frame);
  672. if (ret < 0) {
  673. av_frame_unref(qf->frame);
  674. return ret;
  675. }
  676. } else {
  677. ret = av_frame_ref(qf->frame, frame);
  678. if (ret < 0)
  679. return ret;
  680. }
  681. qf->surface_internal.Info = q->param.mfx.FrameInfo;
  682. qf->surface_internal.Info.PicStruct =
  683. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  684. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  685. MFX_PICSTRUCT_FIELD_BFF;
  686. if (frame->repeat_pict == 1)
  687. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  688. else if (frame->repeat_pict == 2)
  689. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  690. else if (frame->repeat_pict == 4)
  691. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  692. qf->surface_internal.Data.PitchLow = qf->frame->linesize[0];
  693. qf->surface_internal.Data.Y = qf->frame->data[0];
  694. qf->surface_internal.Data.UV = qf->frame->data[1];
  695. qf->surface = &qf->surface_internal;
  696. }
  697. qf->surface->Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  698. *surface = qf->surface;
  699. return 0;
  700. }
  701. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  702. {
  703. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  704. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  705. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  706. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  707. av_log(avctx, AV_LOG_WARNING,
  708. "Interlaced coding is supported"
  709. " at Main/High Profile Level 2.1-4.1\n");
  710. }
  711. }
  712. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  713. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  714. {
  715. AVPacket new_pkt = { 0 };
  716. mfxBitstream *bs;
  717. mfxFrameSurface1 *surf = NULL;
  718. mfxSyncPoint sync = NULL;
  719. int ret;
  720. if (frame) {
  721. ret = submit_frame(q, frame, &surf);
  722. if (ret < 0) {
  723. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  724. return ret;
  725. }
  726. }
  727. ret = av_new_packet(&new_pkt, q->packet_size);
  728. if (ret < 0) {
  729. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  730. return ret;
  731. }
  732. bs = av_mallocz(sizeof(*bs));
  733. if (!bs) {
  734. av_packet_unref(&new_pkt);
  735. return AVERROR(ENOMEM);
  736. }
  737. bs->Data = new_pkt.data;
  738. bs->MaxLength = new_pkt.size;
  739. do {
  740. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, &sync);
  741. if (ret == MFX_WRN_DEVICE_BUSY) {
  742. av_usleep(500);
  743. continue;
  744. }
  745. break;
  746. } while ( 1 );
  747. if (ret < 0) {
  748. av_packet_unref(&new_pkt);
  749. av_freep(&bs);
  750. if (ret == MFX_ERR_MORE_DATA)
  751. return 0;
  752. av_log(avctx, AV_LOG_ERROR, "EncodeFrameAsync returned %d\n", ret);
  753. return ff_qsv_error(ret);
  754. }
  755. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM) {
  756. if (frame->interlaced_frame)
  757. print_interlace_msg(avctx, q);
  758. else
  759. av_log(avctx, AV_LOG_WARNING,
  760. "EncodeFrameAsync returned 'incompatible param' code\n");
  761. }
  762. if (sync) {
  763. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  764. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  765. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  766. } else {
  767. av_packet_unref(&new_pkt);
  768. av_freep(&bs);
  769. }
  770. if (!av_fifo_space(q->async_fifo) ||
  771. (!frame && av_fifo_size(q->async_fifo))) {
  772. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  773. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  774. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  775. MFXVideoCORE_SyncOperation(q->session, sync, 60000);
  776. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  777. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  778. new_pkt.size = bs->DataLength;
  779. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  780. bs->FrameType & MFX_FRAMETYPE_xIDR)
  781. new_pkt.flags |= AV_PKT_FLAG_KEY;
  782. #if FF_API_CODED_FRAME
  783. FF_DISABLE_DEPRECATION_WARNINGS
  784. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  785. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  786. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  787. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  788. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  789. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  790. FF_ENABLE_DEPRECATION_WARNINGS
  791. #endif
  792. av_freep(&bs);
  793. if (pkt->data) {
  794. if (pkt->size < new_pkt.size) {
  795. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  796. pkt->size, new_pkt.size);
  797. av_packet_unref(&new_pkt);
  798. return AVERROR(EINVAL);
  799. }
  800. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  801. pkt->size = new_pkt.size;
  802. ret = av_packet_copy_props(pkt, &new_pkt);
  803. av_packet_unref(&new_pkt);
  804. if (ret < 0)
  805. return ret;
  806. } else
  807. *pkt = new_pkt;
  808. *got_packet = 1;
  809. }
  810. return 0;
  811. }
  812. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  813. {
  814. QSVFrame *cur;
  815. if (q->session)
  816. MFXVideoENCODE_Close(q->session);
  817. q->session = NULL;
  818. ff_qsv_close_internal_session(&q->internal_qs);
  819. cur = q->work_frames;
  820. while (cur) {
  821. q->work_frames = cur->next;
  822. av_frame_free(&cur->frame);
  823. av_freep(&cur);
  824. cur = q->work_frames;
  825. }
  826. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  827. AVPacket pkt;
  828. mfxSyncPoint sync;
  829. mfxBitstream *bs;
  830. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  831. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  832. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  833. av_freep(&bs);
  834. av_packet_unref(&pkt);
  835. }
  836. av_fifo_free(q->async_fifo);
  837. q->async_fifo = NULL;
  838. av_freep(&q->opaque_surfaces);
  839. av_buffer_unref(&q->opaque_alloc_buf);
  840. av_freep(&q->extparam);
  841. return 0;
  842. }