]> git.sesse.net Git - ffmpeg/blobdiff - libavcodec/qsvenc.c
qsvdec: only access hwaccel_context is the pixel format is QSV
[ffmpeg] / libavcodec / qsvenc.c
index 7e5c11e6f770e23d7b2f671f3cfda871f4058a16..ba07db6e99122d780b1ec8c77dd34ff42b21f76f 100644 (file)
@@ -26,6 +26,8 @@
 #include <mfx/mfxvideo.h>
 
 #include "libavutil/common.h"
+#include "libavutil/hwcontext.h"
+#include "libavutil/hwcontext_qsv.h"
 #include "libavutil/mem.h"
 #include "libavutil/log.h"
 #include "libavutil/time.h"
@@ -203,7 +205,7 @@ static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
            print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
 
     av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %"PRIu16"; ", co2->MaxFrameSize);
-#if QSV_VERSION_ATLEAST(1, 9)
+#if QSV_HAVE_MAX_SLICE_SIZE
     av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %"PRIu16"; ", co2->MaxSliceSize);
 #endif
     av_log(avctx, AV_LOG_VERBOSE, "\n");
@@ -266,10 +268,96 @@ static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
     }
 }
 
-static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
+static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
+{
+    const char *rc_desc;
+    mfxU16      rc_mode;
+
+    int want_la     = q->la_depth >= 0;
+    int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
+    int want_vcm    = q->vcm;
+
+    if (want_la && !QSV_HAVE_LA) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
+        return AVERROR(ENOSYS);
+    }
+    if (want_vcm && !QSV_HAVE_VCM) {
+        av_log(avctx, AV_LOG_ERROR,
+               "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
+        return AVERROR(ENOSYS);
+    }
+
+    if (want_la + want_qscale + want_vcm > 1) {
+        av_log(avctx, AV_LOG_ERROR,
+               "More than one of: { constant qscale, lookahead, VCM } requested, "
+               "only one of them can be used at a time.\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (want_qscale) {
+        rc_mode = MFX_RATECONTROL_CQP;
+        rc_desc = "constant quantization parameter (CQP)";
+    }
+#if QSV_HAVE_VCM
+    else if (want_vcm) {
+        rc_mode = MFX_RATECONTROL_VCM;
+        rc_desc = "video conferencing mode (VCM)";
+    }
+#endif
+#if QSV_HAVE_LA
+    else if (want_la) {
+        rc_mode = MFX_RATECONTROL_LA;
+        rc_desc = "VBR with lookahead (LA)";
+
+#if QSV_HAVE_ICQ
+        if (avctx->global_quality > 0) {
+            rc_mode = MFX_RATECONTROL_LA_ICQ;
+            rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
+        }
+#endif
+    }
+#endif
+#if QSV_HAVE_ICQ
+    else if (avctx->global_quality > 0) {
+        rc_mode = MFX_RATECONTROL_ICQ;
+        rc_desc = "intelligent constant quality (ICQ)";
+    }
+#endif
+    else if (avctx->rc_max_rate == avctx->bit_rate) {
+        rc_mode = MFX_RATECONTROL_CBR;
+        rc_desc = "constant bitrate (CBR)";
+    } else if (!avctx->rc_max_rate) {
+        rc_mode = MFX_RATECONTROL_AVBR;
+        rc_desc = "average variable bitrate (AVBR)";
+    } else {
+        rc_mode = MFX_RATECONTROL_VBR;
+        rc_desc = "variable bitrate (VBR)";
+    }
+
+    q->param.mfx.RateControlMethod = rc_mode;
+    av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
+
+    return 0;
+}
+
+static int rc_supported(QSVEncContext *q)
 {
-    const char *ratecontrol_desc;
+    mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
+    mfxStatus ret;
+
+    ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
+    if (ret < 0 ||
+        param_out.mfx.RateControlMethod != q->param.mfx.RateControlMethod)
+        return 0;
+    return 1;
+}
 
+static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
+{
+    enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
+                                   avctx->sw_pix_fmt : avctx->pix_fmt;
+    const AVPixFmtDescriptor *desc;
     float quant;
     int ret;
 
@@ -295,7 +383,12 @@ static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
     q->param.mfx.EncodedOrder       = 0;
     q->param.mfx.BufferSizeInKB     = 0;
 
-    q->param.mfx.FrameInfo.FourCC         = MFX_FOURCC_NV12;
+    desc = av_pix_fmt_desc_get(sw_format);
+    if (!desc)
+        return AVERROR_BUG;
+
+    ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
+
     q->param.mfx.FrameInfo.Width          = FFALIGN(avctx->width, q->width_align);
     q->param.mfx.FrameInfo.Height         = FFALIGN(avctx->height, 32);
     q->param.mfx.FrameInfo.CropX          = 0;
@@ -306,8 +399,16 @@ static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
     q->param.mfx.FrameInfo.AspectRatioH   = avctx->sample_aspect_ratio.den;
     q->param.mfx.FrameInfo.PicStruct      = MFX_PICSTRUCT_PROGRESSIVE;
     q->param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
-    q->param.mfx.FrameInfo.BitDepthLuma   = 8;
-    q->param.mfx.FrameInfo.BitDepthChroma = 8;
+    q->param.mfx.FrameInfo.BitDepthLuma   = desc->comp[0].depth;
+    q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
+    q->param.mfx.FrameInfo.Shift          = desc->comp[0].depth > 8;
+
+    if (avctx->hw_frames_ctx) {
+        AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
+        AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
+        q->param.mfx.FrameInfo.Width  = frames_hwctx->surfaces[0].Info.Width;
+        q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
+    }
 
     if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
         q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
@@ -317,25 +418,16 @@ static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
         q->param.mfx.FrameInfo.FrameRateExtD  = avctx->time_base.num;
     }
 
-    if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
-        q->param.mfx.RateControlMethod = MFX_RATECONTROL_CQP;
-        ratecontrol_desc = "constant quantization parameter (CQP)";
-    } else if (avctx->rc_max_rate == avctx->bit_rate) {
-        q->param.mfx.RateControlMethod = MFX_RATECONTROL_CBR;
-        ratecontrol_desc = "constant bitrate (CBR)";
-    } else if (!avctx->rc_max_rate) {
-        q->param.mfx.RateControlMethod = MFX_RATECONTROL_AVBR;
-        ratecontrol_desc = "average variable bitrate (AVBR)";
-    } else {
-        q->param.mfx.RateControlMethod = MFX_RATECONTROL_VBR;
-        ratecontrol_desc = "variable bitrate (VBR)";
-    }
-
-    av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", ratecontrol_desc);
+    ret = select_rc_mode(avctx, q);
+    if (ret < 0)
+        return ret;
 
     switch (q->param.mfx.RateControlMethod) {
     case MFX_RATECONTROL_CBR:
     case MFX_RATECONTROL_VBR:
+#if QSV_HAVE_VCM
+    case MFX_RATECONTROL_VCM:
+#endif
         q->param.mfx.InitialDelayInKB = avctx->rc_initial_buffer_occupancy / 1000;
         q->param.mfx.TargetKbps       = avctx->bit_rate / 1000;
         q->param.mfx.MaxKbps          = avctx->rc_max_rate / 1000;
@@ -353,6 +445,19 @@ static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
         q->param.mfx.Convergence = q->avbr_convergence;
         q->param.mfx.Accuracy    = q->avbr_accuracy;
         break;
+#if QSV_HAVE_LA
+    case MFX_RATECONTROL_LA:
+        q->param.mfx.TargetKbps  = avctx->bit_rate / 1000;
+        q->extco2.LookAheadDepth = q->la_depth;
+        break;
+#if QSV_HAVE_ICQ
+    case MFX_RATECONTROL_LA_ICQ:
+        q->extco2.LookAheadDepth = q->la_depth;
+    case MFX_RATECONTROL_ICQ:
+        q->param.mfx.ICQQuality  = avctx->global_quality;
+        break;
+#endif
+#endif
     }
 
     // the HEVC encoder plugin currently fails if coding options
