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