]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsv.c
Merge commit 'cca5e4f040971db6de0bfe6968f00c021d8a9c42'
[ffmpeg] / libavcodec / qsv.c
1 /*
2  * Intel MediaSDK QSV encoder/decoder shared code
3  *
4  * This file is part of FFmpeg.
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include <mfx/mfxvideo.h>
22 #include <mfx/mfxplugin.h>
23 #include <mfx/mfxjpeg.h>
24
25 #include <stdio.h>
26 #include <string.h>
27
28 #include "libavutil/avstring.h"
29 #include "libavutil/common.h"
30 #include "libavutil/error.h"
31 #include "libavutil/hwcontext.h"
32 #include "libavutil/hwcontext_qsv.h"
33 #include "libavutil/imgutils.h"
34
35 #include "avcodec.h"
36 #include "qsv_internal.h"
37
38 #if QSV_VERSION_ATLEAST(1, 12)
39 #include "mfx/mfxvp8.h"
40 #endif
41
42 int ff_qsv_codec_id_to_mfx(enum AVCodecID codec_id)
43 {
44     switch (codec_id) {
45     case AV_CODEC_ID_H264:
46         return MFX_CODEC_AVC;
47 #if QSV_VERSION_ATLEAST(1, 8)
48     case AV_CODEC_ID_HEVC:
49         return MFX_CODEC_HEVC;
50 #endif
51     case AV_CODEC_ID_MPEG1VIDEO:
52     case AV_CODEC_ID_MPEG2VIDEO:
53         return MFX_CODEC_MPEG2;
54     case AV_CODEC_ID_VC1:
55         return MFX_CODEC_VC1;
56 #if QSV_VERSION_ATLEAST(1, 12)
57     case AV_CODEC_ID_VP8:
58         return MFX_CODEC_VP8;
59 #endif
60     case AV_CODEC_ID_MJPEG:
61         return MFX_CODEC_JPEG;
62     default:
63         break;
64     }
65
66     return AVERROR(ENOSYS);
67 }
68
69 int ff_qsv_profile_to_mfx(enum AVCodecID codec_id, int profile)
70 {
71     if (profile == FF_PROFILE_UNKNOWN)
72         return MFX_PROFILE_UNKNOWN;
73     switch (codec_id) {
74     case AV_CODEC_ID_H264:
75     case AV_CODEC_ID_HEVC:
76         return profile;
77     case AV_CODEC_ID_VC1:
78         return 4 * profile + 1;
79     case AV_CODEC_ID_MPEG2VIDEO:
80         return 0x10 * profile;
81     }
82     return MFX_PROFILE_UNKNOWN;
83 }
84
85 static const struct {
86     mfxStatus   mfxerr;
87     int         averr;
88     const char *desc;
89 } qsv_errors[] = {
90     { MFX_ERR_NONE,                     0,               "success"                              },
91     { MFX_ERR_UNKNOWN,                  AVERROR_UNKNOWN, "unknown error"                        },
92     { MFX_ERR_NULL_PTR,                 AVERROR(EINVAL), "NULL pointer"                         },
93     { MFX_ERR_UNSUPPORTED,              AVERROR(ENOSYS), "unsupported"                          },
94     { MFX_ERR_MEMORY_ALLOC,             AVERROR(ENOMEM), "failed to allocate memory"            },
95     { MFX_ERR_NOT_ENOUGH_BUFFER,        AVERROR(ENOMEM), "insufficient input/output buffer"     },
96     { MFX_ERR_INVALID_HANDLE,           AVERROR(EINVAL), "invalid handle"                       },
97     { MFX_ERR_LOCK_MEMORY,              AVERROR(EIO),    "failed to lock the memory block"      },
98     { MFX_ERR_NOT_INITIALIZED,          AVERROR_BUG,     "not initialized"                      },
99     { MFX_ERR_NOT_FOUND,                AVERROR(ENOSYS), "specified object was not found"       },
100     /* the following 3 errors should always be handled explicitly, so those "mappings"
101      * are for completeness only */
102     { MFX_ERR_MORE_DATA,                AVERROR_UNKNOWN, "expect more data at input"            },
103     { MFX_ERR_MORE_SURFACE,             AVERROR_UNKNOWN, "expect more surface at output"        },
104     { MFX_ERR_MORE_BITSTREAM,           AVERROR_UNKNOWN, "expect more bitstream at output"      },
105     { MFX_ERR_ABORTED,                  AVERROR_UNKNOWN, "operation aborted"                    },
106     { MFX_ERR_DEVICE_LOST,              AVERROR(EIO),    "device lost"                          },
107     { MFX_ERR_INCOMPATIBLE_VIDEO_PARAM, AVERROR(EINVAL), "incompatible video parameters"        },
108     { MFX_ERR_INVALID_VIDEO_PARAM,      AVERROR(EINVAL), "invalid video parameters"             },
109     { MFX_ERR_UNDEFINED_BEHAVIOR,       AVERROR_BUG,     "undefined behavior"                   },
110     { MFX_ERR_DEVICE_FAILED,            AVERROR(EIO),    "device failed"                        },
111     { MFX_ERR_INCOMPATIBLE_AUDIO_PARAM, AVERROR(EINVAL), "incompatible audio parameters"        },
112     { MFX_ERR_INVALID_AUDIO_PARAM,      AVERROR(EINVAL), "invalid audio parameters"             },
113
114     { MFX_WRN_IN_EXECUTION,             0,               "operation in execution"               },
115     { MFX_WRN_DEVICE_BUSY,              0,               "device busy"                          },
116     { MFX_WRN_VIDEO_PARAM_CHANGED,      0,               "video parameters changed"             },
117     { MFX_WRN_PARTIAL_ACCELERATION,     0,               "partial acceleration"                 },
118     { MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, 0,               "incompatible video parameters"        },
119     { MFX_WRN_VALUE_NOT_CHANGED,        0,               "value is saturated"                   },
120     { MFX_WRN_OUT_OF_RANGE,             0,               "value out of range"                   },
121     { MFX_WRN_FILTER_SKIPPED,           0,               "filter skipped"                       },
122     { MFX_WRN_INCOMPATIBLE_AUDIO_PARAM, 0,               "incompatible audio parameters"        },
123 };
124
125 int ff_qsv_map_error(mfxStatus mfx_err, const char **desc)
126 {
127     int i;
128     for (i = 0; i < FF_ARRAY_ELEMS(qsv_errors); i++) {
129         if (qsv_errors[i].mfxerr == mfx_err) {
130             if (desc)
131                 *desc = qsv_errors[i].desc;
132             return qsv_errors[i].averr;
133         }
134     }
135     if (desc)
136         *desc = "unknown error";
137     return AVERROR_UNKNOWN;
138 }
139
140 int ff_qsv_print_error(void *log_ctx, mfxStatus err,
141                        const char *error_string)
142 {
143     const char *desc;
144     int ret;
145     ret = ff_qsv_map_error(err, &desc);
146     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
147     return ret;
148 }
149
150 int ff_qsv_print_warning(void *log_ctx, mfxStatus err,
151                          const char *warning_string)
152 {
153     const char *desc;
154     int ret;
155     ret = ff_qsv_map_error(err, &desc);
156     av_log(log_ctx, AV_LOG_WARNING, "%s: %s (%d)\n", warning_string, desc, err);
157     return ret;
158 }
159
160 static enum AVPixelFormat qsv_map_fourcc(uint32_t fourcc)
161 {
162     switch (fourcc) {
163     case MFX_FOURCC_NV12: return AV_PIX_FMT_NV12;
164     case MFX_FOURCC_P010: return AV_PIX_FMT_P010;
165     case MFX_FOURCC_P8:   return AV_PIX_FMT_PAL8;
166     }
167     return AV_PIX_FMT_NONE;
168 }
169
170 int ff_qsv_map_pixfmt(enum AVPixelFormat format, uint32_t *fourcc)
171 {
172     switch (format) {
173     case AV_PIX_FMT_YUV420P:
174     case AV_PIX_FMT_YUVJ420P:
175     case AV_PIX_FMT_NV12:
176         *fourcc = MFX_FOURCC_NV12;
177         return AV_PIX_FMT_NV12;
178     case AV_PIX_FMT_YUV420P10:
179     case AV_PIX_FMT_P010:
180         *fourcc = MFX_FOURCC_P010;
181         return AV_PIX_FMT_P010;
182     default:
183         return AVERROR(ENOSYS);
184     }
185 }
186
187 int ff_qsv_find_surface_idx(QSVFramesContext *ctx, QSVFrame *frame)
188 {
189     int i;
190     for (i = 0; i < ctx->nb_mids; i++) {
191         QSVMid *mid = &ctx->mids[i];
192         if (mid->handle == frame->surface.Data.MemId)
193             return i;
194     }
195     return AVERROR_BUG;
196 }
197
198 enum AVPictureType ff_qsv_map_pictype(int mfx_pic_type)
199 {
200     enum AVPictureType type;
201     switch (mfx_pic_type & 0x7) {
202     case MFX_FRAMETYPE_I:
203         if (mfx_pic_type & MFX_FRAMETYPE_S)
204             type = AV_PICTURE_TYPE_SI;
205         else
206             type = AV_PICTURE_TYPE_I;
207         break;
208     case MFX_FRAMETYPE_B:
209         type = AV_PICTURE_TYPE_B;
210         break;
211     case MFX_FRAMETYPE_P:
212         if (mfx_pic_type & MFX_FRAMETYPE_S)
213             type = AV_PICTURE_TYPE_SP;
214         else
215             type = AV_PICTURE_TYPE_P;
216         break;
217     }
218
219     return type;
220 }
221
222 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
223                             void *logctx)
224 {
225     if (!load_plugins || !*load_plugins)
226         return 0;
227
228     while (*load_plugins) {
229         mfxPluginUID uid;
230         mfxStatus ret;
231         int i, err = 0;
232
233         char *plugin = av_get_token(&load_plugins, ":");
234         if (!plugin)
235             return AVERROR(ENOMEM);
236         if (strlen(plugin) != 2 * sizeof(uid.Data)) {
237             av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID length\n");
238             err = AVERROR(EINVAL);
239             goto load_plugin_fail;
240         }
241
242         for (i = 0; i < sizeof(uid.Data); i++) {
243             err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
244             if (err != 1) {
245                 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
246                 err = AVERROR(EINVAL);
247                 goto load_plugin_fail;
248             }
249
250         }
251
252         ret = MFXVideoUSER_Load(session, &uid, 1);
253         if (ret < 0) {
254             char errorbuf[128];
255             snprintf(errorbuf, sizeof(errorbuf),
256                      "Could not load the requested plugin '%s'", plugin);
257             err = ff_qsv_print_error(logctx, ret, errorbuf);
258             goto load_plugin_fail;
259         }
260
261         if (*load_plugins)
262             load_plugins++;
263 load_plugin_fail:
264         av_freep(&plugin);
265         if (err < 0)
266             return err;
267     }
268
269     return 0;
270
271 }
272
273 int ff_qsv_init_internal_session(AVCodecContext *avctx, mfxSession *session,
274                                  const char *load_plugins)
275 {
276     mfxIMPL impl   = MFX_IMPL_AUTO_ANY;
277     mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
278
279     const char *desc;
280     int ret;
281
282     ret = MFXInit(impl, &ver, session);
283     if (ret < 0)
284         return ff_qsv_print_error(avctx, ret,
285                                   "Error initializing an internal MFX session");
286
287     ret = qsv_load_plugins(*session, load_plugins, avctx);
288     if (ret < 0) {
289         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
290         return ret;
291     }
292
293     MFXQueryIMPL(*session, &impl);
294
295     switch (MFX_IMPL_BASETYPE(impl)) {
296     case MFX_IMPL_SOFTWARE:
297         desc = "software";
298         break;
299     case MFX_IMPL_HARDWARE:
300     case MFX_IMPL_HARDWARE2:
301     case MFX_IMPL_HARDWARE3:
302     case MFX_IMPL_HARDWARE4:
303         desc = "hardware accelerated";
304         break;
305     default:
306         desc = "unknown";
307     }
308
309     av_log(avctx, AV_LOG_VERBOSE,
310            "Initialized an internal MFX session using %s implementation\n",
311            desc);
312
313     return 0;
314 }
315
316 static void mids_buf_free(void *opaque, uint8_t *data)
317 {
318     AVBufferRef *hw_frames_ref = opaque;
319     av_buffer_unref(&hw_frames_ref);
320     av_freep(&data);
321 }
322
323 static AVBufferRef *qsv_create_mids(AVBufferRef *hw_frames_ref)
324 {
325     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
326     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
327     int                  nb_surfaces = frames_hwctx->nb_surfaces;
328
329     AVBufferRef *mids_buf, *hw_frames_ref1;
330     QSVMid *mids;
331     int i;
332
333     hw_frames_ref1 = av_buffer_ref(hw_frames_ref);
334     if (!hw_frames_ref1)
335         return NULL;
336
337     mids = av_mallocz_array(nb_surfaces, sizeof(*mids));
338     if (!mids) {
339         av_buffer_unref(&hw_frames_ref1);
340         return NULL;
341     }
342
343     mids_buf = av_buffer_create((uint8_t*)mids, nb_surfaces * sizeof(*mids),
344                                 mids_buf_free, hw_frames_ref1, 0);
345     if (!mids_buf) {
346         av_buffer_unref(&hw_frames_ref1);
347         av_freep(&mids);
348         return NULL;
349     }
350
351     for (i = 0; i < nb_surfaces; i++) {
352         QSVMid *mid = &mids[i];
353         mid->handle        = frames_hwctx->surfaces[i].Data.MemId;
354         mid->hw_frames_ref = hw_frames_ref1;
355     }
356
357     return mids_buf;
358 }
359
360 static int qsv_setup_mids(mfxFrameAllocResponse *resp, AVBufferRef *hw_frames_ref,
361                           AVBufferRef *mids_buf)
362 {
363     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
364     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
365     QSVMid                     *mids = (QSVMid*)mids_buf->data;
366     int                  nb_surfaces = frames_hwctx->nb_surfaces;
367     int i;
368
369     // the allocated size of the array is two larger than the number of
370     // surfaces, we store the references to the frames context and the
371     // QSVMid array there
372     resp->mids = av_mallocz_array(nb_surfaces + 2, sizeof(*resp->mids));
373     if (!resp->mids)
374         return AVERROR(ENOMEM);
375
376     for (i = 0; i < nb_surfaces; i++)
377         resp->mids[i] = &mids[i];
378     resp->NumFrameActual = nb_surfaces;
379
380     resp->mids[resp->NumFrameActual] = (mfxMemId)av_buffer_ref(hw_frames_ref);
381     if (!resp->mids[resp->NumFrameActual]) {
382         av_freep(&resp->mids);
383         return AVERROR(ENOMEM);
384     }
385
386     resp->mids[resp->NumFrameActual + 1] = av_buffer_ref(mids_buf);
387     if (!resp->mids[resp->NumFrameActual + 1]) {
388         av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
389         av_freep(&resp->mids);
390         return AVERROR(ENOMEM);
391     }
392
393     return 0;
394 }
395
396 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
397                                  mfxFrameAllocResponse *resp)
398 {
399     QSVFramesContext *ctx = pthis;
400     int ret;
401
402     /* this should only be called from an encoder or decoder and
403      * only allocates video memory frames */
404     if (!(req->Type & (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET |
405                        MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))         ||
406         !(req->Type & (MFX_MEMTYPE_FROM_DECODE | MFX_MEMTYPE_FROM_ENCODE)))
407         return MFX_ERR_UNSUPPORTED;
408
409     if (req->Type & MFX_MEMTYPE_EXTERNAL_FRAME) {
410         /* external frames -- fill from the caller-supplied frames context */
411         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
412         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
413         mfxFrameInfo      *i  = &req->Info;
414         mfxFrameInfo      *i1 = &frames_hwctx->surfaces[0].Info;
415
416         if (i->Width  > i1->Width  || i->Height > i1->Height ||
417             i->FourCC != i1->FourCC || i->ChromaFormat != i1->ChromaFormat) {
418             av_log(ctx->logctx, AV_LOG_ERROR, "Mismatching surface properties in an "
419                    "allocation request: %dx%d %d %d vs %dx%d %d %d\n",
420                    i->Width,  i->Height,  i->FourCC,  i->ChromaFormat,
421                    i1->Width, i1->Height, i1->FourCC, i1->ChromaFormat);
422             return MFX_ERR_UNSUPPORTED;
423         }
424
425         ret = qsv_setup_mids(resp, ctx->hw_frames_ctx, ctx->mids_buf);
426         if (ret < 0) {
427             av_log(ctx->logctx, AV_LOG_ERROR,
428                    "Error filling an external frame allocation request\n");
429             return MFX_ERR_MEMORY_ALLOC;
430         }
431     } else if (req->Type & MFX_MEMTYPE_INTERNAL_FRAME) {
432         /* internal frames -- allocate a new hw frames context */
433         AVHWFramesContext *ext_frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
434         mfxFrameInfo      *i  = &req->Info;
435
436         AVBufferRef *frames_ref, *mids_buf;
437         AVHWFramesContext *frames_ctx;
438         AVQSVFramesContext *frames_hwctx;
439
440         frames_ref = av_hwframe_ctx_alloc(ext_frames_ctx->device_ref);
441         if (!frames_ref)
442             return MFX_ERR_MEMORY_ALLOC;
443
444         frames_ctx   = (AVHWFramesContext*)frames_ref->data;
445         frames_hwctx = frames_ctx->hwctx;
446
447         frames_ctx->format            = AV_PIX_FMT_QSV;
448         frames_ctx->sw_format         = qsv_map_fourcc(i->FourCC);
449         frames_ctx->width             = i->Width;
450         frames_ctx->height            = i->Height;
451         frames_ctx->initial_pool_size = req->NumFrameSuggested;
452
453         frames_hwctx->frame_type      = req->Type;
454
455         ret = av_hwframe_ctx_init(frames_ref);
456         if (ret < 0) {
457             av_log(ctx->logctx, AV_LOG_ERROR,
458                    "Error initializing a frames context for an internal frame "
459                    "allocation request\n");
460             av_buffer_unref(&frames_ref);
461             return MFX_ERR_MEMORY_ALLOC;
462         }
463
464         mids_buf = qsv_create_mids(frames_ref);
465         if (!mids_buf) {
466             av_buffer_unref(&frames_ref);
467             return MFX_ERR_MEMORY_ALLOC;
468         }
469
470         ret = qsv_setup_mids(resp, frames_ref, mids_buf);
471         av_buffer_unref(&mids_buf);
472         av_buffer_unref(&frames_ref);
473         if (ret < 0) {
474             av_log(ctx->logctx, AV_LOG_ERROR,
475                    "Error filling an internal frame allocation request\n");
476             return MFX_ERR_MEMORY_ALLOC;
477         }
478     } else {
479         return MFX_ERR_UNSUPPORTED;
480     }
481
482     return MFX_ERR_NONE;
483 }
484
485 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
486 {
487     av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
488     av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual + 1]);
489     av_freep(&resp->mids);
490     return MFX_ERR_NONE;
491 }
492
493 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
494 {
495     QSVMid *qsv_mid = mid;
496     AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)qsv_mid->hw_frames_ref->data;
497     AVQSVFramesContext *hw_frames_hwctx = hw_frames_ctx->hwctx;
498     int ret;
499
500     if (qsv_mid->locked_frame)
501         return MFX_ERR_UNDEFINED_BEHAVIOR;
502
503     /* Allocate a system memory frame that will hold the mapped data. */
504     qsv_mid->locked_frame = av_frame_alloc();
505     if (!qsv_mid->locked_frame)
506         return MFX_ERR_MEMORY_ALLOC;
507     qsv_mid->locked_frame->format  = hw_frames_ctx->sw_format;
508
509     /* wrap the provided handle in a hwaccel AVFrame */
510     qsv_mid->hw_frame = av_frame_alloc();
511     if (!qsv_mid->hw_frame)
512         goto fail;
513
514     qsv_mid->hw_frame->data[3] = (uint8_t*)&qsv_mid->surf;
515     qsv_mid->hw_frame->format  = AV_PIX_FMT_QSV;
516
517     // doesn't really matter what buffer is used here
518     qsv_mid->hw_frame->buf[0]  = av_buffer_alloc(1);
519     if (!qsv_mid->hw_frame->buf[0])
520         goto fail;
521
522     qsv_mid->hw_frame->width   = hw_frames_ctx->width;
523     qsv_mid->hw_frame->height  = hw_frames_ctx->height;
524
525     qsv_mid->hw_frame->hw_frames_ctx = av_buffer_ref(qsv_mid->hw_frames_ref);
526     if (!qsv_mid->hw_frame->hw_frames_ctx)
527         goto fail;
528
529     qsv_mid->surf.Info = hw_frames_hwctx->surfaces[0].Info;
530     qsv_mid->surf.Data.MemId = qsv_mid->handle;
531
532     /* map the data to the system memory */
533     ret = av_hwframe_map(qsv_mid->locked_frame, qsv_mid->hw_frame,
534                          AV_HWFRAME_MAP_DIRECT);
535     if (ret < 0)
536         goto fail;
537
538     ptr->Pitch = qsv_mid->locked_frame->linesize[0];
539     ptr->Y     = qsv_mid->locked_frame->data[0];
540     ptr->U     = qsv_mid->locked_frame->data[1];
541     ptr->V     = qsv_mid->locked_frame->data[1] + 1;
542
543     return MFX_ERR_NONE;
544 fail:
545     av_frame_free(&qsv_mid->hw_frame);
546     av_frame_free(&qsv_mid->locked_frame);
547     return MFX_ERR_MEMORY_ALLOC;
548 }
549
550 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
551 {
552     QSVMid *qsv_mid = mid;
553
554     av_frame_free(&qsv_mid->locked_frame);
555     av_frame_free(&qsv_mid->hw_frame);
556
557     return MFX_ERR_NONE;
558 }
559
560 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
561 {
562     QSVMid *qsv_mid = (QSVMid*)mid;
563     *hdl = qsv_mid->handle;
564     return MFX_ERR_NONE;
565 }
566
567 int ff_qsv_init_session_device(AVCodecContext *avctx, mfxSession *psession,
568                                AVBufferRef *device_ref, const char *load_plugins)
569 {
570     static const mfxHandleType handle_types[] = {
571         MFX_HANDLE_VA_DISPLAY,
572         MFX_HANDLE_D3D9_DEVICE_MANAGER,
573         MFX_HANDLE_D3D11_DEVICE,
574     };
575     AVHWDeviceContext    *device_ctx = (AVHWDeviceContext*)device_ref->data;
576     AVQSVDeviceContext *device_hwctx = device_ctx->hwctx;
577     mfxSession        parent_session = device_hwctx->session;
578
579     mfxSession    session;
580     mfxVersion    ver;
581     mfxIMPL       impl;
582     mfxHDL        handle = NULL;
583     mfxHandleType handle_type;
584     mfxStatus err;
585
586     int i, ret;
587
588     err = MFXQueryIMPL(parent_session, &impl);
589     if (err == MFX_ERR_NONE)
590         err = MFXQueryVersion(parent_session, &ver);
591     if (err != MFX_ERR_NONE)
592         return ff_qsv_print_error(avctx, err,
593                                   "Error querying the session attributes");
594
595     for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
596         err = MFXVideoCORE_GetHandle(parent_session, handle_types[i], &handle);
597         if (err == MFX_ERR_NONE) {
598             handle_type = handle_types[i];
599             break;
600         }
601         handle = NULL;
602     }
603     if (!handle) {
604         av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
605                "from the session\n");
606     }
607
608     err = MFXInit(impl, &ver, &session);
609     if (err != MFX_ERR_NONE)
610         return ff_qsv_print_error(avctx, err,
611                                   "Error initializing a child MFX session");
612
613     if (handle) {
614         err = MFXVideoCORE_SetHandle(session, handle_type, handle);
615         if (err != MFX_ERR_NONE)
616             return ff_qsv_print_error(avctx, err,
617                                       "Error setting a HW handle");
618     }
619
620     if (QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 25)) {
621         err = MFXJoinSession(parent_session, session);
622         if (err != MFX_ERR_NONE)
623             return ff_qsv_print_error(avctx, err,
624                                       "Error joining session");
625     }
626
627     ret = qsv_load_plugins(session, load_plugins, avctx);
628     if (ret < 0) {
629         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
630         return ret;
631     }
632
633     *psession = session;
634     return 0;
635 }
636
637 int ff_qsv_init_session_frames(AVCodecContext *avctx, mfxSession *psession,
638                                QSVFramesContext *qsv_frames_ctx,
639                                const char *load_plugins, int opaque)
640 {
641     mfxFrameAllocator frame_allocator = {
642         .pthis  = qsv_frames_ctx,
643         .Alloc  = qsv_frame_alloc,
644         .Lock   = qsv_frame_lock,
645         .Unlock = qsv_frame_unlock,
646         .GetHDL = qsv_frame_get_hdl,
647         .Free   = qsv_frame_free,
648     };
649
650     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)qsv_frames_ctx->hw_frames_ctx->data;
651     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
652
653     mfxSession    session;
654     mfxStatus err;
655
656     int ret;
657
658     ret = ff_qsv_init_session_device(avctx, &session,
659                                      frames_ctx->device_ref, load_plugins);
660     if (ret < 0)
661         return ret;
662
663     if (!opaque) {
664         qsv_frames_ctx->logctx = avctx;
665
666         /* allocate the memory ids for the external frames */
667         av_buffer_unref(&qsv_frames_ctx->mids_buf);
668         qsv_frames_ctx->mids_buf = qsv_create_mids(qsv_frames_ctx->hw_frames_ctx);
669         if (!qsv_frames_ctx->mids_buf)
670             return AVERROR(ENOMEM);
671         qsv_frames_ctx->mids    = (QSVMid*)qsv_frames_ctx->mids_buf->data;
672         qsv_frames_ctx->nb_mids = frames_hwctx->nb_surfaces;
673
674         err = MFXVideoCORE_SetFrameAllocator(session, &frame_allocator);
675         if (err != MFX_ERR_NONE)
676             return ff_qsv_print_error(avctx, err,
677                                       "Error setting a frame allocator");
678     }
679
680     *psession = session;
681     return 0;
682 }