]> git.sesse.net Git - ffmpeg/blob - libavutil/hwcontext_dxva2.c
Merge commit 'de2ae3c1fae5a2eb539b9abd7bc2a9ca8c286ff0'
[ffmpeg] / 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 pDirect3DCreate9Ex(UINT, IDirect3D9Ex **);
44 typedef HRESULT WINAPI pCreateDeviceManager9(UINT *, IDirect3DDeviceManager9 **);
45
46 #define FF_D3DCREATE_FLAGS (D3DCREATE_SOFTWARE_VERTEXPROCESSING | \
47                             D3DCREATE_MULTITHREADED | \
48                             D3DCREATE_FPU_PRESERVE)
49
50 static const D3DPRESENT_PARAMETERS dxva2_present_params = {
51     .Windowed         = TRUE,
52     .BackBufferWidth  = 640,
53     .BackBufferHeight = 480,
54     .BackBufferCount  = 0,
55     .SwapEffect       = D3DSWAPEFFECT_DISCARD,
56     .Flags            = D3DPRESENTFLAG_VIDEO,
57 };
58
59 typedef struct DXVA2FramesContext {
60     IDirect3DSurface9 **surfaces_internal;
61     int              nb_surfaces_used;
62
63     HANDLE  device_handle;
64     IDirectXVideoAccelerationService *service;
65
66     D3DFORMAT format;
67 } DXVA2FramesContext;
68
69 typedef struct DXVA2DevicePriv {
70     HMODULE d3dlib;
71     HMODULE dxva2lib;
72
73     HANDLE device_handle;
74
75     IDirect3D9       *d3d9;
76     IDirect3DDevice9 *d3d9device;
77 } DXVA2DevicePriv;
78
79 static const struct {
80     D3DFORMAT d3d_format;
81     enum AVPixelFormat pix_fmt;
82 } supported_formats[] = {
83     { MKTAG('N', 'V', '1', '2'), AV_PIX_FMT_NV12 },
84     { MKTAG('P', '0', '1', '0'), AV_PIX_FMT_P010 },
85 };
86
87 DEFINE_GUID(video_decoder_service,   0xfc51a551, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
88 DEFINE_GUID(video_processor_service, 0xfc51a552, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
89
90 static void dxva2_frames_uninit(AVHWFramesContext *ctx)
91 {
92     AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
93     AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
94     DXVA2FramesContext *s = ctx->internal->priv;
95     int i;
96
97     if (frames_hwctx->decoder_to_release)
98         IDirectXVideoDecoder_Release(frames_hwctx->decoder_to_release);
99
100     if (s->surfaces_internal) {
101         for (i = 0; i < frames_hwctx->nb_surfaces; i++) {
102             if (s->surfaces_internal[i])
103                 IDirect3DSurface9_Release(s->surfaces_internal[i]);
104         }
105     }
106     av_freep(&s->surfaces_internal);
107
108     if (s->service) {
109         IDirectXVideoAccelerationService_Release(s->service);
110         s->service = NULL;
111     }
112
113     if (s->device_handle != INVALID_HANDLE_VALUE) {
114         IDirect3DDeviceManager9_CloseDeviceHandle(device_hwctx->devmgr, s->device_handle);
115         s->device_handle = INVALID_HANDLE_VALUE;
116     }
117 }
118
119 static AVBufferRef *dxva2_pool_alloc(void *opaque, int size)
120 {
121     AVHWFramesContext      *ctx = (AVHWFramesContext*)opaque;
122     DXVA2FramesContext       *s = ctx->internal->priv;
123     AVDXVA2FramesContext *hwctx = ctx->hwctx;
124
125     if (s->nb_surfaces_used < hwctx->nb_surfaces) {
126         s->nb_surfaces_used++;
127         return av_buffer_create((uint8_t*)s->surfaces_internal[s->nb_surfaces_used - 1],
128                                 sizeof(*hwctx->surfaces), NULL, 0, 0);
129     }
130
131     return NULL;
132 }
133
134 static int dxva2_init_pool(AVHWFramesContext *ctx)
135 {
136     AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
137     AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
138     DXVA2FramesContext              *s = ctx->internal->priv;
139     int decode = (frames_hwctx->surface_type == DXVA2_VideoDecoderRenderTarget);
140
141     int i;
142     HRESULT hr;
143
144     if (ctx->initial_pool_size <= 0)
145         return 0;
146
147     hr = IDirect3DDeviceManager9_OpenDeviceHandle(device_hwctx->devmgr, &s->device_handle);
148     if (FAILED(hr)) {
149         av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
150         return AVERROR_UNKNOWN;
151     }
152
153     hr = IDirect3DDeviceManager9_GetVideoService(device_hwctx->devmgr,
154                                                  s->device_handle,
155                                                  decode ? &video_decoder_service : &video_processor_service,
156                                                  (void **)&s->service);
157     if (FAILED(hr)) {
158         av_log(ctx, AV_LOG_ERROR, "Failed to create the video service\n");
159         return AVERROR_UNKNOWN;
160     }
161
162     for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
163         if (ctx->sw_format == supported_formats[i].pix_fmt) {
164             s->format = supported_formats[i].d3d_format;
165             break;
166         }
167     }
168     if (i == FF_ARRAY_ELEMS(supported_formats)) {
169         av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n",
170                av_get_pix_fmt_name(ctx->sw_format));
171         return AVERROR(EINVAL);
172     }
173
174     s->surfaces_internal = av_mallocz_array(ctx->initial_pool_size,
175                                             sizeof(*s->surfaces_internal));
176     if (!s->surfaces_internal)
177         return AVERROR(ENOMEM);
178
179     hr = IDirectXVideoAccelerationService_CreateSurface(s->service,
180                                                         ctx->width, ctx->height,
181                                                         ctx->initial_pool_size - 1,
182                                                         s->format, D3DPOOL_DEFAULT, 0,
183                                                         frames_hwctx->surface_type,
184                                                         s->surfaces_internal, NULL);
185     if (FAILED(hr)) {
186         av_log(ctx, AV_LOG_ERROR, "Could not create the surfaces\n");
187         return AVERROR_UNKNOWN;
188     }
189
190     ctx->internal->pool_internal = av_buffer_pool_init2(sizeof(*s->surfaces_internal),
191                                                         ctx, dxva2_pool_alloc, NULL);
192     if (!ctx->internal->pool_internal)
193         return AVERROR(ENOMEM);
194
195     frames_hwctx->surfaces    = s->surfaces_internal;
196     frames_hwctx->nb_surfaces = ctx->initial_pool_size;
197
198     return 0;
199 }
200
201 static int dxva2_frames_init(AVHWFramesContext *ctx)
202 {
203     AVDXVA2FramesContext *hwctx = ctx->hwctx;
204     DXVA2FramesContext       *s = ctx->internal->priv;
205     int ret;
206
207     if (hwctx->surface_type != DXVA2_VideoDecoderRenderTarget &&
208         hwctx->surface_type != DXVA2_VideoProcessorRenderTarget) {
209         av_log(ctx, AV_LOG_ERROR, "Unknown surface type: %lu\n",
210                hwctx->surface_type);
211         return AVERROR(EINVAL);
212     }
213
214     s->device_handle = INVALID_HANDLE_VALUE;
215
216     /* init the frame pool if the caller didn't provide one */
217     if (!ctx->pool) {
218         ret = dxva2_init_pool(ctx);
219         if (ret < 0) {
220             av_log(ctx, AV_LOG_ERROR, "Error creating an internal frame pool\n");
221             return ret;
222         }
223     }
224
225     return 0;
226 }
227
228 static int dxva2_get_buffer(AVHWFramesContext *ctx, AVFrame *frame)
229 {
230     frame->buf[0] = av_buffer_pool_get(ctx->pool);
231     if (!frame->buf[0])
232         return AVERROR(ENOMEM);
233
234     frame->data[3] = frame->buf[0]->data;
235     frame->format  = AV_PIX_FMT_DXVA2_VLD;
236     frame->width   = ctx->width;
237     frame->height  = ctx->height;
238
239     return 0;
240 }
241
242 static int dxva2_transfer_get_formats(AVHWFramesContext *ctx,
243                                       enum AVHWFrameTransferDirection dir,
244                                       enum AVPixelFormat **formats)
245 {
246     enum AVPixelFormat *fmts;
247
248     fmts = av_malloc_array(2, sizeof(*fmts));
249     if (!fmts)
250         return AVERROR(ENOMEM);
251
252     fmts[0] = ctx->sw_format;
253     fmts[1] = AV_PIX_FMT_NONE;
254
255     *formats = fmts;
256
257     return 0;
258 }
259
260 static int dxva2_transfer_data(AVHWFramesContext *ctx, AVFrame *dst,
261                                const AVFrame *src)
262 {
263     IDirect3DSurface9 *surface;
264     D3DSURFACE_DESC    surfaceDesc;
265     D3DLOCKED_RECT     LockedRect;
266     HRESULT            hr;
267
268     uint8_t *surf_data[4]     = { NULL };
269     int      surf_linesize[4] = { 0 };
270     int i;
271
272     int download = !!src->hw_frames_ctx;
273
274     surface = (IDirect3DSurface9*)(download ? src->data[3] : dst->data[3]);
275
276     hr = IDirect3DSurface9_GetDesc(surface, &surfaceDesc);
277     if (FAILED(hr)) {
278         av_log(ctx, AV_LOG_ERROR, "Error getting a surface description\n");
279         return AVERROR_UNKNOWN;
280     }
281
282     hr = IDirect3DSurface9_LockRect(surface, &LockedRect, NULL,
283                                     download ? D3DLOCK_READONLY : D3DLOCK_DISCARD);
284     if (FAILED(hr)) {
285         av_log(ctx, AV_LOG_ERROR, "Unable to lock DXVA2 surface\n");
286         return AVERROR_UNKNOWN;
287     }
288
289     for (i = 0; download ? dst->data[i] : src->data[i]; i++)
290         surf_linesize[i] = LockedRect.Pitch;
291
292     av_image_fill_pointers(surf_data, ctx->sw_format, surfaceDesc.Height,
293                            (uint8_t*)LockedRect.pBits, surf_linesize);
294
295     if (download) {
296         ptrdiff_t src_linesize1[4], dst_linesize1[4];
297         for (i = 0; i < 4; i++) {
298             dst_linesize1[i] = dst->linesize[i];
299             src_linesize1[i] = surf_linesize[i];
300         }
301         av_image_copy_uc_from(dst->data, dst_linesize1, surf_data, src_linesize1,
302                               ctx->sw_format, src->width, src->height);
303     } else {
304         av_image_copy(surf_data, surf_linesize, src->data, src->linesize,
305                       ctx->sw_format, src->width, src->height);
306     }
307
308     IDirect3DSurface9_UnlockRect(surface);
309
310     return 0;
311 }
312
313 static void dxva2_device_free(AVHWDeviceContext *ctx)
314 {
315     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
316     DXVA2DevicePriv       *priv = ctx->user_opaque;
317
318     if (hwctx->devmgr && priv->device_handle != INVALID_HANDLE_VALUE)
319         IDirect3DDeviceManager9_CloseDeviceHandle(hwctx->devmgr, priv->device_handle);
320
321     if (hwctx->devmgr)
322         IDirect3DDeviceManager9_Release(hwctx->devmgr);
323
324     if (priv->d3d9device)
325         IDirect3DDevice9_Release(priv->d3d9device);
326
327     if (priv->d3d9)
328         IDirect3D9_Release(priv->d3d9);
329
330     if (priv->d3dlib)
331         dlclose(priv->d3dlib);
332
333     if (priv->dxva2lib)
334         dlclose(priv->dxva2lib);
335
336     av_freep(&ctx->user_opaque);
337 }
338
339 static int dxva2_device_create9(AVHWDeviceContext *ctx, UINT adapter)
340 {
341     DXVA2DevicePriv *priv = ctx->user_opaque;
342     D3DPRESENT_PARAMETERS d3dpp = dxva2_present_params;
343     D3DDISPLAYMODE d3ddm;
344     HRESULT hr;
345     pDirect3DCreate9 *createD3D = (pDirect3DCreate9 *)dlsym(priv->d3dlib, "Direct3DCreate9");
346     if (!createD3D) {
347         av_log(ctx, AV_LOG_ERROR, "Failed to locate Direct3DCreate9\n");
348         return AVERROR_UNKNOWN;
349     }
350
351     priv->d3d9 = createD3D(D3D_SDK_VERSION);
352     if (!priv->d3d9) {
353         av_log(ctx, AV_LOG_ERROR, "Failed to create IDirect3D object\n");
354         return AVERROR_UNKNOWN;
355     }
356
357     IDirect3D9_GetAdapterDisplayMode(priv->d3d9, adapter, &d3ddm);
358
359     d3dpp.BackBufferFormat = d3ddm.Format;
360
361     hr = IDirect3D9_CreateDevice(priv->d3d9, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
362                                  FF_D3DCREATE_FLAGS,
363                                  &d3dpp, &priv->d3d9device);
364     if (FAILED(hr)) {
365         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device\n");
366         return AVERROR_UNKNOWN;
367     }
368
369     return 0;
370 }
371
372 static int dxva2_device_create9ex(AVHWDeviceContext *ctx, UINT adapter)
373 {
374     DXVA2DevicePriv *priv = ctx->user_opaque;
375     D3DPRESENT_PARAMETERS d3dpp = dxva2_present_params;
376     D3DDISPLAYMODEEX modeex = {0};
377     IDirect3D9Ex *d3d9ex = NULL;
378     IDirect3DDevice9Ex *exdev = NULL;
379     HRESULT hr;
380     pDirect3DCreate9Ex *createD3DEx = (pDirect3DCreate9Ex *)dlsym(priv->d3dlib, "Direct3DCreate9Ex");
381     if (!createD3DEx)
382         return AVERROR(ENOSYS);
383
384     hr = createD3DEx(D3D_SDK_VERSION, &d3d9ex);
385     if (FAILED(hr))
386         return AVERROR_UNKNOWN;
387
388     IDirect3D9Ex_GetAdapterDisplayModeEx(d3d9ex, adapter, &modeex, NULL);
389
390     d3dpp.BackBufferFormat = modeex.Format;
391
392     hr = IDirect3D9Ex_CreateDeviceEx(d3d9ex, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
393                                      FF_D3DCREATE_FLAGS,
394                                      &d3dpp, NULL, &exdev);
395     if (FAILED(hr)) {
396         IDirect3D9Ex_Release(d3d9ex);
397         return AVERROR_UNKNOWN;
398     }
399
400     av_log(ctx, AV_LOG_VERBOSE, "Using D3D9Ex device.\n");
401     priv->d3d9 = (IDirect3D9 *)d3d9ex;
402     priv->d3d9device = (IDirect3DDevice9 *)exdev;
403     return 0;
404 }
405
406 static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device,
407                                AVDictionary *opts, int flags)
408 {
409     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
410     DXVA2DevicePriv *priv;
411     pCreateDeviceManager9 *createDeviceManager = NULL;
412     unsigned resetToken = 0;
413     UINT adapter = D3DADAPTER_DEFAULT;
414     HRESULT hr;
415     int err;
416
417     if (device)
418         adapter = atoi(device);
419
420     priv = av_mallocz(sizeof(*priv));
421     if (!priv)
422         return AVERROR(ENOMEM);
423
424     ctx->user_opaque = priv;
425     ctx->free        = dxva2_device_free;
426
427     priv->device_handle = INVALID_HANDLE_VALUE;
428
429     priv->d3dlib = dlopen("d3d9.dll", 0);
430     if (!priv->d3dlib) {
431         av_log(ctx, AV_LOG_ERROR, "Failed to load D3D9 library\n");
432         return AVERROR_UNKNOWN;
433     }
434     priv->dxva2lib = dlopen("dxva2.dll", 0);
435     if (!priv->dxva2lib) {
436         av_log(ctx, AV_LOG_ERROR, "Failed to load DXVA2 library\n");
437         return AVERROR_UNKNOWN;
438     }
439
440     createDeviceManager = (pCreateDeviceManager9 *)dlsym(priv->dxva2lib,
441                                                          "DXVA2CreateDirect3DDeviceManager9");
442     if (!createDeviceManager) {
443         av_log(ctx, AV_LOG_ERROR, "Failed to locate DXVA2CreateDirect3DDeviceManager9\n");
444         return AVERROR_UNKNOWN;
445     }
446
447     if (dxva2_device_create9ex(ctx, adapter) < 0) {
448         // Retry with "classic" d3d9
449         err = dxva2_device_create9(ctx, adapter);
450         if (err < 0)
451             return err;
452     }
453
454     hr = createDeviceManager(&resetToken, &hwctx->devmgr);
455     if (FAILED(hr)) {
456         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device manager\n");
457         return AVERROR_UNKNOWN;
458     }
459
460     hr = IDirect3DDeviceManager9_ResetDevice(hwctx->devmgr, priv->d3d9device, resetToken);
461     if (FAILED(hr)) {
462         av_log(ctx, AV_LOG_ERROR, "Failed to bind Direct3D device to device manager\n");
463         return AVERROR_UNKNOWN;
464     }
465
466     hr = IDirect3DDeviceManager9_OpenDeviceHandle(hwctx->devmgr, &priv->device_handle);
467     if (FAILED(hr)) {
468         av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
469         return AVERROR_UNKNOWN;
470     }
471
472     return 0;
473 }
474
475 const HWContextType ff_hwcontext_type_dxva2 = {
476     .type                 = AV_HWDEVICE_TYPE_DXVA2,
477     .name                 = "DXVA2",
478
479     .device_hwctx_size    = sizeof(AVDXVA2DeviceContext),
480     .frames_hwctx_size    = sizeof(AVDXVA2FramesContext),
481     .frames_priv_size     = sizeof(DXVA2FramesContext),
482
483     .device_create        = dxva2_device_create,
484     .frames_init          = dxva2_frames_init,
485     .frames_uninit        = dxva2_frames_uninit,
486     .frames_get_buffer    = dxva2_get_buffer,
487     .transfer_get_formats = dxva2_transfer_get_formats,
488     .transfer_data_to     = dxva2_transfer_data,
489     .transfer_data_from   = dxva2_transfer_data,
490
491     .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_DXVA2_VLD, AV_PIX_FMT_NONE },
492 };