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