2 * Intel MediaSDK QSV encoder/decoder shared code
4 * This file is part of Libav.
6 * Libav 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 * Libav 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 Libav; 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);
63 { MFX_ERR_NONE, 0, "success" },
64 { MFX_ERR_UNKNOWN, AVERROR_UNKNOWN, "unknown error" },
65 { MFX_ERR_NULL_PTR, AVERROR(EINVAL), "NULL pointer" },
66 { MFX_ERR_UNSUPPORTED, AVERROR(ENOSYS), "unsupported" },
67 { MFX_ERR_MEMORY_ALLOC, AVERROR(ENOMEM), "failed to allocate memory" },
68 { MFX_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOMEM), "insufficient input/output buffer" },
69 { MFX_ERR_INVALID_HANDLE, AVERROR(EINVAL), "invalid handle" },
70 { MFX_ERR_LOCK_MEMORY, AVERROR(EIO), "failed to lock the memory block" },
71 { MFX_ERR_NOT_INITIALIZED, AVERROR_BUG, "not initialized" },
72 { MFX_ERR_NOT_FOUND, AVERROR(ENOSYS), "specified object was not found" },
73 { MFX_ERR_MORE_DATA, AVERROR(EAGAIN), "expect more data at input" },
74 { MFX_ERR_MORE_SURFACE, AVERROR(EAGAIN), "expect more surface at output" },
75 { MFX_ERR_ABORTED, AVERROR_UNKNOWN, "operation aborted" },
76 { MFX_ERR_DEVICE_LOST, AVERROR(EIO), "device lost" },
77 { MFX_ERR_INCOMPATIBLE_VIDEO_PARAM, AVERROR(EINVAL), "incompatible video parameters" },
78 { MFX_ERR_INVALID_VIDEO_PARAM, AVERROR(EINVAL), "invalid video parameters" },
79 { MFX_ERR_UNDEFINED_BEHAVIOR, AVERROR_BUG, "undefined behavior" },
80 { MFX_ERR_DEVICE_FAILED, AVERROR(EIO), "device failed" },
81 { MFX_ERR_MORE_BITSTREAM, AVERROR(EAGAIN), "expect more bitstream at output" },
82 { MFX_ERR_INCOMPATIBLE_AUDIO_PARAM, AVERROR(EINVAL), "incompatible audio parameters" },
83 { MFX_ERR_INVALID_AUDIO_PARAM, AVERROR(EINVAL), "invalid audio parameters" },
85 { MFX_WRN_IN_EXECUTION, 0, "operation in execution" },
86 { MFX_WRN_DEVICE_BUSY, 0, "device busy" },
87 { MFX_WRN_VIDEO_PARAM_CHANGED, 0, "video parameters changed" },
88 { MFX_WRN_PARTIAL_ACCELERATION, 0, "partial acceleration" },
89 { MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, 0, "incompatible video parameters" },
90 { MFX_WRN_VALUE_NOT_CHANGED, 0, "value is saturated" },
91 { MFX_WRN_OUT_OF_RANGE, 0, "value out of range" },
92 { MFX_WRN_FILTER_SKIPPED, 0, "filter skipped" },
93 { MFX_WRN_INCOMPATIBLE_AUDIO_PARAM, 0, "incompatible audio parameters" },
96 int ff_qsv_map_error(mfxStatus mfx_err, const char **desc)
99 for (i = 0; i < FF_ARRAY_ELEMS(qsv_errors); i++) {
100 if (qsv_errors[i].mfxerr == mfx_err) {
102 *desc = qsv_errors[i].desc;
103 return qsv_errors[i].averr;
107 *desc = "unknown error";
108 return AVERROR_UNKNOWN;
111 int ff_qsv_print_error(void *log_ctx, mfxStatus err,
112 const char *error_string)
116 ret = ff_qsv_map_error(err, &desc);
117 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
121 int ff_qsv_print_warning(void *log_ctx, mfxStatus err,
122 const char *warning_string)
126 ret = ff_qsv_map_error(err, &desc);
127 av_log(log_ctx, AV_LOG_WARNING, "%s: %s (%d)\n", warning_string, desc, err);
131 static enum AVPixelFormat qsv_map_fourcc(uint32_t fourcc)
134 case MFX_FOURCC_NV12: return AV_PIX_FMT_NV12;
135 case MFX_FOURCC_P010: return AV_PIX_FMT_P010;
136 case MFX_FOURCC_P8: return AV_PIX_FMT_PAL8;
138 return AV_PIX_FMT_NONE;
141 int ff_qsv_map_pixfmt(enum AVPixelFormat format, uint32_t *fourcc)
144 case AV_PIX_FMT_YUV420P:
145 case AV_PIX_FMT_YUVJ420P:
146 case AV_PIX_FMT_NV12:
147 *fourcc = MFX_FOURCC_NV12;
148 return AV_PIX_FMT_NV12;
149 case AV_PIX_FMT_YUV420P10:
150 case AV_PIX_FMT_P010:
151 *fourcc = MFX_FOURCC_P010;
152 return AV_PIX_FMT_P010;
154 return AVERROR(ENOSYS);
158 int ff_qsv_find_surface_idx(QSVFramesContext *ctx, QSVFrame *frame)
161 for (i = 0; i < ctx->nb_mids; i++) {
162 QSVMid *mid = &ctx->mids[i];
163 if (mid->handle == frame->surface.Data.MemId)
169 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
172 if (!load_plugins || !*load_plugins)
175 while (*load_plugins) {
180 char *plugin = av_get_token(&load_plugins, ":");
182 return AVERROR(ENOMEM);
183 if (strlen(plugin) != 2 * sizeof(uid.Data)) {
184 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID length\n");
185 err = AVERROR(EINVAL);
186 goto load_plugin_fail;
189 for (i = 0; i < sizeof(uid.Data); i++) {
190 err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
192 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
193 err = AVERROR(EINVAL);
194 goto load_plugin_fail;
199 ret = MFXVideoUSER_Load(session, &uid, 1);
202 snprintf(errorbuf, sizeof(errorbuf),
203 "Could not load the requested plugin '%s'", plugin);
204 err = ff_qsv_print_error(logctx, ret, errorbuf);
205 goto load_plugin_fail;
220 int ff_qsv_init_internal_session(AVCodecContext *avctx, mfxSession *session,
221 const char *load_plugins)
223 mfxIMPL impl = MFX_IMPL_AUTO_ANY;
224 mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
229 ret = MFXInit(impl, &ver, session);
231 return ff_qsv_print_error(avctx, ret,
232 "Error initializing an internal MFX session");
234 ret = qsv_load_plugins(*session, load_plugins, avctx);
236 av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
240 MFXQueryIMPL(*session, &impl);
242 switch (MFX_IMPL_BASETYPE(impl)) {
243 case MFX_IMPL_SOFTWARE:
246 case MFX_IMPL_HARDWARE:
247 case MFX_IMPL_HARDWARE2:
248 case MFX_IMPL_HARDWARE3:
249 case MFX_IMPL_HARDWARE4:
250 desc = "hardware accelerated";
256 av_log(avctx, AV_LOG_VERBOSE,
257 "Initialized an internal MFX session using %s implementation\n",
263 static void mids_buf_free(void *opaque, uint8_t *data)
265 AVBufferRef *hw_frames_ref = opaque;
266 av_buffer_unref(&hw_frames_ref);
270 static AVBufferRef *qsv_create_mids(AVBufferRef *hw_frames_ref)
272 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
273 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
274 int nb_surfaces = frames_hwctx->nb_surfaces;
276 AVBufferRef *mids_buf, *hw_frames_ref1;
280 hw_frames_ref1 = av_buffer_ref(hw_frames_ref);
284 mids = av_mallocz_array(nb_surfaces, sizeof(*mids));
286 av_buffer_unref(&hw_frames_ref1);
290 mids_buf = av_buffer_create((uint8_t*)mids, nb_surfaces * sizeof(*mids),
291 mids_buf_free, hw_frames_ref1, 0);
293 av_buffer_unref(&hw_frames_ref1);
298 for (i = 0; i < nb_surfaces; i++) {
299 QSVMid *mid = &mids[i];
300 mid->handle = frames_hwctx->surfaces[i].Data.MemId;
301 mid->hw_frames_ref = hw_frames_ref1;
307 static int qsv_setup_mids(mfxFrameAllocResponse *resp, AVBufferRef *hw_frames_ref,
308 AVBufferRef *mids_buf)
310 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
311 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
312 QSVMid *mids = (QSVMid*)mids_buf->data;
313 int nb_surfaces = frames_hwctx->nb_surfaces;
316 // the allocated size of the array is two larger than the number of
317 // surfaces, we store the references to the frames context and the
318 // QSVMid array there
319 resp->mids = av_mallocz_array(nb_surfaces + 2, sizeof(*resp->mids));
321 return AVERROR(ENOMEM);
323 for (i = 0; i < nb_surfaces; i++)
324 resp->mids[i] = &mids[i];
325 resp->NumFrameActual = nb_surfaces;
327 resp->mids[resp->NumFrameActual] = (mfxMemId)av_buffer_ref(hw_frames_ref);
328 if (!resp->mids[resp->NumFrameActual]) {
329 av_freep(&resp->mids);
330 return AVERROR(ENOMEM);
333 resp->mids[resp->NumFrameActual + 1] = av_buffer_ref(mids_buf);
334 if (!resp->mids[resp->NumFrameActual + 1]) {
335 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
336 av_freep(&resp->mids);
337 return AVERROR(ENOMEM);
343 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
344 mfxFrameAllocResponse *resp)
346 QSVFramesContext *ctx = pthis;
349 /* this should only be called from an encoder or decoder and
350 * only allocates video memory frames */
351 if (!(req->Type & (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET |
352 MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET)) ||
353 !(req->Type & (MFX_MEMTYPE_FROM_DECODE | MFX_MEMTYPE_FROM_ENCODE)))
354 return MFX_ERR_UNSUPPORTED;
356 if (req->Type & MFX_MEMTYPE_EXTERNAL_FRAME) {
357 /* external frames -- fill from the caller-supplied frames context */
358 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
359 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
360 mfxFrameInfo *i = &req->Info;
361 mfxFrameInfo *i1 = &frames_hwctx->surfaces[0].Info;
363 if (i->Width != i1->Width || i->Height != i1->Height ||
364 i->FourCC != i1->FourCC || i->ChromaFormat != i1->ChromaFormat) {
365 av_log(ctx->logctx, AV_LOG_ERROR, "Mismatching surface properties in an "
366 "allocation request: %dx%d %d %d vs %dx%d %d %d\n",
367 i->Width, i->Height, i->FourCC, i->ChromaFormat,
368 i1->Width, i1->Height, i1->FourCC, i1->ChromaFormat);
369 return MFX_ERR_UNSUPPORTED;
372 ret = qsv_setup_mids(resp, ctx->hw_frames_ctx, ctx->mids_buf);
374 av_log(ctx->logctx, AV_LOG_ERROR,
375 "Error filling an external frame allocation request\n");
376 return MFX_ERR_MEMORY_ALLOC;
378 } else if (req->Type & MFX_MEMTYPE_INTERNAL_FRAME) {
379 /* internal frames -- allocate a new hw frames context */
380 AVHWFramesContext *ext_frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
381 mfxFrameInfo *i = &req->Info;
383 AVBufferRef *frames_ref, *mids_buf;
384 AVHWFramesContext *frames_ctx;
385 AVQSVFramesContext *frames_hwctx;
387 frames_ref = av_hwframe_ctx_alloc(ext_frames_ctx->device_ref);
389 return MFX_ERR_MEMORY_ALLOC;
391 frames_ctx = (AVHWFramesContext*)frames_ref->data;
392 frames_hwctx = frames_ctx->hwctx;
394 frames_ctx->format = AV_PIX_FMT_QSV;
395 frames_ctx->sw_format = qsv_map_fourcc(i->FourCC);
396 frames_ctx->width = i->Width;
397 frames_ctx->height = i->Height;
398 frames_ctx->initial_pool_size = req->NumFrameSuggested;
400 frames_hwctx->frame_type = req->Type;
402 ret = av_hwframe_ctx_init(frames_ref);
404 av_log(ctx->logctx, AV_LOG_ERROR,
405 "Error initializing a frames context for an internal frame "
406 "allocation request\n");
407 av_buffer_unref(&frames_ref);
408 return MFX_ERR_MEMORY_ALLOC;
411 mids_buf = qsv_create_mids(frames_ref);
413 av_buffer_unref(&frames_ref);
414 return MFX_ERR_MEMORY_ALLOC;
417 ret = qsv_setup_mids(resp, frames_ref, mids_buf);
418 av_buffer_unref(&mids_buf);
419 av_buffer_unref(&frames_ref);
421 av_log(ctx->logctx, AV_LOG_ERROR,
422 "Error filling an internal frame allocation request\n");
423 return MFX_ERR_MEMORY_ALLOC;
426 return MFX_ERR_UNSUPPORTED;
432 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
434 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
435 av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual + 1]);
436 av_freep(&resp->mids);
440 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
442 QSVMid *qsv_mid = mid;
443 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)qsv_mid->hw_frames_ref->data;
444 AVQSVFramesContext *hw_frames_hwctx = hw_frames_ctx->hwctx;
449 if (qsv_mid->locked_frame)
450 return MFX_ERR_UNDEFINED_BEHAVIOR;
452 /* Allocate a system memory frame that will hold the mapped data. */
453 qsv_mid->locked_frame = av_frame_alloc();
454 if (!qsv_mid->locked_frame)
455 return MFX_ERR_MEMORY_ALLOC;
456 qsv_mid->locked_frame->format = hw_frames_ctx->sw_format;
458 /* wrap the provided handle in a hwaccel AVFrame */
459 qsv_mid->hw_frame = av_frame_alloc();
460 if (!qsv_mid->hw_frame)
463 qsv_mid->hw_frame->data[3] = (uint8_t*)&qsv_mid->surf;
464 qsv_mid->hw_frame->format = AV_PIX_FMT_QSV;
466 // doesn't really matter what buffer is used here
467 qsv_mid->hw_frame->buf[0] = av_buffer_alloc(1);
468 if (!qsv_mid->hw_frame->buf[0])
471 qsv_mid->hw_frame->width = hw_frames_ctx->width;
472 qsv_mid->hw_frame->height = hw_frames_ctx->height;
474 qsv_mid->hw_frame->hw_frames_ctx = av_buffer_ref(qsv_mid->hw_frames_ref);
475 if (!qsv_mid->hw_frame->hw_frames_ctx)
478 qsv_mid->surf.Info = hw_frames_hwctx->surfaces[0].Info;
479 qsv_mid->surf.Data.MemId = qsv_mid->handle;
481 /* map the data to the system memory */
482 ret = av_hwframe_map(qsv_mid->locked_frame, qsv_mid->hw_frame,
483 AV_HWFRAME_MAP_DIRECT);
487 ptr->Pitch = qsv_mid->locked_frame->linesize[0];
488 ptr->Y = qsv_mid->locked_frame->data[0];
489 ptr->U = qsv_mid->locked_frame->data[1];
490 ptr->V = qsv_mid->locked_frame->data[1] + 1;
494 av_frame_free(&qsv_mid->hw_frame);
495 av_frame_free(&qsv_mid->locked_frame);
496 return MFX_ERR_MEMORY_ALLOC;
499 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
501 QSVMid *qsv_mid = mid;
504 av_frame_free(&qsv_mid->locked_frame);
505 av_frame_free(&qsv_mid->hw_frame);
510 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
512 QSVMid *qsv_mid = (QSVMid*)mid;
513 *hdl = qsv_mid->handle;
517 int ff_qsv_init_session_hwcontext(AVCodecContext *avctx, mfxSession *psession,
518 QSVFramesContext *qsv_frames_ctx,
519 const char *load_plugins, int opaque)
521 static const mfxHandleType handle_types[] = {
522 MFX_HANDLE_VA_DISPLAY,
523 MFX_HANDLE_D3D9_DEVICE_MANAGER,
524 MFX_HANDLE_D3D11_DEVICE,
526 mfxFrameAllocator frame_allocator = {
527 .pthis = qsv_frames_ctx,
528 .Alloc = qsv_frame_alloc,
529 .Lock = qsv_frame_lock,
530 .Unlock = qsv_frame_unlock,
531 .GetHDL = qsv_frame_get_hdl,
532 .Free = qsv_frame_free,
535 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)qsv_frames_ctx->hw_frames_ctx->data;
536 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
537 AVQSVDeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
538 mfxSession parent_session = device_hwctx->session;
543 mfxHDL handle = NULL;
544 mfxHandleType handle_type;
549 err = MFXQueryIMPL(parent_session, &impl);
550 if (err == MFX_ERR_NONE)
551 err = MFXQueryVersion(parent_session, &ver);
552 if (err != MFX_ERR_NONE)
553 return ff_qsv_print_error(avctx, err,
554 "Error querying the session attributes");
556 for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
557 err = MFXVideoCORE_GetHandle(parent_session, handle_types[i], &handle);
558 if (err == MFX_ERR_NONE) {
559 handle_type = handle_types[i];
565 av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
566 "from the session\n");
569 err = MFXInit(impl, &ver, &session);
570 if (err != MFX_ERR_NONE)
571 return ff_qsv_print_error(avctx, err,
572 "Error initializing a child MFX session");
575 err = MFXVideoCORE_SetHandle(session, handle_type, handle);
576 if (err != MFX_ERR_NONE)
577 return ff_qsv_print_error(avctx, err,
578 "Error setting a HW handle");
581 ret = qsv_load_plugins(session, load_plugins, avctx);
583 av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
588 qsv_frames_ctx->logctx = avctx;
590 /* allocate the memory ids for the external frames */
591 av_buffer_unref(&qsv_frames_ctx->mids_buf);
592 qsv_frames_ctx->mids_buf = qsv_create_mids(qsv_frames_ctx->hw_frames_ctx);
593 if (!qsv_frames_ctx->mids_buf)
594 return AVERROR(ENOMEM);
595 qsv_frames_ctx->mids = (QSVMid*)qsv_frames_ctx->mids_buf->data;
596 qsv_frames_ctx->nb_mids = frames_hwctx->nb_surfaces;
598 err = MFXVideoCORE_SetFrameAllocator(session, &frame_allocator);
599 if (err != MFX_ERR_NONE)
600 return ff_qsv_print_error(avctx, err,
601 "Error setting a frame allocator");