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