@@ -360,10 +465,87 @@ static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
     if (avctx->codec_id != AV_CODEC_ID_HEVC) {
         q->extco.Header.BufferId      = MFX_EXTBUFF_CODING_OPTION;
         q->extco.Header.BufferSz      = sizeof(q->extco);
-        q->extco.CAVLC                = avctx->coder_type == FF_CODER_TYPE_VLC ?
-                                        MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
+#if FF_API_CODER_TYPE
+FF_DISABLE_DEPRECATION_WARNINGS
+        if (avctx->coder_type != 0)
+            q->cavlc = avctx->coder_type == FF_CODER_TYPE_VLC;
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+        q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
+                                  : MFX_CODINGOPTION_UNKNOWN;
+
+        if (q->rdo >= 0)
+            q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+
+        if (avctx->codec_id == AV_CODEC_ID_H264) {
+            if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
+                q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
+                                             MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+
+            if (q->single_sei_nal_unit >= 0)
+                q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+            if (q->recovery_point_sei >= 0)
+                q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+            q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
+        }
 
         q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
+
+#if QSV_HAVE_CO2
+        if (avctx->codec_id == AV_CODEC_ID_H264) {
+            q->extco2.Header.BufferId     = MFX_EXTBUFF_CODING_OPTION2;
+            q->extco2.Header.BufferSz     = sizeof(q->extco2);
+
+            if (q->int_ref_type >= 0)
+                q->extco2.IntRefType = q->int_ref_type;
+            if (q->int_ref_cycle_size >= 0)
+                q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
+            if (q->int_ref_qp_delta != INT16_MIN)
+                q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
+
+            if (q->bitrate_limit >= 0)
+                q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+            if (q->mbbrc >= 0)
+                q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+            if (q->extbrc >= 0)
+                q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+
+            if (q->max_frame_size >= 0)
+                q->extco2.MaxFrameSize = q->max_frame_size;
+#if QSV_HAVE_MAX_SLICE_SIZE
+            if (q->max_slice_size >= 0)
+                q->extco2.MaxSliceSize = q->max_slice_size;
+#endif
+
+#if QSV_HAVE_TRELLIS
+            q->extco2.Trellis = q->trellis;
+#endif
+
+#if QSV_HAVE_BREF_TYPE
+#if FF_API_PRIVATE_OPT
+FF_DISABLE_DEPRECATION_WARNINGS
+            if (avctx->b_frame_strategy >= 0)
+                q->b_strategy = avctx->b_frame_strategy;
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+            if (q->b_strategy >= 0)
+                q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
+            if (q->adaptive_i >= 0)
+                q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+            if (q->adaptive_b >= 0)
+                q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
+#endif
+
+            q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
+        }
+#endif
+    }
+
+    if (!rc_supported(q)) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Selected ratecontrol mode is not supported by the QSV "
+               "runtime. Choose a different mode.\n");
+        return AVERROR(ENOSYS);
     }
 
     return 0;
