]> git.sesse.net Git - ffmpeg/blob - libavutil/hwcontext_d3d11va.c
hwcontext_d3d11va: allocate staging texture lazily
[ffmpeg] / libavutil / hwcontext_d3d11va.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 // Include thread.h before redefining _WIN32_WINNT, to get
22 // the right implementation for AVOnce
23 #include "thread.h"
24
25 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600
26 #undef _WIN32_WINNT
27 #define _WIN32_WINNT 0x0600
28 #endif
29 #define COBJMACROS
30
31 #include <initguid.h>
32 #include <d3d11.h>
33 #include <dxgi1_2.h>
34
35 #include "avassert.h"
36 #include "common.h"
37 #include "hwcontext.h"
38 #include "hwcontext_d3d11va.h"
39 #include "hwcontext_internal.h"
40 #include "imgutils.h"
41 #include "pixdesc.h"
42 #include "pixfmt.h"
43
44 typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY)(REFIID riid, void **ppFactory);
45
46 static AVOnce functions_loaded = AV_ONCE_INIT;
47
48 static PFN_CREATE_DXGI_FACTORY mCreateDXGIFactory;
49 static PFN_D3D11_CREATE_DEVICE mD3D11CreateDevice;
50
51 static av_cold void load_functions(void)
52 {
53 #if HAVE_LOADLIBRARY
54     // We let these "leak" - this is fine, as unloading has no great benefit, and
55     // Windows will mark a DLL as loaded forever if its internal refcount overflows
56     // from too many LoadLibrary calls.
57     HANDLE d3dlib, dxgilib;
58
59     d3dlib  = LoadLibrary("d3d11.dll");
60     dxgilib = LoadLibrary("dxgi.dll");
61     if (!d3dlib || !dxgilib)
62         return;
63
64     mD3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE) GetProcAddress(d3dlib, "D3D11CreateDevice");
65     mCreateDXGIFactory = (PFN_CREATE_DXGI_FACTORY) GetProcAddress(dxgilib, "CreateDXGIFactory");
66 #else
67     // In UWP (which lacks LoadLibrary), CreateDXGIFactory isn't available,
68     // only CreateDXGIFactory1
69     mD3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE) D3D11CreateDevice;
70     mCreateDXGIFactory = (PFN_CREATE_DXGI_FACTORY) CreateDXGIFactory1;
71 #endif
72 }
73
74 typedef struct D3D11VAFramesContext {
75     int nb_surfaces_used;
76
77     DXGI_FORMAT format;
78
79     ID3D11Texture2D *staging_texture;
80 } D3D11VAFramesContext;
81
82 static const struct {
83     DXGI_FORMAT d3d_format;
84     enum AVPixelFormat pix_fmt;
85 } supported_formats[] = {
86     { DXGI_FORMAT_NV12, AV_PIX_FMT_NV12 },
87     { DXGI_FORMAT_P010, AV_PIX_FMT_P010 },
88 };
89
90 static void d3d11va_default_lock(void *ctx)
91 {
92     WaitForSingleObjectEx(ctx, INFINITE, FALSE);
93 }
94
95 static void d3d11va_default_unlock(void *ctx)
96 {
97     ReleaseMutex(ctx);
98 }
99
100 static void d3d11va_frames_uninit(AVHWFramesContext *ctx)
101 {
102     AVD3D11VAFramesContext *frames_hwctx = ctx->hwctx;
103     D3D11VAFramesContext *s = ctx->internal->priv;
104
105     if (frames_hwctx->texture)
106         ID3D11Texture2D_Release(frames_hwctx->texture);
107     frames_hwctx->texture = NULL;
108
109     if (s->staging_texture)
110         ID3D11Texture2D_Release(s->staging_texture);
111     s->staging_texture = NULL;
112 }
113
114 static void free_texture(void *opaque, uint8_t *data)
115 {
116     ID3D11Texture2D_Release((ID3D11Texture2D *)opaque);
117 }
118
119 static AVBufferRef *wrap_texture_buf(ID3D11Texture2D *tex, int index)
120 {
121     AVBufferRef *buf;
122     AVD3D11FrameDescriptor *desc = av_mallocz(sizeof(*desc));
123     if (!desc) {
124         ID3D11Texture2D_Release(tex);
125         return NULL;
126     }
127
128     desc->texture = tex;
129     desc->index   = index;
130
131     buf = av_buffer_create((uint8_t *)desc, sizeof(desc), free_texture, tex, 0);
132     if (!buf) {
133         ID3D11Texture2D_Release(tex);
134         av_free(desc);
135         return NULL;
136     }
137
138     return buf;
139 }
140
141 static AVBufferRef *d3d11va_alloc_single(AVHWFramesContext *ctx)
142 {
143     D3D11VAFramesContext       *s = ctx->internal->priv;
144     AVD3D11VAFramesContext *hwctx = ctx->hwctx;
145     AVD3D11VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
146     HRESULT hr;
147     ID3D11Texture2D *tex;
148     D3D11_TEXTURE2D_DESC texDesc = {
149         .Width      = ctx->width,
150         .Height     = ctx->height,
151         .MipLevels  = 1,
152         .Format     = s->format,
153         .SampleDesc = { .Count = 1 },
154         .ArraySize  = 1,
155         .Usage      = D3D11_USAGE_DEFAULT,
156         .BindFlags  = hwctx->BindFlags,
157         .MiscFlags  = hwctx->MiscFlags,
158     };
159
160     hr = ID3D11Device_CreateTexture2D(device_hwctx->device, &texDesc, NULL, &tex);
161     if (FAILED(hr)) {
162         av_log(ctx, AV_LOG_ERROR, "Could not create the texture (%lx)\n", (long)hr);
163         return NULL;
164     }
165
166     return wrap_texture_buf(tex, 0);
167 }
168
169 static AVBufferRef *d3d11va_pool_alloc(void *opaque, int size)
170 {
171     AVHWFramesContext        *ctx = (AVHWFramesContext*)opaque;
172     D3D11VAFramesContext       *s = ctx->internal->priv;
173     AVD3D11VAFramesContext *hwctx = ctx->hwctx;
174     D3D11_TEXTURE2D_DESC  texDesc;
175
176     if (!hwctx->texture)
177         return d3d11va_alloc_single(ctx);
178
179     ID3D11Texture2D_GetDesc(hwctx->texture, &texDesc);
180
181     if (s->nb_surfaces_used >= texDesc.ArraySize) {
182         av_log(ctx, AV_LOG_ERROR, "Static surface pool size exceeded.\n");
183         return NULL;
184     }
185
186     ID3D11Texture2D_AddRef(hwctx->texture);
187     return wrap_texture_buf(hwctx->texture, s->nb_surfaces_used++);
188 }
189
190 static int d3d11va_frames_init(AVHWFramesContext *ctx)
191 {
192     AVD3D11VAFramesContext *hwctx        = ctx->hwctx;
193     AVD3D11VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
194     D3D11VAFramesContext              *s = ctx->internal->priv;
195
196     int i;
197     HRESULT hr;
198     D3D11_TEXTURE2D_DESC texDesc;
199
200     for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
201         if (ctx->sw_format == supported_formats[i].pix_fmt) {
202             s->format = supported_formats[i].d3d_format;
203             break;
204         }
205     }
206     if (i == FF_ARRAY_ELEMS(supported_formats)) {
207         av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n",
208                av_get_pix_fmt_name(ctx->sw_format));
209         return AVERROR(EINVAL);
210     }
211
212     texDesc = (D3D11_TEXTURE2D_DESC){
213         .Width      = ctx->width,
214         .Height     = ctx->height,
215         .MipLevels  = 1,
216         .Format     = s->format,
217         .SampleDesc = { .Count = 1 },
218         .ArraySize  = ctx->initial_pool_size,
219         .Usage      = D3D11_USAGE_DEFAULT,
220         .BindFlags  = hwctx->BindFlags,
221         .MiscFlags  = hwctx->MiscFlags,
222     };
223
224     if (hwctx->texture) {
225         D3D11_TEXTURE2D_DESC texDesc2;
226         ID3D11Texture2D_GetDesc(hwctx->texture, &texDesc2);
227
228         if (texDesc.Width != texDesc2.Width ||
229             texDesc.Height != texDesc2.Height ||
230             texDesc.Format != texDesc2.Format) {
231             av_log(ctx, AV_LOG_ERROR, "User-provided texture has mismatching parameters\n");
232             return AVERROR(EINVAL);
233         }
234     } else if (texDesc.ArraySize > 0) {
235         hr = ID3D11Device_CreateTexture2D(device_hwctx->device, &texDesc, NULL, &hwctx->texture);
236         if (FAILED(hr)) {
237             av_log(ctx, AV_LOG_ERROR, "Could not create the texture (%lx)\n", (long)hr);
238             return AVERROR_UNKNOWN;
239         }
240     }
241
242     ctx->internal->pool_internal = av_buffer_pool_init2(sizeof(AVD3D11FrameDescriptor),
243                                                         ctx, d3d11va_pool_alloc, NULL);
244     if (!ctx->internal->pool_internal)
245         return AVERROR(ENOMEM);
246
247     return 0;
248 }
249
250 static int d3d11va_get_buffer(AVHWFramesContext *ctx, AVFrame *frame)
251 {
252     AVD3D11FrameDescriptor *desc;
253
254     frame->buf[0] = av_buffer_pool_get(ctx->pool);
255     if (!frame->buf[0])
256         return AVERROR(ENOMEM);
257
258     desc = (AVD3D11FrameDescriptor *)frame->buf[0]->data;
259
260     frame->data[0] = (uint8_t *)desc->texture;
261     frame->data[1] = (uint8_t *)desc->index;
262     frame->format  = AV_PIX_FMT_D3D11;
263     frame->width   = ctx->width;
264     frame->height  = ctx->height;
265
266     return 0;
267 }
268
269 static int d3d11va_transfer_get_formats(AVHWFramesContext *ctx,
270                                         enum AVHWFrameTransferDirection dir,
271                                         enum AVPixelFormat **formats)
272 {
273     enum AVPixelFormat *fmts;
274
275     fmts = av_malloc_array(2, sizeof(*fmts));
276     if (!fmts)
277         return AVERROR(ENOMEM);
278
279     fmts[0] = ctx->sw_format;
280     fmts[1] = AV_PIX_FMT_NONE;
281
282     *formats = fmts;
283
284     return 0;
285 }
286
287 static int d3d11va_create_staging_texture(AVHWFramesContext *ctx)
288 {
289     AVD3D11VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
290     D3D11VAFramesContext              *s = ctx->internal->priv;
291     HRESULT hr;
292     D3D11_TEXTURE2D_DESC texDesc = {
293         .Width          = ctx->width,
294         .Height         = ctx->height,
295         .MipLevels      = 1,
296         .Format         = s->format,
297         .SampleDesc     = { .Count = 1 },
298         .ArraySize      = 1,
299         .Usage          = D3D11_USAGE_STAGING,
300         .CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE,
301     };
302
303     hr = ID3D11Device_CreateTexture2D(device_hwctx->device, &texDesc, NULL, &s->staging_texture);
304     if (FAILED(hr)) {
305         av_log(ctx, AV_LOG_ERROR, "Could not create the staging texture (%lx)\n", (long)hr);
306         return AVERROR_UNKNOWN;
307     }
308
309     return 0;
310 }
311
312 static void fill_texture_ptrs(uint8_t *data[4], int linesize[4],
313                               AVHWFramesContext *ctx,
314                               D3D11_TEXTURE2D_DESC *desc,
315                               D3D11_MAPPED_SUBRESOURCE *map)
316 {
317     int i;
318
319     for (i = 0; i < 4; i++)
320         linesize[i] = map->RowPitch;
321
322     av_image_fill_pointers(data, ctx->sw_format, desc->Height,
323                            (uint8_t*)map->pData, linesize);
324 }
325
326 static int d3d11va_transfer_data(AVHWFramesContext *ctx, AVFrame *dst,
327                                  const AVFrame *src)
328 {
329     AVD3D11VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
330     D3D11VAFramesContext              *s = ctx->internal->priv;
331     int download = src->format == AV_PIX_FMT_D3D11;
332     const AVFrame *frame = download ? src : dst;
333     const AVFrame *other = download ? dst : src;
334     // (The interface types are compatible.)
335     ID3D11Resource *texture = (ID3D11Resource *)(ID3D11Texture2D *)frame->data[0];
336     int index = (intptr_t)frame->data[1];
337     ID3D11Resource *staging;
338     int w = FFMIN(dst->width,  src->width);
339     int h = FFMIN(dst->height, src->height);
340     uint8_t *map_data[4];
341     int map_linesize[4];
342     D3D11_TEXTURE2D_DESC desc;
343     D3D11_MAPPED_SUBRESOURCE map;
344     HRESULT hr;
345
346     if (frame->hw_frames_ctx->data != (uint8_t *)ctx || other->format != ctx->sw_format)
347         return AVERROR(EINVAL);
348
349     device_hwctx->lock(device_hwctx->lock_ctx);
350
351     if (!s->staging_texture) {
352         int res = d3d11va_create_staging_texture(ctx);
353         if (res < 0)
354             return res;
355     }
356
357     staging = (ID3D11Resource *)s->staging_texture;
358
359     ID3D11Texture2D_GetDesc(s->staging_texture, &desc);
360
361     if (download) {
362         ID3D11DeviceContext_CopySubresourceRegion(device_hwctx->device_context,
363                                                   staging, 0, 0, 0, 0,
364                                                   texture, index, NULL);
365
366         hr = ID3D11DeviceContext_Map(device_hwctx->device_context,
367                                      staging, 0, D3D11_MAP_READ, 0, &map);
368         if (FAILED(hr))
369             goto map_failed;
370
371         fill_texture_ptrs(map_data, map_linesize, ctx, &desc, &map);
372
373         av_image_copy(dst->data, dst->linesize, map_data, map_linesize,
374                       ctx->sw_format, w, h);
375
376         ID3D11DeviceContext_Unmap(device_hwctx->device_context, staging, 0);
377     } else {
378         hr = ID3D11DeviceContext_Map(device_hwctx->device_context,
379                                      staging, 0, D3D11_MAP_WRITE, 0, &map);
380         if (FAILED(hr))
381             goto map_failed;
382
383         fill_texture_ptrs(map_data, map_linesize, ctx, &desc, &map);
384
385         av_image_copy(map_data, map_linesize, src->data, src->linesize,
386                       ctx->sw_format, w, h);
387
388         ID3D11DeviceContext_Unmap(device_hwctx->device_context, staging, 0);
389
390         ID3D11DeviceContext_CopySubresourceRegion(device_hwctx->device_context,
391                                                   texture, index, 0, 0, 0,
392                                                   staging, 0, NULL);
393     }
394
395     device_hwctx->unlock(device_hwctx->lock_ctx);
396     return 0;
397
398 map_failed:
399     av_log(ctx, AV_LOG_ERROR, "Unable to lock D3D11VA surface (%lx)\n", (long)hr);
400     device_hwctx->unlock(device_hwctx->lock_ctx);
401     return AVERROR_UNKNOWN;
402 }
403
404 static int d3d11va_device_init(AVHWDeviceContext *hwdev)
405 {
406     AVD3D11VADeviceContext *device_hwctx = hwdev->hwctx;
407     HRESULT hr;
408
409     if (!device_hwctx->lock) {
410         device_hwctx->lock_ctx = CreateMutex(NULL, 0, NULL);
411         if (device_hwctx->lock_ctx == INVALID_HANDLE_VALUE) {
412             av_log(NULL, AV_LOG_ERROR, "Failed to create a mutex\n");
413             return AVERROR(EINVAL);
414         }
415         device_hwctx->lock   = d3d11va_default_lock;
416         device_hwctx->unlock = d3d11va_default_unlock;
417     }
418
419     if (!device_hwctx->device_context) {
420         ID3D11Device_GetImmediateContext(device_hwctx->device, &device_hwctx->device_context);
421         if (!device_hwctx->device_context)
422             return AVERROR_UNKNOWN;
423     }
424
425     if (!device_hwctx->video_device) {
426         hr = ID3D11DeviceContext_QueryInterface(device_hwctx->device, &IID_ID3D11VideoDevice,
427                                                 (void **)&device_hwctx->video_device);
428         if (FAILED(hr))
429             return AVERROR_UNKNOWN;
430     }
431
432     if (!device_hwctx->video_context) {
433         hr = ID3D11DeviceContext_QueryInterface(device_hwctx->device_context, &IID_ID3D11VideoContext,
434                                                 (void **)&device_hwctx->video_context);
435         if (FAILED(hr))
436             return AVERROR_UNKNOWN;
437     }
438
439     return 0;
440 }
441
442 static void d3d11va_device_uninit(AVHWDeviceContext *hwdev)
443 {
444     AVD3D11VADeviceContext *device_hwctx = hwdev->hwctx;
445
446     if (device_hwctx->device)
447         ID3D11Device_Release(device_hwctx->device);
448
449     if (device_hwctx->device_context)
450         ID3D11DeviceContext_Release(device_hwctx->device_context);
451
452     if (device_hwctx->video_device)
453         ID3D11VideoDevice_Release(device_hwctx->video_device);
454
455     if (device_hwctx->video_context)
456         ID3D11VideoContext_Release(device_hwctx->video_context);
457
458     if (device_hwctx->lock == d3d11va_default_lock)
459         CloseHandle(device_hwctx->lock_ctx);
460 }
461
462 static int d3d11va_device_create(AVHWDeviceContext *ctx, const char *device,
463                                  AVDictionary *opts, int flags)
464 {
465     AVD3D11VADeviceContext *device_hwctx = ctx->hwctx;
466
467     HRESULT hr;
468     IDXGIAdapter           *pAdapter = NULL;
469     ID3D10Multithread      *pMultithread;
470     UINT creationFlags = D3D11_CREATE_DEVICE_VIDEO_SUPPORT;
471     int ret;
472
473     if ((ret = ff_thread_once(&functions_loaded, load_functions)) != 0)
474         return AVERROR_UNKNOWN;
475     if (!mD3D11CreateDevice || !mCreateDXGIFactory) {
476         av_log(ctx, AV_LOG_ERROR, "Failed to load D3D11 library or its functions\n");
477         return AVERROR_UNKNOWN;
478     }
479
480     if (device) {
481         IDXGIFactory2 *pDXGIFactory;
482         hr = mCreateDXGIFactory(&IID_IDXGIFactory2, (void **)&pDXGIFactory);
483         if (SUCCEEDED(hr)) {
484             int adapter = atoi(device);
485             if (FAILED(IDXGIFactory2_EnumAdapters(pDXGIFactory, adapter, &pAdapter)))
486                 pAdapter = NULL;
487             IDXGIFactory2_Release(pDXGIFactory);
488         }
489     }
490
491     hr = mD3D11CreateDevice(pAdapter, pAdapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, NULL, creationFlags, NULL, 0,
492                    D3D11_SDK_VERSION, &device_hwctx->device, NULL, NULL);
493     if (pAdapter)
494         IDXGIAdapter_Release(pAdapter);
495     if (FAILED(hr)) {
496         av_log(ctx, AV_LOG_ERROR, "Failed to create Direct3D device (%lx)\n", (long)hr);
497         return AVERROR_UNKNOWN;
498     }
499
500     hr = ID3D11Device_QueryInterface(device_hwctx->device, &IID_ID3D10Multithread, (void **)&pMultithread);
501     if (SUCCEEDED(hr)) {
502         ID3D10Multithread_SetMultithreadProtected(pMultithread, TRUE);
503         ID3D10Multithread_Release(pMultithread);
504     }
505
506     return 0;
507 }
508
509 const HWContextType ff_hwcontext_type_d3d11va = {
510     .type                 = AV_HWDEVICE_TYPE_D3D11VA,
511     .name                 = "D3D11VA",
512
513     .device_hwctx_size    = sizeof(AVD3D11VADeviceContext),
514     .frames_hwctx_size    = sizeof(AVD3D11VAFramesContext),
515     .frames_priv_size     = sizeof(D3D11VAFramesContext),
516
517     .device_create        = d3d11va_device_create,
518     .device_init          = d3d11va_device_init,
519     .device_uninit        = d3d11va_device_uninit,
520     .frames_init          = d3d11va_frames_init,
521     .frames_uninit        = d3d11va_frames_uninit,
522     .frames_get_buffer    = d3d11va_get_buffer,
523     .transfer_get_formats = d3d11va_transfer_get_formats,
524     .transfer_data_to     = d3d11va_transfer_data,
525     .transfer_data_from   = d3d11va_transfer_data,
526
527     .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_D3D11, AV_PIX_FMT_NONE },
528 };