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