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