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