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