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