@@ -371,6 +553,8 @@ static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
 
 static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
 {
+    AVCPBProperties *cpb_props;
+
     uint8_t sps_buf[128];
     uint8_t pps_buf[128];
 
@@ -417,7 +601,8 @@ static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
 
     ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
     if (ret < 0)
-        return ff_qsv_error(ret);
+        return ff_qsv_print_error(avctx, ret,
+                                  "Error calling GetVideoParam");
 
     q->packet_size = q->param.mfx.BufferSizeInKB * 1000;
 
@@ -437,6 +622,14 @@ static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
     avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
     memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
 
+    cpb_props = ff_add_cpb_side_data(avctx);
+    if (!cpb_props)
+        return AVERROR(ENOMEM);
+    cpb_props->max_bitrate = avctx->rc_max_rate;
+    cpb_props->min_bitrate = avctx->rc_min_rate;
+    cpb_props->avg_bitrate = avctx->bit_rate;
+    cpb_props->buffer_size = avctx->rc_buffer_size;
+
     dump_video_param(avctx, q, ext_buffers + 1);
 
     return 0;
@@ -479,46 +672,88 @@ static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
     return 0;
 }
 
+static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
+{
+    int ret;
+
+    if (avctx->hwaccel_context) {
+        AVQSVContext *qsv = avctx->hwaccel_context;
+        q->session = qsv->session;
+    } else if (avctx->hw_frames_ctx) {
+        q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
+        if (!q->frames_ctx.hw_frames_ctx)
+            return AVERROR(ENOMEM);
+
+        ret = ff_qsv_init_session_hwcontext(avctx, &q->internal_session,
+                                            &q->frames_ctx, q->load_plugins,
+                                            q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY);
+        if (ret < 0) {
+            av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
+            return ret;
+        }
+
+        q->session = q->internal_session;
+    } else {
+        ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
+                                           q->load_plugins);
+        if (ret < 0)
+            return ret;
+
+        q->session = q->internal_session;
+    }
+
+    return 0;
+}
+
 int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
 {
+    int iopattern = 0;
     int opaque_alloc = 0;
     int ret;
 
-    q->param.IOPattern  = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
     q->param.AsyncDepth = q->async_depth;
 
     q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
-                                  (sizeof(AVPacket) + sizeof(mfxSyncPoint) + sizeof(mfxBitstream*)));
+                                  (sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*)));
     if (!q->async_fifo)
         return AVERROR(ENOMEM);
 
     if (avctx->hwaccel_context) {
         AVQSVContext *qsv = avctx->hwaccel_context;
 
-        q->session         = qsv->session;
-        q->param.IOPattern = qsv->iopattern;
-
+        iopattern    = qsv->iopattern;
         opaque_alloc = qsv->opaque_alloc;
     }
 
