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