]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsv.c
Merge commit '4ab61cd983b539749bd621ea271624ddb5196a8e'
[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
24 #include <stdio.h>
25 #include <string.h>
26
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
34 #include "avcodec.h"
35 #include "qsv_internal.h"
36
37 int ff_qsv_codec_id_to_mfx(enum AVCodecID codec_id)
38 {
39     switch (codec_id) {
40     case AV_CODEC_ID_H264:
41         return MFX_CODEC_AVC;
42 #if QSV_VERSION_ATLEAST(1, 8)
43     case AV_CODEC_ID_HEVC:
44         return MFX_CODEC_HEVC;
45 #endif
46     case AV_CODEC_ID_MPEG1VIDEO:
47     case AV_CODEC_ID_MPEG2VIDEO:
48         return MFX_CODEC_MPEG2;
49     case AV_CODEC_ID_VC1:
50         return MFX_CODEC_VC1;
51     default:
52         break;
53     }
54
55     return AVERROR(ENOSYS);
56 }
57
58 int ff_qsv_profile_to_mfx(enum AVCodecID codec_id, int profile)
59 {
60     if (profile == FF_PROFILE_UNKNOWN)
61         return MFX_PROFILE_UNKNOWN;
62     switch (codec_id) {
63     case AV_CODEC_ID_H264:
64     case AV_CODEC_ID_HEVC:
65         return profile;
66     case AV_CODEC_ID_VC1:
67         return 4 * profile + 1;
68     case AV_CODEC_ID_MPEG2VIDEO:
69         return 0x10 * profile;
70     }
71     return MFX_PROFILE_UNKNOWN;
72 }
73
74 static const struct {
75     mfxStatus   mfxerr;
76     int         averr;
77     const char *desc;
78 } qsv_errors[] = {
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"             },
100
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"        },
110 };
111
112 int ff_qsv_map_error(mfxStatus mfx_err, const char **desc)
113 {
114     int i;
115     for (i = 0; i < FF_ARRAY_ELEMS(qsv_errors); i++) {
116         if (qsv_errors[i].mfxerr == mfx_err) {
117             if (desc)
118                 *desc = qsv_errors[i].desc;
119             return qsv_errors[i].averr;
120         }
121     }
122     if (desc)
123         *desc = "unknown error";
124     return AVERROR_UNKNOWN;
125 }
126
127 int ff_qsv_print_error(void *log_ctx, mfxStatus err,
128                        const char *error_string)
129 {
130     const char *desc;
131     int ret;
132     ret = ff_qsv_map_error(err, &desc);
133     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
134     return ret;
135 }
136
137 int ff_qsv_print_warning(void *log_ctx, mfxStatus err,
138                          const char *warning_string)
139 {
140     const char *desc;
141     int ret;
142     ret = ff_qsv_map_error(err, &desc);
143     av_log(log_ctx, AV_LOG_WARNING, "%s: %s (%d)\n", warning_string, desc, err);
144     return ret;
145 }
146
147 static enum AVPixelFormat qsv_map_fourcc(uint32_t fourcc)
148 {
149     switch (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;
153     }
154     return AV_PIX_FMT_NONE;
155 }
156
157 int ff_qsv_map_pixfmt(enum AVPixelFormat format, uint32_t *fourcc)
158 {
159     switch (format) {
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;
169     default:
170         return AVERROR(ENOSYS);
171     }
172 }
173
174 int ff_qsv_find_surface_idx(QSVFramesContext *ctx, QSVFrame *frame)
175 {
176     int i;
177     for (i = 0; i < ctx->nb_mids; i++) {
178         QSVMid *mid = &ctx->mids[i];
179         if (mid->handle == frame->surface.Data.MemId)
180             return i;
181     }
182     return AVERROR_BUG;
183 }
184
185 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
186                             void *logctx)
187 {
188     if (!load_plugins || !*load_plugins)
189         return 0;
190
191     while (*load_plugins) {
192         mfxPluginUID uid;
193         mfxStatus ret;
194         int i, err = 0;
195
196         char *plugin = av_get_token(&load_plugins, ":");
197         if (!plugin)
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;
203         }
204
205         for (i = 0; i < sizeof(uid.Data); i++) {
206             err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
207             if (err != 1) {
208                 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
209                 err = AVERROR(EINVAL);
210                 goto load_plugin_fail;
211             }
212
213         }
214
215         ret = MFXVideoUSER_Load(session, &uid, 1);
216         if (ret < 0) {
217             char errorbuf[128];
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;
222         }
223
224         if (*load_plugins)
225             load_plugins++;
226 load_plugin_fail:
227         av_freep(&plugin);
228         if (err < 0)
229             return err;
230     }
231
232     return 0;
233
234 }
235
236 int ff_qsv_init_internal_session(AVCodecContext *avctx, mfxSession *session,
237                                  const char *load_plugins)
238 {
239     mfxIMPL impl   = MFX_IMPL_AUTO_ANY;
240     mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
241
242     const char *desc;
243     int ret;
244
245     ret = MFXInit(impl, &ver, session);
246     if (ret < 0)
247         return ff_qsv_print_error(avctx, ret,
248                                   "Error initializing an internal MFX session");
249
250     ret = qsv_load_plugins(*session, load_plugins, avctx);
251     if (ret < 0) {
252         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
253         return ret;
254     }
255
256     MFXQueryIMPL(*session, &impl);
257
258     switch (MFX_IMPL_BASETYPE(impl)) {
259     case MFX_IMPL_SOFTWARE:
260         desc = "software";
261         break;
262     case MFX_IMPL_HARDWARE:
263     case MFX_IMPL_HARDWARE2:
264     case MFX_IMPL_HARDWARE3:
265     case MFX_IMPL_HARDWARE4:
266         desc = "hardware accelerated";
267         break;
268     default:
269         desc = "unknown";
270     }
271
272     av_log(avctx, AV_LOG_VERBOSE,
273            "Initialized an internal MFX session using %s implementation\n",
274            desc);
275
276     return 0;
277 }
278
279 static void mids_buf_free(void *opaque, uint8_t *data)
280 {
281     AVBufferRef *hw_frames_ref = opaque;
282     av_buffer_unref(&hw_frames_ref);
283     av_freep(&data);
284 }
285
286 static AVBufferRef *qsv_create_mids(AVBufferRef *hw_frames_ref)
287 {
288     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
289     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
290     int                  nb_surfaces = frames_hwctx->nb_surfaces;
291
292     AVBufferRef *mids_buf, *hw_frames_ref1;
293     QSVMid *mids;
294     int i;
295
296     hw_frames_ref1 = av_buffer_ref(hw_frames_ref);
297     if (!hw_frames_ref1)
298         return NULL;
299
300     mids = av_mallocz_array(nb_surfaces, sizeof(*mids));
301     if (!mids) {
302         av_buffer_unref(&hw_frames_ref1);
303         return NULL;
304     }
305
306     mids_buf = av_buffer_create((uint8_t*)mids, nb_surfaces * sizeof(*mids),
307                                 mids_buf_free, hw_frames_ref1, 0);
308     if (!mids_buf) {
309         av_buffer_unref(&hw_frames_ref1);
310         av_freep(&mids);
311         return NULL;
312     }
313
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;
318     }
319
320     return mids_buf;
321 }
322
323 static int qsv_setup_mids(mfxFrameAllocResponse *resp, AVBufferRef *hw_frames_ref,
324                           AVBufferRef *mids_buf)
325 {
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;
330     int i;
331
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));
336     if (!resp->mids)
337         return AVERROR(ENOMEM);
338
339     for (i = 0; i < nb_surfaces; i++)
340         resp->mids[i] = &mids[i];
341     resp->NumFrameActual = nb_surfaces;
342
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);
347     }
348
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);
354     }
355
356     return 0;
357 }
358
359 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
360                                  mfxFrameAllocResponse *resp)
361 {
362     QSVFramesContext *ctx = pthis;
363     int ret;
364
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;
371
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;
378
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;
386         }
387
388         ret = qsv_setup_mids(resp, ctx->hw_frames_ctx, ctx->mids_buf);
389         if (ret < 0) {
390             av_log(ctx->logctx, AV_LOG_ERROR,
391                    "Error filling an external frame allocation request\n");
392             return MFX_ERR_MEMORY_ALLOC;
393         }
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;
398
399         AVBufferRef *frames_ref, *mids_buf;
400         AVHWFramesContext *frames_ctx;
401         AVQSVFramesContext *frames_hwctx;
402
403         frames_ref = av_hwframe_ctx_alloc(ext_frames_ctx->device_ref);
404         if (!frames_ref)
405             return MFX_ERR_MEMORY_ALLOC;
406
407         frames_ctx   = (AVHWFramesContext*)frames_ref->data;
408         frames_hwctx = frames_ctx->hwctx;
409
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;
415
416         frames_hwctx->frame_type      = req->Type;
417
418         ret = av_hwframe_ctx_init(frames_ref);
419         if (ret < 0) {
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;
425         }
426
427         mids_buf = qsv_create_mids(frames_ref);
428         if (!mids_buf) {
429             av_buffer_unref(&frames_ref);
430             return MFX_ERR_MEMORY_ALLOC;
431         }
432
433         ret = qsv_setup_mids(resp, frames_ref, mids_buf);
434         av_buffer_unref(&mids_buf);
435         av_buffer_unref(&frames_ref);
436         if (ret < 0) {
437             av_log(ctx->logctx, AV_LOG_ERROR,
438                    "Error filling an internal frame allocation request\n");
439             return MFX_ERR_MEMORY_ALLOC;
440         }
441     } else {
442         return MFX_ERR_UNSUPPORTED;
443     }
444
445     return MFX_ERR_NONE;
446 }
447
448 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
449 {
450     av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
451     av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual + 1]);
452     av_freep(&resp->mids);
453     return MFX_ERR_NONE;
454 }
455
456 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
457 {
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;
461     int size;
462     int ret;
463     mfxStatus err;
464
465     if (qsv_mid->locked_frame)
466         return MFX_ERR_UNDEFINED_BEHAVIOR;
467
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;
473
474     /* wrap the provided handle in a hwaccel AVFrame */
475     qsv_mid->hw_frame = av_frame_alloc();
476     if (!qsv_mid->hw_frame)
477         goto fail;
478
479     qsv_mid->hw_frame->data[3] = (uint8_t*)&qsv_mid->surf;
480     qsv_mid->hw_frame->format  = AV_PIX_FMT_QSV;
481
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])
485         goto fail;
486
487     qsv_mid->hw_frame->width   = hw_frames_ctx->width;
488     qsv_mid->hw_frame->height  = hw_frames_ctx->height;
489
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)
492         goto fail;
493
494     qsv_mid->surf.Info = hw_frames_hwctx->surfaces[0].Info;
495     qsv_mid->surf.Data.MemId = qsv_mid->handle;
496
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);
500     if (ret < 0)
501         goto fail;
502
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;
507
508     return MFX_ERR_NONE;
509 fail:
510     av_frame_free(&qsv_mid->hw_frame);
511     av_frame_free(&qsv_mid->locked_frame);
512     return MFX_ERR_MEMORY_ALLOC;
513 }
514
515 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
516 {
517     QSVMid *qsv_mid = mid;
518     int ret;
519
520     av_frame_free(&qsv_mid->locked_frame);
521     av_frame_free(&qsv_mid->hw_frame);
522
523     return MFX_ERR_NONE;
524 }
525
526 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
527 {
528     QSVMid *qsv_mid = (QSVMid*)mid;
529     *hdl = qsv_mid->handle;
530     return MFX_ERR_NONE;
531 }
532
533 int ff_qsv_init_session_hwcontext(AVCodecContext *avctx, mfxSession *psession,
534                                   QSVFramesContext *qsv_frames_ctx,
535                                   const char *load_plugins, int opaque)
536 {
537     static const mfxHandleType handle_types[] = {
538         MFX_HANDLE_VA_DISPLAY,
539         MFX_HANDLE_D3D9_DEVICE_MANAGER,
540         MFX_HANDLE_D3D11_DEVICE,
541     };
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,
549     };
550
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;
555
556     mfxSession    session;
557     mfxVersion    ver;
558     mfxIMPL       impl;
559     mfxHDL        handle = NULL;
560     mfxHandleType handle_type;
561     mfxStatus err;
562
563     int i, ret;
564
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");
571
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];
576             break;
577         }
578         handle = NULL;
579     }
580     if (!handle) {
581         av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
582                "from the session\n");
583     }
584
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");
589
590     if (handle) {
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");
595     }
596
597     ret = qsv_load_plugins(session, load_plugins, avctx);
598     if (ret < 0) {
599         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
600         return ret;
601     }
602
603     if (!opaque) {
604         qsv_frames_ctx->logctx = avctx;
605
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;
613
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");
618     }
619
620     *psession = session;
621     return 0;
622 }