]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsvenc.c
lavc/qsvenc: set BRCParamMultiplier to aviod BRC overflow
[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 FFmpeg.
8  *
9  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/hwcontext.h"
30 #include "libavutil/hwcontext_qsv.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/log.h"
33 #include "libavutil/time.h"
34 #include "libavutil/imgutils.h"
35 #include "libavcodec/bytestream.h"
36
37 #include "avcodec.h"
38 #include "internal.h"
39 #include "qsv.h"
40 #include "qsv_internal.h"
41 #include "qsvenc.h"
42
43 static const struct {
44     mfxU16 profile;
45     const char *name;
46 } profile_names[] = {
47     { MFX_PROFILE_AVC_BASELINE,                 "baseline"              },
48     { MFX_PROFILE_AVC_MAIN,                     "main"                  },
49     { MFX_PROFILE_AVC_EXTENDED,                 "extended"              },
50     { MFX_PROFILE_AVC_HIGH,                     "high"                  },
51 #if QSV_VERSION_ATLEAST(1, 15)
52     { MFX_PROFILE_AVC_HIGH_422,                 "high 422"              },
53 #endif
54 #if QSV_VERSION_ATLEAST(1, 4)
55     { MFX_PROFILE_AVC_CONSTRAINED_BASELINE,     "constrained baseline"  },
56     { MFX_PROFILE_AVC_CONSTRAINED_HIGH,         "constrained high"      },
57     { MFX_PROFILE_AVC_PROGRESSIVE_HIGH,         "progressive high"      },
58 #endif
59     { MFX_PROFILE_MPEG2_SIMPLE,                 "simple"                },
60     { MFX_PROFILE_MPEG2_MAIN,                   "main"                  },
61     { MFX_PROFILE_MPEG2_HIGH,                   "high"                  },
62     { MFX_PROFILE_VC1_SIMPLE,                   "simple"                },
63     { MFX_PROFILE_VC1_MAIN,                     "main"                  },
64     { MFX_PROFILE_VC1_ADVANCED,                 "advanced"              },
65 #if QSV_VERSION_ATLEAST(1, 8)
66     { MFX_PROFILE_HEVC_MAIN,                    "main"                  },
67     { MFX_PROFILE_HEVC_MAIN10,                  "main10"                },
68     { MFX_PROFILE_HEVC_MAINSP,                  "mainsp"                },
69 #endif
70 };
71
72 static const char *print_profile(mfxU16 profile)
73 {
74     int i;
75     for (i = 0; i < FF_ARRAY_ELEMS(profile_names); i++)
76         if (profile == profile_names[i].profile)
77             return profile_names[i].name;
78     return "unknown";
79 }
80
81 static const struct {
82     mfxU16      rc_mode;
83     const char *name;
84 } rc_names[] = {
85     { MFX_RATECONTROL_CBR,     "CBR" },
86     { MFX_RATECONTROL_VBR,     "VBR" },
87     { MFX_RATECONTROL_CQP,     "CQP" },
88 #if QSV_HAVE_AVBR
89     { MFX_RATECONTROL_AVBR,    "AVBR" },
90 #endif
91 #if QSV_HAVE_LA
92     { MFX_RATECONTROL_LA,      "LA" },
93 #endif
94 #if QSV_HAVE_ICQ
95     { MFX_RATECONTROL_ICQ,     "ICQ" },
96     { MFX_RATECONTROL_LA_ICQ,  "LA_ICQ" },
97 #endif
98 #if QSV_HAVE_VCM
99     { MFX_RATECONTROL_VCM,     "VCM" },
100 #endif
101 #if QSV_VERSION_ATLEAST(1, 10)
102     { MFX_RATECONTROL_LA_EXT,  "LA_EXT" },
103 #endif
104 #if QSV_HAVE_LA_HRD
105     { MFX_RATECONTROL_LA_HRD,  "LA_HRD" },
106 #endif
107 #if QSV_HAVE_QVBR
108     { MFX_RATECONTROL_QVBR,    "QVBR" },
109 #endif
110 };
111
112 static const char *print_ratecontrol(mfxU16 rc_mode)
113 {
114     int i;
115     for (i = 0; i < FF_ARRAY_ELEMS(rc_names); i++)
116         if (rc_mode == rc_names[i].rc_mode)
117             return rc_names[i].name;
118     return "unknown";
119 }
120
121 static const char *print_threestate(mfxU16 val)
122 {
123     if (val == MFX_CODINGOPTION_ON)
124         return "ON";
125     else if (val == MFX_CODINGOPTION_OFF)
126         return "OFF";
127     return "unknown";
128 }
129
130 static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
131                              mfxExtBuffer **coding_opts)
132 {
133     mfxInfoMFX *info = &q->param.mfx;
134
135     mfxExtCodingOption   *co = (mfxExtCodingOption*)coding_opts[0];
136 #if QSV_HAVE_CO2
137     mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[1];
138 #endif
139
140     av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
141            print_profile(info->CodecProfile), info->CodecLevel);
142
143     av_log(avctx, AV_LOG_VERBOSE, "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag: ",
144            info->GopPicSize, info->GopRefDist);
145     if (info->GopOptFlag & MFX_GOP_CLOSED)
146         av_log(avctx, AV_LOG_VERBOSE, "closed ");
147     if (info->GopOptFlag & MFX_GOP_STRICT)
148         av_log(avctx, AV_LOG_VERBOSE, "strict ");
149     av_log(avctx, AV_LOG_VERBOSE, "; IdrInterval: %"PRIu16"\n", info->IdrInterval);
150
151     av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
152            info->TargetUsage, print_ratecontrol(info->RateControlMethod));
153
154     if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
155         info->RateControlMethod == MFX_RATECONTROL_VBR
156 #if QSV_HAVE_VCM
157         || info->RateControlMethod == MFX_RATECONTROL_VCM
158 #endif
159         ) {
160         av_log(avctx, AV_LOG_VERBOSE,
161                "BufferSizeInKB: %"PRIu16"; InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
162                info->BufferSizeInKB, info->InitialDelayInKB, info->TargetKbps, info->MaxKbps, info->BRCParamMultiplier);
163     } else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
164         av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
165                info->QPI, info->QPP, info->QPB);
166     }
167 #if QSV_HAVE_AVBR
168     else if (info->RateControlMethod == MFX_RATECONTROL_AVBR) {
169         av_log(avctx, AV_LOG_VERBOSE,
170                "TargetKbps: %"PRIu16"; Accuracy: %"PRIu16"; Convergence: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
171                info->TargetKbps, info->Accuracy, info->Convergence, info->BRCParamMultiplier);
172     }
173 #endif
174 #if QSV_HAVE_LA
175     else if (info->RateControlMethod == MFX_RATECONTROL_LA
176 #if QSV_HAVE_LA_HRD
177              || info->RateControlMethod == MFX_RATECONTROL_LA_HRD
178 #endif
179              ) {
180         av_log(avctx, AV_LOG_VERBOSE,
181                "TargetKbps: %"PRIu16"; LookAheadDepth: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
182                info->TargetKbps, co2->LookAheadDepth, info->BRCParamMultiplier);
183     }
184 #endif
185 #if QSV_HAVE_ICQ
186     else if (info->RateControlMethod == MFX_RATECONTROL_ICQ) {
187         av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
188     } else if (info->RateControlMethod == MFX_RATECONTROL_LA_ICQ) {
189         av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"; LookAheadDepth: %"PRIu16"\n",
190                info->ICQQuality, co2->LookAheadDepth);
191     }
192 #endif
193
194     av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
195            info->NumSlice, info->NumRefFrame);
196     av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
197            print_threestate(co->RateDistortionOpt));
198
199 #if QSV_HAVE_CO2
200     av_log(avctx, AV_LOG_VERBOSE,
201            "RecoveryPointSEI: %s IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
202            print_threestate(co->RecoveryPointSEI), co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
203
204     av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %"PRIu16"; ", co2->MaxFrameSize);
205 #if QSV_HAVE_MAX_SLICE_SIZE
206     av_log(avctx, AV_LOG_VERBOSE, "MaxSliceSize: %"PRIu16"; ", co2->MaxSliceSize);
207 #endif
208     av_log(avctx, AV_LOG_VERBOSE, "\n");
209
210     av_log(avctx, AV_LOG_VERBOSE,
211            "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
212            print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
213            print_threestate(co2->ExtBRC));
214
215 #if QSV_HAVE_TRELLIS
216     av_log(avctx, AV_LOG_VERBOSE, "Trellis: ");
217     if (co2->Trellis & MFX_TRELLIS_OFF) {
218         av_log(avctx, AV_LOG_VERBOSE, "off");
219     } else if (!co2->Trellis) {
220         av_log(avctx, AV_LOG_VERBOSE, "auto");
221     } else {
222         if (co2->Trellis & MFX_TRELLIS_I) av_log(avctx, AV_LOG_VERBOSE, "I");
223         if (co2->Trellis & MFX_TRELLIS_P) av_log(avctx, AV_LOG_VERBOSE, "P");
224         if (co2->Trellis & MFX_TRELLIS_B) av_log(avctx, AV_LOG_VERBOSE, "B");
225     }
226     av_log(avctx, AV_LOG_VERBOSE, "\n");
227 #endif
228
229 #if QSV_HAVE_VDENC
230     av_log(avctx, AV_LOG_VERBOSE, "VDENC: %s\n", print_threestate(info->LowPower));
231 #endif
232
233 #if QSV_VERSION_ATLEAST(1, 8)
234     av_log(avctx, AV_LOG_VERBOSE,
235            "RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: ",
236            print_threestate(co2->RepeatPPS), co2->NumMbPerSlice);
237     switch (co2->LookAheadDS) {
238     case MFX_LOOKAHEAD_DS_OFF: av_log(avctx, AV_LOG_VERBOSE, "off");     break;
239     case MFX_LOOKAHEAD_DS_2x:  av_log(avctx, AV_LOG_VERBOSE, "2x");      break;
240     case MFX_LOOKAHEAD_DS_4x:  av_log(avctx, AV_LOG_VERBOSE, "4x");      break;
241     default:                   av_log(avctx, AV_LOG_VERBOSE, "unknown"); break;
242     }
243     av_log(avctx, AV_LOG_VERBOSE, "\n");
244
245     av_log(avctx, AV_LOG_VERBOSE, "AdaptiveI: %s; AdaptiveB: %s; BRefType: ",
246            print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB));
247     switch (co2->BRefType) {
248     case MFX_B_REF_OFF:     av_log(avctx, AV_LOG_VERBOSE, "off");       break;
249     case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "pyramid");   break;
250     default:                av_log(avctx, AV_LOG_VERBOSE, "auto");      break;
251     }
252     av_log(avctx, AV_LOG_VERBOSE, "\n");
253 #endif
254
255 #if QSV_VERSION_ATLEAST(1, 9)
256     av_log(avctx, AV_LOG_VERBOSE,
257            "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
258            co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
259 #endif
260 #endif
261
262     if (avctx->codec_id == AV_CODEC_ID_H264) {
263         av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
264                co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
265         av_log(avctx, AV_LOG_VERBOSE,
266                "NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
267                print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
268                print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
269     }
270
271     av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
272            info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
273
274 }
275
276 static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
277 {
278     const char *rc_desc;
279     mfxU16      rc_mode;
280
281     int want_la     = q->look_ahead;
282     int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
283     int want_vcm    = q->vcm;
284
285     if (want_la && !QSV_HAVE_LA) {
286         av_log(avctx, AV_LOG_ERROR,
287                "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");
288         return AVERROR(ENOSYS);
289     }
290     if (want_vcm && !QSV_HAVE_VCM) {
291         av_log(avctx, AV_LOG_ERROR,
292                "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
293         return AVERROR(ENOSYS);
294     }
295
296     if (want_la + want_qscale + want_vcm > 1) {
297         av_log(avctx, AV_LOG_ERROR,
298                "More than one of: { constant qscale, lookahead, VCM } requested, "
299                "only one of them can be used at a time.\n");
300         return AVERROR(EINVAL);
301     }
302
303     if (!want_qscale && avctx->global_quality > 0 && !QSV_HAVE_ICQ){
304         av_log(avctx, AV_LOG_ERROR,
305                "ICQ ratecontrol mode requested, but is not supported by this SDK version\n");
306         return AVERROR(ENOSYS);
307     }
308
309     if (want_qscale) {
310         rc_mode = MFX_RATECONTROL_CQP;
311         rc_desc = "constant quantization parameter (CQP)";
312     }
313 #if QSV_HAVE_VCM
314     else if (want_vcm) {
315         rc_mode = MFX_RATECONTROL_VCM;
316         rc_desc = "video conferencing mode (VCM)";
317     }
318 #endif
319 #if QSV_HAVE_LA
320     else if (want_la) {
321         rc_mode = MFX_RATECONTROL_LA;
322         rc_desc = "VBR with lookahead (LA)";
323
324 #if QSV_HAVE_ICQ
325         if (avctx->global_quality > 0) {
326             rc_mode = MFX_RATECONTROL_LA_ICQ;
327             rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
328         }
329 #endif
330     }
331 #endif
332 #if QSV_HAVE_ICQ
333     else if (avctx->global_quality > 0) {
334         rc_mode = MFX_RATECONTROL_ICQ;
335         rc_desc = "intelligent constant quality (ICQ)";
336     }
337 #endif
338     else if (avctx->rc_max_rate == avctx->bit_rate) {
339         rc_mode = MFX_RATECONTROL_CBR;
340         rc_desc = "constant bitrate (CBR)";
341     }
342 #if QSV_HAVE_AVBR
343     else if (!avctx->rc_max_rate) {
344         rc_mode = MFX_RATECONTROL_AVBR;
345         rc_desc = "average variable bitrate (AVBR)";
346     }
347 #endif
348     else {
349         rc_mode = MFX_RATECONTROL_VBR;
350         rc_desc = "variable bitrate (VBR)";
351     }
352
353     q->param.mfx.RateControlMethod = rc_mode;
354     av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
355
356     return 0;
357 }
358
359 static int check_enc_param(AVCodecContext *avctx, QSVEncContext *q)
360 {
361     mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
362     mfxStatus ret;
363
364 #define UNMATCH(x) (param_out.mfx.x != q->param.mfx.x)
365
366     ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
367
368     if (ret < 0) {
369         if (UNMATCH(CodecId))
370             av_log(avctx, AV_LOG_ERROR, "Current codec type is unsupported\n");
371         if (UNMATCH(CodecProfile))
372             av_log(avctx, AV_LOG_ERROR, "Current profile is unsupported\n");
373         if (UNMATCH(RateControlMethod))
374             av_log(avctx, AV_LOG_ERROR, "Selected ratecontrol mode is unsupported\n");
375         if (UNMATCH(LowPower))
376               av_log(avctx, AV_LOG_ERROR, "Low power mode is unsupported\n");
377         if (UNMATCH(FrameInfo.FrameRateExtN) || UNMATCH(FrameInfo.FrameRateExtD))
378               av_log(avctx, AV_LOG_ERROR, "Current frame rate is unsupported\n");
379         if (UNMATCH(FrameInfo.PicStruct))
380               av_log(avctx, AV_LOG_ERROR, "Current picture structure is unsupported\n");
381         if (UNMATCH(FrameInfo.Width) || UNMATCH(FrameInfo.Height))
382               av_log(avctx, AV_LOG_ERROR, "Current resolution is unsupported\n");
383         if (UNMATCH(FrameInfo.FourCC))
384               av_log(avctx, AV_LOG_ERROR, "Current pixel format is unsupported\n");
385         return 0;
386     }
387     return 1;
388 }
389
390 static int init_video_param_jpeg(AVCodecContext *avctx, QSVEncContext *q)
391 {
392     enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
393                                    avctx->sw_pix_fmt : avctx->pix_fmt;
394     const AVPixFmtDescriptor *desc;
395     int ret;
396
397     ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
398     if (ret < 0)
399         return AVERROR_BUG;
400     q->param.mfx.CodecId = ret;
401
402     if (avctx->level > 0)
403         q->param.mfx.CodecLevel = avctx->level;
404     q->param.mfx.CodecProfile       = q->profile;
405
406     desc = av_pix_fmt_desc_get(sw_format);
407     if (!desc)
408         return AVERROR_BUG;
409
410     ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
411
412     q->param.mfx.FrameInfo.CropX          = 0;
413     q->param.mfx.FrameInfo.CropY          = 0;
414     q->param.mfx.FrameInfo.CropW          = avctx->width;
415     q->param.mfx.FrameInfo.CropH          = avctx->height;
416     q->param.mfx.FrameInfo.AspectRatioW   = avctx->sample_aspect_ratio.num;
417     q->param.mfx.FrameInfo.AspectRatioH   = avctx->sample_aspect_ratio.den;
418     q->param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
419     q->param.mfx.FrameInfo.BitDepthLuma   = desc->comp[0].depth;
420     q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
421     q->param.mfx.FrameInfo.Shift          = desc->comp[0].depth > 8;
422
423     q->param.mfx.FrameInfo.Width  = FFALIGN(avctx->width, 16);
424     q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 16);
425
426     if (avctx->hw_frames_ctx) {
427         AVHWFramesContext *frames_ctx    = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
428         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
429         q->param.mfx.FrameInfo.Width  = frames_hwctx->surfaces[0].Info.Width;
430         q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
431     }
432
433     if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
434         q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
435         q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
436     } else {
437         q->param.mfx.FrameInfo.FrameRateExtN  = avctx->time_base.den;
438         q->param.mfx.FrameInfo.FrameRateExtD  = avctx->time_base.num;
439     }
440
441     q->param.mfx.Interleaved          = 1;
442     q->param.mfx.Quality              = av_clip(avctx->global_quality, 1, 100);
443     q->param.mfx.RestartInterval      = 0;
444
445     return 0;
446 }
447
448 static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
449 {
450     enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
451                                    avctx->sw_pix_fmt : avctx->pix_fmt;
452     const AVPixFmtDescriptor *desc;
453     float quant;
454     int target_bitrate_kbps, max_bitrate_kbps, brc_param_multiplier;
455     int buffer_size_in_kilobytes, initial_delay_in_kilobytes;
456     int ret;
457     mfxVersion ver;
458
459     ret = MFXQueryVersion(q->session,&ver);
460     if (ret != MFX_ERR_NONE) {
461         av_log(avctx, AV_LOG_ERROR, "Error getting the session handle\n");
462         return AVERROR_UNKNOWN;
463     }
464
465     ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
466     if (ret < 0)
467         return AVERROR_BUG;
468     q->param.mfx.CodecId = ret;
469
470     if (avctx->level > 0)
471         q->param.mfx.CodecLevel = avctx->level;
472
473     if (avctx->compression_level == FF_COMPRESSION_DEFAULT) {
474         avctx->compression_level = q->preset;
475     } else if (avctx->compression_level >= 0) {
476         if (avctx->compression_level > MFX_TARGETUSAGE_BEST_SPEED) {
477             av_log(avctx, AV_LOG_WARNING, "Invalid compression level: "
478                     "valid range is 0-%d, using %d instead\n",
479                     MFX_TARGETUSAGE_BEST_SPEED, MFX_TARGETUSAGE_BEST_SPEED);
480             avctx->compression_level = MFX_TARGETUSAGE_BEST_SPEED;
481         }
482     }
483
484 #if QSV_HAVE_VDENC
485     q->param.mfx.LowPower           = q->low_power ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
486 #endif
487     q->param.mfx.CodecProfile       = q->profile;
488     q->param.mfx.TargetUsage        = avctx->compression_level;
489     q->param.mfx.GopPicSize         = FFMAX(0, avctx->gop_size);
490     q->param.mfx.GopRefDist         = FFMAX(-1, avctx->max_b_frames) + 1;
491     q->param.mfx.GopOptFlag         = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
492                                       MFX_GOP_CLOSED : 0;
493     q->param.mfx.IdrInterval        = q->idr_interval;
494     q->param.mfx.NumSlice           = avctx->slices;
495     q->param.mfx.NumRefFrame        = FFMAX(0, avctx->refs);
496     q->param.mfx.EncodedOrder       = 0;
497     q->param.mfx.BufferSizeInKB     = 0;
498
499     desc = av_pix_fmt_desc_get(sw_format);
500     if (!desc)
501         return AVERROR_BUG;
502
503     ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC);
504
505     q->param.mfx.FrameInfo.CropX          = 0;
506     q->param.mfx.FrameInfo.CropY          = 0;
507     q->param.mfx.FrameInfo.CropW          = avctx->width;
508     q->param.mfx.FrameInfo.CropH          = avctx->height;
509     q->param.mfx.FrameInfo.AspectRatioW   = avctx->sample_aspect_ratio.num;
510     q->param.mfx.FrameInfo.AspectRatioH   = avctx->sample_aspect_ratio.den;
511     q->param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
512     q->param.mfx.FrameInfo.BitDepthLuma   = desc->comp[0].depth;
513     q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
514     q->param.mfx.FrameInfo.Shift          = desc->comp[0].depth > 8;
515
516     // If the minor version is greater than or equal to 19,
517     // then can use the same alignment settings as H.264 for HEVC
518     q->width_align = (avctx->codec_id != AV_CODEC_ID_HEVC ||
519                       QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 19)) ? 16 : 32;
520     q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
521
522     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
523         // it is important that PicStruct be setup correctly from the
524         // start--otherwise, encoding doesn't work and results in a bunch
525         // of incompatible video parameter errors
526         q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
527         // height alignment always must be 32 for interlaced video
528         q->height_align = 32;
529     } else {
530         q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
531         // for progressive video, the height should be aligned to 16 for
532         // H.264.  For HEVC, depending on the version of MFX, it should be
533         // either 32 or 16.  The lower number is better if possible.
534         q->height_align = avctx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16;
535     }
536     q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
537
538     if (avctx->hw_frames_ctx) {
539         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
540         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
541         q->param.mfx.FrameInfo.Width  = frames_hwctx->surfaces[0].Info.Width;
542         q->param.mfx.FrameInfo.Height = frames_hwctx->surfaces[0].Info.Height;
543     }
544
545     if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
546         q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
547         q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
548     } else {
549         q->param.mfx.FrameInfo.FrameRateExtN  = avctx->time_base.den;
550         q->param.mfx.FrameInfo.FrameRateExtD  = avctx->time_base.num;
551     }
552
553     ret = select_rc_mode(avctx, q);
554     if (ret < 0)
555         return ret;
556
557     //libmfx BRC parameters are 16 bits thus maybe overflow, then BRCParamMultiplier is needed
558     buffer_size_in_kilobytes   = avctx->rc_buffer_size / 8000;
559     initial_delay_in_kilobytes = avctx->rc_initial_buffer_occupancy / 1000;
560     target_bitrate_kbps        = avctx->bit_rate / 1000;
561     max_bitrate_kbps           = avctx->rc_max_rate / 1000;
562     brc_param_multiplier       = (FFMAX(FFMAX3(target_bitrate_kbps, max_bitrate_kbps, buffer_size_in_kilobytes),
563                                   initial_delay_in_kilobytes) + 0x10000) / 0x10000;
564
565     switch (q->param.mfx.RateControlMethod) {
566     case MFX_RATECONTROL_CBR:
567     case MFX_RATECONTROL_VBR:
568 #if QSV_HAVE_VCM
569     case MFX_RATECONTROL_VCM:
570 #endif
571         q->param.mfx.BufferSizeInKB   = buffer_size_in_kilobytes / brc_param_multiplier;
572         q->param.mfx.InitialDelayInKB = initial_delay_in_kilobytes / brc_param_multiplier;
573         q->param.mfx.TargetKbps       = target_bitrate_kbps / brc_param_multiplier;
574         q->param.mfx.MaxKbps          = max_bitrate_kbps / brc_param_multiplier;
575         q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
576         break;
577     case MFX_RATECONTROL_CQP:
578         quant = avctx->global_quality / FF_QP2LAMBDA;
579
580         q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
581         q->param.mfx.QPP = av_clip(quant, 0, 51);
582         q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
583
584         break;
585 #if QSV_HAVE_AVBR
586     case MFX_RATECONTROL_AVBR:
587         q->param.mfx.TargetKbps  = target_bitrate_kbps / brc_param_multiplier;
588         q->param.mfx.Convergence = q->avbr_convergence;
589         q->param.mfx.Accuracy    = q->avbr_accuracy;
590         q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
591         break;
592 #endif
593 #if QSV_HAVE_LA
594     case MFX_RATECONTROL_LA:
595         q->param.mfx.TargetKbps  = target_bitrate_kbps / brc_param_multiplier;
596         q->extco2.LookAheadDepth = q->look_ahead_depth;
597         q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
598         break;
599 #if QSV_HAVE_ICQ
600     case MFX_RATECONTROL_LA_ICQ:
601         q->extco2.LookAheadDepth = q->look_ahead_depth;
602     case MFX_RATECONTROL_ICQ:
603         q->param.mfx.ICQQuality  = avctx->global_quality;
604         break;
605 #endif
606 #endif
607     }
608
609     // the HEVC encoder plugin currently fails if coding options
610     // are provided
611     if (avctx->codec_id != AV_CODEC_ID_HEVC) {
612         q->extco.Header.BufferId      = MFX_EXTBUFF_CODING_OPTION;
613         q->extco.Header.BufferSz      = sizeof(q->extco);
614
615         q->extco.PicTimingSEI         = q->pic_timing_sei ?
616                                         MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
617
618         if (q->rdo >= 0)
619             q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
620
621         if (avctx->codec_id == AV_CODEC_ID_H264) {
622 #if FF_API_CODER_TYPE
623 FF_DISABLE_DEPRECATION_WARNINGS
624             if (avctx->coder_type >= 0)
625                 q->cavlc = avctx->coder_type == FF_CODER_TYPE_VLC;
626 FF_ENABLE_DEPRECATION_WARNINGS
627 #endif
628             q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
629                                       : MFX_CODINGOPTION_UNKNOWN;
630
631             if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
632                 q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
633                                              MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
634
635             if (q->single_sei_nal_unit >= 0)
636                 q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
637             if (q->recovery_point_sei >= 0)
638                 q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
639             q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
640             q->extco.AUDelimiter          = q->aud ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
641         }
642
643         q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
644
645         if (avctx->codec_id == AV_CODEC_ID_H264) {
646 #if QSV_HAVE_CO2
647             q->extco2.Header.BufferId     = MFX_EXTBUFF_CODING_OPTION2;
648             q->extco2.Header.BufferSz     = sizeof(q->extco2);
649
650             if (q->int_ref_type >= 0)
651                 q->extco2.IntRefType = q->int_ref_type;
652             if (q->int_ref_cycle_size >= 0)
653                 q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
654             if (q->int_ref_qp_delta != INT16_MIN)
655                 q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
656
657             if (q->bitrate_limit >= 0)
658                 q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
659             if (q->mbbrc >= 0)
660                 q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
661             if (q->extbrc >= 0)
662                 q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
663
664             if (q->max_frame_size >= 0)
665                 q->extco2.MaxFrameSize = q->max_frame_size;
666 #if QSV_HAVE_MAX_SLICE_SIZE
667             if (q->max_slice_size >= 0)
668                 q->extco2.MaxSliceSize = q->max_slice_size;
669 #endif
670
671 #if QSV_HAVE_TRELLIS
672             q->extco2.Trellis = q->trellis;
673 #endif
674
675 #if QSV_VERSION_ATLEAST(1, 8)
676             q->extco2.LookAheadDS = q->look_ahead_downsampling;
677             q->extco2.RepeatPPS   = q->repeat_pps ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
678
679 #if FF_API_PRIVATE_OPT
680 FF_DISABLE_DEPRECATION_WARNINGS
681             if (avctx->b_frame_strategy >= 0)
682                 q->b_strategy = avctx->b_frame_strategy;
683 FF_ENABLE_DEPRECATION_WARNINGS
684 #endif
685             if (q->b_strategy >= 0)
686                 q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
687             if (q->adaptive_i >= 0)
688                 q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
689             if (q->adaptive_b >= 0)
690                 q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
691 #endif
692
693 #if QSV_VERSION_ATLEAST(1, 9)
694             if (avctx->qmin >= 0 && avctx->qmax >= 0 && avctx->qmin > avctx->qmax) {
695                 av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are set but invalid, please make sure min <= max\n");
696                 return AVERROR(EINVAL);
697             }
698             if (avctx->qmin >= 0) {
699                 q->extco2.MinQPI = avctx->qmin > 51 ? 51 : avctx->qmin;
700                 q->extco2.MinQPP = q->extco2.MinQPB = q->extco2.MinQPI;
701             }
702             if (avctx->qmax >= 0) {
703                 q->extco2.MaxQPI = avctx->qmax > 51 ? 51 : avctx->qmax;
704                 q->extco2.MaxQPP = q->extco2.MaxQPB = q->extco2.MaxQPI;
705             }
706 #endif
707             q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
708 #endif
709
710 #if QSV_HAVE_MF
711             if (QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 25)) {
712                 q->extmfp.Header.BufferId     = MFX_EXTBUFF_MULTI_FRAME_PARAM;
713                 q->extmfp.Header.BufferSz     = sizeof(q->extmfp);
714
715                 q->extmfp.MFMode = q->mfmode;
716                 av_log(avctx,AV_LOG_VERBOSE,"MFMode:%d\n", q->extmfp.MFMode);
717                 q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extmfp;
718             }
719 #endif
720         }
721     }
722
723     if (!check_enc_param(avctx,q)) {
724         av_log(avctx, AV_LOG_ERROR,
725                "some encoding parameters are not supported by the QSV "
726                "runtime. Please double check the input parameters.\n");
727         return AVERROR(ENOSYS);
728     }
729
730     return 0;
731 }
732
733 static int qsv_retrieve_enc_jpeg_params(AVCodecContext *avctx, QSVEncContext *q)
734 {
735     int ret = 0;
736
737     ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
738     if (ret < 0)
739         return ff_qsv_print_error(avctx, ret,
740                                   "Error calling GetVideoParam");
741
742     q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
743
744     // for qsv mjpeg the return value maybe 0 so alloc the buffer
745     if (q->packet_size == 0)
746         q->packet_size = q->param.mfx.FrameInfo.Height * q->param.mfx.FrameInfo.Width * 4;
747
748     return 0;
749 }
750
751 static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
752 {
753     AVCPBProperties *cpb_props;
754
755     uint8_t sps_buf[128];
756     uint8_t pps_buf[128];
757
758     mfxExtCodingOptionSPSPPS extradata = {
759         .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
760         .Header.BufferSz = sizeof(extradata),
761         .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
762         .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
763     };
764
765     mfxExtCodingOption co = {
766         .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
767         .Header.BufferSz = sizeof(co),
768     };
769 #if QSV_HAVE_CO2
770     mfxExtCodingOption2 co2 = {
771         .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
772         .Header.BufferSz = sizeof(co2),
773     };
774 #endif
775
776     mfxExtBuffer *ext_buffers[] = {
777         (mfxExtBuffer*)&extradata,
778         (mfxExtBuffer*)&co,
779 #if QSV_HAVE_CO2
780         (mfxExtBuffer*)&co2,
781 #endif
782     };
783
784     int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
785     int ret;
786
787     q->param.ExtParam    = ext_buffers;
788     q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
789
790     ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
791     if (ret < 0)
792         return ff_qsv_print_error(avctx, ret,
793                                   "Error calling GetVideoParam");
794
795     q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
796
797     if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)) {
798         av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
799         return AVERROR_UNKNOWN;
800     }
801
802     avctx->extradata = av_malloc(extradata.SPSBufSize + need_pps * extradata.PPSBufSize +
803                                  AV_INPUT_BUFFER_PADDING_SIZE);
804     if (!avctx->extradata)
805         return AVERROR(ENOMEM);
806
807     memcpy(avctx->extradata,                        sps_buf, extradata.SPSBufSize);
808     if (need_pps)
809         memcpy(avctx->extradata + extradata.SPSBufSize, pps_buf, extradata.PPSBufSize);
810     avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
811     memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
812
813     cpb_props = ff_add_cpb_side_data(avctx);
814     if (!cpb_props)
815         return AVERROR(ENOMEM);
816     cpb_props->max_bitrate = avctx->rc_max_rate;
817     cpb_props->min_bitrate = avctx->rc_min_rate;
818     cpb_props->avg_bitrate = avctx->bit_rate;
819     cpb_props->buffer_size = avctx->rc_buffer_size;
820
821     dump_video_param(avctx, q, ext_buffers + 1);
822
823     return 0;
824 }
825
826 static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
827 {
828     AVQSVContext *qsv = avctx->hwaccel_context;
829     mfxFrameSurface1 *surfaces;
830     int nb_surfaces, i;
831
832     nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested;
833
834     q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
835     if (!q->opaque_alloc_buf)
836         return AVERROR(ENOMEM);
837
838     q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
839     if (!q->opaque_surfaces)
840         return AVERROR(ENOMEM);
841
842     surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
843     for (i = 0; i < nb_surfaces; i++) {
844         surfaces[i].Info      = q->req.Info;
845         q->opaque_surfaces[i] = surfaces + i;
846     }
847
848     q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
849     q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
850     q->opaque_alloc.In.Surfaces     = q->opaque_surfaces;
851     q->opaque_alloc.In.NumSurface   = nb_surfaces;
852     q->opaque_alloc.In.Type         = q->req.Type;
853
854     q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
855
856     qsv->nb_opaque_surfaces = nb_surfaces;
857     qsv->opaque_surfaces    = q->opaque_alloc_buf;
858     qsv->opaque_alloc_type  = q->req.Type;
859
860     return 0;
861 }
862
863 static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
864 {
865     int ret;
866
867     if (avctx->hwaccel_context) {
868         AVQSVContext *qsv = avctx->hwaccel_context;
869         q->session = qsv->session;
870     } else if (avctx->hw_frames_ctx) {
871         q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
872         if (!q->frames_ctx.hw_frames_ctx)
873             return AVERROR(ENOMEM);
874
875         ret = ff_qsv_init_session_frames(avctx, &q->internal_session,
876                                          &q->frames_ctx, q->load_plugins,
877                                          q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY);
878         if (ret < 0) {
879             av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
880             return ret;
881         }
882
883         q->session = q->internal_session;
884     } else if (avctx->hw_device_ctx) {
885         ret = ff_qsv_init_session_device(avctx, &q->internal_session,
886                                          avctx->hw_device_ctx, q->load_plugins);
887         if (ret < 0)
888             return ret;
889
890         q->session = q->internal_session;
891     } else {
892         ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
893                                            q->load_plugins);
894         if (ret < 0)
895             return ret;
896
897         q->session = q->internal_session;
898     }
899
900     return 0;
901 }
902
903 static inline unsigned int qsv_fifo_item_size(void)
904 {
905     return sizeof(AVPacket) + sizeof(mfxSyncPoint*) + sizeof(mfxBitstream*);
906 }
907
908 static inline unsigned int qsv_fifo_size(const AVFifoBuffer* fifo)
909 {
910     return av_fifo_size(fifo)/qsv_fifo_item_size();
911 }
912
913 int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
914 {
915     int iopattern = 0;
916     int opaque_alloc = 0;
917     int ret;
918
919     q->param.AsyncDepth = q->async_depth;
920
921     q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
922     if (!q->async_fifo)
923         return AVERROR(ENOMEM);
924
925     if (avctx->hwaccel_context) {
926         AVQSVContext *qsv = avctx->hwaccel_context;
927
928         iopattern    = qsv->iopattern;
929         opaque_alloc = qsv->opaque_alloc;
930     }
931
932     if (avctx->hw_frames_ctx) {
933         AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
934         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
935
936         if (!iopattern) {
937             if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
938                 iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
939             else if (frames_hwctx->frame_type &
940                      (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
941                 iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
942         }
943     }
944
945     if (!iopattern)
946         iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
947     q->param.IOPattern = iopattern;
948
949     ret = qsvenc_init_session(avctx, q);
950     if (ret < 0)
951         return ret;
952
953     // in the mfxInfoMFX struct, JPEG is different from other codecs
954     switch (avctx->codec_id) {
955     case AV_CODEC_ID_MJPEG:
956         ret = init_video_param_jpeg(avctx, q);
957         break;
958     default:
959         ret = init_video_param(avctx, q);
960         break;
961     }
962     if (ret < 0)
963         return ret;
964
965     ret = MFXVideoENCODE_Query(q->session, &q->param, &q->param);
966     if (ret == MFX_WRN_PARTIAL_ACCELERATION) {
967         av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
968     } else if (ret < 0) {
969         return ff_qsv_print_error(avctx, ret,
970                                   "Error querying encoder params");
971     }
972
973     ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
974     if (ret < 0)
975         return ff_qsv_print_error(avctx, ret,
976                                   "Error querying (IOSurf) the encoding parameters");
977
978     if (opaque_alloc) {
979         ret = qsv_init_opaque_alloc(avctx, q);
980         if (ret < 0)
981             return ret;
982     }
983
984     if (avctx->hwaccel_context) {
985         AVQSVContext *qsv = avctx->hwaccel_context;
986         int i, j;
987
988         q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,
989                                        sizeof(*q->extparam));
990         if (!q->extparam)
991             return AVERROR(ENOMEM);
992
993         q->param.ExtParam = q->extparam;
994         for (i = 0; i < qsv->nb_ext_buffers; i++)
995             q->param.ExtParam[i] = qsv->ext_buffers[i];
996         q->param.NumExtParam = qsv->nb_ext_buffers;
997
998         for (i = 0; i < q->nb_extparam_internal; i++) {
999             for (j = 0; j < qsv->nb_ext_buffers; j++) {
1000                 if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
1001                     break;
1002             }
1003             if (j < qsv->nb_ext_buffers)
1004                 continue;
1005
1006             q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
1007         }
1008     } else {
1009         q->param.ExtParam    = q->extparam_internal;
1010         q->param.NumExtParam = q->nb_extparam_internal;
1011     }
1012
1013     ret = MFXVideoENCODE_Init(q->session, &q->param);
1014     if (ret < 0)
1015         return ff_qsv_print_error(avctx, ret,
1016                                   "Error initializing the encoder");
1017     else if (ret > 0)
1018         ff_qsv_print_warning(avctx, ret,
1019                              "Warning in encoder initialization");
1020
1021     switch (avctx->codec_id) {
1022     case AV_CODEC_ID_MJPEG:
1023         ret = qsv_retrieve_enc_jpeg_params(avctx, q);
1024         break;
1025     default:
1026         ret = qsv_retrieve_enc_params(avctx, q);
1027         break;
1028     }
1029     if (ret < 0) {
1030         av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
1031         return ret;
1032     }
1033
1034     q->avctx = avctx;
1035
1036     return 0;
1037 }
1038
1039 static void free_encoder_ctrl_payloads(mfxEncodeCtrl* enc_ctrl)
1040 {
1041     if (enc_ctrl) {
1042         int i;
1043         for (i = 0; i < enc_ctrl->NumPayload && i < QSV_MAX_ENC_PAYLOAD; i++) {
1044             av_free(enc_ctrl->Payload[i]);
1045         }
1046         enc_ctrl->NumPayload = 0;
1047     }
1048 }
1049
1050 static void clear_unused_frames(QSVEncContext *q)
1051 {
1052     QSVFrame *cur = q->work_frames;
1053     while (cur) {
1054         if (cur->used && !cur->surface.Data.Locked) {
1055             free_encoder_ctrl_payloads(&cur->enc_ctrl);
1056             if (cur->frame->format == AV_PIX_FMT_QSV) {
1057                 av_frame_unref(cur->frame);
1058             }
1059             cur->used = 0;
1060         }
1061         cur = cur->next;
1062     }
1063 }
1064
1065 static int get_free_frame(QSVEncContext *q, QSVFrame **f)
1066 {
1067     QSVFrame *frame, **last;
1068
1069     clear_unused_frames(q);
1070
1071     frame = q->work_frames;
1072     last  = &q->work_frames;
1073     while (frame) {
1074         if (!frame->used) {
1075             *f = frame;
1076             frame->used = 1;
1077             return 0;
1078         }
1079
1080         last  = &frame->next;
1081         frame = frame->next;
1082     }
1083
1084     frame = av_mallocz(sizeof(*frame));
1085     if (!frame)
1086         return AVERROR(ENOMEM);
1087     frame->frame = av_frame_alloc();
1088     if (!frame->frame) {
1089         av_freep(&frame);
1090         return AVERROR(ENOMEM);
1091     }
1092     frame->enc_ctrl.Payload = av_mallocz(sizeof(mfxPayload*) * QSV_MAX_ENC_PAYLOAD);
1093     if (!frame->enc_ctrl.Payload) {
1094         av_freep(&frame);
1095         return AVERROR(ENOMEM);
1096     }
1097     *last = frame;
1098
1099     *f = frame;
1100     frame->used = 1;
1101
1102     return 0;
1103 }
1104
1105 static int submit_frame(QSVEncContext *q, const AVFrame *frame,
1106                         QSVFrame **new_frame)
1107 {
1108     QSVFrame *qf;
1109     int ret;
1110
1111     ret = get_free_frame(q, &qf);
1112     if (ret < 0)
1113         return ret;
1114
1115     if (frame->format == AV_PIX_FMT_QSV) {
1116         ret = av_frame_ref(qf->frame, frame);
1117         if (ret < 0)
1118             return ret;
1119
1120         qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
1121
1122         if (q->frames_ctx.mids) {
1123             ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
1124             if (ret < 0)
1125                 return ret;
1126
1127             qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
1128         }
1129     } else {
1130         /* make a copy if the input is not padded as libmfx requires */
1131         /* and to make allocation continious for data[0]/data[1] */
1132          if ((frame->height & 31 || frame->linesize[0] & (q->width_align - 1)) ||
1133             (frame->data[1] - frame->data[0] != frame->linesize[0] * FFALIGN(qf->frame->height, q->height_align))) {
1134             qf->frame->height = FFALIGN(frame->height, q->height_align);
1135             qf->frame->width  = FFALIGN(frame->width, q->width_align);
1136
1137             qf->frame->format = frame->format;
1138
1139             if (!qf->frame->data[0]) {
1140                 ret = av_frame_get_buffer(qf->frame, q->width_align);
1141                 if (ret < 0)
1142                     return ret;
1143             }
1144
1145             qf->frame->height = frame->height;
1146             qf->frame->width  = frame->width;
1147
1148             ret = av_frame_copy(qf->frame, frame);
1149             if (ret < 0) {
1150                 av_frame_unref(qf->frame);
1151                 return ret;
1152             }
1153         } else {
1154             ret = av_frame_ref(qf->frame, frame);
1155             if (ret < 0)
1156                 return ret;
1157         }
1158
1159         qf->surface.Info = q->param.mfx.FrameInfo;
1160
1161         qf->surface.Info.PicStruct =
1162             !frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
1163             frame->top_field_first   ? MFX_PICSTRUCT_FIELD_TFF :
1164                                        MFX_PICSTRUCT_FIELD_BFF;
1165         if (frame->repeat_pict == 1)
1166             qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
1167         else if (frame->repeat_pict == 2)
1168             qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
1169         else if (frame->repeat_pict == 4)
1170             qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
1171
1172         qf->surface.Data.PitchLow  = qf->frame->linesize[0];
1173         qf->surface.Data.Y         = qf->frame->data[0];
1174         qf->surface.Data.UV        = qf->frame->data[1];
1175     }
1176
1177     qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
1178
1179     *new_frame = qf;
1180
1181     return 0;
1182 }
1183
1184 static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
1185 {
1186     if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
1187         if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
1188             q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
1189             q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
1190             av_log(avctx, AV_LOG_WARNING,
1191                    "Interlaced coding is supported"
1192                    " at Main/High Profile Level 2.2-4.0\n");
1193     }
1194 }
1195
1196 static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
1197                         const AVFrame *frame)
1198 {
1199     AVPacket new_pkt = { 0 };
1200     mfxBitstream *bs;
1201 #if QSV_VERSION_ATLEAST(1, 26)
1202     mfxExtAVCEncodedFrameInfo *enc_info;
1203     mfxExtBuffer **enc_buf;
1204 #endif
1205
1206     mfxFrameSurface1 *surf = NULL;
1207     mfxSyncPoint *sync     = NULL;
1208     QSVFrame *qsv_frame = NULL;
1209     mfxEncodeCtrl* enc_ctrl = NULL;
1210     int ret;
1211
1212     if (frame) {
1213         ret = submit_frame(q, frame, &qsv_frame);
1214         if (ret < 0) {
1215             av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
1216             return ret;
1217         }
1218     }
1219     if (qsv_frame) {
1220         surf = &qsv_frame->surface;
1221         enc_ctrl = &qsv_frame->enc_ctrl;
1222         memset(enc_ctrl, 0, sizeof(mfxEncodeCtrl));
1223
1224         if (frame->pict_type == AV_PICTURE_TYPE_I) {
1225             enc_ctrl->FrameType = MFX_FRAMETYPE_I | MFX_FRAMETYPE_REF;
1226             if (q->forced_idr)
1227                 enc_ctrl->FrameType |= MFX_FRAMETYPE_IDR;
1228         }
1229     }
1230
1231     ret = av_new_packet(&new_pkt, q->packet_size);
1232     if (ret < 0) {
1233         av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
1234         return ret;
1235     }
1236
1237     bs = av_mallocz(sizeof(*bs));
1238     if (!bs) {
1239         av_packet_unref(&new_pkt);
1240         return AVERROR(ENOMEM);
1241     }
1242     bs->Data      = new_pkt.data;
1243     bs->MaxLength = new_pkt.size;
1244
1245 #if QSV_VERSION_ATLEAST(1, 26)
1246     if (avctx->codec_id == AV_CODEC_ID_H264) {
1247         enc_info = av_mallocz(sizeof(*enc_info));
1248         if (!enc_info)
1249             return AVERROR(ENOMEM);
1250
1251         enc_info->Header.BufferId = MFX_EXTBUFF_ENCODED_FRAME_INFO;
1252         enc_info->Header.BufferSz = sizeof (*enc_info);
1253         bs->NumExtParam = 1;
1254         enc_buf = av_mallocz(sizeof(mfxExtBuffer *));
1255         if (!enc_buf)
1256             return AVERROR(ENOMEM);
1257         enc_buf[0] = (mfxExtBuffer *)enc_info;
1258
1259         bs->ExtParam = enc_buf;
1260     }
1261 #endif
1262
1263     if (q->set_encode_ctrl_cb) {
1264         q->set_encode_ctrl_cb(avctx, frame, &qsv_frame->enc_ctrl);
1265     }
1266
1267     sync = av_mallocz(sizeof(*sync));
1268     if (!sync) {
1269         av_freep(&bs);
1270  #if QSV_VERSION_ATLEAST(1, 26)
1271         if (avctx->codec_id == AV_CODEC_ID_H264) {
1272             av_freep(&enc_info);
1273             av_freep(&enc_buf);
1274         }
1275  #endif
1276         av_packet_unref(&new_pkt);
1277         return AVERROR(ENOMEM);
1278     }
1279
1280     do {
1281         ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, bs, sync);
1282         if (ret == MFX_WRN_DEVICE_BUSY)
1283             av_usleep(500);
1284     } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
1285
1286     if (ret > 0)
1287         ff_qsv_print_warning(avctx, ret, "Warning during encoding");
1288
1289     if (ret < 0) {
1290         av_packet_unref(&new_pkt);
1291         av_freep(&bs);
1292 #if QSV_VERSION_ATLEAST(1, 26)
1293         if (avctx->codec_id == AV_CODEC_ID_H264) {
1294             av_freep(&enc_info);
1295             av_freep(&enc_buf);
1296         }
1297 #endif
1298         av_freep(&sync);
1299         return (ret == MFX_ERR_MORE_DATA) ?
1300                0 : ff_qsv_print_error(avctx, ret, "Error during encoding");
1301     }
1302
1303     if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)
1304         print_interlace_msg(avctx, q);
1305
1306     if (*sync) {
1307         av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
1308         av_fifo_generic_write(q->async_fifo, &sync,    sizeof(sync),    NULL);
1309         av_fifo_generic_write(q->async_fifo, &bs,      sizeof(bs),    NULL);
1310     } else {
1311         av_freep(&sync);
1312         av_packet_unref(&new_pkt);
1313         av_freep(&bs);
1314 #if QSV_VERSION_ATLEAST(1, 26)
1315         if (avctx->codec_id == AV_CODEC_ID_H264) {
1316             av_freep(&enc_info);
1317             av_freep(&enc_buf);
1318         }
1319 #endif
1320     }
1321
1322     return 0;
1323 }
1324
1325 int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
1326                   AVPacket *pkt, const AVFrame *frame, int *got_packet)
1327 {
1328     int ret;
1329
1330     ret = encode_frame(avctx, q, frame);
1331     if (ret < 0)
1332         return ret;
1333
1334     if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
1335         (!frame && av_fifo_size(q->async_fifo))) {
1336         AVPacket new_pkt;
1337         mfxBitstream *bs;
1338         mfxSyncPoint *sync;
1339 #if QSV_VERSION_ATLEAST(1, 26)
1340         mfxExtAVCEncodedFrameInfo *enc_info;
1341         mfxExtBuffer **enc_buf;
1342 #endif
1343         enum AVPictureType pict_type;
1344
1345         av_fifo_generic_read(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);
1346         av_fifo_generic_read(q->async_fifo, &sync,    sizeof(sync),    NULL);
1347         av_fifo_generic_read(q->async_fifo, &bs,      sizeof(bs),      NULL);
1348
1349         do {
1350             ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
1351         } while (ret == MFX_WRN_IN_EXECUTION);
1352
1353         new_pkt.dts  = av_rescale_q(bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
1354         new_pkt.pts  = av_rescale_q(bs->TimeStamp,       (AVRational){1, 90000}, avctx->time_base);
1355         new_pkt.size = bs->DataLength;
1356
1357         if (bs->FrameType & MFX_FRAMETYPE_IDR || bs->FrameType & MFX_FRAMETYPE_xIDR) {
1358             new_pkt.flags |= AV_PKT_FLAG_KEY;
1359             pict_type = AV_PICTURE_TYPE_I;
1360         } else if (bs->FrameType & MFX_FRAMETYPE_I || bs->FrameType & MFX_FRAMETYPE_xI)
1361             pict_type = AV_PICTURE_TYPE_I;
1362         else if (bs->FrameType & MFX_FRAMETYPE_P || bs->FrameType & MFX_FRAMETYPE_xP)
1363             pict_type = AV_PICTURE_TYPE_P;
1364         else if (bs->FrameType & MFX_FRAMETYPE_B || bs->FrameType & MFX_FRAMETYPE_xB)
1365             pict_type = AV_PICTURE_TYPE_B;
1366         else if (bs->FrameType == MFX_FRAMETYPE_UNKNOWN) {
1367             pict_type = AV_PICTURE_TYPE_NONE;
1368             av_log(avctx, AV_LOG_WARNING, "Unknown FrameType, set pict_type to AV_PICTURE_TYPE_NONE.\n");
1369         } else {
1370             av_log(avctx, AV_LOG_ERROR, "Invalid FrameType:%d.\n", bs->FrameType);
1371             return AVERROR_INVALIDDATA;
1372         }
1373
1374 #if FF_API_CODED_FRAME
1375 FF_DISABLE_DEPRECATION_WARNINGS
1376         avctx->coded_frame->pict_type = pict_type;
1377 FF_ENABLE_DEPRECATION_WARNINGS
1378 #endif
1379
1380 #if QSV_VERSION_ATLEAST(1, 26)
1381         if (avctx->codec_id == AV_CODEC_ID_H264) {
1382             enc_buf = bs->ExtParam;
1383             enc_info = (mfxExtAVCEncodedFrameInfo *)(*bs->ExtParam);
1384             ff_side_data_set_encoder_stats(&new_pkt,
1385                 enc_info->QP * FF_QP2LAMBDA, NULL, 0, pict_type);
1386             av_freep(&enc_info);
1387             av_freep(&enc_buf);
1388         }
1389 #endif
1390         av_freep(&bs);
1391         av_freep(&sync);
1392
1393         if (pkt->data) {
1394             if (pkt->size < new_pkt.size) {
1395                 av_log(avctx, AV_LOG_ERROR, "Submitted buffer not large enough: %d < %d\n",
1396                        pkt->size, new_pkt.size);
1397                 av_packet_unref(&new_pkt);
1398                 return AVERROR(EINVAL);
1399             }
1400
1401             memcpy(pkt->data, new_pkt.data, new_pkt.size);
1402             pkt->size = new_pkt.size;
1403
1404             ret = av_packet_copy_props(pkt, &new_pkt);
1405             av_packet_unref(&new_pkt);
1406             if (ret < 0)
1407                 return ret;
1408         } else
1409             *pkt = new_pkt;
1410
1411         *got_packet = 1;
1412     }
1413
1414     return 0;
1415 }
1416
1417 int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
1418 {
1419     QSVFrame *cur;
1420
1421     if (q->session)
1422         MFXVideoENCODE_Close(q->session);
1423     if (q->internal_session)
1424         MFXClose(q->internal_session);
1425     q->session          = NULL;
1426     q->internal_session = NULL;
1427
1428     av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
1429     av_buffer_unref(&q->frames_ctx.mids_buf);
1430
1431     cur = q->work_frames;
1432     while (cur) {
1433         q->work_frames = cur->next;
1434         av_frame_free(&cur->frame);
1435         av_free(cur->enc_ctrl.Payload);
1436         av_freep(&cur);
1437         cur = q->work_frames;
1438     }
1439
1440     while (q->async_fifo && av_fifo_size(q->async_fifo)) {
1441         AVPacket pkt;
1442         mfxSyncPoint *sync;
1443         mfxBitstream *bs;
1444
1445         av_fifo_generic_read(q->async_fifo, &pkt,  sizeof(pkt),  NULL);
1446         av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
1447         av_fifo_generic_read(q->async_fifo, &bs,   sizeof(bs),   NULL);
1448
1449         av_freep(&sync);
1450         av_freep(&bs);
1451         av_packet_unref(&pkt);
1452     }
1453     av_fifo_free(q->async_fifo);
1454     q->async_fifo = NULL;
1455
1456     av_freep(&q->opaque_surfaces);
1457     av_buffer_unref(&q->opaque_alloc_buf);
1458
1459     av_freep(&q->extparam);
1460
1461     return 0;
1462 }