]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsv.c
Merge commit 'b57e38f52cc3f31a27105c28887d57cd6812c3eb'
[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
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "libavutil/avstring.h"
28 #include "libavutil/common.h"
29 #include "libavutil/error.h"
30 #include "libavutil/hwcontext.h"
31 #include "libavutil/hwcontext_qsv.h"
32
33 #include "avcodec.h"
34 #include "qsv_internal.h"
35
36 int ff_qsv_codec_id_to_mfx(enum AVCodecID codec_id)
37 {
38     switch (codec_id) {
39     case AV_CODEC_ID_H264:
40         return MFX_CODEC_AVC;
41 #if QSV_VERSION_ATLEAST(1, 8)
42     case AV_CODEC_ID_HEVC:
43         return MFX_CODEC_HEVC;
44 #endif
45     case AV_CODEC_ID_MPEG1VIDEO:
46     case AV_CODEC_ID_MPEG2VIDEO:
47         return MFX_CODEC_MPEG2;
48     case AV_CODEC_ID_VC1:
49         return MFX_CODEC_VC1;
50     default:
51         break;
52     }
53
54     return AVERROR(ENOSYS);
55 }
56
57 int ff_qsv_profile_to_mfx(enum AVCodecID codec_id, int profile)
58 {
59     if (profile == FF_PROFILE_UNKNOWN)
60         return MFX_PROFILE_UNKNOWN;
61     switch (codec_id) {
62     case AV_CODEC_ID_H264:
63     case AV_CODEC_ID_HEVC:
64         return profile;
65     case AV_CODEC_ID_VC1:
66         return 4 * profile + 1;
67     case AV_CODEC_ID_MPEG2VIDEO:
68         return 0x10 * profile;
69     }
70     return MFX_PROFILE_UNKNOWN;
71 }
72
73 static const struct {
74     mfxStatus   mfxerr;
75     int         averr;
76     const char *desc;
77 } qsv_errors[] = {
78     { MFX_ERR_NONE,                     0,               "success"                              },
79     { MFX_ERR_UNKNOWN,                  AVERROR_UNKNOWN, "unknown error"                        },
80     { MFX_ERR_NULL_PTR,                 AVERROR(EINVAL), "NULL pointer"                         },
81     { MFX_ERR_UNSUPPORTED,              AVERROR(ENOSYS), "unsupported"                          },
82     { MFX_ERR_MEMORY_ALLOC,             AVERROR(ENOMEM), "failed to allocate memory"            },
83     { MFX_ERR_NOT_ENOUGH_BUFFER,        AVERROR(ENOMEM), "insufficient input/output buffer"     },
84     { MFX_ERR_INVALID_HANDLE,           AVERROR(EINVAL), "invalid handle"                       },
85     { MFX_ERR_LOCK_MEMORY,              AVERROR(EIO),    "failed to lock the memory block"      },
86     { MFX_ERR_NOT_INITIALIZED,          AVERROR_BUG,     "not initialized"                      },
87     { MFX_ERR_NOT_FOUND,                AVERROR(ENOSYS), "specified object was not found"       },
88     { MFX_ERR_MORE_DATA,                AVERROR(EAGAIN), "expect more data at input"            },
89     { MFX_ERR_MORE_SURFACE,             AVERROR(EAGAIN), "expect more surface at output"        },
90     { MFX_ERR_ABORTED,                  AVERROR_UNKNOWN, "operation aborted"                    },
91     { MFX_ERR_DEVICE_LOST,              AVERROR(EIO),    "device lost"                          },
92     { MFX_ERR_INCOMPATIBLE_VIDEO_PARAM, AVERROR(EINVAL), "incompatible video parameters"        },
93     { MFX_ERR_INVALID_VIDEO_PARAM,      AVERROR(EINVAL), "invalid video parameters"             },
94     { MFX_ERR_UNDEFINED_BEHAVIOR,       AVERROR_BUG,     "undefined behavior"                   },
95     { MFX_ERR_DEVICE_FAILED,            AVERROR(EIO),    "device failed"                        },
96     { MFX_ERR_MORE_BITSTREAM,           AVERROR(EAGAIN), "expect more bitstream at output"      },
97     { MFX_ERR_INCOMPATIBLE_AUDIO_PARAM, AVERROR(EINVAL), "incompatible audio parameters"        },
98     { MFX_ERR_INVALID_AUDIO_PARAM,      AVERROR(EINVAL), "invalid audio parameters"             },
99
100     { MFX_WRN_IN_EXECUTION,             0,               "operation in execution"               },
101     { MFX_WRN_DEVICE_BUSY,              0,               "device busy"                          },
102     { MFX_WRN_VIDEO_PARAM_CHANGED,      0,               "video parameters changed"             },
103     { MFX_WRN_PARTIAL_ACCELERATION,     0,               "partial acceleration"                 },
104     { MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, 0,               "incompatible video parameters"        },
105     { MFX_WRN_VALUE_NOT_CHANGED,        0,               "value is saturated"                   },
106     { MFX_WRN_OUT_OF_RANGE,             0,               "value out of range"                   },
107     { MFX_WRN_FILTER_SKIPPED,           0,               "filter skipped"                       },
108     { MFX_WRN_INCOMPATIBLE_AUDIO_PARAM, 0,               "incompatible audio parameters"        },
109 };
110
111 int ff_qsv_map_error(mfxStatus mfx_err, const char **desc)
112 {
113     int i;
114     for (i = 0; i < FF_ARRAY_ELEMS(qsv_errors); i++) {
115         if (qsv_errors[i].mfxerr == mfx_err) {
116             if (desc)
117                 *desc = qsv_errors[i].desc;
118             return qsv_errors[i].averr;
119         }
120     }
121     if (desc)
122         *desc = "unknown error";
123     return AVERROR_UNKNOWN;
124 }
125
126 int ff_qsv_print_error(void *log_ctx, mfxStatus err,
127                        const char *error_string)
128 {
129     const char *desc;
130     int ret;
131     ret = ff_qsv_map_error(err, &desc);
132     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
133     return ret;
134 }
135
136 int ff_qsv_print_warning(void *log_ctx, mfxStatus err,
137                          const char *warning_string)
138 {
139     const char *desc;
140     int ret;
141     ret = ff_qsv_map_error(err, &desc);
142     av_log(log_ctx, AV_LOG_WARNING, "%s: %s (%d)\n", warning_string, desc, err);
143     return ret;
144 }
145
146 int ff_qsv_map_pixfmt(enum AVPixelFormat format, uint32_t *fourcc)
147 {
148     switch (format) {
149     case AV_PIX_FMT_YUV420P:
150     case AV_PIX_FMT_YUVJ420P:
151     case AV_PIX_FMT_NV12:
152         *fourcc = MFX_FOURCC_NV12;
153         return AV_PIX_FMT_NV12;
154     case AV_PIX_FMT_YUV420P10:
155     case AV_PIX_FMT_P010:
156         *fourcc = MFX_FOURCC_P010;
157         return AV_PIX_FMT_P010;
158     default:
159         return AVERROR(ENOSYS);
160     }
161 }
162
163 static int qsv_load_plugins(mfxSession session, const char *load_plugins,
164                             void *logctx)
165 {
166     if (!load_plugins || !*load_plugins)
167         return 0;
168
169     while (*load_plugins) {
170         mfxPluginUID uid;
171         mfxStatus ret;
172         int i, err = 0;
173
174         char *plugin = av_get_token(&load_plugins, ":");
175         if (!plugin)
176             return AVERROR(ENOMEM);
177         if (strlen(plugin) != 2 * sizeof(uid.Data)) {
178             av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID length\n");
179             err = AVERROR(EINVAL);
180             goto load_plugin_fail;
181         }
182
183         for (i = 0; i < sizeof(uid.Data); i++) {
184             err = sscanf(plugin + 2 * i, "%2hhx", uid.Data + i);
185             if (err != 1) {
186                 av_log(logctx, AV_LOG_ERROR, "Invalid plugin UID\n");
187                 err = AVERROR(EINVAL);
188                 goto load_plugin_fail;
189             }
190
191         }
192
193         ret = MFXVideoUSER_Load(session, &uid, 1);
194         if (ret < 0) {
195             char errorbuf[128];
196             snprintf(errorbuf, sizeof(errorbuf),
197                      "Could not load the requested plugin '%s'", plugin);
198             err = ff_qsv_print_error(logctx, ret, errorbuf);
199             goto load_plugin_fail;
200         }
201
202         if (*load_plugins)
203             load_plugins++;
204 load_plugin_fail:
205         av_freep(&plugin);
206         if (err < 0)
207             return err;
208     }
209
210     return 0;
211
212 }
213
214 int ff_qsv_init_internal_session(AVCodecContext *avctx, mfxSession *session,
215                                  const char *load_plugins)
216 {
217     mfxIMPL impl   = MFX_IMPL_AUTO_ANY;
218     mfxVersion ver = { { QSV_VERSION_MINOR, QSV_VERSION_MAJOR } };
219
220     const char *desc;
221     int ret;
222
223     ret = MFXInit(impl, &ver, session);
224     if (ret < 0)
225         return ff_qsv_print_error(avctx, ret,
226                                   "Error initializing an internal MFX session");
227
228     ret = qsv_load_plugins(*session, load_plugins, avctx);
229     if (ret < 0) {
230         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
231         return ret;
232     }
233
234     MFXQueryIMPL(*session, &impl);
235
236     switch (MFX_IMPL_BASETYPE(impl)) {
237     case MFX_IMPL_SOFTWARE:
238         desc = "software";
239         break;
240     case MFX_IMPL_HARDWARE:
241     case MFX_IMPL_HARDWARE2:
242     case MFX_IMPL_HARDWARE3:
243     case MFX_IMPL_HARDWARE4:
244         desc = "hardware accelerated";
245         break;
246     default:
247         desc = "unknown";
248     }
249
250     av_log(avctx, AV_LOG_VERBOSE,
251            "Initialized an internal MFX session using %s implementation\n",
252            desc);
253
254     return 0;
255 }
256
257 static mfxStatus qsv_frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
258                                  mfxFrameAllocResponse *resp)
259 {
260     QSVFramesContext *ctx = pthis;
261     mfxFrameInfo      *i  = &req->Info;
262     mfxFrameInfo      *i1 = &ctx->info;
263
264     if (!(req->Type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET) ||
265         !(req->Type & (MFX_MEMTYPE_FROM_DECODE | MFX_MEMTYPE_FROM_ENCODE)) ||
266         !(req->Type & MFX_MEMTYPE_EXTERNAL_FRAME))
267         return MFX_ERR_UNSUPPORTED;
268     if (i->Width  != i1->Width || i->Height != i1->Height ||
269         i->FourCC != i1->FourCC || i->ChromaFormat != i1->ChromaFormat) {
270         av_log(ctx, AV_LOG_ERROR, "Mismatching surface properties in an "
271                "allocation request: %dx%d %d %d vs %dx%d %d %d\n",
272                i->Width,  i->Height,  i->FourCC,  i->ChromaFormat,
273                i1->Width, i1->Height, i1->FourCC, i1->ChromaFormat);
274         return MFX_ERR_UNSUPPORTED;
275     }
276
277     resp->mids           = ctx->mids;
278     resp->NumFrameActual = ctx->nb_mids;
279
280     return MFX_ERR_NONE;
281 }
282
283 static mfxStatus qsv_frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
284 {
285     return MFX_ERR_NONE;
286 }
287
288 static mfxStatus qsv_frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
289 {
290     return MFX_ERR_UNSUPPORTED;
291 }
292
293 static mfxStatus qsv_frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
294 {
295     return MFX_ERR_UNSUPPORTED;
296 }
297
298 static mfxStatus qsv_frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
299 {
300     *hdl = mid;
301     return MFX_ERR_NONE;
302 }
303
304 int ff_qsv_init_session_hwcontext(AVCodecContext *avctx, mfxSession *psession,
305                                   QSVFramesContext *qsv_frames_ctx,
306                                   const char *load_plugins, int opaque)
307 {
308     static const mfxHandleType handle_types[] = {
309         MFX_HANDLE_VA_DISPLAY,
310         MFX_HANDLE_D3D9_DEVICE_MANAGER,
311         MFX_HANDLE_D3D11_DEVICE,
312     };
313     mfxFrameAllocator frame_allocator = {
314         .pthis  = qsv_frames_ctx,
315         .Alloc  = qsv_frame_alloc,
316         .Lock   = qsv_frame_lock,
317         .Unlock = qsv_frame_unlock,
318         .GetHDL = qsv_frame_get_hdl,
319         .Free   = qsv_frame_free,
320     };
321
322     AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)qsv_frames_ctx->hw_frames_ctx->data;
323     AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
324     AVQSVDeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
325     mfxSession        parent_session = device_hwctx->session;
326
327     mfxSession    session;
328     mfxVersion    ver;
329     mfxIMPL       impl;
330     mfxHDL        handle = NULL;
331     mfxHandleType handle_type;
332     mfxStatus err;
333
334     int i, ret;
335
336     err = MFXQueryIMPL(parent_session, &impl);
337     if (err == MFX_ERR_NONE)
338         err = MFXQueryVersion(parent_session, &ver);
339     if (err != MFX_ERR_NONE)
340         return ff_qsv_print_error(avctx, err,
341                                   "Error querying the session attributes");
342
343     for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
344         err = MFXVideoCORE_GetHandle(parent_session, handle_types[i], &handle);
345         if (err == MFX_ERR_NONE) {
346             handle_type = handle_types[i];
347             break;
348         }
349         handle = NULL;
350     }
351     if (!handle) {
352         av_log(avctx, AV_LOG_VERBOSE, "No supported hw handle could be retrieved "
353                "from the session\n");
354     }
355
356     err = MFXInit(impl, &ver, &session);
357     if (err != MFX_ERR_NONE)
358         return ff_qsv_print_error(avctx, err,
359                                   "Error initializing a child MFX session");
360
361     if (handle) {
362         err = MFXVideoCORE_SetHandle(session, handle_type, handle);
363         if (err != MFX_ERR_NONE)
364             return ff_qsv_print_error(avctx, err,
365                                       "Error setting a HW handle");
366     }
367
368     ret = qsv_load_plugins(session, load_plugins, avctx);
369     if (ret < 0) {
370         av_log(avctx, AV_LOG_ERROR, "Error loading plugins\n");
371         return ret;
372     }
373
374     if (!opaque) {
375         av_freep(&qsv_frames_ctx->mids);
376         qsv_frames_ctx->mids = av_mallocz_array(frames_hwctx->nb_surfaces,
377                                                 sizeof(*qsv_frames_ctx->mids));
378         if (!qsv_frames_ctx->mids)
379             return AVERROR(ENOMEM);
380
381         qsv_frames_ctx->info    = frames_hwctx->surfaces[0].Info;
382         qsv_frames_ctx->nb_mids = frames_hwctx->nb_surfaces;
383         for (i = 0; i < frames_hwctx->nb_surfaces; i++)
384             qsv_frames_ctx->mids[i] = frames_hwctx->surfaces[i].Data.MemId;
385
386         err = MFXVideoCORE_SetFrameAllocator(session, &frame_allocator);
387         if (err != MFX_ERR_NONE)
388             return ff_qsv_print_error(avctx, err,
389                                       "Error setting a frame allocator");
390     }
391
392     *psession = session;
393     return 0;
394 }