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
21 #include <mfx/mfxvideo.h>
22 #include <mfx/mfxplugin.h>
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"
35 #include "qsv_internal.h"
37 int ff_qsv_codec_id_to_mfx(enum AVCodecID codec_id)
40 case AV_CODEC_ID_H264:
42 #if QSV_VERSION_ATLEAST(1, 8)
43 case AV_CODEC_ID_HEVC:
44 return MFX_CODEC_HEVC;
46 case AV_CODEC_ID_MPEG1VIDEO:
47 case AV_CODEC_ID_MPEG2VIDEO:
48 return MFX_CODEC_MPEG2;
55 return AVERROR(ENOSYS);
58 int ff_qsv_profile_to_mfx(enum AVCodecID codec_id, int profile)
60 if (profile == FF_PROFILE_UNKNOWN)
61 return MFX_PROFILE_UNKNOWN;
63 case AV_CODEC_ID_H264:
64 case AV_CODEC_ID_HEVC:
67 return 4 * profile + 1;
68 case AV_CODEC_ID_MPEG2VIDEO:
69 return 0x10 * profile;
71 return MFX_PROFILE_UNKNOWN;
79 { MFX_ERR_NONE, 0, "success" },
80 { MFX_ERR_UNKNOWN, AVERROR_UNKNOWN, "unknown error" },
81 { MFX_ERR_NULL_PTR, AVERROR(EINVAL), "NULL pointer" },
82 { MFX_ERR_UNSUPPORTED, AVERROR(ENOSYS), "unsupported" },
83 { MFX_ERR_MEMORY_ALLOC, AVERROR(ENOMEM), "failed to allocate memory" },
84 { MFX_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOMEM), "insufficient input/output buffer" },
85 { MFX_ERR_INVALID_HANDLE, AVERROR(EINVAL), "invalid handle" },
86 { MFX_ERR_LOCK_MEMORY, AVERROR(EIO), "failed to lock the memory block" },
87 { MFX_ERR_NOT_INITIALIZED, AVERROR_BUG, "not initialized" },
88 { MFX_ERR_NOT_FOUND, AVERROR(ENOSYS), "specified object was not found" },
89 { MFX_ERR_MORE_DATA, AVERROR(EAGAIN), "expect more data at input" },
90 { MFX_ERR_MORE_SURFACE, AVERROR(EAGAIN), "expect more surface at output" },
91 { MFX_ERR_ABORTED, AVERROR_UNKNOWN, "operation aborted" },
92 { MFX_ERR_DEVICE_LOST, AVERROR(EIO), "device lost" },
93 { MFX_ERR_INCOMPATIBLE_VIDEO_PARAM, AVERROR(EINVAL), "incompatible video parameters" },
94 { MFX_ERR_INVALID_VIDEO_PARAM, AVERROR(EINVAL), "invalid video parameters" },
95 { MFX_ERR_UNDEFINED_BEHAVIOR, AVERROR_BUG, "undefined behavior" },
96 { MFX_ERR_DEVICE_FAILED, AVERROR(EIO), "device failed" },
97 { MFX_ERR_MORE_BITSTREAM, AVERROR(EAGAIN), "expect more bitstream at output" },
98 { MFX_ERR_INCOMPATIBLE_AUDIO_PARAM, AVERROR(EINVAL), "incompatible audio parameters" },
99 { MFX_ERR_INVALID_AUDIO_PARAM, AVERROR(EINVAL), "invalid audio parameters" },
101 { MFX_WRN_IN_EXECUTION, 0, "operation in execution" },
102 { MFX_WRN_DEVICE_BUSY, 0, "device busy" },
103 { MFX_WRN_VIDEO_PARAM_CHANGED, 0, "video parameters changed" },
104 { MFX_WRN_PARTIAL_ACCELERATION, 0, "partial acceleration" },
105 { MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, 0, "incompatible video parameters" },
106 { MFX_WRN_VALUE_NOT_CHANGED, 0, "value is saturated" },
107 { MFX_WRN_OUT_OF_RANGE, 0, "value out of range" },
108 { MFX_WRN_FILTER_SKIPPED, 0, "filter skipped" },
109 { MFX_WRN_INCOMPATIBLE_AUDIO_PARAM, 0, "incompatible audio parameters" },
112 int ff_qsv_map_error(mfxStatus mfx_err, const char **desc)
115 for (i = 0; i < FF_ARRAY_ELEMS(qsv_errors); i++) {
116 if (qsv_errors[i].mfxerr == mfx_err) {
118 *desc = qsv_errors[i].desc;
119 return qsv_errors[i].averr;
123 *desc = "unknown error";
124 return AVERROR_UNKNOWN;
127 int ff_qsv_print_error(void *log_ctx, mfxStatus err,
128 const char *error_string)
132 ret = ff_qsv_map_error(err, &desc);
133 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
137 int ff_qsv_print_warning(void *log_ctx, mfxStatus err,
138 const char *warning_string)
142 ret = ff_qsv_map_error(err, &desc);
143 av_log(log_ctx, AV_LOG_WARNING, "%s: %s (%d)\n", warning_string, desc, err);
147 static enum AVPixelFormat qsv_map_fourcc(uint32_t fourcc)
150 case MFX_FOURCC_NV12: return AV_PIX_FMT_NV12;
151 case MFX_FOURCC_P010: return AV_PIX_FMT_P010;
152 case MFX_FOURCC_P8: return AV_PIX_FMT_PAL8;
154 return AV_PIX_FMT_NONE;
157 int ff_qsv_map_pixfmt(enum AVPixelFormat format, uint32_t *fourcc)
160 case AV_PIX_FMT_YUV420P:
161 case AV_PIX_FMT_YUVJ420P:
162 case AV_PIX_FMT_NV12:
163 *fourcc = MFX_FOURCC_NV12;
164 return AV_PIX_FMT_NV12;
165 case AV_PIX_FMT_YUV420P10:
166 case AV_PIX_FMT_P010:
167 *fourcc = MFX_FOURCC_P010;
168 return AV_PIX_FMT_P010;
170 return AVERROR(ENOSYS);
174 int ff_qsv_find_surface_idx(QSVFramesContext *ctx, QSVFrame *frame)
177 for (i = 0; i < ctx->nb_mids; i++) {
178 QSVMid *mid = &ctx->mids[i];
179 if (mid->handle == frame->surface.Data.MemId)
185 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
188 if (!load_plugins || !*load_plugins)
191 while (*load_plugins) {
196 char *plugin = av_get_token(&load_plugins, ":");
198 return AVERROR(ENOMEM);
199 if (strlen(plugin) != 2 * sizeof(uid.Data)) {
200 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID length\n");
201 err = AVERROR(EINVAL);
202 goto load_plugin_fail;
205 for (i = 0; i < sizeof(uid.Data); i++) {
206 err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
208 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
209 err = AVERROR(EINVAL);
210 goto load_plugin_fail;
215 ret = MFXVideoUSER_Load(session, &uid, 1);
218 snprintf(errorbuf, sizeof(errorbuf),
219 "Could not load the requested plugin '%s'", plugin);
220 err = ff_qsv_print_error(logctx, ret, errorbuf);
221 goto load_plugin_fail;
236 int ff_qsv_init_internal_session(AVCodecContext *avctx, mfxSession *session,
237 const char *load_plugins)
239 mfxIMPL impl = MFX_IMPL_AUTO_ANY;
240 mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
245 ret = MFXInit(impl, &ver, session);
247 return ff_qsv_print_error(avctx, ret,
248 "Error initializing an internal MFX session");
250 ret = qsv_load_plugins(*session, load_plugins, avctx);
252 av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
256 MFXQueryIMPL(*session, &impl);
258 switch (MFX_IMPL_BASETYPE(impl)) {
259 case MFX_IMPL_SOFTWARE:
262 case MFX_IMPL_HARDWARE:
263 case MFX_IMPL_HARDWARE2:
264 case MFX_IMPL_HARDWARE3:
265 case MFX_IMPL_HARDWARE4:
266 desc = "hardware accelerated";
272 av_log(avctx, AV_LOG_VERBOSE,
273 "Initialized an internal MFX session using %s implementation\n",
279 static void mids_buf_free(void *opaque, uint8_t *data)
281 AVBufferRef *hw_frames_ref = opaque;
282 av_buffer_unref(&hw_frames_ref);
286 static AVBufferRef *qsv_create_mids(AVBufferRef *hw_frames_ref)
288 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
289 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
290 int nb_surfaces = frames_hwctx->nb_surfaces;
292 AVBufferRef *mids_buf, *hw_frames_ref1;
296 hw_frames_ref1 = av_buffer_ref(hw_frames_ref);
300 mids = av_mallocz_array(nb_surfaces, sizeof(*mids));
302 av_buffer_unref(&hw_frames_ref1);
306 mids_buf = av_buffer_create((uint8_t*)mids, nb_surfaces * sizeof(*mids),
307 mids_buf_free, hw_frames_ref1, 0);
309 av_buffer_unref(&hw_frames_ref1);
314 for (i = 0; i < nb_surfaces; i++) {
315 QSVMid *mid = &mids[i];
316 mid->handle = frames_hwctx->surfaces[i].Data.MemId;
317 mid->hw_frames_ref = hw_frames_ref1;
323 static int qsv_setup_mids(mfxFrameAllocResponse *resp, AVBufferRef *hw_frames_ref,
324 AVBufferRef *mids_buf)
326 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
327 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
328 QSVMid *mids = (QSVMid*)mids_buf->data;
329 int nb_surfaces = frames_hwctx->nb_surfaces;
332 // the allocated size of the array is two larger than the number of
333 // surfaces, we store the references to the frames context and the
334 // QSVMid array there
335 resp->mids = av_mallocz_array(nb_surfaces + 2, sizeof(*resp->mids));
337 return AVERROR(ENOMEM);
339 for (i = 0; i < nb_surfaces; i++)
340 resp->mids[i] = &mids[i];
341 resp->NumFrameActual = nb_surfaces;
343 resp->mids[resp->NumFrameActual] = (mfxMemId)av_buffer_ref(hw_frames_ref);
344 if (!resp->mids[resp->NumFrameActual]) {
345 av_freep(&resp->mids);
346 return AVERROR(ENOMEM);
349 resp->mids[resp->NumFrameActual + 1] = av_buffer_ref(mids_buf);
350 if (!resp->mids[resp->NumFrameActual + 1]) {
351 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
352 av_freep(&resp->mids);
353 return AVERROR(ENOMEM);
359 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
360 mfxFrameAllocResponse *resp)
362 QSVFramesContext *ctx = pthis;
365 /* this should only be called from an encoder or decoder and
366 * only allocates video memory frames */
367 if (!(req->Type & (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET |
368 MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET)) ||
369 !(req->Type & (MFX_MEMTYPE_FROM_DECODE | MFX_MEMTYPE_FROM_ENCODE)))
370 return MFX_ERR_UNSUPPORTED;
372 if (req->Type & MFX_MEMTYPE_EXTERNAL_FRAME) {
373 /* external frames -- fill from the caller-supplied frames context */
374 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
375 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
376 mfxFrameInfo *i = &req->Info;
377 mfxFrameInfo *i1 = &frames_hwctx->surfaces[0].Info;
379 if (i->Width != i1->Width || i->Height != i1->Height ||
380 i->FourCC != i1->FourCC || i->ChromaFormat != i1->ChromaFormat) {
381 av_log(ctx->logctx, AV_LOG_ERROR, "Mismatching surface properties in an "
382 "allocation request: %dx%d %d %d vs %dx%d %d %d\n",
383 i->Width, i->Height, i->FourCC, i->ChromaFormat,
384 i1->Width, i1->Height, i1->FourCC, i1->ChromaFormat);
385 return MFX_ERR_UNSUPPORTED;
388 ret = qsv_setup_mids(resp, ctx->hw_frames_ctx, ctx->mids_buf);
390 av_log(ctx->logctx, AV_LOG_ERROR,
391 "Error filling an external frame allocation request\n");
392 return MFX_ERR_MEMORY_ALLOC;
394 } else if (req->Type & MFX_MEMTYPE_INTERNAL_FRAME) {
395 /* internal frames -- allocate a new hw frames context */
396 AVHWFramesContext *ext_frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
397 mfxFrameInfo *i = &req->Info;
399 AVBufferRef *frames_ref, *mids_buf;
400 AVHWFramesContext *frames_ctx;
401 AVQSVFramesContext *frames_hwctx;
403 frames_ref = av_hwframe_ctx_alloc(ext_frames_ctx->device_ref);
405 return MFX_ERR_MEMORY_ALLOC;
407 frames_ctx = (AVHWFramesContext*)frames_ref->data;
408 frames_hwctx = frames_ctx->hwctx;
410 frames_ctx->format = AV_PIX_FMT_QSV;
411 frames_ctx->sw_format = qsv_map_fourcc(i->FourCC);
412 frames_ctx->width = i->Width;
413 frames_ctx->height = i->Height;
414 frames_ctx->initial_pool_size = req->NumFrameSuggested;
416 frames_hwctx->frame_type = req->Type;
418 ret = av_hwframe_ctx_init(frames_ref);
420 av_log(ctx->logctx, AV_LOG_ERROR,
421 "Error initializing a frames context for an internal frame "
422 "allocation request\n");
423 av_buffer_unref(&frames_ref);
424 return MFX_ERR_MEMORY_ALLOC;
427 mids_buf = qsv_create_mids(frames_ref);
429 av_buffer_unref(&frames_ref);
430 return MFX_ERR_MEMORY_ALLOC;
433 ret = qsv_setup_mids(resp, frames_ref, mids_buf);
434 av_buffer_unref(&mids_buf);
435 av_buffer_unref(&frames_ref);
437 av_log(ctx->logctx, AV_LOG_ERROR,
438 "Error filling an internal frame allocation request\n");
439 return MFX_ERR_MEMORY_ALLOC;
442 return MFX_ERR_UNSUPPORTED;
448 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
450 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
451 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual + 1]);
452 av_freep(&resp->mids);
456 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
458 QSVMid *qsv_mid = mid;
459 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)qsv_mid->hw_frames_ref->data;
460 AVQSVFramesContext *hw_frames_hwctx = hw_frames_ctx->hwctx;
465 if (qsv_mid->locked_frame)
466 return MFX_ERR_UNDEFINED_BEHAVIOR;
468 /* Allocate a system memory frame that will hold the mapped data. */
469 qsv_mid->locked_frame = av_frame_alloc();
470 if (!qsv_mid->locked_frame)
471 return MFX_ERR_MEMORY_ALLOC;
472 qsv_mid->locked_frame->format = hw_frames_ctx->sw_format;
474 /* wrap the provided handle in a hwaccel AVFrame */
475 qsv_mid->hw_frame = av_frame_alloc();
476 if (!qsv_mid->hw_frame)
479 qsv_mid->hw_frame->data[3] = (uint8_t*)&qsv_mid->surf;
480 qsv_mid->hw_frame->format = AV_PIX_FMT_QSV;
482 // doesn't really matter what buffer is used here
483 qsv_mid->hw_frame->buf[0] = av_buffer_alloc(1);
484 if (!qsv_mid->hw_frame->buf[0])
487 qsv_mid->hw_frame->width = hw_frames_ctx->width;
488 qsv_mid->hw_frame->height = hw_frames_ctx->height;
490 qsv_mid->hw_frame->hw_frames_ctx = av_buffer_ref(qsv_mid->hw_frames_ref);
491 if (!qsv_mid->hw_frame->hw_frames_ctx)
494 qsv_mid->surf.Info = hw_frames_hwctx->surfaces[0].Info;
495 qsv_mid->surf.Data.MemId = qsv_mid->handle;
497 /* map the data to the system memory */
498 ret = av_hwframe_map(qsv_mid->locked_frame, qsv_mid->hw_frame,
499 AV_HWFRAME_MAP_DIRECT);
503 ptr->Pitch = qsv_mid->locked_frame->linesize[0];
504 ptr->Y = qsv_mid->locked_frame->data[0];
505 ptr->U = qsv_mid->locked_frame->data[1];
506 ptr->V = qsv_mid->locked_frame->data[1] + 1;
510 av_frame_free(&qsv_mid->hw_frame);
511 av_frame_free(&qsv_mid->locked_frame);
512 return MFX_ERR_MEMORY_ALLOC;
515 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
517 QSVMid *qsv_mid = mid;
520 av_frame_free(&qsv_mid->locked_frame);
521 av_frame_free(&qsv_mid->hw_frame);
526 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
528 QSVMid *qsv_mid = (QSVMid*)mid;
529 *hdl = qsv_mid->handle;
533 int ff_qsv_init_session_hwcontext(AVCodecContext *avctx, mfxSession *psession,
534 QSVFramesContext *qsv_frames_ctx,
535 const char *load_plugins, int opaque)
537 static const mfxHandleType handle_types[] = {
538 MFX_HANDLE_VA_DISPLAY,
539 MFX_HANDLE_D3D9_DEVICE_MANAGER,
540 MFX_HANDLE_D3D11_DEVICE,
542 mfxFrameAllocator frame_allocator = {
543 .pthis = qsv_frames_ctx,
544 .Alloc = qsv_frame_alloc,
545 .Lock = qsv_frame_lock,
546 .Unlock = qsv_frame_unlock,
547 .GetHDL = qsv_frame_get_hdl,
548 .Free = qsv_frame_free,
551 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)qsv_frames_ctx->hw_frames_ctx->data;
552 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
553 AVQSVDeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
554 mfxSession parent_session = device_hwctx->session;
559 mfxHDL handle = NULL;
560 mfxHandleType handle_type;
565 err = MFXQueryIMPL(parent_session, &impl);
566 if (err == MFX_ERR_NONE)
567 err = MFXQueryVersion(parent_session, &ver);
568 if (err != MFX_ERR_NONE)
569 return ff_qsv_print_error(avctx, err,
570 "Error querying the session attributes");
572 for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
573 err = MFXVideoCORE_GetHandle(parent_session, handle_types[i], &handle);
574 if (err == MFX_ERR_NONE) {
575 handle_type = handle_types[i];
581 av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
582 "from the session\n");
585 err = MFXInit(impl, &ver, &session);
586 if (err != MFX_ERR_NONE)
587 return ff_qsv_print_error(avctx, err,
588 "Error initializing a child MFX session");
591 err = MFXVideoCORE_SetHandle(session, handle_type, handle);
592 if (err != MFX_ERR_NONE)
593 return ff_qsv_print_error(avctx, err,
594 "Error setting a HW handle");
597 ret = qsv_load_plugins(session, load_plugins, avctx);
599 av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
604 qsv_frames_ctx->logctx = avctx;
606 /* allocate the memory ids for the external frames */
607 av_buffer_unref(&qsv_frames_ctx->mids_buf);
608 qsv_frames_ctx->mids_buf = qsv_create_mids(qsv_frames_ctx->hw_frames_ctx);
609 if (!qsv_frames_ctx->mids_buf)
610 return AVERROR(ENOMEM);
611 qsv_frames_ctx->mids = (QSVMid*)qsv_frames_ctx->mids_buf->data;
612 qsv_frames_ctx->nb_mids = frames_hwctx->nb_surfaces;
614 err = MFXVideoCORE_SetFrameAllocator(session, &frame_allocator);
615 if (err != MFX_ERR_NONE)
616 return ff_qsv_print_error(avctx, err,
617 "Error setting a frame allocator");