FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
hwcontext_dxva2.c
Go to the documentation of this file.
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 
41 typedef IDirect3D9* WINAPI pDirect3DCreate9(UINT);
42 typedef HRESULT WINAPI pCreateDeviceManager9(UINT *, IDirect3DDeviceManager9 **);
43 
44 typedef struct DXVA2FramesContext {
45  IDirect3DSurface9 **surfaces_internal;
47 
49  IDirectXVideoAccelerationService *service;
50 
51  D3DFORMAT format;
53 
54 typedef struct DXVA2DevicePriv {
57 
59 
60  IDirect3D9 *d3d9;
61  IDirect3DDevice9 *d3d9device;
63 
64 static const struct {
65  D3DFORMAT d3d_format;
67 } supported_formats[] = {
68  { MKTAG('N', 'V', '1', '2'), AV_PIX_FMT_NV12 },
69  { MKTAG('P', '0', '1', '0'), AV_PIX_FMT_P010 },
70 };
71 
72 DEFINE_GUID(video_decoder_service, 0xfc51a551, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
73 DEFINE_GUID(video_processor_service, 0xfc51a552, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02);
74 
76 {
77  AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
78  AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
80  int i;
81 
82  if (frames_hwctx->decoder_to_release)
83  IDirectXVideoDecoder_Release(frames_hwctx->decoder_to_release);
84 
85  if (s->surfaces_internal) {
86  for (i = 0; i < frames_hwctx->nb_surfaces; i++) {
87  if (s->surfaces_internal[i])
88  IDirect3DSurface9_Release(s->surfaces_internal[i]);
89  }
90  }
92 
93  if (s->service) {
94  IDirectXVideoAccelerationService_Release(s->service);
95  s->service = NULL;
96  }
97 
99  IDirect3DDeviceManager9_CloseDeviceHandle(device_hwctx->devmgr, s->device_handle);
101  }
102 }
103 
104 static AVBufferRef *dxva2_pool_alloc(void *opaque, int size)
105 {
108  AVDXVA2FramesContext *hwctx = ctx->hwctx;
109 
110  if (s->nb_surfaces_used < hwctx->nb_surfaces) {
111  s->nb_surfaces_used++;
113  sizeof(*hwctx->surfaces), NULL, 0, 0);
114  }
115 
116  return NULL;
117 }
118 
120 {
121  AVDXVA2FramesContext *frames_hwctx = ctx->hwctx;
122  AVDXVA2DeviceContext *device_hwctx = ctx->device_ctx->hwctx;
124  int decode = (frames_hwctx->surface_type == DXVA2_VideoDecoderRenderTarget);
125 
126  int i;
127  HRESULT hr;
128 
129  if (ctx->initial_pool_size <= 0)
130  return 0;
131 
132  hr = IDirect3DDeviceManager9_OpenDeviceHandle(device_hwctx->devmgr, &s->device_handle);
133  if (FAILED(hr)) {
134  av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
135  return AVERROR_UNKNOWN;
136  }
137 
138  hr = IDirect3DDeviceManager9_GetVideoService(device_hwctx->devmgr,
139  s->device_handle,
140  decode ? &video_decoder_service : &video_processor_service,
141  (void **)&s->service);
142  if (FAILED(hr)) {
143  av_log(ctx, AV_LOG_ERROR, "Failed to create the video service\n");
144  return AVERROR_UNKNOWN;
145  }
146 
147  for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
148  if (ctx->sw_format == supported_formats[i].pix_fmt) {
149  s->format = supported_formats[i].d3d_format;
150  break;
151  }
152  }
153  if (i == FF_ARRAY_ELEMS(supported_formats)) {
154  av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n",
156  return AVERROR(EINVAL);
157  }
158 
160  sizeof(*s->surfaces_internal));
161  if (!s->surfaces_internal)
162  return AVERROR(ENOMEM);
163 
164  hr = IDirectXVideoAccelerationService_CreateSurface(s->service,
165  ctx->width, ctx->height,
166  ctx->initial_pool_size - 1,
167  s->format, D3DPOOL_DEFAULT, 0,
168  frames_hwctx->surface_type,
169  s->surfaces_internal, NULL);
170  if (FAILED(hr)) {
171  av_log(ctx, AV_LOG_ERROR, "Could not create the surfaces\n");
172  return AVERROR_UNKNOWN;
173  }
174 
176  ctx, dxva2_pool_alloc, NULL);
177  if (!ctx->internal->pool_internal)
178  return AVERROR(ENOMEM);
179 
180  frames_hwctx->surfaces = s->surfaces_internal;
181  frames_hwctx->nb_surfaces = ctx->initial_pool_size;
182 
183  return 0;
184 }
185 
187 {
188  AVDXVA2FramesContext *hwctx = ctx->hwctx;
190  int ret;
191 
192  if (hwctx->surface_type != DXVA2_VideoDecoderRenderTarget &&
193  hwctx->surface_type != DXVA2_VideoProcessorRenderTarget) {
194  av_log(ctx, AV_LOG_ERROR, "Unknown surface type: %lu\n",
195  hwctx->surface_type);
196  return AVERROR(EINVAL);
197  }
198 
200 
201  /* init the frame pool if the caller didn't provide one */
202  if (!ctx->pool) {
203  ret = dxva2_init_pool(ctx);
204  if (ret < 0) {
205  av_log(ctx, AV_LOG_ERROR, "Error creating an internal frame pool\n");
206  return ret;
207  }
208  }
209 
210  return 0;
211 }
212 
214 {
215  frame->buf[0] = av_buffer_pool_get(ctx->pool);
216  if (!frame->buf[0])
217  return AVERROR(ENOMEM);
218 
219  frame->data[3] = frame->buf[0]->data;
220  frame->format = AV_PIX_FMT_DXVA2_VLD;
221  frame->width = ctx->width;
222  frame->height = ctx->height;
223 
224  return 0;
225 }
226 
229  enum AVPixelFormat **formats)
230 {
231  enum AVPixelFormat *fmts;
232 
233  fmts = av_malloc_array(2, sizeof(*fmts));
234  if (!fmts)
235  return AVERROR(ENOMEM);
236 
237  fmts[0] = ctx->sw_format;
238  fmts[1] = AV_PIX_FMT_NONE;
239 
240  *formats = fmts;
241 
242  return 0;
243 }
244 
246  const AVFrame *src)
247 {
248  IDirect3DSurface9 *surface;
249  D3DSURFACE_DESC surfaceDesc;
250  D3DLOCKED_RECT LockedRect;
251  HRESULT hr;
252 
253  int download = !!src->hw_frames_ctx;
254  int bytes_per_component;
255 
256  switch (ctx->sw_format) {
257  case AV_PIX_FMT_NV12:
258  bytes_per_component = 1;
259  break;
260  case AV_PIX_FMT_P010:
261  bytes_per_component = 2;
262  break;
263  default:
264  av_assert0(0);
265  }
266 
267  surface = (IDirect3DSurface9*)(download ? src->data[3] : dst->data[3]);
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 
275  hr = IDirect3DSurface9_LockRect(surface, &LockedRect, NULL,
276  download ? D3DLOCK_READONLY : D3DLOCK_DISCARD);
277  if (FAILED(hr)) {
278  av_log(ctx, AV_LOG_ERROR, "Unable to lock DXVA2 surface\n");
279  return AVERROR_UNKNOWN;
280  }
281 
282  if (download) {
283  av_image_copy_plane(dst->data[0], dst->linesize[0],
284  (uint8_t*)LockedRect.pBits, LockedRect.Pitch,
285  src->width * bytes_per_component, src->height);
286  av_image_copy_plane(dst->data[1], dst->linesize[1],
287  (uint8_t*)LockedRect.pBits + LockedRect.Pitch * surfaceDesc.Height,
288  LockedRect.Pitch, src->width * bytes_per_component, src->height / 2);
289  } else {
290  av_image_copy_plane((uint8_t*)LockedRect.pBits, LockedRect.Pitch,
291  dst->data[0], dst->linesize[0],
292  src->width * bytes_per_component, src->height);
293  av_image_copy_plane((uint8_t*)LockedRect.pBits + LockedRect.Pitch * surfaceDesc.Height,
294  LockedRect.Pitch, dst->data[1], dst->linesize[1],
295  src->width * bytes_per_component, src->height / 2);
296  }
297 
298  IDirect3DSurface9_UnlockRect(surface);
299 
300  return 0;
301 }
302 
304 {
305  AVDXVA2DeviceContext *hwctx = ctx->hwctx;
306  DXVA2DevicePriv *priv = ctx->user_opaque;
307 
308  if (hwctx->devmgr && priv->device_handle != INVALID_HANDLE_VALUE)
309  IDirect3DDeviceManager9_CloseDeviceHandle(hwctx->devmgr, priv->device_handle);
310 
311  if (hwctx->devmgr)
312  IDirect3DDeviceManager9_Release(hwctx->devmgr);
313 
314  if (priv->d3d9device)
315  IDirect3DDevice9_Release(priv->d3d9device);
316 
317  if (priv->d3d9)
318  IDirect3D9_Release(priv->d3d9);
319 
320  if (priv->d3dlib)
321  FreeLibrary(priv->d3dlib);
322 
323  if (priv->dxva2lib)
324  FreeLibrary(priv->dxva2lib);
325 
326  av_freep(&ctx->user_opaque);
327 }
328 
329 static int dxva2_device_create(AVHWDeviceContext *ctx, const char *device,
330  AVDictionary *opts, int flags)
331 {
332  AVDXVA2DeviceContext *hwctx = ctx->hwctx;
333  DXVA2DevicePriv *priv;
334 
335  pDirect3DCreate9 *createD3D = NULL;
336  pCreateDeviceManager9 *createDeviceManager = NULL;
337  D3DPRESENT_PARAMETERS d3dpp = {0};
338  D3DDISPLAYMODE d3ddm;
339  unsigned resetToken = 0;
340  UINT adapter = D3DADAPTER_DEFAULT;
341  HRESULT hr;
342 
343  if (device)
344  adapter = atoi(device);
345 
346  priv = av_mallocz(sizeof(*priv));
347  if (!priv)
348  return AVERROR(ENOMEM);
349 
350  ctx->user_opaque = priv;
351  ctx->free = dxva2_device_free;
352 
354 
355  priv->d3dlib = LoadLibrary("d3d9.dll");
356  if (!priv->d3dlib) {
357  av_log(ctx, AV_LOG_ERROR, "Failed to load D3D9 library\n");
358  return AVERROR_UNKNOWN;
359  }
360  priv->dxva2lib = LoadLibrary("dxva2.dll");
361  if (!priv->dxva2lib) {
362  av_log(ctx, AV_LOG_ERROR, "Failed to load DXVA2 library\n");
363  return AVERROR_UNKNOWN;
364  }
365 
366  createD3D = (pDirect3DCreate9 *)GetProcAddress(priv->d3dlib, "Direct3DCreate9");
367  if (!createD3D) {
368  av_log(ctx, AV_LOG_ERROR, "Failed to locate Direct3DCreate9\n");
369  return AVERROR_UNKNOWN;
370  }
371  createDeviceManager = (pCreateDeviceManager9 *)GetProcAddress(priv->dxva2lib,
372  "DXVA2CreateDirect3DDeviceManager9");
373  if (!createDeviceManager) {
374  av_log(ctx, AV_LOG_ERROR, "Failed to locate DXVA2CreateDirect3DDeviceManager9\n");
375  return AVERROR_UNKNOWN;
376  }
377 
378  priv->d3d9 = createD3D(D3D_SDK_VERSION);
379  if (!priv->d3d9) {
380  av_log(ctx, AV_LOG_ERROR, "Failed to create IDirect3D object\n");
381  return AVERROR_UNKNOWN;
382  }
383 
384  IDirect3D9_GetAdapterDisplayMode(priv->d3d9, adapter, &d3ddm);
385  d3dpp.Windowed = TRUE;
386  d3dpp.BackBufferWidth = 640;
387  d3dpp.BackBufferHeight = 480;
388  d3dpp.BackBufferCount = 0;
389  d3dpp.BackBufferFormat = d3ddm.Format;
390  d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
391  d3dpp.Flags = D3DPRESENTFLAG_VIDEO;
392 
393  hr = IDirect3D9_CreateDevice(priv->d3d9, adapter, D3DDEVTYPE_HAL, GetDesktopWindow(),
394  D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
395  &d3dpp, &priv->d3d9device);
396  if (FAILED(hr)) {
397  av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device\n");
398  return AVERROR_UNKNOWN;
399  }
400 
401  hr = createDeviceManager(&resetToken, &hwctx->devmgr);
402  if (FAILED(hr)) {
403  av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device manager\n");
404  return AVERROR_UNKNOWN;
405  }
406 
407  hr = IDirect3DDeviceManager9_ResetDevice(hwctx->devmgr, priv->d3d9device, resetToken);
408  if (FAILED(hr)) {
409  av_log(ctx, AV_LOG_ERROR, "Failed to bind Direct3D device to device manager\n");
410  return AVERROR_UNKNOWN;
411  }
412 
413  hr = IDirect3DDeviceManager9_OpenDeviceHandle(hwctx->devmgr, &priv->device_handle);
414  if (FAILED(hr)) {
415  av_log(ctx, AV_LOG_ERROR, "Failed to open device handle\n");
416  return AVERROR_UNKNOWN;
417  }
418 
419  return 0;
420 }
421 
424  .name = "DXVA2",
425 
426  .device_hwctx_size = sizeof(AVDXVA2DeviceContext),
427  .frames_hwctx_size = sizeof(AVDXVA2FramesContext),
428  .frames_priv_size = sizeof(DXVA2FramesContext),
429 
430  .device_create = dxva2_device_create,
431  .frames_init = dxva2_frames_init,
432  .frames_uninit = dxva2_frames_uninit,
433  .frames_get_buffer = dxva2_get_buffer,
434  .transfer_get_formats = dxva2_transfer_get_formats,
435  .transfer_data_to = dxva2_transfer_data,
436  .transfer_data_from = dxva2_transfer_data,
437 
439 };
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
Definition: hwcontext.h:54
#define NULL
Definition: coverity.c:32
const char * s
Definition: avisynth_c.h:768
This structure describes decoded (raw) audio or video data.
Definition: frame.h:184
This struct is allocated as AVHWFramesContext.hwctx.
misc image utilities
static const struct @233 supported_formats[]
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
Definition: frame.h:367
An API-specific header for AV_HWDEVICE_TYPE_DXVA2.
static enum AVSampleFormat formats[]
Definition: avresample.c:163
int width
The allocated dimensions of the frames in this pool.
Definition: hwcontext.h:222
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:252
static int dxva2_transfer_data(AVHWFramesContext *ctx, AVFrame *dst, const AVFrame *src)
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame...
Definition: frame.h:534
#define AV_PIX_FMT_P010
Definition: pixfmt.h:384
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
AVBufferPool * pool_internal
enum AVHWDeviceType type
uint8_t
enum AVPixelFormat pix_fmt
DWORD surface_type
The surface type (e.g.
static AVFrame * frame
void * hwctx
The format-specific data, allocated and freed by libavutil along with this context.
Definition: hwcontext.h:85
IDirect3D9 *WINAPI pDirect3DCreate9(UINT)
ptrdiff_t size
Definition: opengl_enc.c:101
#define av_log(a,...)
static AVBufferRef * dxva2_pool_alloc(void *opaque, int size)
int width
width and height of the video frame
Definition: frame.h:236
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
static int dxva2_get_buffer(AVHWFramesContext *ctx, AVFrame *frame)
IDirectXVideoDecoder * decoder_to_release
Certain drivers require the decoder to be destroyed before the surfaces.
void(* free)(struct AVHWDeviceContext *ctx)
This field may be set by the caller before calling av_hwdevice_ctx_init().
Definition: hwcontext.h:97
#define AVERROR(e)
Definition: error.h:43
void * HMODULE
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition: pixfmt.h:90
simple assert() macros that are a bit more flexible than ISO C assert().
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
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:226
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
PVOID HANDLE
static int dxva2_frames_init(AVHWFramesContext *ctx)
IDirectXVideoAccelerationService * service
AVFormatContext * ctx
Definition: movenc.c:48
#define TRUE
Definition: windows2linux.h:33
#define src
Definition: vp9dsp.c:530
#define LoadLibrary(x)
Definition: avisynth.c:43
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:217
#define FF_ARRAY_ELEMS(a)
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:248
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:215
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:148
AVHWFramesInternal * internal
Private data used internally by libavutil.
Definition: hwcontext.h:127
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:262
static void dxva2_device_free(AVHWDeviceContext *ctx)
DWORD HRESULT
static int flags
Definition: cpu.c:47
#define FAILED(hr)
Definition: windows2linux.h:48
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:198
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:44
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition: error.h:71
IDirect3DSurface9 ** surfaces
The surface pool.
AVHWFrameTransferDirection
Definition: hwcontext.h:328
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.
int height
Definition: frame.h:236
#define av_freep(p)
unsigned int UINT
static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
Definition: ffmpeg.c:2035
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:380
#define av_malloc_array(a, b)
#define INVALID_HANDLE_VALUE
Definition: windows2linux.h:47
void av_image_copy_plane(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int bytewidth, int height)
Copy image plane from src to dst.
Definition: imgutils.c:287
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:2182
#define FreeLibrary
Definition: avisynth.c:45
#define MKTAG(a, b, c, d)
Definition: common.h:342
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:60