Merge commit '2ef87815fec059504370ae3050cc243a53553915'
[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     uint8_t *surf_data[4]     = { NULL };
255     int      surf_linesize[4] = { 0 };
256     int i;
257
258     int download = !!src->hw_frames_ctx;
259
260     surface = (IDirect3DSurface9*)(download ? src->data[3] : dst->data[3]);
261
262     hr = IDirect3DSurface9_GetDesc(surface, &surfaceDesc);
263     if (FAILED(hr)) {
264         av_log(ctx, AV_LOG_ERROR, "Error getting a surface description\n");
265         return AVERROR_UNKNOWN;
266     }
267
268     hr = IDirect3DSurface9_LockRect(surface, &LockedRect, NULL,
269                                     download ? D3DLOCK_READONLY : D3DLOCK_DISCARD);
270     if (FAILED(hr)) {
271         av_log(ctx, AV_LOG_ERROR, "Unable to lock DXVA2 surface\n");
272         return AVERROR_UNKNOWN;
273     }
274
275     for (i = 0; download ? dst->data[i] : src->data[i]; i++)
276         surf_linesize[i] = LockedRect.Pitch;
277
278     av_image_fill_pointers(surf_data, ctx->sw_format, surfaceDesc.Height,
279                            (uint8_t*)LockedRect.pBits, surf_linesize);
280
281     if (download) {
282         av_image_copy(dst->data, dst->linesize, surf_data, surf_linesize,
283                       ctx->sw_format, src->width, src->height);
284     } else {
285         av_image_copy(surf_data, surf_linesize, src->data, src->linesize,
286                       ctx->sw_format, src->width, src->height);
287     }
288
289     IDirect3DSurface9_UnlockRect(surface);
290
291     return 0;
292 }
293
294 static void dxva2_device_free(AVHWDeviceContext *ctx)
295 {
296     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
297     DXVA2DevicePriv       *priv = ctx->user_opaque;
298
299     if (hwctx->devmgr && priv->device_handle != INVALID_HANDLE_VALUE)
300         IDirect3DDeviceManager9_CloseDeviceHandle(hwctx->devmgr, priv->device_handle);
301
302     if (hwctx->devmgr)
303         IDirect3DDeviceManager9_Release(hwctx->devmgr);
304
305     if (priv->d3d9device)
306         IDirect3DDevice9_Release(priv->d3d9device);
307
308     if (priv->d3d9)
309         IDirect3D9_Release(priv->d3d9);
310
311     if (priv->d3dlib)
312         dlclose(priv->d3dlib);
313
314     if (priv->dxva2lib)
315         dlclose(priv->dxva2lib);
316
317     av_freep(&ctx->user_opaque);
318 }
319
320 static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device,
321                                AVDictionary *opts, int flags)
322 {
323     AVDXVA2DeviceContext *hwctx = ctx->hwctx;
324     DXVA2DevicePriv *priv;
325
326     pDirect3DCreate9 *createD3D = NULL;
327     pCreateDeviceManager9 *createDeviceManager = NULL;
328     D3DPRESENT_PARAMETERS d3dpp = {0};
329     D3DDISPLAYMODE        d3ddm;
330     unsigned resetToken = 0;
331     UINT adapter = D3DADAPTER_DEFAULT;
332     HRESULT hr;
333
334     if (device)
335         adapter = atoi(device);
336
337     priv = av_mallocz(sizeof(*priv));
338     if (!priv)
339         return AVERROR(ENOMEM);
340
341     ctx->user_opaque = priv;
342     ctx->free        = dxva2_device_free;
343
344     priv->device_handle = INVALID_HANDLE_VALUE;
345
346     priv->d3dlib = dlopen("d3d9.dll", 0);
347     if (!priv->d3dlib) {
348         av_log(ctx, AV_LOG_ERROR, "Failed to load D3D9 library\n");
349         return AVERROR_UNKNOWN;
350     }
351     priv->dxva2lib = dlopen("dxva2.dll", 0);
352     if (!priv->dxva2lib) {
353         av_log(ctx, AV_LOG_ERROR, "Failed to load DXVA2 library\n");
354         return AVERROR_UNKNOWN;
355     }
356
357     createD3D = (pDirect3DCreate9 *)dlsym(priv->d3dlib, "Direct3DCreate9");
358     if (!createD3D) {
359         av_log(ctx, AV_LOG_ERROR, "Failed to locate Direct3DCreate9\n");
360         return AVERROR_UNKNOWN;
361     }
362     createDeviceManager = (pCreateDeviceManager9 *)dlsym(priv->dxva2lib,
363                                                          "DXVA2CreateDirect3DDeviceManager9");
364     if (!createDeviceManager) {
365         av_log(ctx, AV_LOG_ERROR, "Failed to locate DXVA2CreateDirect3DDeviceManager9\n");
366         return AVERROR_UNKNOWN;
367     }
368
369     priv->d3d9 = createD3D(D3D_SDK_VERSION);
370     if (!priv->d3d9) {
371         av_log(ctx, AV_LOG_ERROR, "Failed to create IDirect3D object\n");
372         return AVERROR_UNKNOWN;
373     }
374
375     IDirect3D9_GetAdapterDisplayMode(priv->d3d9, adapter, &d3ddm);
376     d3dpp.Windowed         = TRUE;
377     d3dpp.BackBufferWidth  = 640;
378     d3dpp.BackBufferHeight = 480;
379     d3dpp.BackBufferCount  = 0;
380     d3dpp.BackBufferFormat = d3ddm.Format;
381     d3dpp.SwapEffect       = D3DSWAPEFFECT_DISCARD;
382     d3dpp.Flags            = D3DPRESENTFLAG_VIDEO;
383
384     hr = IDirect3D9_CreateDevice(priv->d3d9, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
385                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
386                                  &d3dpp, &priv->d3d9device);
387     if (FAILED(hr)) {
388         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device\n");
389         return AVERROR_UNKNOWN;
390     }
391
392     hr = createDeviceManager(&resetToken, &hwctx->devmgr);
393     if (FAILED(hr)) {
394         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device manager\n");
395         return AVERROR_UNKNOWN;
396     }
397
398     hr = IDirect3DDeviceManager9_ResetDevice(hwctx->devmgr, priv->d3d9device, resetToken);
399     if (FAILED(hr)) {
400         av_log(ctx, AV_LOG_ERROR, "Failed to bind Direct3D device to device manager\n");
401         return AVERROR_UNKNOWN;
402     }
403
404     hr = IDirect3DDeviceManager9_OpenDeviceHandle(hwctx->devmgr, &priv->device_handle);
405     if (FAILED(hr)) {
406         av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
407         return AVERROR_UNKNOWN;
408     }
409
410     return 0;
411 }
412
413 const HWContextType ff_hwcontext_type_dxva2 = {
414     .type                 = AV_HWDEVICE_TYPE_DXVA2,
415     .name                 = "DXVA2",
416
417     .device_hwctx_size    = sizeof(AVDXVA2DeviceContext),
418     .frames_hwctx_size    = sizeof(AVDXVA2FramesContext),
419     .frames_priv_size     = sizeof(DXVA2FramesContext),
420
421     .device_create        = dxva2_device_create,
422     .frames_init          = dxva2_frames_init,
423     .frames_uninit        = dxva2_frames_uninit,
424     .frames_get_buffer    = dxva2_get_buffer,
425     .transfer_get_formats = dxva2_transfer_get_formats,
426     .transfer_data_to     = dxva2_transfer_data,
427     .transfer_data_from   = dxva2_transfer_data,
428
429     .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_DXVA2_VLD, AV_PIX_FMT_NONE },
430 };