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.

445 lines
14KB

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