]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsv.c
avcodec/mjpegdec: Check for odd progressive RGB
[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 = AV_PICTURE_TYPE_NONE;
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     default:
219         av_assert0(0);
220     }
221
222     return type;
223 }
224
225 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
226                             void *logctx)
227 {
228     if (!load_plugins || !*load_plugins)
229         return 0;
230
231     while (*load_plugins) {
232         mfxPluginUID uid;
233         mfxStatus ret;
234         int i, err = 0;
235
236         char *plugin = av_get_token(&load_plugins, ":");
237         if (!plugin)
238             return AVERROR(ENOMEM);
239         if (strlen(plugin) != 2 * sizeof(uid.Data)) {
240             av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID length\n");
241             err = AVERROR(EINVAL);
242             goto load_plugin_fail;
243         }
244
245         for (i = 0; i < sizeof(uid.Data); i++) {
246             err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
247             if (err != 1) {
248                 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
249                 err = AVERROR(EINVAL);
250                 goto load_plugin_fail;
251             }
252
253         }
254
255         ret = MFXVideoUSER_Load(session, &uid, 1);
256         if (ret < 0) {
257             char errorbuf[128];
258             snprintf(errorbuf, sizeof(errorbuf),
259                      "Could not load the requested plugin '%s'", plugin);
260             err = ff_qsv_print_error(logctx, ret, errorbuf);
261             goto load_plugin_fail;
262         }
263
264         if (*load_plugins)
265             load_plugins++;
266 load_plugin_fail:
267         av_freep(&plugin);
268         if (err < 0)
269             return err;
270     }
271
272     return 0;
273
274 }
275
276 int ff_qsv_init_internal_session(AVCodecContext *avctx, mfxSession *session,
277                                  const char *load_plugins)
278 {
279     mfxIMPL impl   = MFX_IMPL_AUTO_ANY;
280     mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
281
282     const char *desc;
283     int ret;
284
285     ret = MFXInit(impl, &ver, session);
286     if (ret < 0)
287         return ff_qsv_print_error(avctx, ret,
288                                   "Error initializing an internal MFX session");
289
290     ret = qsv_load_plugins(*session, load_plugins, avctx);
291     if (ret < 0) {
292         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
293         return ret;
294     }
295
296     MFXQueryIMPL(*session, &impl);
297
298     switch (MFX_IMPL_BASETYPE(impl)) {
299     case MFX_IMPL_SOFTWARE:
300         desc = "software";
301         break;
302     case MFX_IMPL_HARDWARE:
303     case MFX_IMPL_HARDWARE2:
304     case MFX_IMPL_HARDWARE3:
305     case MFX_IMPL_HARDWARE4:
306         desc = "hardware accelerated";
307         break;
308     default:
309         desc = "unknown";
310     }
311
312     av_log(avctx, AV_LOG_VERBOSE,
313            "Initialized an internal MFX session using %s implementation\n",
314            desc);
315
316     return 0;
317 }
318
319 static void mids_buf_free(void *opaque, uint8_t *data)
320 {
321     AVBufferRef *hw_frames_ref = opaque;
322     av_buffer_unref(&hw_frames_ref);
323     av_freep(&data);
324 }
325
326 static AVBufferRef *qsv_create_mids(AVBufferRef *hw_frames_ref)
327 {
328     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
329     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
330     int                  nb_surfaces = frames_hwctx->nb_surfaces;
331
332     AVBufferRef *mids_buf, *hw_frames_ref1;
333     QSVMid *mids;
334     int i;
335
336     hw_frames_ref1 = av_buffer_ref(hw_frames_ref);
337     if (!hw_frames_ref1)
338         return NULL;
339
340     mids = av_mallocz_array(nb_surfaces, sizeof(*mids));
341     if (!mids) {
342         av_buffer_unref(&hw_frames_ref1);
343         return NULL;
344     }
345
346     mids_buf = av_buffer_create((uint8_t*)mids, nb_surfaces * sizeof(*mids),
347                                 mids_buf_free, hw_frames_ref1, 0);
348     if (!mids_buf) {
349         av_buffer_unref(&hw_frames_ref1);
350         av_freep(&mids);
351         return NULL;
352     }
353
354     for (i = 0; i < nb_surfaces; i++) {
355         QSVMid *mid = &mids[i];
356         mid->handle        = frames_hwctx->surfaces[i].Data.MemId;
357         mid->hw_frames_ref = hw_frames_ref1;
358     }
359
360     return mids_buf;
361 }
362
363 static int qsv_setup_mids(mfxFrameAllocResponse *resp, AVBufferRef *hw_frames_ref,
364                           AVBufferRef *mids_buf)
365 {
366     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)hw_frames_ref->data;
367     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
368     QSVMid                     *mids = (QSVMid*)mids_buf->data;
369     int                  nb_surfaces = frames_hwctx->nb_surfaces;
370     int i;
371
372     // the allocated size of the array is two larger than the number of
373     // surfaces, we store the references to the frames context and the
374     // QSVMid array there
375     resp->mids = av_mallocz_array(nb_surfaces + 2, sizeof(*resp->mids));
376     if (!resp->mids)
377         return AVERROR(ENOMEM);
378
379     for (i = 0; i < nb_surfaces; i++)
380         resp->mids[i] = &mids[i];
381     resp->NumFrameActual = nb_surfaces;
382
383     resp->mids[resp->NumFrameActual] = (mfxMemId)av_buffer_ref(hw_frames_ref);
384     if (!resp->mids[resp->NumFrameActual]) {
385         av_freep(&resp->mids);
386         return AVERROR(ENOMEM);
387     }
388
389     resp->mids[resp->NumFrameActual + 1] = av_buffer_ref(mids_buf);
390     if (!resp->mids[resp->NumFrameActual + 1]) {
391         av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
392         av_freep(&resp->mids);
393         return AVERROR(ENOMEM);
394     }
395
396     return 0;
397 }
398
399 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
400                                  mfxFrameAllocResponse *resp)
401 {
402     QSVFramesContext *ctx = pthis;
403     int ret;
404
405     /* this should only be called from an encoder or decoder and
406      * only allocates video memory frames */
407     if (!(req->Type & (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET |
408                        MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))         ||
409         !(req->Type & (MFX_MEMTYPE_FROM_DECODE | MFX_MEMTYPE_FROM_ENCODE)))
410         return MFX_ERR_UNSUPPORTED;
411
412     if (req->Type & MFX_MEMTYPE_EXTERNAL_FRAME) {
413         /* external frames -- fill from the caller-supplied frames context */
414         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
415         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
416         mfxFrameInfo      *i  = &req->Info;
417         mfxFrameInfo      *i1 = &frames_hwctx->surfaces[0].Info;
418
419         if (i->Width  > i1->Width  || i->Height > i1->Height ||
420             i->FourCC != i1->FourCC || i->ChromaFormat != i1->ChromaFormat) {
421             av_log(ctx->logctx, AV_LOG_ERROR, "Mismatching surface properties in an "
422                    "allocation request: %dx%d %d %d vs %dx%d %d %d\n",
423                    i->Width,  i->Height,  i->FourCC,  i->ChromaFormat,
424                    i1->Width, i1->Height, i1->FourCC, i1->ChromaFormat);
425             return MFX_ERR_UNSUPPORTED;
426         }
427
428         ret = qsv_setup_mids(resp, ctx->hw_frames_ctx, ctx->mids_buf);
429         if (ret < 0) {
430             av_log(ctx->logctx, AV_LOG_ERROR,
431                    "Error filling an external frame allocation request\n");
432             return MFX_ERR_MEMORY_ALLOC;
433         }
434     } else if (req->Type & MFX_MEMTYPE_INTERNAL_FRAME) {
435         /* internal frames -- allocate a new hw frames context */
436         AVHWFramesContext *ext_frames_ctx = (AVHWFramesContext*)ctx->hw_frames_ctx->data;
437         mfxFrameInfo      *i  = &req->Info;
438
439         AVBufferRef *frames_ref, *mids_buf;
440         AVHWFramesContext *frames_ctx;
441         AVQSVFramesContext *frames_hwctx;
442
443         frames_ref = av_hwframe_ctx_alloc(ext_frames_ctx->device_ref);
444         if (!frames_ref)
445             return MFX_ERR_MEMORY_ALLOC;
446
447         frames_ctx   = (AVHWFramesContext*)frames_ref->data;
448         frames_hwctx = frames_ctx->hwctx;
449
450         frames_ctx->format            = AV_PIX_FMT_QSV;
451         frames_ctx->sw_format         = qsv_map_fourcc(i->FourCC);
452         frames_ctx->width             = i->Width;
453         frames_ctx->height            = i->Height;
454         frames_ctx->initial_pool_size = req->NumFrameSuggested;
455
456         frames_hwctx->frame_type      = req->Type;
457
458         ret = av_hwframe_ctx_init(frames_ref);
459         if (ret < 0) {
460             av_log(ctx->logctx, AV_LOG_ERROR,
461                    "Error initializing a frames context for an internal frame "
462                    "allocation request\n");
463             av_buffer_unref(&frames_ref);
464             return MFX_ERR_MEMORY_ALLOC;
465         }
466
467         mids_buf = qsv_create_mids(frames_ref);
468         if (!mids_buf) {
469             av_buffer_unref(&frames_ref);
470             return MFX_ERR_MEMORY_ALLOC;
471         }
472
473         ret = qsv_setup_mids(resp, frames_ref, mids_buf);
474         av_buffer_unref(&mids_buf);
475         av_buffer_unref(&frames_ref);
476         if (ret < 0) {
477             av_log(ctx->logctx, AV_LOG_ERROR,
478                    "Error filling an internal frame allocation request\n");
479             return MFX_ERR_MEMORY_ALLOC;
480         }
481     } else {
482         return MFX_ERR_UNSUPPORTED;
483     }
484
485     return MFX_ERR_NONE;
486 }
487
488 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
489 {
490     av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual]);
491     av_buffer_unref((AVBufferRef**)&resp->mids[resp->NumFrameActual + 1]);
492     av_freep(&resp->mids);
493     return MFX_ERR_NONE;
494 }
495
496 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
497 {
498     QSVMid *qsv_mid = mid;
499     AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)qsv_mid->hw_frames_ref->data;
500     AVQSVFramesContext *hw_frames_hwctx = hw_frames_ctx->hwctx;
501     int ret;
502
503     if (qsv_mid->locked_frame)
504         return MFX_ERR_UNDEFINED_BEHAVIOR;
505
506     /* Allocate a system memory frame that will hold the mapped data. */
507     qsv_mid->locked_frame = av_frame_alloc();
508     if (!qsv_mid->locked_frame)
509         return MFX_ERR_MEMORY_ALLOC;
510     qsv_mid->locked_frame->format  = hw_frames_ctx->sw_format;
511
512     /* wrap the provided handle in a hwaccel AVFrame */
513     qsv_mid->hw_frame = av_frame_alloc();
514     if (!qsv_mid->hw_frame)
515         goto fail;
516
517     qsv_mid->hw_frame->data[3] = (uint8_t*)&qsv_mid->surf;
518     qsv_mid->hw_frame->format  = AV_PIX_FMT_QSV;
519
520     // doesn't really matter what buffer is used here
521     qsv_mid->hw_frame->buf[0]  = av_buffer_alloc(1);
522     if (!qsv_mid->hw_frame->buf[0])
523         goto fail;
524
525     qsv_mid->hw_frame->width   = hw_frames_ctx->width;
526     qsv_mid->hw_frame->height  = hw_frames_ctx->height;
527
528     qsv_mid->hw_frame->hw_frames_ctx = av_buffer_ref(qsv_mid->hw_frames_ref);
529     if (!qsv_mid->hw_frame->hw_frames_ctx)
530         goto fail;
531
532     qsv_mid->surf.Info = hw_frames_hwctx->surfaces[0].Info;
533     qsv_mid->surf.Data.MemId = qsv_mid->handle;
534
535     /* map the data to the system memory */
536     ret = av_hwframe_map(qsv_mid->locked_frame, qsv_mid->hw_frame,
537                          AV_HWFRAME_MAP_DIRECT);
538     if (ret < 0)
539         goto fail;
540
541     ptr->Pitch = qsv_mid->locked_frame->linesize[0];
542     ptr->Y     = qsv_mid->locked_frame->data[0];
543     ptr->U     = qsv_mid->locked_frame->data[1];
544     ptr->V     = qsv_mid->locked_frame->data[1] + 1;
545
546     return MFX_ERR_NONE;
547 fail:
548     av_frame_free(&qsv_mid->hw_frame);
549     av_frame_free(&qsv_mid->locked_frame);
550     return MFX_ERR_MEMORY_ALLOC;
551 }
552
553 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
554 {
555     QSVMid *qsv_mid = mid;
556
557     av_frame_free(&qsv_mid->locked_frame);
558     av_frame_free(&qsv_mid->hw_frame);
559
560     return MFX_ERR_NONE;
561 }
562
563 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
564 {
565     QSVMid *qsv_mid = (QSVMid*)mid;
566     *hdl = qsv_mid->handle;
567     return MFX_ERR_NONE;
568 }
569
570 int ff_qsv_init_session_device(AVCodecContext *avctx, mfxSession *psession,
571                                AVBufferRef *device_ref, const char *load_plugins)
572 {
573     static const mfxHandleType handle_types[] = {
574         MFX_HANDLE_VA_DISPLAY,
575         MFX_HANDLE_D3D9_DEVICE_MANAGER,
576         MFX_HANDLE_D3D11_DEVICE,
577     };
578     AVHWDeviceContext    *device_ctx = (AVHWDeviceContext*)device_ref->data;
579     AVQSVDeviceContext *device_hwctx = device_ctx->hwctx;
580     mfxSession        parent_session = device_hwctx->session;
581
582     mfxSession    session;
583     mfxVersion    ver;
584     mfxIMPL       impl;
585     mfxHDL        handle = NULL;
586     mfxHandleType handle_type;
587     mfxStatus err;
588
589     int i, ret;
590
591     err = MFXQueryIMPL(parent_session, &impl);
592     if (err == MFX_ERR_NONE)
593         err = MFXQueryVersion(parent_session, &ver);
594     if (err != MFX_ERR_NONE)
595         return ff_qsv_print_error(avctx, err,
596                                   "Error querying the session attributes");
597
598     for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
599         err = MFXVideoCORE_GetHandle(parent_session, handle_types[i], &handle);
600         if (err == MFX_ERR_NONE) {
601             handle_type = handle_types[i];
602             break;
603         }
604         handle = NULL;
605     }
606     if (!handle) {
607         av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
608                "from the session\n");
609     }
610
611     err = MFXInit(impl, &ver, &session);
612     if (err != MFX_ERR_NONE)
613         return ff_qsv_print_error(avctx, err,
614                                   "Error initializing a child MFX session");
615
616     if (handle) {
617         err = MFXVideoCORE_SetHandle(session, handle_type, handle);
618         if (err != MFX_ERR_NONE)
619             return ff_qsv_print_error(avctx, err,
620                                       "Error setting a HW handle");
621     }
622
623     if (QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 25)) {
624         err = MFXJoinSession(parent_session, session);
625         if (err != MFX_ERR_NONE)
626             return ff_qsv_print_error(avctx, err,
627                                       "Error joining session");
628     }
629
630     ret = qsv_load_plugins(session, load_plugins, avctx);
631     if (ret < 0) {
632         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
633         return ret;
634     }
635
636     *psession = session;
637     return 0;
638 }
639
640 int ff_qsv_init_session_frames(AVCodecContext *avctx, mfxSession *psession,
641                                QSVFramesContext *qsv_frames_ctx,
642                                const char *load_plugins, int opaque)
643 {
644     mfxFrameAllocator frame_allocator = {
645         .pthis  = qsv_frames_ctx,
646         .Alloc  = qsv_frame_alloc,
647         .Lock   = qsv_frame_lock,
648         .Unlock = qsv_frame_unlock,
649         .GetHDL = qsv_frame_get_hdl,
650         .Free   = qsv_frame_free,
651     };
652
653     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)qsv_frames_ctx->hw_frames_ctx->data;
654     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
655
656     mfxSession    session;
657     mfxStatus err;
658
659     int ret;
660
661     ret = ff_qsv_init_session_device(avctx, &session,
662                                      frames_ctx->device_ref, load_plugins);
663     if (ret < 0)
664         return ret;
665
666     if (!opaque) {
667         qsv_frames_ctx->logctx = avctx;
668
669         /* allocate the memory ids for the external frames */
670         av_buffer_unref(&qsv_frames_ctx->mids_buf);
671         qsv_frames_ctx->mids_buf = qsv_create_mids(qsv_frames_ctx->hw_frames_ctx);
672         if (!qsv_frames_ctx->mids_buf)
673             return AVERROR(ENOMEM);
674         qsv_frames_ctx->mids    = (QSVMid*)qsv_frames_ctx->mids_buf->data;
675         qsv_frames_ctx->nb_mids = frames_hwctx->nb_surfaces;
676
677         err = MFXVideoCORE_SetFrameAllocator(session, &frame_allocator);
678         if (err != MFX_ERR_NONE)
679             return ff_qsv_print_error(avctx, err,
680                                       "Error setting a frame allocator");
681     }
682
683     *psession = session;
684     return 0;
685 }