avutil/hwcontext_dxva.c: Use new safe dlopen code.
[ffmpeg.git] / libavutil / hwcontext_dxva2.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <windows.h>
20
21 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600
22 #undef _WIN32_WINNT
23 #define _WIN32_WINNT 0x0600
24 #endif
25 #define DXVA2API_USE_BITFIELDS
26 #define COBJMACROS
27
28 #include <d3d9.h>
29 #include <dxva2api.h>
30 #include <initguid.h>
31
32 #include "avassert.h"
33 #include "common.h"
34 #include "hwcontext.h"
35 #include "hwcontext_dxva2.h"
36 #include "hwcontext_internal.h"
37 #include "imgutils.h"
38 #include "pixdesc.h"
39 #include "pixfmt.h"
40 #include "compat/w32dlfcn.h"
41
42 typedef IDirect3D9* WINAPI pDirect3DCreate9(UINT);
43 typedef HRESULT WINAPI pCreateDeviceManager9(UINT *, IDirect3DDeviceManager9 **);
44
45 typedef struct DXVA2FramesContext {
46     IDirect3DSurface9 **surfaces_internal;
47     int              nb_surfaces_used;
48
49     HANDLE  device_handle;
50     IDirectXVideoAccelerationService *service;
51
52     D3DFORMAT format;
53 } DXVA2FramesContext;
54
55 typedef struct DXVA2DevicePriv {
56     HMODULE d3dlib;
57     HMODULE dxva2lib;
58
59     HANDLE device_handle;
60
61     IDirect3D9       *d3d9;
62     IDirect3DDevice9 *d3d9device;
63 } DXVA2DevicePriv;
64
65 static const struct {
66     D3DFORMAT d3d_format;
67     enum AVPixelFormat pix_fmt;
68 } supported_formats[] = {
69     { MKTAG('N', 'V', '1', '2'), AV_PIX_FMT_NV12 },
70     { MKTAG('P', '0', '1', '0'), AV_PIX_FMT_P010 },
71 };
72
73 DEFINE_GUID(video_decoder_service,   0xfc51a551, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
74 DEFINE_GUID(video_processor_service, 0xfc51a552, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
75
76 static void dxva2_frames_uninit(AVHWFramesContext *ctx)
77 {
78     AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
79     AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
80     DXVA2FramesContext *s = ctx->internal->priv;
81     int i;
82
83     if (frames_hwctx->decoder_to_release)
84         IDirectXVideoDecoder_Release(frames_hwctx->decoder_to_release);
85
86     if (s->surfaces_internal) {
87         for (i = 0; i < frames_hwctx->nb_surfaces; i++) {
88             if (s->surfaces_internal[i])
89                 IDirect3DSurface9_Release(s->surfaces_internal[i]);
90         }
91     }
92     av_freep(&s->surfaces_internal);
93
94     if (s->service) {
95         IDirectXVideoAccelerationService_Release(s->service);
96         s->service = NULL;
97     }
98
99     if (s->device_handle != INVALID_HANDLE_VALUE) {
100         IDirect3DDeviceManager9_CloseDeviceHandle(device_hwctx->devmgr, s->device_handle);
101         s->device_handle = INVALID_HANDLE_VALUE;
102     }
103 }
104
105 static AVBufferRef *dxva2_pool_alloc(void *opaque, int size)
106 {
107     AVHWFramesContext      *ctx = (AVHWFramesContext*)opaque;
108     DXVA2FramesContext       *s = ctx->internal->priv;
109     AVDXVA2FramesContext *hwctx = ctx->hwctx;
110
111     if (s->nb_surfaces_used < hwctx->nb_surfaces) {
112         s->nb_surfaces_used++;
113         return av_buffer_create((uint8_t*)s->surfaces_internal[s->nb_surfaces_used - 1],
114                                 sizeof(*hwctx->surfaces), NULL, 0, 0);
115     }
116
117     return NULL;
118 }
119
120 static int dxva2_init_pool(AVHWFramesContext *ctx)
121 {
122     AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
123     AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
124     DXVA2FramesContext              *s = ctx->internal->priv;
125     int decode = (frames_hwctx->surface_type == DXVA2_VideoDecoderRenderTarget);
126
127     int i;
128     HRESULT hr;
129
130     if (ctx->initial_pool_size <= 0)
131         return 0;
132
133     hr = IDirect3DDeviceManager9_OpenDeviceHandle(device_hwctx->devmgr, &s->device_handle);
134     if (FAILED(hr)) {
135         av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
136         return AVERROR_UNKNOWN;
137     }
138
139     hr = IDirect3DDeviceManager9_GetVideoService(device_hwctx->devmgr,
140                                                  s->device_handle,
141                                                  decode ? &video_decoder_service : &video_processor_service,
142                                                  (void **)&s->service);
143     if (FAILED(hr)) {
144         av_log(ctx, AV_LOG_ERROR, "Failed to create the video service\n");
145         return AVERROR_UNKNOWN;
146     }
147
148     for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
149         if (ctx->sw_format == supported_formats[i].pix_fmt) {
150             s->format = supported_formats[i].d3d_format;
151             break;
152         }
153     }
154     if (i == FF_ARRAY_ELEMS(supported_formats)) {
155         av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n",
156                av_get_pix_fmt_name(ctx->sw_format));
157         return AVERROR(EINVAL);
158     }
159
160     s->surfaces_internal = av_mallocz_array(ctx->initial_pool_size,
161                                             sizeof(*s->surfaces_internal));
162     if (!s->surfaces_internal)
163         return AVERROR(ENOMEM);
164
165     hr = IDirectXVideoAccelerationService_CreateSurface(s->service,
166                                                         ctx->width, ctx->height,
167                                                         ctx->initial_pool_size - 1,
168                                                         s->format, D3DPOOL_DEFAULT, 0,
169                                                         frames_hwctx->surface_type,
170                                                         s->surfaces_internal, NULL);
171     if (FAILED(hr)) {
172         av_log(ctx, AV_LOG_ERROR, "Could not create the surfaces\n");
173         return AVERROR_UNKNOWN;
174     }
175
176     ctx->internal->pool_internal = av_buffer_pool_init2(sizeof(*s->surfaces_internal),
177                                                         ctx, dxva2_pool_alloc, NULL);
178     if (!ctx->internal->pool_internal)
179         return AVERROR(ENOMEM);
180
181     frames_hwctx->surfaces    = s->surfaces_internal;
182     frames_hwctx->nb_surfaces = ctx->initial_pool_size;
183
184     return 0;
185 }
186
187 static int dxva2_frames_init(AVHWFramesContext *ctx)
188 {
189     AVDXVA2FramesContext *hwctx = ctx->hwctx;
190     DXVA2FramesContext       *s = ctx->internal->priv;
191     int ret;
192
193     if (hwctx->surface_type != DXVA2_VideoDecoderRenderTarget &&
194         hwctx->surface_type != DXVA2_VideoProcessorRenderTarget) {
195         av_log(ctx, AV_LOG_ERROR, "Unknown surface type: %lu\n",
196                hwctx->surface_type);
197         return AVERROR(EINVAL);
198     }
199
200     s->device_handle = INVALID_HANDLE_VALUE;
201
202     /* init the frame pool if the caller didn't provide one */
203     if (!ctx->pool) {
204         ret = dxva2_init_pool(ctx);
205         if (ret < 0) {
206             av_log(ctx, AV_LOG_ERROR, "Error creating an internal frame pool\n");
207             return ret;
208         }
209     }
210
211     return 0;
212 }
213
214 static int dxva2_get_buffer(AVHWFramesContext *ctx, AVFrame *frame)
215 {
216     frame->buf[0] = av_buffer_pool_get(ctx->pool);
217     if (!frame->buf[0])
218         return AVERROR(ENOMEM);
219
220     frame->data[3] = frame->buf[0]->data;
221     frame->format  = AV_PIX_FMT_DXVA2_VLD;
222     frame->width   = ctx->width;
223     frame->height  = ctx->height;
224
225     return 0;
226 }
227
228 static int dxva2_transfer_get_formats(AVHWFramesContext *ctx,
229                                       enum AVHWFrameTransferDirection dir,
230                                       enum AVPixelFormat **formats)
231 {
232     enum AVPixelFormat *fmts;
233
234     fmts = av_malloc_array(2, sizeof(*fmts));
235     if (!fmts)
236         return AVERROR(ENOMEM);
237
238     fmts[0] = ctx->sw_format;
239     fmts[1] = AV_PIX_FMT_NONE;
240
241     *formats = fmts;
242
243     return 0;
244 }
245
246 static int dxva2_transfer_data(AVHWFramesContext *ctx, AVFrame *dst,
247                                const AVFrame *src)
248 {
249     IDirect3DSurface9 *surface;
250     D3DSURFACE_DESC    surfaceDesc;
251     D3DLOCKED_RECT     LockedRect;
252     HRESULT            hr;
253
254     int download = !!src->hw_frames_ctx;
255     int bytes_per_component;
256
257     switch (ctx->sw_format) {
258         case AV_PIX_FMT_NV12:
259             bytes_per_component = 1;
260             break;
261         case AV_PIX_FMT_P010:
262             bytes_per_component = 2;
263             break;
264         default:
265             av_assert0(0);
266     }
267
268     surface = (IDirect3DSurface9*)(download ? src->data[3] : dst->data[3]);
269
270     hr = IDirect3DSurface9_GetDesc(surface, &surfaceDesc);
271     if (FAILED(hr)) {
272         av_log(ctx, AV_LOG_ERROR, "Error getting a surface description\n");
273         return AVERROR_UNKNOWN;
274     }
275
276     hr = IDirect3DSurface9_LockRect(surface, &LockedRect, NULL,
277                                     download ? D3DLOCK_READONLY : D3DLOCK_DISCARD);
278     if (FAILED(hr)) {
279         av_log(ctx, AV_LOG_ERROR, "Unable to lock DXVA2 surface\n");
280         return AVERROR_UNKNOWN;
281     }
282
283     if (download) {
284         av_image_copy_plane(dst->data[0], dst->linesize[0],
285                             (uint8_t*)LockedRect.pBits, LockedRect.Pitch,
286                             src->width * bytes_per_component, src->height);
287         av_image_copy_plane(dst->data[1], dst->linesize[1],
288                             (uint8_t*)LockedRect.pBits + LockedRect.Pitch * surfaceDesc.Height,
289                             LockedRect.Pitch, src->width * bytes_per_component, src->height / 2);
290     } else {
291         av_image_copy_plane((uint8_t*)LockedRect.pBits, LockedRect.Pitch,
292                             dst->data[0], dst->linesize[0],
293                             src->width * bytes_per_component, src->height);
294         av_image_copy_plane((uint8_t*)LockedRect.pBits + LockedRect.Pitch * surfaceDesc.Height,
295                             LockedRect.Pitch, dst->data[1], dst->linesize[1],
296                             src->width * bytes_per_component, src->height / 2);
297     }
298
299     IDirect3DSurface9_UnlockRect(surface);
300
301     return 0;
302 }
303
304 static void dxva2_device_free(AVHWDeviceContext *ctx)
305 {
306     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
307     DXVA2DevicePriv       *priv = ctx->user_opaque;
308
309     if (hwctx->devmgr && priv->device_handle != INVALID_HANDLE_VALUE)
310         IDirect3DDeviceManager9_CloseDeviceHandle(hwctx->devmgr, priv->device_handle);
311
312     if (hwctx->devmgr)
313         IDirect3DDeviceManager9_Release(hwctx->devmgr);
314
315     if (priv->d3d9device)
316         IDirect3DDevice9_Release(priv->d3d9device);
317
318     if (priv->d3d9)
319         IDirect3D9_Release(priv->d3d9);
320
321     if (priv->d3dlib)
322         dlclose(priv->d3dlib);
323
324     if (priv->dxva2lib)
325         dlclose(priv->dxva2lib);
326
327     av_freep(&ctx->user_opaque);
328 }
329
330 static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device,
331                                AVDictionary *opts, int flags)
332 {
333     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
334     DXVA2DevicePriv *priv;
335
336     pDirect3DCreate9 *createD3D = NULL;
337     pCreateDeviceManager9 *createDeviceManager = NULL;
338     D3DPRESENT_PARAMETERS d3dpp = {0};
339     D3DDISPLAYMODE        d3ddm;
340     unsigned resetToken = 0;
341     UINT adapter = D3DADAPTER_DEFAULT;
342     HRESULT hr;
343
344     if (device)
345         adapter = atoi(device);
346
347     priv = av_mallocz(sizeof(*priv));
348     if (!priv)
349         return AVERROR(ENOMEM);
350
351     ctx->user_opaque = priv;
352     ctx->free        = dxva2_device_free;
353
354     priv->device_handle = INVALID_HANDLE_VALUE;
355
356     priv->d3dlib = dlopen("d3d9.dll", 0);
357     if (!priv->d3dlib) {
358         av_log(ctx, AV_LOG_ERROR, "Failed to load D3D9 library\n");
359         return AVERROR_UNKNOWN;
360     }
361     priv->dxva2lib = dlopen("dxva2.dll", 0);
362     if (!priv->dxva2lib) {
363         av_log(ctx, AV_LOG_ERROR, "Failed to load DXVA2 library\n");
364         return AVERROR_UNKNOWN;
365     }
366
367     createD3D = (pDirect3DCreate9 *)dlsym(priv->d3dlib, "Direct3DCreate9");
368     if (!createD3D) {
369         av_log(ctx, AV_LOG_ERROR, "Failed to locate Direct3DCreate9\n");
370         return AVERROR_UNKNOWN;
371     }
372     createDeviceManager = (pCreateDeviceManager9 *)dlsym(priv->dxva2lib,
373                                                          "DXVA2CreateDirect3DDeviceManager9");
374     if (!createDeviceManager) {
375         av_log(ctx, AV_LOG_ERROR, "Failed to locate DXVA2CreateDirect3DDeviceManager9\n");
376         return AVERROR_UNKNOWN;
377     }
378
379     priv->d3d9 = createD3D(D3D_SDK_VERSION);
380     if (!priv->d3d9) {
381         av_log(ctx, AV_LOG_ERROR, "Failed to create IDirect3D object\n");
382         return AVERROR_UNKNOWN;
383     }
384
385     IDirect3D9_GetAdapterDisplayMode(priv->d3d9, adapter, &d3ddm);
386     d3dpp.Windowed         = TRUE;
387     d3dpp.BackBufferWidth  = 640;
388     d3dpp.BackBufferHeight = 480;
389     d3dpp.BackBufferCount  = 0;
390     d3dpp.BackBufferFormat = d3ddm.Format;
391     d3dpp.SwapEffect       = D3DSWAPEFFECT_DISCARD;
392     d3dpp.Flags            = D3DPRESENTFLAG_VIDEO;
393
394     hr = IDirect3D9_CreateDevice(priv->d3d9, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
395                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
396                                  &d3dpp, &priv->d3d9device);
397     if (FAILED(hr)) {
398         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device\n");
399         return AVERROR_UNKNOWN;
400     }
401
402     hr = createDeviceManager(&resetToken, &hwctx->devmgr);
403     if (FAILED(hr)) {
404         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device manager\n");
405         return AVERROR_UNKNOWN;
406     }
407
408     hr = IDirect3DDeviceManager9_ResetDevice(hwctx->devmgr, priv->d3d9device, resetToken);
409     if (FAILED(hr)) {
410         av_log(ctx, AV_LOG_ERROR, "Failed to bind Direct3D device to device manager\n");
411         return AVERROR_UNKNOWN;
412     }
413
414     hr = IDirect3DDeviceManager9_OpenDeviceHandle(hwctx->devmgr, &priv->device_handle);
415     if (FAILED(hr)) {
416         av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
417         return AVERROR_UNKNOWN;
418     }
419
420     return 0;
421 }
422
423 const HWContextType ff_hwcontext_type_dxva2 = {
424     .type                 = AV_HWDEVICE_TYPE_DXVA2,
425     .name                 = "DXVA2",
426
427     .device_hwctx_size    = sizeof(AVDXVA2DeviceContext),
428     .frames_hwctx_size    = sizeof(AVDXVA2FramesContext),
429     .frames_priv_size     = sizeof(DXVA2FramesContext),
430
431     .device_create        = dxva2_device_create,
432     .frames_init          = dxva2_frames_init,
433     .frames_uninit        = dxva2_frames_uninit,
434     .frames_get_buffer    = dxva2_get_buffer,
435     .transfer_get_formats = dxva2_transfer_get_formats,
436     .transfer_data_to     = dxva2_transfer_data,
437     .transfer_data_from   = dxva2_transfer_data,
438
439     .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_DXVA2_VLD, AV_PIX_FMT_NONE },
440 };