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