aarch64: vp9itxfm: Move the load_add_store macro out from the itxfm16 pass2 function
[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 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         av_image_copy(dst->data, dst->linesize, surf_data, surf_linesize,
297                       ctx->sw_format, src->width, src->height);
298     } else {
299         av_image_copy(surf_data, surf_linesize, src->data, src->linesize,
300                       ctx->sw_format, src->width, src->height);
301     }
302
303     IDirect3DSurface9_UnlockRect(surface);
304
305     return 0;
306 }
307
308 static void dxva2_device_free(AVHWDeviceContext *ctx)
309 {
310     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
311     DXVA2DevicePriv       *priv = ctx->user_opaque;
312
313     if (hwctx->devmgr && priv->device_handle != INVALID_HANDLE_VALUE)
314         IDirect3DDeviceManager9_CloseDeviceHandle(hwctx->devmgr, priv->device_handle);
315
316     if (hwctx->devmgr)
317         IDirect3DDeviceManager9_Release(hwctx->devmgr);
318
319     if (priv->d3d9device)
320         IDirect3DDevice9_Release(priv->d3d9device);
321
322     if (priv->d3d9)
323         IDirect3D9_Release(priv->d3d9);
324
325     if (priv->d3dlib)
326         dlclose(priv->d3dlib);
327
328     if (priv->dxva2lib)
329         dlclose(priv->dxva2lib);
330
331     av_freep(&ctx->user_opaque);
332 }
333
334 static int dxva2_device_create9(AVHWDeviceContext *ctx, UINT adapter)
335 {
336     DXVA2DevicePriv *priv = ctx->user_opaque;
337     D3DPRESENT_PARAMETERS d3dpp = dxva2_present_params;
338     D3DDISPLAYMODE d3ddm;
339     HRESULT hr;
340     pDirect3DCreate9 *createD3D = (pDirect3DCreate9 *)dlsym(priv->d3dlib, "Direct3DCreate9");
341     if (!createD3D) {
342         av_log(ctx, AV_LOG_ERROR, "Failed to locate Direct3DCreate9\n");
343         return AVERROR_UNKNOWN;
344     }
345
346     priv->d3d9 = createD3D(D3D_SDK_VERSION);
347     if (!priv->d3d9) {
348         av_log(ctx, AV_LOG_ERROR, "Failed to create IDirect3D object\n");
349         return AVERROR_UNKNOWN;
350     }
351
352     IDirect3D9_GetAdapterDisplayMode(priv->d3d9, adapter, &d3ddm);
353
354     d3dpp.BackBufferFormat = d3ddm.Format;
355
356     hr = IDirect3D9_CreateDevice(priv->d3d9, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
357                                  FF_D3DCREATE_FLAGS,
358                                  &d3dpp, &priv->d3d9device);
359     if (FAILED(hr)) {
360         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device\n");
361         return AVERROR_UNKNOWN;
362     }
363
364     return 0;
365 }
366
367 static int dxva2_device_create9ex(AVHWDeviceContext *ctx, UINT adapter)
368 {
369     DXVA2DevicePriv *priv = ctx->user_opaque;
370     D3DPRESENT_PARAMETERS d3dpp = dxva2_present_params;
371     D3DDISPLAYMODEEX modeex = {0};
372     IDirect3D9Ex *d3d9ex = NULL;
373     IDirect3DDevice9Ex *exdev = NULL;
374     HRESULT hr;
375     pDirect3DCreate9Ex *createD3DEx = (pDirect3DCreate9Ex *)dlsym(priv->d3dlib, "Direct3DCreate9Ex");
376     if (!createD3DEx)
377         return AVERROR(ENOSYS);
378
379     hr = createD3DEx(D3D_SDK_VERSION, &d3d9ex);
380     if (FAILED(hr))
381         return AVERROR_UNKNOWN;
382
383     IDirect3D9Ex_GetAdapterDisplayModeEx(d3d9ex, adapter, &modeex, NULL);
384
385     d3dpp.BackBufferFormat = modeex.Format;
386
387     hr = IDirect3D9Ex_CreateDeviceEx(d3d9ex, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
388                                      FF_D3DCREATE_FLAGS,
389                                      &d3dpp, NULL, &exdev);
390     if (FAILED(hr)) {
391         IDirect3D9Ex_Release(d3d9ex);
392         return AVERROR_UNKNOWN;
393     }
394
395     av_log(ctx, AV_LOG_VERBOSE, "Using D3D9Ex device.\n");
396     priv->d3d9 = (IDirect3D9 *)d3d9ex;
397     priv->d3d9device = (IDirect3DDevice9 *)exdev;
398     return 0;
399 }
400
401 static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device,
402                                AVDictionary *opts, int flags)
403 {
404     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
405     DXVA2DevicePriv *priv;
406     pCreateDeviceManager9 *createDeviceManager = NULL;
407     unsigned resetToken = 0;
408     UINT adapter = D3DADAPTER_DEFAULT;
409     HRESULT hr;
410     int err;
411
412     if (device)
413         adapter = atoi(device);
414
415     priv = av_mallocz(sizeof(*priv));
416     if (!priv)
417         return AVERROR(ENOMEM);
418
419     ctx->user_opaque = priv;
420     ctx->free        = dxva2_device_free;
421
422     priv->device_handle = INVALID_HANDLE_VALUE;
423
424     priv->d3dlib = dlopen("d3d9.dll", 0);
425     if (!priv->d3dlib) {
426         av_log(ctx, AV_LOG_ERROR, "Failed to load D3D9 library\n");
427         return AVERROR_UNKNOWN;
428     }
429     priv->dxva2lib = dlopen("dxva2.dll", 0);
430     if (!priv->dxva2lib) {
431         av_log(ctx, AV_LOG_ERROR, "Failed to load DXVA2 library\n");
432         return AVERROR_UNKNOWN;
433     }
434
435     createDeviceManager = (pCreateDeviceManager9 *)dlsym(priv->dxva2lib,
436                                                          "DXVA2CreateDirect3DDeviceManager9");
437     if (!createDeviceManager) {
438         av_log(ctx, AV_LOG_ERROR, "Failed to locate DXVA2CreateDirect3DDeviceManager9\n");
439         return AVERROR_UNKNOWN;
440     }
441
442     if (dxva2_device_create9ex(ctx, adapter) < 0) {
443         // Retry with "classic" d3d9
444         err = dxva2_device_create9(ctx, adapter);
445         if (err < 0)
446             return err;
447     }
448
449     hr = createDeviceManager(&resetToken, &hwctx->devmgr);
450     if (FAILED(hr)) {
451         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device manager\n");
452         return AVERROR_UNKNOWN;
453     }
454
455     hr = IDirect3DDeviceManager9_ResetDevice(hwctx->devmgr, priv->d3d9device, resetToken);
456     if (FAILED(hr)) {
457         av_log(ctx, AV_LOG_ERROR, "Failed to bind Direct3D device to device manager\n");
458         return AVERROR_UNKNOWN;
459     }
460
461     hr = IDirect3DDeviceManager9_OpenDeviceHandle(hwctx->devmgr, &priv->device_handle);
462     if (FAILED(hr)) {
463         av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
464         return AVERROR_UNKNOWN;
465     }
466
467     return 0;
468 }
469
470 const HWContextType ff_hwcontext_type_dxva2 = {
471     .type                 = AV_HWDEVICE_TYPE_DXVA2,
472     .name                 = "DXVA2",
473
474     .device_hwctx_size    = sizeof(AVDXVA2DeviceContext),
475     .frames_hwctx_size    = sizeof(AVDXVA2FramesContext),
476     .frames_priv_size     = sizeof(DXVA2FramesContext),
477
478     .device_create        = dxva2_device_create,
479     .frames_init          = dxva2_frames_init,
480     .frames_uninit        = dxva2_frames_uninit,
481     .frames_get_buffer    = dxva2_get_buffer,
482     .transfer_get_formats = dxva2_transfer_get_formats,
483     .transfer_data_to     = dxva2_transfer_data,
484     .transfer_data_from   = dxva2_transfer_data,
485
486     .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_DXVA2_VLD, AV_PIX_FMT_NONE },
487 };