Libav
hwcontext_dxva2.c
Go to the documentation of this file.
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;
46 
47  HANDLE device_handle;
48  IDirectXVideoAccelerationService *service;
49 
50  D3DFORMAT format;
52 
53 typedef struct DXVA2DevicePriv {
54  HMODULE d3dlib;
55  HMODULE dxva2lib;
56 
57  HANDLE device_handle;
58 
59  IDirect3D9 *d3d9;
60  IDirect3DDevice9 *d3d9device;
62 
63 static const struct {
64  D3DFORMAT d3d_format;
66 } supported_formats[] = {
67  { MKTAG('N', 'V', '1', '2'), AV_PIX_FMT_NV12 },
68  { MKTAG('P', '0', '1', '0'), AV_PIX_FMT_P010 },
69 };
70 
71 DEFINE_GUID(video_decoder_service, 0xfc51a551, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
72 DEFINE_GUID(video_processor_service, 0xfc51a552, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
73 
75 {
76  AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
77  AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
78  DXVA2FramesContext *s = ctx->internal->priv;
79  int i;
80 
81  if (frames_hwctx->decoder_to_release)
82  IDirectXVideoDecoder_Release(frames_hwctx->decoder_to_release);
83 
84  if (s->surfaces_internal) {
85  for (i = 0; i < frames_hwctx->nb_surfaces; i++) {
86  if (s->surfaces_internal[i])
87  IDirect3DSurface9_Release(s->surfaces_internal[i]);
88  }
89  }
91 
92  if (s->service) {
93  IDirectXVideoAccelerationService_Release(s->service);
94  s->service = NULL;
95  }
96 
97  if (s->device_handle != INVALID_HANDLE_VALUE) {
98  IDirect3DDeviceManager9_CloseDeviceHandle(device_hwctx->devmgr, s->device_handle);
99  s->device_handle = INVALID_HANDLE_VALUE;
100  }
101 }
102 
103 static AVBufferRef *dxva2_pool_alloc(void *opaque, int size)
104 {
106  DXVA2FramesContext *s = ctx->internal->priv;
107  AVDXVA2FramesContext *hwctx = ctx->hwctx;
108 
109  if (s->nb_surfaces_used < hwctx->nb_surfaces) {
110  s->nb_surfaces_used++;
112  sizeof(*hwctx->surfaces), NULL, 0, 0);
113  }
114 
115  return NULL;
116 }
117 
119 {
120  AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
121  AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
122  DXVA2FramesContext *s = ctx->internal->priv;
123  int decode = (frames_hwctx->surface_type == DXVA2_VideoDecoderRenderTarget);
124 
125  int i;
126  HRESULT hr;
127 
128  if (ctx->initial_pool_size <= 0)
129  return 0;
130 
131  hr = IDirect3DDeviceManager9_OpenDeviceHandle(device_hwctx->devmgr, &s->device_handle);
132  if (FAILED(hr)) {
133  av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
134  return AVERROR_UNKNOWN;
135  }
136 
137  hr = IDirect3DDeviceManager9_GetVideoService(device_hwctx->devmgr,
138  s->device_handle,
139  decode ? &video_decoder_service : &video_processor_service,
140  (void **)&s->service);
141  if (FAILED(hr)) {
142  av_log(ctx, AV_LOG_ERROR, "Failed to create the video service\n");
143  return AVERROR_UNKNOWN;
144  }
145 
146  for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
147  if (ctx->sw_format == supported_formats[i].pix_fmt) {
148  s->format = supported_formats[i].d3d_format;
149  break;
150  }
151  }
152  if (i == FF_ARRAY_ELEMS(supported_formats)) {
153  av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n",
155  return AVERROR(EINVAL);
156  }
157 
159  sizeof(*s->surfaces_internal));
160  if (!s->surfaces_internal)
161  return AVERROR(ENOMEM);
162 
163  hr = IDirectXVideoAccelerationService_CreateSurface(s->service,
164  ctx->width, ctx->height,
165  ctx->initial_pool_size - 1,
166  s->format, D3DPOOL_DEFAULT, 0,
167  frames_hwctx->surface_type,
168  s->surfaces_internal, NULL);
169  if (FAILED(hr)) {
170  av_log(ctx, AV_LOG_ERROR, "Could not create the surfaces\n");
171  return AVERROR_UNKNOWN;
172  }
173 
175  ctx, dxva2_pool_alloc, NULL);
176  if (!ctx->internal->pool_internal)
177  return AVERROR(ENOMEM);
178 
179  frames_hwctx->surfaces = s->surfaces_internal;
180  frames_hwctx->nb_surfaces = ctx->initial_pool_size;
181 
182  return 0;
183 }
184 
186 {
187  AVDXVA2FramesContext *hwctx = ctx->hwctx;
188  DXVA2FramesContext *s = ctx->internal->priv;
189  int ret;
190 
191  if (hwctx->surface_type != DXVA2_VideoDecoderRenderTarget &&
192  hwctx->surface_type != DXVA2_VideoProcessorRenderTarget) {
193  av_log(ctx, AV_LOG_ERROR, "Unknown surface type: %lu\n",
194  hwctx->surface_type);
195  return AVERROR(EINVAL);
196  }
197 
198  s->device_handle = INVALID_HANDLE_VALUE;
199 
200  /* init the frame pool if the caller didn't provide one */
201  if (!ctx->pool) {
202  ret = dxva2_init_pool(ctx);
203  if (ret < 0) {
204  av_log(ctx, AV_LOG_ERROR, "Error creating an internal frame pool\n");
205  return ret;
206  }
207  }
208 
209  return 0;
210 }
211 
213 {
214  frame->buf[0] = av_buffer_pool_get(ctx->pool);
215  if (!frame->buf[0])
216  return AVERROR(ENOMEM);
217 
218  frame->data[3] = frame->buf[0]->data;
219  frame->format = AV_PIX_FMT_DXVA2_VLD;
220  frame->width = ctx->width;
221  frame->height = ctx->height;
222 
223  return 0;
224 }
225 
228  enum AVPixelFormat **formats)
229 {
230  enum AVPixelFormat *fmts;
231 
232  fmts = av_malloc_array(2, sizeof(*fmts));
233  if (!fmts)
234  return AVERROR(ENOMEM);
235 
236  fmts[0] = ctx->sw_format;
237  fmts[1] = AV_PIX_FMT_NONE;
238 
239  *formats = fmts;
240 
241  return 0;
242 }
243 
245  const AVFrame *src)
246 {
247  IDirect3DSurface9 *surface;
248  D3DSURFACE_DESC surfaceDesc;
249  D3DLOCKED_RECT LockedRect;
250  HRESULT hr;
251 
252  uint8_t *surf_data[4] = { NULL };
253  int surf_linesize[4] = { 0 };
254  int i;
255 
256  int download = !!src->hw_frames_ctx;
257 
258  surface = (IDirect3DSurface9*)(download ? src->data[3] : dst->data[3]);
259 
260  hr = IDirect3DSurface9_GetDesc(surface, &surfaceDesc);
261  if (FAILED(hr)) {
262  av_log(ctx, AV_LOG_ERROR, "Error getting a surface description\n");
263  return AVERROR_UNKNOWN;
264  }
265 
266  hr = IDirect3DSurface9_LockRect(surface, &LockedRect, NULL,
267  download ? D3DLOCK_READONLY : D3DLOCK_DISCARD);
268  if (FAILED(hr)) {
269  av_log(ctx, AV_LOG_ERROR, "Unable to lock DXVA2 surface\n");
270  return AVERROR_UNKNOWN;
271  }
272 
273  for (i = 0; download ? dst->data[i] : src->data[i]; i++)
274  surf_linesize[i] = LockedRect.Pitch;
275 
276  av_image_fill_pointers(surf_data, ctx->sw_format, surfaceDesc.Height,
277  (uint8_t*)LockedRect.pBits, surf_linesize);
278 
279  if (download) {
280  av_image_copy(dst->data, dst->linesize, surf_data, surf_linesize,
281  ctx->sw_format, src->width, src->height);
282  } else {
283  av_image_copy(surf_data, surf_linesize, src->data, src->linesize,
284  ctx->sw_format, src->width, src->height);
285  }
286 
287  IDirect3DSurface9_UnlockRect(surface);
288 
289  return 0;
290 }
291 
293 {
294  AVDXVA2DeviceContext *hwctx = ctx->hwctx;
295  DXVA2DevicePriv *priv = ctx->user_opaque;
296 
297  if (hwctx->devmgr && priv->device_handle != INVALID_HANDLE_VALUE)
298  IDirect3DDeviceManager9_CloseDeviceHandle(hwctx->devmgr, priv->device_handle);
299 
300  if (hwctx->devmgr)
301  IDirect3DDeviceManager9_Release(hwctx->devmgr);
302 
303  if (priv->d3d9device)
304  IDirect3DDevice9_Release(priv->d3d9device);
305 
306  if (priv->d3d9)
307  IDirect3D9_Release(priv->d3d9);
308 
309  if (priv->d3dlib)
310  FreeLibrary(priv->d3dlib);
311 
312  if (priv->dxva2lib)
313  FreeLibrary(priv->dxva2lib);
314 
315  av_freep(&ctx->user_opaque);
316 }
317 
318 static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device,
319  AVDictionary *opts, int flags)
320 {
321  AVDXVA2DeviceContext *hwctx = ctx->hwctx;
322  DXVA2DevicePriv *priv;
323 
324  pDirect3DCreate9 *createD3D = NULL;
325  pCreateDeviceManager9 *createDeviceManager = NULL;
326  D3DPRESENT_PARAMETERS d3dpp = {0};
327  D3DDISPLAYMODE d3ddm;
328  unsigned resetToken = 0;
329  UINT adapter = D3DADAPTER_DEFAULT;
330  HRESULT hr;
331 
332  if (device)
333  adapter = atoi(device);
334 
335  priv = av_mallocz(sizeof(*priv));
336  if (!priv)
337  return AVERROR(ENOMEM);
338 
339  ctx->user_opaque = priv;
340  ctx->free = dxva2_device_free;
341 
342  priv->device_handle = INVALID_HANDLE_VALUE;
343 
344  priv->d3dlib = LoadLibrary("d3d9.dll");
345  if (!priv->d3dlib) {
346  av_log(ctx, AV_LOG_ERROR, "Failed to load D3D9 library\n");
347  return AVERROR_UNKNOWN;
348  }
349  priv->dxva2lib = LoadLibrary("dxva2.dll");
350  if (!priv->dxva2lib) {
351  av_log(ctx, AV_LOG_ERROR, "Failed to load DXVA2 library\n");
352  return AVERROR_UNKNOWN;
353  }
354 
355  createD3D = (pDirect3DCreate9 *)GetProcAddress(priv->d3dlib, "Direct3DCreate9");
356  if (!createD3D) {
357  av_log(ctx, AV_LOG_ERROR, "Failed to locate Direct3DCreate9\n");
358  return AVERROR_UNKNOWN;
359  }
360  createDeviceManager = (pCreateDeviceManager9 *)GetProcAddress(priv->dxva2lib,
361  "DXVA2CreateDirect3DDeviceManager9");
362  if (!createDeviceManager) {
363  av_log(ctx, AV_LOG_ERROR, "Failed to locate DXVA2CreateDirect3DDeviceManager9\n");
364  return AVERROR_UNKNOWN;
365  }
366 
367  priv->d3d9 = createD3D(D3D_SDK_VERSION);
368  if (!priv->d3d9) {
369  av_log(ctx, AV_LOG_ERROR, "Failed to create IDirect3D object\n");
370  return AVERROR_UNKNOWN;
371  }
372 
373  IDirect3D9_GetAdapterDisplayMode(priv->d3d9, adapter, &d3ddm);
374  d3dpp.Windowed = TRUE;
375  d3dpp.BackBufferWidth = 640;
376  d3dpp.BackBufferHeight = 480;
377  d3dpp.BackBufferCount = 0;
378  d3dpp.BackBufferFormat = d3ddm.Format;
379  d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
380  d3dpp.Flags = D3DPRESENTFLAG_VIDEO;
381 
382  hr = IDirect3D9_CreateDevice(priv->d3d9, adapter, D3DDEVTYPE_HAL, GetShellWindow(),
383  D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
384  &d3dpp, &priv->d3d9device);
385  if (FAILED(hr)) {
386  av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device\n");
387  return AVERROR_UNKNOWN;
388  }
389 
390  hr = createDeviceManager(&resetToken, &hwctx->devmgr);
391  if (FAILED(hr)) {
392  av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device manager\n");
393  return AVERROR_UNKNOWN;
394  }
395 
396  hr = IDirect3DDeviceManager9_ResetDevice(hwctx->devmgr, priv->d3d9device, resetToken);
397  if (FAILED(hr)) {
398  av_log(ctx, AV_LOG_ERROR, "Failed to bind Direct3D device to device manager\n");
399  return AVERROR_UNKNOWN;
400  }
401 
402  hr = IDirect3DDeviceManager9_OpenDeviceHandle(hwctx->devmgr, &priv->device_handle);
403  if (FAILED(hr)) {
404  av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
405  return AVERROR_UNKNOWN;
406  }
407 
408  return 0;
409 }
410 
413  .name = "DXVA2",
414 
415  .device_hwctx_size = sizeof(AVDXVA2DeviceContext),
416  .frames_hwctx_size = sizeof(AVDXVA2FramesContext),
417  .frames_priv_size = sizeof(DXVA2FramesContext),
418 
419  .device_create = dxva2_device_create,
420  .frames_init = dxva2_frames_init,
421  .frames_uninit = dxva2_frames_uninit,
422  .frames_get_buffer = dxva2_get_buffer,
423  .transfer_get_formats = dxva2_transfer_get_formats,
424  .transfer_data_to = dxva2_transfer_data,
425  .transfer_data_from = dxva2_transfer_data,
426 
428 };
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
Definition: hwcontext.h:54
int size
This structure describes decoded (raw) audio or video data.
Definition: frame.h:140
This struct is allocated as AVHWFramesContext.hwctx.
misc image utilities
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
Definition: frame.h:308
An API-specific header for AV_HWDEVICE_TYPE_DXVA2.
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
static enum AVSampleFormat formats[]
Definition: avresample.c:163
int width
The allocated dimensions of the frames in this pool.
Definition: hwcontext.h:222
#define FF_ARRAY_ELEMS(a)
static int dxva2_transfer_data(AVHWFramesContext *ctx, AVFrame *dst, const AVFrame *src)
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:202
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame...
Definition: frame.h:365
#define AV_PIX_FMT_P010
Definition: pixfmt.h:288
AVBufferPool * pool_internal
enum AVHWDeviceType type
uint8_t
enum AVPixelFormat pix_fmt
DWORD surface_type
The surface type (e.g.
void * hwctx
The format-specific data, allocated and freed by libavutil along with this context.
Definition: hwcontext.h:85
IDirect3D9 *WINAPI pDirect3DCreate9(UINT)
static int flags
Definition: log.c:50
#define src
Definition: vp8dsp.c:254
static AVBufferRef * dxva2_pool_alloc(void *opaque, int size)
int width
width and height of the video frame
Definition: frame.h:179
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:124
static int dxva2_get_buffer(AVHWFramesContext *ctx, AVFrame *frame)
IDirectXVideoDecoder * decoder_to_release
Certain drivers require the decoder to be destroyed before the surfaces.
#define AVERROR(e)
Definition: error.h:43
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition: pixfmt.h:86
IDirect3DDeviceManager9 * devmgr
AVBufferRef * av_buffer_create(uint8_t *data, int size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
Definition: buffer.c:28
void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Copy image in src_data to dst_data.
Definition: imgutils.c:268
static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device, AVDictionary *opts, int flags)
int initial_pool_size
Initial size of the frame pool.
Definition: hwcontext.h:192
AVDictionary * opts
Definition: movenc.c:50
IDirect3DDevice9 * d3d9device
AVHWDeviceContext * device_ctx
The parent AVHWDeviceContext.
Definition: hwcontext.h:142
static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
Definition: avconv.c:1288
static int dxva2_frames_init(AVHWFramesContext *ctx)
IDirectXVideoAccelerationService * service
AVFormatContext * ctx
Definition: movenc.c:48
#define LoadLibrary(x)
Definition: avisynth.c:44
D3DFORMAT d3d_format
AVBufferPool * av_buffer_pool_init2(int size, void *opaque, AVBufferRef *(*alloc)(void *opaque, int size), void(*pool_free)(void *opaque))
Allocate and initialize a buffer pool with a more complex allocator.
Definition: buffer.c:197
static void dxva2_frames_uninit(AVHWFramesContext *ctx)
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:191
NULL
Definition: eval.c:55
int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height, uint8_t *ptr, const int linesizes[4])
Fill plane data pointers for an image with pixel format pix_fmt and height height.
Definition: imgutils.c:100
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:158
uint8_t * data
The data buffer.
Definition: buffer.h:89
void * hwctx
The format-specific data, allocated and freed automatically along with this context.
Definition: hwcontext.h:155
HRESULT WINAPI pCreateDeviceManager9(UINT *, IDirect3DDeviceManager9 **)
DEFINE_GUID(video_decoder_service, 0xfc51a551, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02)
static int dxva2_transfer_get_formats(AVHWFramesContext *ctx, enum AVHWFrameTransferDirection dir, enum AVPixelFormat **formats)
This struct describes a set or pool of "hardware" frames (i.e.
Definition: hwcontext.h:117
HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer. ...
Definition: pixfmt.h:137
AVHWFramesInternal * internal
Private data used internally by libavutil.
Definition: hwcontext.h:127
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:257
static void dxva2_device_free(AVHWDeviceContext *ctx)
static void * av_malloc_array(size_t nmemb, size_t size)
Definition: mem.h:92
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:146
void * user_opaque
Arbitrary user data, to be used e.g.
Definition: hwcontext.h:102
A reference to a data buffer.
Definition: buffer.h:81
IDirect3D9 * d3d9
IDirect3DSurface9 ** surfaces_internal
common internal and external API header
#define GetProcAddress
Definition: avisynth.c:45
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition: error.h:61
IDirect3DSurface9 ** surfaces
The surface pool.
AVHWFrameTransferDirection
Definition: hwcontext.h:336
pixel format definitions
AVBufferPool * pool
A pool from which the frames are allocated by av_hwframe_get_buffer().
Definition: hwcontext.h:183
This struct is allocated as AVHWDeviceContext.hwctx.
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:205
void(* free)(struct AVHWDeviceContext *ctx)
This field may be set by the caller before calling av_hwdevice_ctx_init().
Definition: hwcontext.h:97
int height
Definition: frame.h:179
static const struct @162 supported_formats[]
static int dxva2_init_pool(AVHWFramesContext *ctx)
AVBufferRef * av_buffer_pool_get(AVBufferPool *pool)
Allocate a new AVBuffer, reusing an old buffer from the pool when available.
Definition: buffer.c:310
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:1704
#define FreeLibrary
Definition: avisynth.c:46
#define MKTAG(a, b, c, d)
Definition: common.h:256
const HWContextType ff_hwcontext_type_dxva2
enum AVPixelFormat sw_format
The pixel format identifying the actual data layout of the hardware frames.
Definition: hwcontext.h:215
AVPixelFormat
Pixel format.
Definition: pixfmt.h:57
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:211