-    if (!q->session) {
-        ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
-                                           q->load_plugins);
-        if (ret < 0)
-            return ret;
+    if (avctx->hw_frames_ctx) {
+        AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
+        AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
 
-        q->session = q->internal_session;
+        if (!iopattern) {
+            if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
+                iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
+            else if (frames_hwctx->frame_type &
+                     (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
+                iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
+        }
     }
 
+    if (!iopattern)
+        iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
+    q->param.IOPattern = iopattern;
+
+    ret = qsvenc_init_session(avctx, q);
+    if (ret < 0)
+        return ret;
+
     ret = init_video_param(avctx, q);
     if (ret < 0)
         return ret;
 
     ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
-    if (ret < 0) {
-        av_log(avctx, AV_LOG_ERROR, "Error querying the encoding parameters\n");
-        return ff_qsv_error(ret);
-    }
+    if (ret < 0)
+        return ff_qsv_print_error(avctx, ret,
+                                  "Error querying the encoding parameters");
 
     if (opaque_alloc) {
         ret = qsv_init_opaque_alloc(avctx, q);
@@ -556,10 +791,12 @@ int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
     }
 
     ret = MFXVideoENCODE_Init(q->session, &q->param);
-    if (ret < 0) {
-        av_log(avctx, AV_LOG_ERROR, "Error initializing the encoder\n");
-        return ff_qsv_error(ret);
-    }
+    if (ret < 0)
+        return ff_qsv_print_error(avctx, ret,
+                                  "Error initializing the encoder");
+    else if (ret > 0)
+        ff_qsv_print_warning(avctx, ret,
+                             "Warning in encoder initialization");
 
     ret = qsv_retrieve_enc_params(avctx, q);
     if (ret < 0) {
@@ -695,14 +932,14 @@ static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
     }
 }
 
-int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
-                  AVPacket *pkt, const AVFrame *frame, int *got_packet)
+static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
+                        const AVFrame *frame)
 {
     AVPacket new_pkt = { 0 };
     mfxBitstream *bs;
 
     mfxFrameSurface1 *surf = NULL;
-    mfxSyncPoint sync      = NULL;
+    mfxSyncPoint *sync     = NULL;
     int ret;
 
     if (frame) {
@@ -727,37 +964,68 @@ int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
     bs->Data      = new_pkt.data;
     bs->MaxLength = new_pkt.size;
 
+    sync = av_mallocz(sizeof(*sync));
+    if (!sync) {
+        av_freep(&bs);
+        av_packet_unref(&new_pkt);
+        return AVERROR(ENOMEM);
+    }
+
     do {
-        ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, &sync);
+        ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, sync);
         if (ret == MFX_WRN_DEVICE_BUSY)
             av_usleep(1);
-    } while (ret > 0);
+    } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
+
+    if (ret > 0)
+        ff_qsv_print_warning(avctx, ret, "Warning during encoding");
 
     if (ret < 0) {
         av_packet_unref(&new_pkt);
         av_freep(&bs);
-        return (ret == MFX_ERR_MORE_DATA) ? 0 : ff_qsv_error(ret);
+        av_freep(&sync);
+        return (ret == MFX_ERR_MORE_DATA) ?
+               0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
     }
 
     if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
         print_interlace_msg(avctx, q);
 
