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.

1147 lines
39KB

  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. { MFX_RATECONTROL_AVBR, "AVBR" },
  83. #if QSV_HAVE_LA
  84. { MFX_RATECONTROL_LA, "LA" },
  85. #endif
  86. #if QSV_HAVE_ICQ
  87. { MFX_RATECONTROL_ICQ, "ICQ" },
  88. { MFX_RATECONTROL_LA_ICQ, "LA_ICQ" },
  89. #endif
  90. #if QSV_HAVE_VCM
  91. { MFX_RATECONTROL_VCM, "VCM" },
  92. #endif
  93. #if QSV_VERSION_ATLEAST(1, 10)
  94. { MFX_RATECONTROL_LA_EXT, "LA_EXT" },
  95. #endif
  96. #if QSV_HAVE_LA_HRD
  97. { MFX_RATECONTROL_LA_HRD, "LA_HRD" },
  98. #endif
  99. #if QSV_HAVE_QVBR
  100. { MFX_RATECONTROL_QVBR, "QVBR" },
  101. #endif
  102. };
  103. static const char *print_ratecontrol(mfxU16 rc_mode)
  104. {
  105. int i;
  106. for (i = 0; i < FF_ARRAY_ELEMS(rc_names); i++)
  107. if (rc_mode == rc_names[i].rc_mode)
  108. return rc_names[i].name;
  109. return "unknown";
  110. }
  111. static const char *print_threestate(mfxU16 val)
  112. {
  113. if (val == MFX_CODINGOPTION_ON)
  114. return "ON";
  115. else if (val == MFX_CODINGOPTION_OFF)
  116. return "OFF";
  117. return "unknown";
  118. }
  119. static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
  120. mfxExtBuffer **coding_opts)
  121. {
  122. mfxInfoMFX *info = &q->param.mfx;
  123. mfxExtCodingOption *co = (mfxExtCodingOption*)coding_opts[0];
  124. #if QSV_HAVE_CO2
  125. mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[1];
  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. av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
  175. info->NumSlice, info->NumRefFrame);
  176. av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
  177. print_threestate(co->RateDistortionOpt));
  178. #if QSV_HAVE_CO2
  179. av_log(avctx, AV_LOG_VERBOSE,
  180. "RecoveryPointSEI: %s IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
  181. print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
  182. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %"PRIu16"; ", co2->MaxFrameSize);
  183. #if QSV_HAVE_MAX_SLICE_SIZE
  184. av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %"PRIu16"; ", co2->MaxSliceSize);
  185. #endif
  186. av_log(avctx, AV_LOG_VERBOSE, "\n");
  187. av_log(avctx, AV_LOG_VERBOSE,
  188. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  189. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  190. print_threestate(co2->ExtBRC));
  191. #if QSV_HAVE_TRELLIS
  192. av_log(avctx, AV_LOG_VERBOSE, "Trellis: ");
  193. if (co2->Trellis & MFX_TRELLIS_OFF) {
  194. av_log(avctx, AV_LOG_VERBOSE, "off");
  195. } else if (!co2->Trellis) {
  196. av_log(avctx, AV_LOG_VERBOSE, "auto");
  197. } else {
  198. if (co2->Trellis & MFX_TRELLIS_I) av_log(avctx, AV_LOG_VERBOSE, "I");
  199. if (co2->Trellis & MFX_TRELLIS_P) av_log(avctx, AV_LOG_VERBOSE, "P");
  200. if (co2->Trellis & MFX_TRELLIS_B) av_log(avctx, AV_LOG_VERBOSE, "B");
  201. }
  202. av_log(avctx, AV_LOG_VERBOSE, "\n");
  203. #endif
  204. #if QSV_VERSION_ATLEAST(1, 8)
  205. av_log(avctx, AV_LOG_VERBOSE,
  206. "RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: ",
  207. print_threestate(co2->RepeatPPS), co2->NumMbPerSlice);
  208. switch (co2->LookAheadDS) {
  209. case MFX_LOOKAHEAD_DS_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  210. case MFX_LOOKAHEAD_DS_2x: av_log(avctx, AV_LOG_VERBOSE, "2x"); break;
  211. case MFX_LOOKAHEAD_DS_4x: av_log(avctx, AV_LOG_VERBOSE, "4x"); break;
  212. default: av_log(avctx, AV_LOG_VERBOSE, "unknown"); break;
  213. }
  214. av_log(avctx, AV_LOG_VERBOSE, "\n");
  215. av_log(avctx, AV_LOG_VERBOSE, "AdaptiveI: %s; AdaptiveB: %s; BRefType: ",
  216. print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB));
  217. switch (co2->BRefType) {
  218. case MFX_B_REF_OFF: av_log(avctx, AV_LOG_VERBOSE, "off"); break;
  219. case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "pyramid"); break;
  220. default: av_log(avctx, AV_LOG_VERBOSE, "auto"); break;
  221. }
  222. av_log(avctx, AV_LOG_VERBOSE, "\n");
  223. #endif
  224. #if QSV_VERSION_ATLEAST(1, 9)
  225. av_log(avctx, AV_LOG_VERBOSE,
  226. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  227. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  228. #endif
  229. #endif
  230. if (avctx->codec_id == AV_CODEC_ID_H264) {
  231. av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
  232. co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
  233. av_log(avctx, AV_LOG_VERBOSE,
  234. "NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
  235. print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
  236. print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
  237. }
  238. }
  239. static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
  240. {
  241. const char *rc_desc;
  242. mfxU16 rc_mode;
  243. int want_la = q->look_ahead;
  244. int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  245. int want_vcm = q->vcm;
  246. if (want_la && !QSV_HAVE_LA) {
  247. av_log(avctx, AV_LOG_ERROR,
  248. "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
  249. return AVERROR(ENOSYS);
  250. }
  251. if (want_vcm && !QSV_HAVE_VCM) {
  252. av_log(avctx, AV_LOG_ERROR,
  253. "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
  254. return AVERROR(ENOSYS);
  255. }
  256. if (want_la + want_qscale + want_vcm > 1) {
  257. av_log(avctx, AV_LOG_ERROR,
  258. "More than one of: { constant qscale, lookahead, VCM } requested, "
  259. "only one of them can be used at a time.\n");
  260. return AVERROR(EINVAL);
  261. }
  262. if (want_qscale) {
  263. rc_mode = MFX_RATECONTROL_CQP;
  264. rc_desc = "constant quantization parameter (CQP)";
  265. }
  266. #if QSV_HAVE_VCM
  267. else if (want_vcm) {
  268. rc_mode = MFX_RATECONTROL_VCM;
  269. rc_desc = "video conferencing mode (VCM)";
  270. }
  271. #endif
  272. #if QSV_HAVE_LA
  273. else if (want_la) {
  274. rc_mode = MFX_RATECONTROL_LA;
  275. rc_desc = "VBR with lookahead (LA)";
  276. #if QSV_HAVE_ICQ
  277. if (avctx->global_quality > 0) {
  278. rc_mode = MFX_RATECONTROL_LA_ICQ;
  279. rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
  280. }
  281. #endif
  282. }
  283. #endif
  284. #if QSV_HAVE_ICQ
  285. else if (avctx->global_quality > 0) {
  286. rc_mode = MFX_RATECONTROL_ICQ;
  287. rc_desc = "intelligent constant quality (ICQ)";
  288. }
  289. #endif
  290. else if (avctx->rc_max_rate == avctx->bit_rate) {
  291. rc_mode = MFX_RATECONTROL_CBR;
  292. rc_desc = "constant bitrate (CBR)";
  293. } else if (!avctx->rc_max_rate) {
  294. rc_mode = MFX_RATECONTROL_AVBR;
  295. rc_desc = "average variable bitrate (AVBR)";
  296. } else {
  297. rc_mode = MFX_RATECONTROL_VBR;
  298. rc_desc = "variable bitrate (VBR)";
  299. }
  300. q->param.mfx.RateControlMethod = rc_mode;
  301. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
  302. return 0;
  303. }
  304. static int rc_supported(QSVEncContext *q)
  305. {
  306. mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
  307. mfxStatus ret;
  308. ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
  309. if (ret < 0 ||
  310. param_out.mfx.RateControlMethod != q->param.mfx.RateControlMethod)
  311. return 0;
  312. return 1;
  313. }
  314. static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  315. {
  316. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  317. avctx->sw_pix_fmt : avctx->pix_fmt;
  318. const AVPixFmtDescriptor *desc;
  319. float quant;
  320. int ret;
  321. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  322. if (ret < 0)
  323. return AVERROR_BUG;
  324. q->param.mfx.CodecId = ret;
  325. q->width_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  326. if (avctx->level > 0)
  327. q->param.mfx.CodecLevel = avctx->level;
  328. q->param.mfx.CodecProfile = q->profile;
  329. q->param.mfx.TargetUsage = q->preset;
  330. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  331. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  332. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  333. MFX_GOP_CLOSED : 0;
  334. q->param.mfx.IdrInterval = q->idr_interval;
  335. q->param.mfx.NumSlice = avctx->slices;
  336. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  337. q->param.mfx.EncodedOrder = 0;
  338. q->param.mfx.BufferSizeInKB = 0;
  339. desc = av_pix_fmt_desc_get(sw_format);
  340. if (!desc)
  341. return AVERROR_BUG;
  342. ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
  343. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  344. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 32);
  345. q->param.mfx.FrameInfo.CropX = 0;
  346. q->param.mfx.FrameInfo.CropY = 0;
  347. q->param.mfx.FrameInfo.CropW = avctx->width;
  348. q->param.mfx.FrameInfo.CropH = avctx->height;
  349. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  350. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  351. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  352. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  353. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  354. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  355. q->param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
  356. if (avctx->hw_frames_ctx) {
  357. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  358. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  359. q->param.mfx.FrameInfo.Width = frames_hwctx->surfaces[0].Info.Width;
  360. q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
  361. }
  362. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  363. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  364. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  365. } else {
  366. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  367. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  368. }
  369. ret = select_rc_mode(avctx, q);
  370. if (ret < 0)
  371. return ret;
  372. switch (q->param.mfx.RateControlMethod) {
  373. case MFX_RATECONTROL_CBR:
  374. case MFX_RATECONTROL_VBR:
  375. #if QSV_HAVE_VCM
  376. case MFX_RATECONTROL_VCM:
  377. #endif
  378. q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
  379. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  380. q->param.mfx.MaxKbps = avctx->rc_max_rate / 1000;
  381. break;
  382. case MFX_RATECONTROL_CQP:
  383. quant = avctx->global_quality / FF_QP2LAMBDA;
  384. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  385. q->param.mfx.QPP = av_clip(quant, 0, 51);
  386. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  387. break;
  388. case MFX_RATECONTROL_AVBR:
  389. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  390. q->param.mfx.Convergence = q->avbr_convergence;
  391. q->param.mfx.Accuracy = q->avbr_accuracy;
  392. break;
  393. #if QSV_HAVE_LA
  394. case MFX_RATECONTROL_LA:
  395. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  396. q->extco2.LookAheadDepth = q->look_ahead_depth;
  397. break;
  398. #if QSV_HAVE_ICQ
  399. case MFX_RATECONTROL_LA_ICQ:
  400. q->extco2.LookAheadDepth = q->look_ahead_depth;
  401. case MFX_RATECONTROL_ICQ:
  402. q->param.mfx.ICQQuality = avctx->global_quality;
  403. break;
  404. #endif
  405. #endif
  406. }
  407. // the HEVC encoder plugin currently fails if coding options
  408. // are provided
  409. if (avctx->codec_id != AV_CODEC_ID_HEVC) {
  410. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  411. q->extco.Header.BufferSz = sizeof(q->extco);
  412. #if FF_API_CODER_TYPE
  413. FF_DISABLE_DEPRECATION_WARNINGS
  414. if (avctx->coder_type != 0)
  415. q->cavlc = avctx->coder_type == FF_CODER_TYPE_VLC;
  416. FF_ENABLE_DEPRECATION_WARNINGS
  417. #endif
  418. q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
  419. : MFX_CODINGOPTION_UNKNOWN;
  420. q->extco.PicTimingSEI = q->pic_timing_sei ?
  421. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  422. if (q->rdo >= 0)
  423. q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  424. if (avctx->codec_id == AV_CODEC_ID_H264) {
  425. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  426. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  427. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  428. if (q->single_sei_nal_unit >= 0)
  429. q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  430. if (q->recovery_point_sei >= 0)
  431. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  432. q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
  433. }
  434. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  435. #if QSV_HAVE_CO2
  436. if (avctx->codec_id == AV_CODEC_ID_H264) {
  437. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  438. q->extco2.Header.BufferSz = sizeof(q->extco2);
  439. if (q->int_ref_type >= 0)
  440. q->extco2.IntRefType = q->int_ref_type;
  441. if (q->int_ref_cycle_size >= 0)
  442. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  443. if (q->int_ref_qp_delta != INT16_MIN)
  444. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  445. if (q->bitrate_limit >= 0)
  446. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  447. if (q->mbbrc >= 0)
  448. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  449. if (q->extbrc >= 0)
  450. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  451. if (q->max_frame_size >= 0)
  452. q->extco2.MaxFrameSize = q->max_frame_size;
  453. #if QSV_HAVE_MAX_SLICE_SIZE
  454. if (q->max_slice_size >= 0)
  455. q->extco2.MaxSliceSize = q->max_slice_size;
  456. #endif
  457. #if QSV_HAVE_TRELLIS
  458. q->extco2.Trellis = q->trellis;
  459. #endif
  460. #if QSV_HAVE_BREF_TYPE
  461. #if FF_API_PRIVATE_OPT
  462. FF_DISABLE_DEPRECATION_WARNINGS
  463. if (avctx->b_frame_strategy >= 0)
  464. q->b_strategy = avctx->b_frame_strategy;
  465. FF_ENABLE_DEPRECATION_WARNINGS
  466. #endif
  467. if (q->b_strategy >= 0)
  468. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  469. if (q->adaptive_i >= 0)
  470. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  471. if (q->adaptive_b >= 0)
  472. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  473. #endif
  474. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  475. #if QSV_HAVE_LA_DS
  476. q->extco2.LookAheadDS = q->look_ahead_downsampling;
  477. #endif
  478. }
  479. #endif
  480. }
  481. if (!rc_supported(q)) {
  482. av_log(avctx, AV_LOG_ERROR,
  483. "Selected ratecontrol mode is not supported by the QSV "
  484. "runtime. Choose a different mode.\n");
  485. return AVERROR(ENOSYS);
  486. }
  487. return 0;
  488. }
  489. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  490. {
  491. AVCPBProperties *cpb_props;
  492. uint8_t sps_buf[128];
  493. uint8_t pps_buf[128];
  494. mfxExtCodingOptionSPSPPS extradata = {
  495. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  496. .Header.BufferSz = sizeof(extradata),
  497. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  498. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  499. };
  500. mfxExtCodingOption co = {
  501. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  502. .Header.BufferSz = sizeof(co),
  503. };
  504. #if QSV_HAVE_CO2
  505. mfxExtCodingOption2 co2 = {
  506. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  507. .Header.BufferSz = sizeof(co2),
  508. };
  509. #endif
  510. mfxExtBuffer *ext_buffers[] = {
  511. (mfxExtBuffer*)&extradata,
  512. (mfxExtBuffer*)&co,
  513. #if QSV_HAVE_CO2
  514. (mfxExtBuffer*)&co2,
  515. #endif
  516. };
  517. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  518. int ret;
  519. q->param.ExtParam = ext_buffers;
  520. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  521. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  522. if (ret < 0)
  523. return ff_qsv_print_error(avctx, ret,
  524. "Error calling GetVideoParam");
  525. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  526. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  527. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  528. return AVERROR_UNKNOWN;
  529. }
  530. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  531. AV_INPUT_BUFFER_PADDING_SIZE);
  532. if (!avctx->extradata)
  533. return AVERROR(ENOMEM);
  534. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  535. if (need_pps)
  536. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  537. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  538. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  539. cpb_props = ff_add_cpb_side_data(avctx);
  540. if (!cpb_props)
  541. return AVERROR(ENOMEM);
  542. cpb_props->max_bitrate = avctx->rc_max_rate;
  543. cpb_props->min_bitrate = avctx->rc_min_rate;
  544. cpb_props->avg_bitrate = avctx->bit_rate;
  545. cpb_props->buffer_size = avctx->rc_buffer_size;
  546. dump_video_param(avctx, q, ext_buffers + 1);
  547. return 0;
  548. }
  549. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  550. {
  551. AVQSVContext *qsv = avctx->hwaccel_context;
  552. mfxFrameSurface1 *surfaces;
  553. int nb_surfaces, i;
  554. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested + q->async_depth;
  555. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  556. if (!q->opaque_alloc_buf)
  557. return AVERROR(ENOMEM);
  558. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  559. if (!q->opaque_surfaces)
  560. return AVERROR(ENOMEM);
  561. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  562. for (i = 0; i < nb_surfaces; i++) {
  563. surfaces[i].Info = q->req.Info;
  564. q->opaque_surfaces[i] = surfaces + i;
  565. }
  566. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  567. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  568. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  569. q->opaque_alloc.In.NumSurface = nb_surfaces;
  570. q->opaque_alloc.In.Type = q->req.Type;
  571. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  572. qsv->nb_opaque_surfaces = nb_surfaces;
  573. qsv->opaque_surfaces = q->opaque_alloc_buf;
  574. qsv->opaque_alloc_type = q->req.Type;
  575. return 0;
  576. }
  577. static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
  578. {
  579. int ret;
  580. if (avctx->hwaccel_context) {
  581. AVQSVContext *qsv = avctx->hwaccel_context;
  582. q->session = qsv->session;
  583. } else if (avctx->hw_frames_ctx) {
  584. q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  585. if (!q->frames_ctx.hw_frames_ctx)
  586. return AVERROR(ENOMEM);
  587. ret = ff_qsv_init_session_hwcontext(avctx, &q->internal_session,
  588. &q->frames_ctx, q->load_plugins,
  589. q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY);
  590. if (ret < 0) {
  591. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  592. return ret;
  593. }
  594. q->session = q->internal_session;
  595. } else {
  596. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  597. q->load_plugins);
  598. if (ret < 0)
  599. return ret;
  600. q->session = q->internal_session;
  601. }
  602. return 0;
  603. }
  604. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  605. {
  606. int iopattern = 0;
  607. int opaque_alloc = 0;
  608. int ret;
  609. q->param.AsyncDepth = q->async_depth;
  610. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  611. (sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*)));
  612. if (!q->async_fifo)
  613. return AVERROR(ENOMEM);
  614. if (avctx->hwaccel_context) {
  615. AVQSVContext *qsv = avctx->hwaccel_context;
  616. iopattern = qsv->iopattern;
  617. opaque_alloc = qsv->opaque_alloc;
  618. }
  619. if (avctx->hw_frames_ctx) {
  620. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  621. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  622. if (!iopattern) {
  623. if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
  624. iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
  625. else if (frames_hwctx->frame_type &
  626. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  627. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  628. }
  629. }
  630. if (!iopattern)
  631. iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  632. q->param.IOPattern = iopattern;
  633. ret = qsvenc_init_session(avctx, q);
  634. if (ret < 0)
  635. return ret;
  636. ret = init_video_param(avctx, q);
  637. if (ret < 0)
  638. return ret;
  639. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  640. if (ret < 0)
  641. return ff_qsv_print_error(avctx, ret,
  642. "Error querying the encoding parameters");
  643. if (opaque_alloc) {
  644. ret = qsv_init_opaque_alloc(avctx, q);
  645. if (ret < 0)
  646. return ret;
  647. }
  648. if (avctx->hwaccel_context) {
  649. AVQSVContext *qsv = avctx->hwaccel_context;
  650. int i, j;
  651. q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
  652. sizeof(*q->extparam));
  653. if (!q->extparam)
  654. return AVERROR(ENOMEM);
  655. q->param.ExtParam = q->extparam;
  656. for (i = 0; i < qsv->nb_ext_buffers; i++)
  657. q->param.ExtParam[i] = qsv->ext_buffers[i];
  658. q->param.NumExtParam = qsv->nb_ext_buffers;
  659. for (i = 0; i < q->nb_extparam_internal; i++) {
  660. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  661. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  662. break;
  663. }
  664. if (j < qsv->nb_ext_buffers)
  665. continue;
  666. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  667. }
  668. } else {
  669. q->param.ExtParam = q->extparam_internal;
  670. q->param.NumExtParam = q->nb_extparam_internal;
  671. }
  672. ret = MFXVideoENCODE_Init(q->session, &q->param);
  673. if (ret < 0)
  674. return ff_qsv_print_error(avctx, ret,
  675. "Error initializing the encoder");
  676. else if (ret > 0)
  677. ff_qsv_print_warning(avctx, ret,
  678. "Warning in encoder initialization");
  679. ret = qsv_retrieve_enc_params(avctx, q);
  680. if (ret < 0) {
  681. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  682. return ret;
  683. }
  684. q->avctx = avctx;
  685. return 0;
  686. }
  687. static void free_encoder_ctrl_payloads(mfxEncodeCtrl* enc_ctrl)
  688. {
  689. if (enc_ctrl) {
  690. int i;
  691. for (i = 0; i < enc_ctrl->NumPayload && i < QSV_MAX_ENC_PAYLOAD; i++) {
  692. av_free(enc_ctrl->Payload[i]);
  693. }
  694. enc_ctrl->NumPayload = 0;
  695. }
  696. }
  697. static void clear_unused_frames(QSVEncContext *q)
  698. {
  699. QSVFrame *cur = q->work_frames;
  700. while (cur) {
  701. if (cur->used && !cur->surface.Data.Locked) {
  702. free_encoder_ctrl_payloads(&cur->enc_ctrl);
  703. av_frame_unref(cur->frame);
  704. cur->used = 0;
  705. }
  706. cur = cur->next;
  707. }
  708. }
  709. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  710. {
  711. QSVFrame *frame, **last;
  712. clear_unused_frames(q);
  713. frame = q->work_frames;
  714. last = &q->work_frames;
  715. while (frame) {
  716. if (!frame->used) {
  717. *f = frame;
  718. frame->used = 1;
  719. return 0;
  720. }
  721. last = &frame->next;
  722. frame = frame->next;
  723. }
  724. frame = av_mallocz(sizeof(*frame));
  725. if (!frame)
  726. return AVERROR(ENOMEM);
  727. frame->frame = av_frame_alloc();
  728. if (!frame->frame) {
  729. av_freep(&frame);
  730. return AVERROR(ENOMEM);
  731. }
  732. frame->enc_ctrl.Payload = av_mallocz(sizeof(mfxPayload*) * QSV_MAX_ENC_PAYLOAD);
  733. if (!frame->enc_ctrl.Payload) {
  734. av_freep(&frame);
  735. return AVERROR(ENOMEM);
  736. }
  737. *last = frame;
  738. *f = frame;
  739. frame->used = 1;
  740. return 0;
  741. }
  742. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  743. QSVFrame **new_frame)
  744. {
  745. QSVFrame *qf;
  746. int ret;
  747. ret = get_free_frame(q, &qf);
  748. if (ret < 0)
  749. return ret;
  750. if (frame->format == AV_PIX_FMT_QSV) {
  751. ret = av_frame_ref(qf->frame, frame);
  752. if (ret < 0)
  753. return ret;
  754. qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
  755. if (q->frames_ctx.mids) {
  756. ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
  757. if (ret < 0)
  758. return ret;
  759. qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
  760. }
  761. } else {
  762. /* make a copy if the input is not padded as libmfx requires */
  763. if (frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) {
  764. qf->frame->height = FFALIGN(frame->height, 32);
  765. qf->frame->width = FFALIGN(frame->width, q->width_align);
  766. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  767. if (ret < 0)
  768. return ret;
  769. qf->frame->height = frame->height;
  770. qf->frame->width = frame->width;
  771. ret = av_frame_copy(qf->frame, frame);
  772. if (ret < 0) {
  773. av_frame_unref(qf->frame);
  774. return ret;
  775. }
  776. } else {
  777. ret = av_frame_ref(qf->frame, frame);
  778. if (ret < 0)
  779. return ret;
  780. }
  781. qf->surface.Info = q->param.mfx.FrameInfo;
  782. qf->surface.Info.PicStruct =
  783. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  784. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  785. MFX_PICSTRUCT_FIELD_BFF;
  786. if (frame->repeat_pict == 1)
  787. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  788. else if (frame->repeat_pict == 2)
  789. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  790. else if (frame->repeat_pict == 4)
  791. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  792. qf->surface.Data.PitchLow = qf->frame->linesize[0];
  793. qf->surface.Data.Y = qf->frame->data[0];
  794. qf->surface.Data.UV = qf->frame->data[1];
  795. }
  796. qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  797. *new_frame = qf;
  798. return 0;
  799. }
  800. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  801. {
  802. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  803. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  804. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  805. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  806. av_log(avctx, AV_LOG_WARNING,
  807. "Interlaced coding is supported"
  808. " at Main/High Profile Level 2.1-4.1\n");
  809. }
  810. }
  811. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  812. const AVFrame *frame)
  813. {
  814. AVPacket new_pkt = { 0 };
  815. mfxBitstream *bs;
  816. mfxFrameSurface1 *surf = NULL;
  817. mfxSyncPoint *sync = NULL;
  818. QSVFrame *qsv_frame = NULL;
  819. mfxEncodeCtrl* enc_ctrl = NULL;
  820. int ret;
  821. if (frame) {
  822. ret = submit_frame(q, frame, &qsv_frame);
  823. if (ret < 0) {
  824. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  825. return ret;
  826. }
  827. }
  828. if (qsv_frame) {
  829. surf = &qsv_frame->surface;
  830. enc_ctrl = &qsv_frame->enc_ctrl;
  831. }
  832. ret = av_new_packet(&new_pkt, q->packet_size);
  833. if (ret < 0) {
  834. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  835. return ret;
  836. }
  837. bs = av_mallocz(sizeof(*bs));
  838. if (!bs) {
  839. av_packet_unref(&new_pkt);
  840. return AVERROR(ENOMEM);
  841. }
  842. bs->Data = new_pkt.data;
  843. bs->MaxLength = new_pkt.size;
  844. if (q->set_encode_ctrl_cb) {
  845. q->set_encode_ctrl_cb(avctx, frame, &qsv_frame->enc_ctrl);
  846. }
  847. sync = av_mallocz(sizeof(*sync));
  848. if (!sync) {
  849. av_freep(&bs);
  850. av_packet_unref(&new_pkt);
  851. return AVERROR(ENOMEM);
  852. }
  853. do {
  854. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, bs, sync);
  855. if (ret == MFX_WRN_DEVICE_BUSY)
  856. av_usleep(500);
  857. } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
  858. if (ret > 0)
  859. ff_qsv_print_warning(avctx, ret, "Warning during encoding");
  860. if (ret < 0) {
  861. av_packet_unref(&new_pkt);
  862. av_freep(&bs);
  863. av_freep(&sync);
  864. return (ret == MFX_ERR_MORE_DATA) ?
  865. 0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
  866. }
  867. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  868. print_interlace_msg(avctx, q);
  869. if (*sync) {
  870. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  871. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  872. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  873. } else {
  874. av_freep(&sync);
  875. av_packet_unref(&new_pkt);
  876. av_freep(&bs);
  877. }
  878. return 0;
  879. }
  880. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  881. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  882. {
  883. int ret;
  884. ret = encode_frame(avctx, q, frame);
  885. if (ret < 0)
  886. return ret;
  887. if (!av_fifo_space(q->async_fifo) ||
  888. (!frame && av_fifo_size(q->async_fifo))) {
  889. AVPacket new_pkt;
  890. mfxBitstream *bs;
  891. mfxSyncPoint *sync;
  892. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  893. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  894. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  895. do {
  896. ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
  897. } while (ret == MFX_WRN_IN_EXECUTION);
  898. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  899. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  900. new_pkt.size = bs->DataLength;
  901. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  902. bs->FrameType & MFX_FRAMETYPE_xIDR)
  903. new_pkt.flags |= AV_PKT_FLAG_KEY;
  904. #if FF_API_CODED_FRAME
  905. FF_DISABLE_DEPRECATION_WARNINGS
  906. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  907. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  908. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  909. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  910. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  911. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  912. FF_ENABLE_DEPRECATION_WARNINGS
  913. #endif
  914. av_freep(&bs);
  915. av_freep(&sync);
  916. if (pkt->data) {
  917. if (pkt->size < new_pkt.size) {
  918. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  919. pkt->size, new_pkt.size);
  920. av_packet_unref(&new_pkt);
  921. return AVERROR(EINVAL);
  922. }
  923. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  924. pkt->size = new_pkt.size;
  925. ret = av_packet_copy_props(pkt, &new_pkt);
  926. av_packet_unref(&new_pkt);
  927. if (ret < 0)
  928. return ret;
  929. } else
  930. *pkt = new_pkt;
  931. *got_packet = 1;
  932. }
  933. return 0;
  934. }
  935. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  936. {
  937. QSVFrame *cur;
  938. if (q->session)
  939. MFXVideoENCODE_Close(q->session);
  940. if (q->internal_session)
  941. MFXClose(q->internal_session);
  942. q->session = NULL;
  943. q->internal_session = NULL;
  944. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  945. av_buffer_unref(&q->frames_ctx.mids_buf);
  946. cur = q->work_frames;
  947. while (cur) {
  948. q->work_frames = cur->next;
  949. av_frame_free(&cur->frame);
  950. av_free(cur->enc_ctrl.Payload);
  951. av_freep(&cur);
  952. cur = q->work_frames;
  953. }
  954. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  955. AVPacket pkt;
  956. mfxSyncPoint *sync;
  957. mfxBitstream *bs;
  958. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  959. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  960. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  961. av_freep(&sync);
  962. av_freep(&bs);
  963. av_packet_unref(&pkt);
  964. }
  965. av_fifo_free(q->async_fifo);
  966. q->async_fifo = NULL;
  967. av_freep(&q->opaque_surfaces);
  968. av_buffer_unref(&q->opaque_alloc_buf);
  969. av_freep(&q->extparam);
  970. return 0;
  971. }