2 * Intel MediaSDK QSV encoder/decoder shared code
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/avstring.h"
28 #include "libavutil/common.h"
29 #include "libavutil/error.h"
30 #include "libavutil/hwcontext.h"
31 #include "libavutil/hwcontext_qsv.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/avassert.h"
36 #include "qsv_internal.h"
38 #define MFX_IMPL_VIA_MASK(impl) (0x0f00 & (impl))
39 #define QSV_HAVE_USER_PLUGIN !QSV_ONEVPL
40 #define QSV_HAVE_AUDIO !QSV_ONEVPL
44 #if QSV_HAVE_USER_PLUGIN
45 #include <mfxplugin.h>
49 #include <mfxdispatcher.h>
51 #define MFXUnload(a) do { } while(0)
54 int ff_qsv_codec_id_to_mfx(enum AVCodecID codec_id)
57 case AV_CODEC_ID_H264:
59 case AV_CODEC_ID_HEVC:
60 return MFX_CODEC_HEVC;
61 case AV_CODEC_ID_MPEG1VIDEO:
62 case AV_CODEC_ID_MPEG2VIDEO:
63 return MFX_CODEC_MPEG2;
68 case AV_CODEC_ID_MJPEG:
69 return MFX_CODEC_JPEG;
72 #if QSV_VERSION_ATLEAST(1, 34)
81 return AVERROR(ENOSYS);
87 } qsv_iopatterns[] = {
88 {MFX_IOPATTERN_IN_VIDEO_MEMORY, "input is video memory surface" },
89 {MFX_IOPATTERN_IN_SYSTEM_MEMORY, "input is system memory surface" },
91 {MFX_IOPATTERN_IN_OPAQUE_MEMORY, "input is opaque memory surface" },
93 {MFX_IOPATTERN_OUT_VIDEO_MEMORY, "output is video memory surface" },
94 {MFX_IOPATTERN_OUT_SYSTEM_MEMORY, "output is system memory surface" },
96 {MFX_IOPATTERN_OUT_OPAQUE_MEMORY, "output is opaque memory surface" },
100 int ff_qsv_print_iopattern(void *log_ctx, int mfx_iopattern,
101 const char *extra_string)
103 const char *desc = NULL;
105 for (int i = 0; i < FF_ARRAY_ELEMS(qsv_iopatterns); i++) {
106 if (qsv_iopatterns[i].mfx_iopattern == mfx_iopattern) {
107 desc = qsv_iopatterns[i].desc;
111 desc = "unknown iopattern";
113 av_log(log_ctx, AV_LOG_VERBOSE, "%s: %s\n", extra_string, desc);
117 static const struct {
122 { MFX_ERR_NONE, 0, "success" },
123 { MFX_ERR_UNKNOWN, AVERROR_UNKNOWN, "unknown error" },
124 { MFX_ERR_NULL_PTR, AVERROR(EINVAL), "NULL pointer" },
125 { MFX_ERR_UNSUPPORTED, AVERROR(ENOSYS), "unsupported" },
126 { MFX_ERR_MEMORY_ALLOC, AVERROR(ENOMEM), "failed to allocate memory" },
127 { MFX_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOMEM), "insufficient input/output buffer" },
128 { MFX_ERR_INVALID_HANDLE, AVERROR(EINVAL), "invalid handle" },
129 { MFX_ERR_LOCK_MEMORY, AVERROR(EIO), "failed to lock the memory block" },
130 { MFX_ERR_NOT_INITIALIZED, AVERROR_BUG, "not initialized" },
131 { MFX_ERR_NOT_FOUND, AVERROR(ENOSYS), "specified object was not found" },
132 /* the following 3 errors should always be handled explicitly, so those "mappings"
133 * are for completeness only */
134 { MFX_ERR_MORE_DATA, AVERROR_UNKNOWN, "expect more data at input" },
135 { MFX_ERR_MORE_SURFACE, AVERROR_UNKNOWN, "expect more surface at output" },
136 { MFX_ERR_MORE_BITSTREAM, AVERROR_UNKNOWN, "expect more bitstream at output" },
137 { MFX_ERR_ABORTED, AVERROR_UNKNOWN, "operation aborted" },
138 { MFX_ERR_DEVICE_LOST, AVERROR(EIO), "device lost" },
139 { MFX_ERR_INCOMPATIBLE_VIDEO_PARAM, AVERROR(EINVAL), "incompatible video parameters" },
140 { MFX_ERR_INVALID_VIDEO_PARAM, AVERROR(EINVAL), "invalid video parameters" },
141 { MFX_ERR_UNDEFINED_BEHAVIOR, AVERROR_BUG, "undefined behavior" },
142 { MFX_ERR_DEVICE_FAILED, AVERROR(EIO), "device failed" },
144 { MFX_ERR_INCOMPATIBLE_AUDIO_PARAM, AVERROR(EINVAL), "incompatible audio parameters" },
145 { MFX_ERR_INVALID_AUDIO_PARAM, AVERROR(EINVAL), "invalid audio parameters" },
147 { MFX_ERR_GPU_HANG, AVERROR(EIO), "GPU Hang" },
148 { MFX_ERR_REALLOC_SURFACE, AVERROR_UNKNOWN, "need bigger surface for output" },
150 { MFX_WRN_IN_EXECUTION, 0, "operation in execution" },
151 { MFX_WRN_DEVICE_BUSY, 0, "device busy" },
152 { MFX_WRN_VIDEO_PARAM_CHANGED, 0, "video parameters changed" },
153 { MFX_WRN_PARTIAL_ACCELERATION, 0, "partial acceleration" },
154 { MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, 0, "incompatible video parameters" },
155 { MFX_WRN_VALUE_NOT_CHANGED, 0, "value is saturated" },
156 { MFX_WRN_OUT_OF_RANGE, 0, "value out of range" },
157 { MFX_WRN_FILTER_SKIPPED, 0, "filter skipped" },
159 { MFX_WRN_INCOMPATIBLE_AUDIO_PARAM, 0, "incompatible audio parameters" },
162 #if QSV_VERSION_ATLEAST(1, 31)
163 { MFX_ERR_NONE_PARTIAL_OUTPUT, 0, "partial output" },
168 * Convert a libmfx error code into an FFmpeg error code.
170 static int qsv_map_error(mfxStatus mfx_err, const char **desc)
173 for (i = 0; i < FF_ARRAY_ELEMS(qsv_errors); i++) {
174 if (qsv_errors[i].mfxerr == mfx_err) {
176 *desc = qsv_errors[i].desc;
177 return qsv_errors[i].averr;
181 *desc = "unknown error";
182 return AVERROR_UNKNOWN;
185 int ff_qsv_print_error(void *log_ctx, mfxStatus err,
186 const char *error_string)
189 int ret = qsv_map_error(err, &desc);
190 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
194 int ff_qsv_print_warning(void *log_ctx, mfxStatus err,
195 const char *warning_string)
198 int ret = qsv_map_error(err, &desc);
199 av_log(log_ctx, AV_LOG_WARNING, "%s: %s (%d)\n", warning_string, desc, err);
203 enum AVPixelFormat ff_qsv_map_fourcc(uint32_t fourcc)
206 case MFX_FOURCC_NV12: return AV_PIX_FMT_NV12;
207 case MFX_FOURCC_P010: return AV_PIX_FMT_P010;
208 case MFX_FOURCC_P8: return AV_PIX_FMT_PAL8;
209 case MFX_FOURCC_A2RGB10: return AV_PIX_FMT_X2RGB10;
210 case MFX_FOURCC_RGB4: return AV_PIX_FMT_BGRA;
211 case MFX_FOURCC_YUY2: return AV_PIX_FMT_YUYV422;
212 case MFX_FOURCC_Y210: return AV_PIX_FMT_Y210;
213 case MFX_FOURCC_AYUV: return AV_PIX_FMT_VUYX;
214 case MFX_FOURCC_Y410: return AV_PIX_FMT_XV30;
215 #if QSV_VERSION_ATLEAST(1, 31)
216 case MFX_FOURCC_P016: return AV_PIX_FMT_P012;
217 case MFX_FOURCC_Y216: return AV_PIX_FMT_Y212;
218 case MFX_FOURCC_Y416: return AV_PIX_FMT_XV36;
221 return AV_PIX_FMT_NONE;
224 int ff_qsv_map_pixfmt(enum AVPixelFormat format, uint32_t *fourcc, uint16_t *shift)
227 case AV_PIX_FMT_YUV420P:
228 case AV_PIX_FMT_YUVJ420P:
229 case AV_PIX_FMT_NV12:
230 *fourcc = MFX_FOURCC_NV12;
232 return AV_PIX_FMT_NV12;
233 case AV_PIX_FMT_YUV420P10:
234 case AV_PIX_FMT_P010:
235 *fourcc = MFX_FOURCC_P010;
237 return AV_PIX_FMT_P010;
238 case AV_PIX_FMT_X2RGB10:
239 *fourcc = MFX_FOURCC_A2RGB10;
241 return AV_PIX_FMT_X2RGB10;
242 case AV_PIX_FMT_BGRA:
243 *fourcc = MFX_FOURCC_RGB4;
245 return AV_PIX_FMT_BGRA;
246 case AV_PIX_FMT_YUV422P:
247 case AV_PIX_FMT_YUYV422:
248 *fourcc = MFX_FOURCC_YUY2;
250 return AV_PIX_FMT_YUYV422;
251 case AV_PIX_FMT_YUV422P10:
252 case AV_PIX_FMT_Y210:
253 *fourcc = MFX_FOURCC_Y210;
255 return AV_PIX_FMT_Y210;
256 case AV_PIX_FMT_VUYX:
257 *fourcc = MFX_FOURCC_AYUV;
259 return AV_PIX_FMT_VUYX;
260 case AV_PIX_FMT_XV30:
261 *fourcc = MFX_FOURCC_Y410;
263 return AV_PIX_FMT_XV30;
264 #if QSV_VERSION_ATLEAST(1, 31)
265 case AV_PIX_FMT_P012:
266 *fourcc = MFX_FOURCC_P016;
268 return AV_PIX_FMT_P012;
269 case AV_PIX_FMT_Y212:
270 *fourcc = MFX_FOURCC_Y216;
272 return AV_PIX_FMT_Y212;
273 case AV_PIX_FMT_XV36:
274 *fourcc = MFX_FOURCC_Y416;
276 return AV_PIX_FMT_XV36;
279 return AVERROR(ENOSYS);
283 int ff_qsv_map_frame_to_surface(const AVFrame *frame, mfxFrameSurface1 *surface)
285 switch (frame->format) {
286 case AV_PIX_FMT_NV12:
287 case AV_PIX_FMT_P010:
288 case AV_PIX_FMT_P012:
289 surface->Data.Y = frame->data[0];
290 surface->Data.UV = frame->data[1];
291 /* The SDK checks Data.V when using system memory for VP9 encoding */
292 surface->Data.V = surface->Data.UV + 1;
294 case AV_PIX_FMT_X2RGB10LE:
295 case AV_PIX_FMT_BGRA:
296 surface->Data.B = frame->data[0];
297 surface->Data.G = frame->data[0] + 1;
298 surface->Data.R = frame->data[0] + 2;
299 surface->Data.A = frame->data[0] + 3;
301 case AV_PIX_FMT_YUYV422:
302 surface->Data.Y = frame->data[0];
303 surface->Data.U = frame->data[0] + 1;
304 surface->Data.V = frame->data[0] + 3;
307 case AV_PIX_FMT_Y210:
308 case AV_PIX_FMT_Y212:
309 surface->Data.Y16 = (mfxU16 *)frame->data[0];
310 surface->Data.U16 = (mfxU16 *)frame->data[0] + 1;
311 surface->Data.V16 = (mfxU16 *)frame->data[0] + 3;
314 case AV_PIX_FMT_VUYX:
315 surface->Data.V = frame->data[0];
316 surface->Data.U = frame->data[0] + 1;
317 surface->Data.Y = frame->data[0] + 2;
318 // Only set Data.A to a valid address, the SDK doesn't
319 // use the value from the frame.
320 surface->Data.A = frame->data[0] + 3;
323 case AV_PIX_FMT_XV30:
324 surface->Data.U = frame->data[0];
327 case AV_PIX_FMT_XV36:
328 surface->Data.U = frame->data[0];
329 surface->Data.Y = frame->data[0] + 2;
330 surface->Data.V = frame->data[0] + 4;
331 // Only set Data.A to a valid address, the SDK doesn't
332 // use the value from the frame.
333 surface->Data.A = frame->data[0] + 6;
337 return AVERROR(ENOSYS);
339 surface->Data.PitchLow = frame->linesize[0];
344 int ff_qsv_find_surface_idx(QSVFramesContext *ctx, QSVFrame *frame)
347 for (i = 0; i < ctx->nb_mids; i++) {
348 QSVMid *mid = &ctx->mids[i];
349 mfxHDLPair *pair = (mfxHDLPair*)frame->surface.Data.MemId;
350 if ((mid->handle_pair->first == pair->first) &&
351 (mid->handle_pair->second == pair->second))
357 enum AVFieldOrder ff_qsv_map_picstruct(int mfx_pic_struct)
359 enum AVFieldOrder field = AV_FIELD_UNKNOWN;
360 switch (mfx_pic_struct & 0xF) {
361 case MFX_PICSTRUCT_PROGRESSIVE:
362 field = AV_FIELD_PROGRESSIVE;
364 case MFX_PICSTRUCT_FIELD_TFF:
367 case MFX_PICSTRUCT_FIELD_BFF:
375 enum AVPictureType ff_qsv_map_pictype(int mfx_pic_type)
377 enum AVPictureType type;
378 switch (mfx_pic_type & 0x7) {
379 case MFX_FRAMETYPE_I:
380 if (mfx_pic_type & MFX_FRAMETYPE_S)
381 type = AV_PICTURE_TYPE_SI;
383 type = AV_PICTURE_TYPE_I;
385 case MFX_FRAMETYPE_B:
386 type = AV_PICTURE_TYPE_B;
388 case MFX_FRAMETYPE_P:
389 if (mfx_pic_type & MFX_FRAMETYPE_S)
390 type = AV_PICTURE_TYPE_SP;
392 type = AV_PICTURE_TYPE_P;
394 case MFX_FRAMETYPE_UNKNOWN:
395 type = AV_PICTURE_TYPE_NONE;
404 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
407 #if QSV_HAVE_USER_PLUGIN
408 if (!load_plugins || !*load_plugins)
411 while (*load_plugins) {
416 char *plugin = av_get_token(&load_plugins, ":");
418 return AVERROR(ENOMEM);
419 if (strlen(plugin) != 2 * sizeof(uid.Data)) {
420 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID length\n");
421 err = AVERROR(EINVAL);
422 goto load_plugin_fail;
425 for (i = 0; i < sizeof(uid.Data); i++) {
426 err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
428 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
429 err = AVERROR(EINVAL);
430 goto load_plugin_fail;
435 ret = MFXVideoUSER_Load(session, &uid, 1);
438 snprintf(errorbuf, sizeof(errorbuf),
439 "Could not load the requested plugin '%s'", plugin);
440 err = ff_qsv_print_error(logctx, ret, errorbuf);
441 goto load_plugin_fail;
457 //This code is only required for Linux since a display handle is required.
458 //For Windows the session is complete and ready to use.
460 #ifdef AVCODEC_QSV_LINUX_SESSION_HANDLE
461 static int ff_qsv_set_display_handle(AVCodecContext *avctx, QSVSession *qs)
463 AVDictionary *child_device_opts = NULL;
464 AVVAAPIDeviceContext *hwctx;
467 av_dict_set(&child_device_opts, "kernel_driver", "i915", 0);
468 av_dict_set(&child_device_opts, "driver", "iHD", 0);
470 ret = av_hwdevice_ctx_create(&qs->va_device_ref, AV_HWDEVICE_TYPE_VAAPI, NULL, child_device_opts, 0);
471 av_dict_free(&child_device_opts);
473 av_log(avctx, AV_LOG_ERROR, "Failed to create a VAAPI device.\n");
476 qs->va_device_ctx = (AVHWDeviceContext*)qs->va_device_ref->data;
477 hwctx = qs->va_device_ctx->hwctx;
479 ret = MFXVideoCORE_SetHandle(qs->session,
480 (mfxHandleType)MFX_HANDLE_VA_DISPLAY, (mfxHDL)hwctx->display);
482 return ff_qsv_print_error(avctx, ret, "Error during set display handle\n");
488 #endif //AVCODEC_QSV_LINUX_SESSION_HANDLE
491 static int qsv_new_mfx_loader(AVCodecContext *avctx,
492 mfxIMPL implementation,
497 mfxLoader loader = NULL;
499 mfxVariant impl_value;
503 av_log(avctx, AV_LOG_ERROR, "Error creating a MFX loader\n");
507 /* Create configurations for implementation */
508 cfg = MFXCreateConfig(loader);
510 av_log(avctx, AV_LOG_ERROR, "Error creating a MFX configurations\n");
514 impl_value.Type = MFX_VARIANT_TYPE_U32;
515 impl_value.Data.U32 = (implementation == MFX_IMPL_SOFTWARE) ?
516 MFX_IMPL_TYPE_SOFTWARE : MFX_IMPL_TYPE_HARDWARE;
517 sts = MFXSetConfigFilterProperty(cfg,
518 (const mfxU8 *)"mfxImplDescription.Impl", impl_value);
519 if (sts != MFX_ERR_NONE) {
520 av_log(avctx, AV_LOG_ERROR, "Error adding a MFX configuration "
521 "property: %d\n", sts);
525 impl_value.Type = MFX_VARIANT_TYPE_U32;
526 impl_value.Data.U32 = pver->Version;
527 sts = MFXSetConfigFilterProperty(cfg,
528 (const mfxU8 *)"mfxImplDescription.ApiVersion.Version",
530 if (sts != MFX_ERR_NONE) {
531 av_log(avctx, AV_LOG_ERROR, "Error adding a MFX configuration "
532 "property: %d\n", sts);
545 return AVERROR_UNKNOWN;
548 static int qsv_create_mfx_session_from_loader(void *ctx, mfxLoader loader, mfxSession *psession)
551 mfxSession session = NULL;
552 uint32_t impl_idx = 0;
555 /* Enumerate all implementations */
556 mfxImplDescription *impl_desc;
558 sts = MFXEnumImplementations(loader, impl_idx,
559 MFX_IMPLCAPS_IMPLDESCSTRUCTURE,
560 (mfxHDL *)&impl_desc);
561 /* Failed to find an available implementation */
562 if (sts == MFX_ERR_NOT_FOUND)
564 else if (sts != MFX_ERR_NONE) {
569 sts = MFXCreateSession(loader, impl_idx, &session);
570 MFXDispReleaseImplDescription(loader, impl_desc);
571 if (sts == MFX_ERR_NONE)
577 if (sts != MFX_ERR_NONE) {
578 av_log(ctx, AV_LOG_ERROR, "Error creating a MFX session: %d.\n", sts);
591 return AVERROR_UNKNOWN;
594 static int qsv_create_mfx_session(AVCodecContext *avctx,
595 mfxIMPL implementation,
598 mfxSession *psession,
601 mfxLoader loader = NULL;
603 /* Don't create a new MFX loader if the input loader is valid */
604 if (*ploader == NULL) {
605 av_log(avctx, AV_LOG_VERBOSE,
606 "Use Intel(R) oneVPL to create MFX session, the required "
607 "implementation version is %d.%d\n",
608 pver->Major, pver->Minor);
610 if (qsv_new_mfx_loader(avctx, implementation, pver, (void **)&loader))
615 av_log(avctx, AV_LOG_VERBOSE,
616 "Use Intel(R) oneVPL to create MFX session with the specified MFX loader\n");
621 if (qsv_create_mfx_session_from_loader(avctx, loader, psession))
630 if (!*ploader && loader)
633 return AVERROR_UNKNOWN;
638 static int qsv_create_mfx_session(AVCodecContext *avctx,
639 mfxIMPL implementation,
642 mfxSession *psession,
645 mfxInitParam init_par = { MFX_IMPL_AUTO_ANY };
646 mfxSession session = NULL;
649 av_log(avctx, AV_LOG_VERBOSE,
650 "Use Intel(R) Media SDK to create MFX session, the required "
651 "implementation version is %d.%d\n",
652 pver->Major, pver->Minor);
657 init_par.GPUCopy = gpu_copy;
658 init_par.Implementation = implementation;
659 init_par.Version = *pver;
660 sts = MFXInitEx(init_par, &session);
662 return ff_qsv_print_error(avctx, sts,
663 "Error initializing a MFX session");
665 ff_qsv_print_warning(avctx, sts,
666 "Warning in MFX initialization");
667 return AVERROR_UNKNOWN;
677 int ff_qsv_init_internal_session(AVCodecContext *avctx, QSVSession *qs,
678 const char *load_plugins, int gpu_copy)
682 MFX_IMPL_AUTO_ANY | MFX_IMPL_VIA_D3D11,
687 mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
692 for (int i = 0; i < FF_ARRAY_ELEMS(impls); i++) {
693 ret = qsv_create_mfx_session(avctx, impls[i], &ver, gpu_copy, &qs->session,
699 if (i == FF_ARRAY_ELEMS(impls) - 1)
702 av_log(avctx, AV_LOG_ERROR, "The current mfx implementation is not "
703 "supported, try next mfx implementation.\n");
706 #ifdef AVCODEC_QSV_LINUX_SESSION_HANDLE
707 ret = ff_qsv_set_display_handle(avctx, qs);
712 ret = qsv_load_plugins(qs->session, load_plugins, avctx);
714 av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
718 ret = MFXQueryIMPL(qs->session, &impl);
719 if (ret != MFX_ERR_NONE)
720 return ff_qsv_print_error(avctx, ret,
721 "Error querying the session attributes");
723 switch (MFX_IMPL_BASETYPE(impl)) {
724 case MFX_IMPL_SOFTWARE:
727 case MFX_IMPL_HARDWARE:
728 case MFX_IMPL_HARDWARE2:
729 case MFX_IMPL_HARDWARE3:
730 case MFX_IMPL_HARDWARE4:
731 desc = "hardware accelerated";
737 av_log(avctx, AV_LOG_VERBOSE,
738 "Initialized an internal MFX session using %s implementation\n",
744 static void mids_buf_free(void *opaque, uint8_t *data)
746 AVBufferRef *hw_frames_ref = opaque;
747 av_buffer_unref(&hw_frames_ref);
751 static AVBufferRef *qsv_create_mids(AVBufferRef *hw_frames_ref)
753 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
754 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
755 int nb_surfaces = frames_hwctx->nb_surfaces;
757 AVBufferRef *mids_buf, *hw_frames_ref1;
761 hw_frames_ref1 = av_buffer_ref(hw_frames_ref);
765 mids = av_calloc(nb_surfaces, sizeof(*mids));
767 av_buffer_unref(&hw_frames_ref1);
771 mids_buf = av_buffer_create((uint8_t*)mids, nb_surfaces * sizeof(*mids),
772 mids_buf_free, hw_frames_ref1, 0);
774 av_buffer_unref(&hw_frames_ref1);
779 for (i = 0; i < nb_surfaces; i++) {
780 QSVMid *mid = &mids[i];
781 mid->handle_pair = (mfxHDLPair*)frames_hwctx->surfaces[i].Data.MemId;
782 mid->hw_frames_ref = hw_frames_ref1;
788 static int qsv_setup_mids(mfxFrameAllocResponse *resp, AVBufferRef *hw_frames_ref,
789 AVBufferRef *mids_buf)
791 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
792 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
793 QSVMid *mids = (QSVMid*)mids_buf->data;
794 int nb_surfaces = frames_hwctx->nb_surfaces;
797 // the allocated size of the array is two larger than the number of
798 // surfaces, we store the references to the frames context and the
799 // QSVMid array there
800 resp->mids = av_calloc(nb_surfaces + 2, sizeof(*resp->mids));
802 return AVERROR(ENOMEM);
804 for (i = 0; i < nb_surfaces; i++)
805 resp->mids[i] = &mids[i];
806 resp->NumFrameActual = nb_surfaces;
808 resp->mids[resp->NumFrameActual] = (mfxMemId)av_buffer_ref(hw_frames_ref);
809 if (!resp->mids[resp->NumFrameActual]) {
810 av_freep(&resp->mids);
811 return AVERROR(ENOMEM);
814 resp->mids[resp->NumFrameActual + 1] = av_buffer_ref(mids_buf);
815 if (!resp->mids[resp->NumFrameActual + 1]) {
816 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
817 av_freep(&resp->mids);
818 return AVERROR(ENOMEM);
824 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
825 mfxFrameAllocResponse *resp)
827 QSVFramesContext *ctx = pthis;
830 /* this should only be called from an encoder or decoder and
831 * only allocates video memory frames */
832 if (!(req->Type & (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET |
833 MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET)) ||
834 !(req->Type & (MFX_MEMTYPE_FROM_DECODE | MFX_MEMTYPE_FROM_ENCODE)))
835 return MFX_ERR_UNSUPPORTED;
837 if (req->Type & MFX_MEMTYPE_EXTERNAL_FRAME) {
838 /* external frames -- fill from the caller-supplied frames context */
839 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
840 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
841 mfxFrameInfo *i = &req->Info;
842 mfxFrameInfo *i1 = &frames_hwctx->surfaces[0].Info;
844 if (i->Width > i1->Width || i->Height > i1->Height ||
845 i->FourCC != i1->FourCC || i->ChromaFormat != i1->ChromaFormat) {
846 av_log(ctx->logctx, AV_LOG_ERROR, "Mismatching surface properties in an "
847 "allocation request: %dx%d %d %d vs %dx%d %d %d\n",
848 i->Width, i->Height, i->FourCC, i->ChromaFormat,
849 i1->Width, i1->Height, i1->FourCC, i1->ChromaFormat);
850 return MFX_ERR_UNSUPPORTED;
853 ret = qsv_setup_mids(resp, ctx->hw_frames_ctx, ctx->mids_buf);
855 av_log(ctx->logctx, AV_LOG_ERROR,
856 "Error filling an external frame allocation request\n");
857 return MFX_ERR_MEMORY_ALLOC;
859 } else if (req->Type & MFX_MEMTYPE_INTERNAL_FRAME) {
860 /* internal frames -- allocate a new hw frames context */
861 AVHWFramesContext *ext_frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
862 mfxFrameInfo *i = &req->Info;
864 AVBufferRef *frames_ref, *mids_buf;
865 AVHWFramesContext *frames_ctx;
866 AVQSVFramesContext *frames_hwctx;
868 frames_ref = av_hwframe_ctx_alloc(ext_frames_ctx->device_ref);
870 return MFX_ERR_MEMORY_ALLOC;
872 frames_ctx = (AVHWFramesContext*)frames_ref->data;
873 frames_hwctx = frames_ctx->hwctx;
875 frames_ctx->format = AV_PIX_FMT_QSV;
876 frames_ctx->sw_format = ff_qsv_map_fourcc(i->FourCC);
877 frames_ctx->width = i->Width;
878 frames_ctx->height = i->Height;
879 frames_ctx->initial_pool_size = req->NumFrameSuggested;
881 frames_hwctx->frame_type = req->Type;
883 ret = av_hwframe_ctx_init(frames_ref);
885 av_log(ctx->logctx, AV_LOG_ERROR,
886 "Error initializing a frames context for an internal frame "
887 "allocation request\n");
888 av_buffer_unref(&frames_ref);
889 return MFX_ERR_MEMORY_ALLOC;
892 mids_buf = qsv_create_mids(frames_ref);
894 av_buffer_unref(&frames_ref);
895 return MFX_ERR_MEMORY_ALLOC;
898 ret = qsv_setup_mids(resp, frames_ref, mids_buf);
899 av_buffer_unref(&mids_buf);
900 av_buffer_unref(&frames_ref);
902 av_log(ctx->logctx, AV_LOG_ERROR,
903 "Error filling an internal frame allocation request\n");
904 return MFX_ERR_MEMORY_ALLOC;
907 return MFX_ERR_UNSUPPORTED;
913 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
915 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
916 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual + 1]);
917 av_freep(&resp->mids);
921 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
923 QSVMid *qsv_mid = mid;
924 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)qsv_mid->hw_frames_ref->data;
925 AVQSVFramesContext *hw_frames_hwctx = hw_frames_ctx->hwctx;
928 if (qsv_mid->locked_frame)
929 return MFX_ERR_UNDEFINED_BEHAVIOR;
931 /* Allocate a system memory frame that will hold the mapped data. */
932 qsv_mid->locked_frame = av_frame_alloc();
933 if (!qsv_mid->locked_frame)
934 return MFX_ERR_MEMORY_ALLOC;
935 qsv_mid->locked_frame->format = hw_frames_ctx->sw_format;
937 /* wrap the provided handle in a hwaccel AVFrame */
938 qsv_mid->hw_frame = av_frame_alloc();
939 if (!qsv_mid->hw_frame)
942 qsv_mid->hw_frame->data[3] = (uint8_t*)&qsv_mid->surf;
943 qsv_mid->hw_frame->format = AV_PIX_FMT_QSV;
945 // doesn't really matter what buffer is used here
946 qsv_mid->hw_frame->buf[0] = av_buffer_alloc(1);
947 if (!qsv_mid->hw_frame->buf[0])
950 qsv_mid->hw_frame->width = hw_frames_ctx->width;
951 qsv_mid->hw_frame->height = hw_frames_ctx->height;
953 qsv_mid->hw_frame->hw_frames_ctx = av_buffer_ref(qsv_mid->hw_frames_ref);
954 if (!qsv_mid->hw_frame->hw_frames_ctx)
957 qsv_mid->surf.Info = hw_frames_hwctx->surfaces[0].Info;
958 qsv_mid->surf.Data.MemId = qsv_mid->handle_pair;
960 /* map the data to the system memory */
961 ret = av_hwframe_map(qsv_mid->locked_frame, qsv_mid->hw_frame,
962 AV_HWFRAME_MAP_DIRECT);
966 ptr->Pitch = qsv_mid->locked_frame->linesize[0];
967 ptr->Y = qsv_mid->locked_frame->data[0];
968 ptr->U = qsv_mid->locked_frame->data[1];
969 ptr->V = qsv_mid->locked_frame->data[1] + 1;
973 av_frame_free(&qsv_mid->hw_frame);
974 av_frame_free(&qsv_mid->locked_frame);
975 return MFX_ERR_MEMORY_ALLOC;
978 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
980 QSVMid *qsv_mid = mid;
982 av_frame_free(&qsv_mid->locked_frame);
983 av_frame_free(&qsv_mid->hw_frame);
988 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
990 QSVMid *qsv_mid = (QSVMid*)mid;
991 mfxHDLPair *pair_dst = (mfxHDLPair*)hdl;
992 mfxHDLPair *pair_src = (mfxHDLPair*)qsv_mid->handle_pair;
994 pair_dst->first = pair_src->first;
996 if (pair_src->second != (mfxMemId)MFX_INFINITE)
997 pair_dst->second = pair_src->second;
1001 int ff_qsv_init_session_device(AVCodecContext *avctx, mfxSession *psession,
1002 AVBufferRef *device_ref, const char *load_plugins,
1005 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)device_ref->data;
1006 AVQSVDeviceContext *device_hwctx = device_ctx->hwctx;
1007 mfxSession parent_session = device_hwctx->session;
1008 void *loader = device_hwctx->loader;
1009 mfxHDL handle = NULL;
1010 int hw_handle_supported = 0;
1015 mfxHandleType handle_type;
1019 err = MFXQueryIMPL(parent_session, &impl);
1020 if (err == MFX_ERR_NONE)
1021 err = MFXQueryVersion(parent_session, &ver);
1022 if (err != MFX_ERR_NONE)
1023 return ff_qsv_print_error(avctx, err,
1024 "Error querying the session attributes");
1026 if (MFX_IMPL_VIA_VAAPI == MFX_IMPL_VIA_MASK(impl)) {
1027 handle_type = MFX_HANDLE_VA_DISPLAY;
1028 hw_handle_supported = 1;
1029 } else if (MFX_IMPL_VIA_D3D11 == MFX_IMPL_VIA_MASK(impl)) {
1030 handle_type = MFX_HANDLE_D3D11_DEVICE;
1031 hw_handle_supported = 1;
1032 } else if (MFX_IMPL_VIA_D3D9 == MFX_IMPL_VIA_MASK(impl)) {
1033 handle_type = MFX_HANDLE_D3D9_DEVICE_MANAGER;
1034 hw_handle_supported = 1;
1037 if (hw_handle_supported) {
1038 err = MFXVideoCORE_GetHandle(parent_session, handle_type, &handle);
1039 if (err != MFX_ERR_NONE) {
1040 return ff_qsv_print_error(avctx, err,
1041 "Error getting handle session");
1045 av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
1046 "from the session\n");
1049 ret = qsv_create_mfx_session(avctx, impl, &ver, gpu_copy, &session,
1055 err = MFXVideoCORE_SetHandle(session, handle_type, handle);
1056 if (err != MFX_ERR_NONE)
1057 return ff_qsv_print_error(avctx, err,
1058 "Error setting a HW handle");
1061 if (QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 25)) {
1062 err = MFXJoinSession(parent_session, session);
1063 if (err != MFX_ERR_NONE)
1064 return ff_qsv_print_error(avctx, err,
1065 "Error joining session");
1068 ret = qsv_load_plugins(session, load_plugins, avctx);
1070 av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
1074 *psession = session;
1078 int ff_qsv_init_session_frames(AVCodecContext *avctx, mfxSession *psession,
1079 QSVFramesContext *qsv_frames_ctx,
1080 const char *load_plugins, int opaque, int gpu_copy)
1082 mfxFrameAllocator frame_allocator = {
1083 .pthis = qsv_frames_ctx,
1084 .Alloc = qsv_frame_alloc,
1085 .Lock = qsv_frame_lock,
1086 .Unlock = qsv_frame_unlock,
1087 .GetHDL = qsv_frame_get_hdl,
1088 .Free = qsv_frame_free,
1091 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)qsv_frames_ctx->hw_frames_ctx->data;
1092 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
1099 ret = ff_qsv_init_session_device(avctx, &session,
1100 frames_ctx->device_ref, load_plugins, gpu_copy);
1105 qsv_frames_ctx->logctx = avctx;
1107 /* allocate the memory ids for the external frames */
1108 av_buffer_unref(&qsv_frames_ctx->mids_buf);
1109 qsv_frames_ctx->mids_buf = qsv_create_mids(qsv_frames_ctx->hw_frames_ctx);
1110 if (!qsv_frames_ctx->mids_buf)
1111 return AVERROR(ENOMEM);
1112 qsv_frames_ctx->mids = (QSVMid*)qsv_frames_ctx->mids_buf->data;
1113 qsv_frames_ctx->nb_mids = frames_hwctx->nb_surfaces;
1115 err = MFXVideoCORE_SetFrameAllocator(session, &frame_allocator);
1116 if (err != MFX_ERR_NONE)
1117 return ff_qsv_print_error(avctx, err,
1118 "Error setting a frame allocator");
1121 *psession = session;
1125 int ff_qsv_close_internal_session(QSVSession *qs)
1128 MFXClose(qs->session);
1133 MFXUnload(qs->loader);
1137 #ifdef AVCODEC_QSV_LINUX_SESSION_HANDLE
1138 av_buffer_unref(&qs->va_device_ref);
1143 void ff_qsv_frame_add_ext_param (AVCodecContext *avctx, QSVFrame *frame,
1144 mfxExtBuffer * param)
1148 for (i = 0; i < frame->num_ext_params; i++) {
1149 mfxExtBuffer *ext_buffer = frame->ext_param[i];
1151 if (ext_buffer->BufferId == param->BufferId) {
1152 av_log(avctx, AV_LOG_WARNING, "A buffer with the same type has been "
1158 if (frame->num_ext_params < QSV_MAX_FRAME_EXT_PARAMS) {
1159 frame->ext_param[frame->num_ext_params] = param;
1160 frame->num_ext_params++;
1161 frame->surface.Data.NumExtParam = frame->num_ext_params;
1163 av_log(avctx, AV_LOG_WARNING, "Ignore this extra buffer because do not "
1164 "have enough space\n");