-    if (sync) {
+    if (*sync) {
         av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
         av_fifo_generic_write(q->async_fifo, &sync,    sizeof(sync),    NULL);
         av_fifo_generic_write(q->async_fifo, &bs,      sizeof(bs),    NULL);
     } else {
+        av_freep(&sync);
         av_packet_unref(&new_pkt);
         av_freep(&bs);
     }
 
+    return 0;
+}
+
+int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
+                  AVPacket *pkt, const AVFrame *frame, int *got_packet)
+{
+    int ret;
+
+    ret = encode_frame(avctx, q, frame);
+    if (ret < 0)
+        return ret;
+
     if (!av_fifo_space(q->async_fifo) ||
         (!frame && av_fifo_size(q->async_fifo))) {
+        AVPacket new_pkt;
+        mfxBitstream *bs;
+        mfxSyncPoint *sync;
+
         av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
         av_fifo_generic_read(q->async_fifo, &sync,    sizeof(sync),    NULL);
         av_fifo_generic_read(q->async_fifo, &bs,      sizeof(bs),      NULL);
 
-        MFXVideoCORE_SyncOperation(q->session, sync, 60000);
+        do {
+            ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
+        } while (ret == MFX_WRN_IN_EXECUTION);
 
         new_pkt.dts  = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
         new_pkt.pts  = av_rescale_q(bs->TimeStamp,       (AVRational){1, 90000}, avctx->time_base);
@@ -779,6 +1047,7 @@ FF_ENABLE_DEPRECATION_WARNINGS
 #endif
 
         av_freep(&bs);
+        av_freep(&sync);
 
         if (pkt->data) {
             if (pkt->size < new_pkt.size) {
@@ -815,6 +1084,10 @@ int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
     q->session          = NULL;
     q->internal_session = NULL;
 
+    av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
+    av_freep(&q->frames_ctx.mids);
+    q->frames_ctx.nb_mids = 0;
+
     cur = q->work_frames;
     while (cur) {
         q->work_frames = cur->next;
@@ -825,13 +1098,14 @@ int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
 
     while (q->async_fifo && av_fifo_size(q->async_fifo)) {
         AVPacket pkt;
-        mfxSyncPoint sync;
+        mfxSyncPoint *sync;
         mfxBitstream *bs;
 
         av_fifo_generic_read(q->async_fifo, &pkt,  sizeof(pkt),  NULL);
         av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
         av_fifo_generic_read(q->async_fifo, &bs,   sizeof(bs),   NULL);
 
+        av_freep(&sync);
         av_freep(&bs);
         av_packet_unref(&pkt);
     }