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.

516 lines
17KB

  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 Libav.
  8. *
  9. * Libav 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. * Libav 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 Libav; 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 int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  37. {
  38. const char *ratecontrol_desc;
  39. float quant;
  40. int ret;
  41. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  42. if (ret < 0)
  43. return AVERROR_BUG;
  44. q->param.mfx.CodecId = ret;
  45. q->width_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
  46. if (avctx->level > 0)
  47. q->param.mfx.CodecLevel = avctx->level;
  48. q->param.mfx.CodecProfile = q->profile;
  49. q->param.mfx.TargetUsage = q->preset;
  50. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  51. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  52. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  53. MFX_GOP_CLOSED : 0;
  54. q->param.mfx.IdrInterval = q->idr_interval;
  55. q->param.mfx.NumSlice = avctx->slices;
  56. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  57. q->param.mfx.EncodedOrder = 0;
  58. q->param.mfx.BufferSizeInKB = 0;
  59. q->param.mfx.FrameInfo.FourCC = MFX_FOURCC_NV12;
  60. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  61. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 32);
  62. q->param.mfx.FrameInfo.CropX = 0;
  63. q->param.mfx.FrameInfo.CropY = 0;
  64. q->param.mfx.FrameInfo.CropW = avctx->width;
  65. q->param.mfx.FrameInfo.CropH = avctx->height;
  66. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  67. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  68. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  69. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
  70. q->param.mfx.FrameInfo.BitDepthLuma = 8;
  71. q->param.mfx.FrameInfo.BitDepthChroma = 8;
  72. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  73. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  74. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  75. } else {
  76. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  77. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  78. }
  79. if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
  80. q->param.mfx.RateControlMethod = MFX_RATECONTROL_CQP;
  81. ratecontrol_desc = "constant quantization parameter (CQP)";
  82. } else if (avctx->rc_max_rate == avctx->bit_rate) {
  83. q->param.mfx.RateControlMethod = MFX_RATECONTROL_CBR;
  84. ratecontrol_desc = "constant bitrate (CBR)";
  85. } else if (!avctx->rc_max_rate) {
  86. q->param.mfx.RateControlMethod = MFX_RATECONTROL_AVBR;
  87. ratecontrol_desc = "average variable bitrate (AVBR)";
  88. } else {
  89. q->param.mfx.RateControlMethod = MFX_RATECONTROL_VBR;
  90. ratecontrol_desc = "variable bitrate (VBR)";
  91. }
  92. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", ratecontrol_desc);
  93. switch (q->param.mfx.RateControlMethod) {
  94. case MFX_RATECONTROL_CBR:
  95. case MFX_RATECONTROL_VBR:
  96. q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
  97. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  98. q->param.mfx.MaxKbps = avctx->bit_rate / 1000;
  99. break;
  100. case MFX_RATECONTROL_CQP:
  101. quant = avctx->global_quality / FF_QP2LAMBDA;
  102. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  103. q->param.mfx.QPP = av_clip(quant, 0, 51);
  104. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  105. break;
  106. case MFX_RATECONTROL_AVBR:
  107. q->param.mfx.TargetKbps = avctx->bit_rate / 1000;
  108. q->param.mfx.Convergence = q->avbr_convergence;
  109. q->param.mfx.Accuracy = q->avbr_accuracy;
  110. break;
  111. }
  112. // the HEVC encoder plugin currently fails if coding options
  113. // are provided
  114. if (avctx->codec_id != AV_CODEC_ID_HEVC) {
  115. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  116. q->extco.Header.BufferSz = sizeof(q->extco);
  117. q->extco.CAVLC = avctx->coder_type == FF_CODER_TYPE_VLC ?
  118. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  119. q->extparam[0] = (mfxExtBuffer *)&q->extco;
  120. q->param.ExtParam = q->extparam;
  121. q->param.NumExtParam = FF_ARRAY_ELEMS(q->extparam);
  122. }
  123. return 0;
  124. }
  125. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  126. {
  127. uint8_t sps_buf[128];
  128. uint8_t pps_buf[128];
  129. mfxExtCodingOptionSPSPPS extradata = {
  130. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  131. .Header.BufferSz = sizeof(extradata),
  132. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  133. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  134. };
  135. mfxExtBuffer *ext_buffers[] = {
  136. (mfxExtBuffer*)&extradata,
  137. };
  138. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  139. int ret;
  140. q->param.ExtParam = ext_buffers;
  141. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  142. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  143. if (ret < 0)
  144. return ff_qsv_error(ret);
  145. q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
  146. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
  147. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  148. return AVERROR_UNKNOWN;
  149. }
  150. avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
  151. FF_INPUT_BUFFER_PADDING_SIZE);
  152. if (!avctx->extradata)
  153. return AVERROR(ENOMEM);
  154. memcpy(avctx->extradata, sps_buf, extradata.SPSBufSize);
  155. if (need_pps)
  156. memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
  157. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  158. memset(avctx->extradata + avctx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  159. return 0;
  160. }
  161. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  162. {
  163. int ret;
  164. q->param.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  165. q->param.AsyncDepth = q->async_depth;
  166. q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
  167. (sizeof(AVPacket) + sizeof(mfxSyncPoint) + sizeof(mfxBitstream*)));
  168. if (!q->async_fifo)
  169. return AVERROR(ENOMEM);
  170. if (avctx->hwaccel_context) {
  171. AVQSVContext *qsv = avctx->hwaccel_context;
  172. q->session = qsv->session;
  173. q->param.IOPattern = qsv->iopattern;
  174. }
  175. if (!q->session) {
  176. ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
  177. q->load_plugins);
  178. if (ret < 0)
  179. return ret;
  180. q->session = q->internal_session;
  181. }
  182. ret = init_video_param(avctx, q);
  183. if (ret < 0)
  184. return ret;
  185. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  186. if (ret < 0) {
  187. av_log(avctx, AV_LOG_ERROR, "Error querying the encoding parameters\n");
  188. return ff_qsv_error(ret);
  189. }
  190. ret = MFXVideoENCODE_Init(q->session, &q->param);
  191. if (ret < 0) {
  192. av_log(avctx, AV_LOG_ERROR, "Error initializing the encoder\n");
  193. return ff_qsv_error(ret);
  194. }
  195. ret = qsv_retrieve_enc_params(avctx, q);
  196. if (ret < 0) {
  197. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  198. return ret;
  199. }
  200. q->avctx = avctx;
  201. return 0;
  202. }
  203. static void clear_unused_frames(QSVEncContext *q)
  204. {
  205. QSVFrame *cur = q->work_frames;
  206. while (cur) {
  207. if (cur->surface && !cur->surface->Data.Locked) {
  208. cur->surface = NULL;
  209. av_frame_unref(cur->frame);
  210. }
  211. cur = cur->next;
  212. }
  213. }
  214. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  215. {
  216. QSVFrame *frame, **last;
  217. clear_unused_frames(q);
  218. frame = q->work_frames;
  219. last = &q->work_frames;
  220. while (frame) {
  221. if (!frame->surface) {
  222. *f = frame;
  223. return 0;
  224. }
  225. last = &frame->next;
  226. frame = frame->next;
  227. }
  228. frame = av_mallocz(sizeof(*frame));
  229. if (!frame)
  230. return AVERROR(ENOMEM);
  231. frame->frame = av_frame_alloc();
  232. if (!frame->frame) {
  233. av_freep(&frame);
  234. return AVERROR(ENOMEM);
  235. }
  236. *last = frame;
  237. *f = frame;
  238. return 0;
  239. }
  240. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  241. mfxFrameSurface1 **surface)
  242. {
  243. QSVFrame *qf;
  244. int ret;
  245. ret = get_free_frame(q, &qf);
  246. if (ret < 0)
  247. return ret;
  248. if (frame->format == AV_PIX_FMT_QSV) {
  249. ret = av_frame_ref(qf->frame, frame);
  250. if (ret < 0)
  251. return ret;
  252. qf->surface = (mfxFrameSurface1*)qf->frame->data[3];
  253. *surface = qf->surface;
  254. return 0;
  255. }
  256. /* make a copy if the input is not padded as libmfx requires */
  257. if (frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) {
  258. qf->frame->height = FFALIGN(frame->height, 32);
  259. qf->frame->width = FFALIGN(frame->width, q->width_align);
  260. ret = ff_get_buffer(q->avctx, qf->frame, AV_GET_BUFFER_FLAG_REF);
  261. if (ret < 0)
  262. return ret;
  263. qf->frame->height = frame->height;
  264. qf->frame->width = frame->width;
  265. ret = av_frame_copy(qf->frame, frame);
  266. if (ret < 0) {
  267. av_frame_unref(qf->frame);
  268. return ret;
  269. }
  270. } else {
  271. ret = av_frame_ref(qf->frame, frame);
  272. if (ret < 0)
  273. return ret;
  274. }
  275. qf->surface_internal.Info = q->param.mfx.FrameInfo;
  276. qf->surface_internal.Info.PicStruct =
  277. !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
  278. frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
  279. MFX_PICSTRUCT_FIELD_BFF;
  280. if (frame->repeat_pict == 1)
  281. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  282. else if (frame->repeat_pict == 2)
  283. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  284. else if (frame->repeat_pict == 4)
  285. qf->surface_internal.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  286. qf->surface_internal.Data.PitchLow = qf->frame->linesize[0];
  287. qf->surface_internal.Data.Y = qf->frame->data[0];
  288. qf->surface_internal.Data.UV = qf->frame->data[1];
  289. qf->surface_internal.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  290. qf->surface = &qf->surface_internal;
  291. *surface = qf->surface;
  292. return 0;
  293. }
  294. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  295. {
  296. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  297. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  298. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  299. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  300. av_log(avctx, AV_LOG_WARNING,
  301. "Interlaced coding is supported"
  302. " at Main/High Profile Level 2.1-4.1\n");
  303. }
  304. }
  305. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  306. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  307. {
  308. AVPacket new_pkt = { 0 };
  309. mfxBitstream *bs;
  310. mfxFrameSurface1 *surf = NULL;
  311. mfxSyncPoint sync = NULL;
  312. int ret;
  313. if (frame) {
  314. ret = submit_frame(q, frame, &surf);
  315. if (ret < 0) {
  316. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  317. return ret;
  318. }
  319. }
  320. ret = av_new_packet(&new_pkt, q->packet_size);
  321. if (ret < 0) {
  322. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  323. return ret;
  324. }
  325. bs = av_mallocz(sizeof(*bs));
  326. if (!bs) {
  327. av_packet_unref(&new_pkt);
  328. return AVERROR(ENOMEM);
  329. }
  330. bs->Data = new_pkt.data;
  331. bs->MaxLength = new_pkt.size;
  332. do {
  333. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, &sync);
  334. if (ret == MFX_WRN_DEVICE_BUSY)
  335. av_usleep(1);
  336. } while (ret > 0);
  337. if (ret < 0) {
  338. av_packet_unref(&new_pkt);
  339. av_freep(&bs);
  340. return (ret == MFX_ERR_MORE_DATA) ? 0 : ff_qsv_error(ret);
  341. }
  342. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
  343. print_interlace_msg(avctx, q);
  344. if (sync) {
  345. av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  346. av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
  347. av_fifo_generic_write(q->async_fifo, &bs, sizeof(bs), NULL);
  348. } else {
  349. av_packet_unref(&new_pkt);
  350. av_freep(&bs);
  351. }
  352. if (!av_fifo_space(q->async_fifo) ||
  353. (!frame && av_fifo_size(q->async_fifo))) {
  354. av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
  355. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  356. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  357. MFXVideoCORE_SyncOperation(q->session, sync, 60000);
  358. new_pkt.dts = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  359. new_pkt.pts = av_rescale_q(bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  360. new_pkt.size = bs->DataLength;
  361. if (bs->FrameType & MFX_FRAMETYPE_IDR ||
  362. bs->FrameType & MFX_FRAMETYPE_xIDR)
  363. new_pkt.flags |= AV_PKT_FLAG_KEY;
  364. #if FF_API_CODED_FRAME
  365. FF_DISABLE_DEPRECATION_WARNINGS
  366. if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
  367. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  368. else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
  369. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  370. else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
  371. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  372. FF_ENABLE_DEPRECATION_WARNINGS
  373. #endif
  374. av_freep(&bs);
  375. if (pkt->data) {
  376. if (pkt->size < new_pkt.size) {
  377. av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
  378. pkt->size, new_pkt.size);
  379. av_packet_unref(&new_pkt);
  380. return AVERROR(EINVAL);
  381. }
  382. memcpy(pkt->data, new_pkt.data, new_pkt.size);
  383. pkt->size = new_pkt.size;
  384. ret = av_packet_copy_props(pkt, &new_pkt);
  385. av_packet_unref(&new_pkt);
  386. if (ret < 0)
  387. return ret;
  388. } else
  389. *pkt = new_pkt;
  390. *got_packet = 1;
  391. }
  392. return 0;
  393. }
  394. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  395. {
  396. QSVFrame *cur;
  397. MFXVideoENCODE_Close(q->session);
  398. if (q->internal_session)
  399. MFXClose(q->internal_session);
  400. q->session = NULL;
  401. q->internal_session = NULL;
  402. cur = q->work_frames;
  403. while (cur) {
  404. q->work_frames = cur->next;
  405. av_frame_free(&cur->frame);
  406. av_freep(&cur);
  407. cur = q->work_frames;
  408. }
  409. while (q->async_fifo && av_fifo_size(q->async_fifo)) {
  410. AVPacket pkt;
  411. mfxSyncPoint sync;
  412. mfxBitstream *bs;
  413. av_fifo_generic_read(q->async_fifo, &pkt, sizeof(pkt), NULL);
  414. av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
  415. av_fifo_generic_read(q->async_fifo, &bs, sizeof(bs), NULL);
  416. av_freep(&bs);
  417. av_packet_unref(&pkt);
  418. }
  419. av_fifo_free(q->async_fifo);
  420. q->async_fifo = NULL;
  421. return 0;
  422. }