]> git.sesse.net Git - vlc/blob - modules/video_output/msw/direct3d11.c
f8817e395c6758fd4d99cb5a958c6b07830eec7d
[vlc] / modules / video_output / msw / direct3d11.c
1 /*****************************************************************************
2  * direct3d11.c: Windows Direct3D11 video output module
3  *****************************************************************************
4  * Copyright (C) 2014-2015 VLC authors and VideoLAN
5  *
6  * Authors: Martell Malone <martellmalone@gmail.com>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif
26
27 #include <vlc_common.h>
28 #include <vlc_plugin.h>
29 #include <vlc_vout_display.h>
30
31 #define COBJMACROS
32 #define INITGUID
33 #include <d3d11.h>
34
35 /* avoided until we can pass ISwapchainPanel without c++/cx mode
36 # include <windows.ui.xaml.media.dxinterop.h> */
37
38 #include "common.h"
39
40 #if !VLC_WINSTORE_APP
41 # define D3D11CreateDeviceAndSwapChain(args...) sys->OurD3D11CreateDeviceAndSwapChain(args)
42 # define D3D11CreateDevice(args...)             sys->OurD3D11CreateDevice(args)
43 # define D3DCompile(args...)                    sys->OurD3DCompile(args)
44 #else
45 # define IDXGISwapChain_Present(args...)        IDXGISwapChain_Present1(args)
46 # define IDXGIFactory_CreateSwapChain(a,b,c,d)  IDXGIFactory2_CreateSwapChainForComposition(a,b,c,NULL,d)
47 # define DXGI_SWAP_CHAIN_DESC                   DXGI_SWAP_CHAIN_DESC1
48 #endif
49
50 static int  Open(vlc_object_t *);
51 static void Close(vlc_object_t *);
52
53 #define D3D11_HELP N_("Recommended video output for Windows 8 and later versions")
54
55 vlc_module_begin ()
56     set_shortname("Direct3D11")
57     set_description(N_("Direct3D11 video output"))
58     set_help(D3D11_HELP)
59     set_category(CAT_VIDEO)
60     set_subcategory(SUBCAT_VIDEO_VOUT)
61     set_capability("vout display", 240)
62     add_shortcut("direct3d11")
63     set_callbacks(Open, Close)
64 vlc_module_end ()
65
66 typedef struct
67 {
68     const char   *name;
69     DXGI_FORMAT  format;
70     vlc_fourcc_t fourcc;
71 } d3d_format_t;
72
73 static const d3d_format_t d3d_formats[] = {
74     { "NV12",   DXGI_FORMAT_NV12,             VLC_CODEC_NV12  },
75     { "RGBA",   DXGI_FORMAT_R8G8B8A8_UNORM,   VLC_CODEC_RGBA  },
76     { NULL, 0, 0 }
77 };
78
79 static const vlc_fourcc_t d3d_subpicture_chromas[] = {
80     VLC_CODEC_RGBA,
81     0
82 };
83
84 struct picture_sys_t
85 {
86     ID3D11Texture2D     *texture;
87     ID3D11DeviceContext *context;
88 };
89
90 static int  Open(vlc_object_t *);
91 static void Close(vlc_object_t *object);
92
93 static void Prepare(vout_display_t *, picture_t *, subpicture_t *subpicture);
94 static void Display(vout_display_t *, picture_t *, subpicture_t *subpicture);
95
96 static int  Direct3D11Create (vout_display_t *);
97 static void Direct3D11Destroy(vout_display_t *);
98
99 static int  Direct3D11Open (vout_display_t *, video_format_t *);
100 static void Direct3D11Close(vout_display_t *);
101
102 static int  Direct3D11CreateResources (vout_display_t *, video_format_t *);
103 static void Direct3D11DestroyResources(vout_display_t *);
104
105 static int  Direct3D11MapTexture(picture_t *);
106
107 /* All the #if 0 contain an alternative method to setup dx11
108    They both need to be benchmarked to see which performs better */
109 #if 0
110 /* I have no idea why MS decided dxgi headers do not define this
111    As they do have prototypes for d3d11 functions */
112 typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY)(REFIID riid, void **ppFactory);
113 #endif
114
115 /* TODO: Move to a direct3d11_shaders header */
116 static const char* globVertexShaderDefault = "\
117   struct VS_INPUT\
118   {\
119     float4 Position   : POSITION;\
120     float2 Texture    : TEXCOORD0;\
121   };\
122   \
123   struct VS_OUTPUT\
124   {\
125     float4 Position   : SV_POSITION;\
126     float2 Texture    : TEXCOORD0;\
127   };\
128   \
129   VS_OUTPUT VS( VS_INPUT In )\
130   {\
131     VS_OUTPUT Output;\
132     Output.Position = float4(In.Position.xy, 0.0f, 1.0f);\
133     Output.Texture = In.Texture;\
134     return Output;\
135   }\
136 ";
137
138 static const char* globPixelShaderDefault = "\
139   Texture2D shaderTexture;\
140   SamplerState SampleType;\
141   \
142   struct PS_INPUT\
143   {\
144     float4 Position   : SV_POSITION;\
145     float2 Texture    : TEXCOORD0;\
146   };\
147   \
148   float4 PS( PS_INPUT In ) : SV_TARGET\
149   {\
150     return shaderTexture.Sample(SampleType, In.Texture);\
151   }\
152 ";
153
154 static const char* globPixelShaderBiplanarYUV2RGB = "\
155   Texture2D shaderTextureY;\
156   Texture2D shaderTextureUV;\
157   SamplerState SampleType;\
158   \
159   struct PS_INPUT\
160   {\
161     float4 Position   : SV_POSITION;\
162     float2 Texture    : TEXCOORD0;\
163   };\
164   \
165   float4 PS( PS_INPUT In ) : SV_TARGET\
166   {\
167     float3 yuv;\
168     float4 rgba;\
169     yuv.x  = shaderTextureY.Sample(SampleType, In.Texture).x;\
170     yuv.yz = shaderTextureUV.Sample(SampleType, In.Texture).xy;\
171     yuv.x  = 1.164 * (yuv.x-0.0625);\
172     yuv.y  = yuv.y - 0.5;\
173     yuv.z  = yuv.z - 0.5;\
174     rgba.x = saturate(yuv.x + 1.596 * yuv.z);\
175     rgba.y = saturate(yuv.x - 0.813 * yuv.z - 0.391 * yuv.y);\
176     rgba.z = saturate(yuv.x + 2.018 * yuv.y);\
177     rgba.w = 1.0;\
178     return rgba;\
179   }\
180 ";
181
182 static int Open(vlc_object_t *object)
183 {
184     vout_display_t *vd = (vout_display_t *)object;
185
186     if (Direct3D11Create(vd)) {
187         msg_Err(vd, "Direct3D11 could not be initialized");
188         Direct3D11Destroy(vd);
189         return VLC_EGENERIC;
190     }
191
192     if (CommonInit(vd))
193         goto error;
194
195     /* TODO : A fallback system */
196     vd->sys->d3dFormat = d3d_formats[0].format;
197     vd->sys->vlcFormat = d3d_formats[0].fourcc;
198
199     video_format_t fmt;
200     if (Direct3D11Open(vd, &fmt)) {
201         msg_Err(vd, "Direct3D11 could not be opened");
202         goto error;
203     }
204
205     vout_display_info_t info  = vd->info;
206     info.is_slow              = true;
207     info.has_double_click     = true;
208     info.has_hide_mouse       = false;
209     info.has_pictures_invalid = true;
210     info.has_event_thread     = true;
211
212     /* TODO : subtitle support */
213     info.subpicture_chromas   = NULL;
214
215     video_format_Clean(&vd->fmt);
216     video_format_Copy(&vd->fmt, &fmt);
217     vd->info = info;
218
219     vd->pool    = CommonPool;
220     vd->prepare = Prepare;
221     vd->display = Display;
222     vd->control = CommonControl;
223     vd->manage  = CommonManage;
224
225     msg_Dbg(vd, "Direct3D11 Open Succeeded");
226
227     return VLC_SUCCESS;
228 error:
229     Direct3D11Close(vd);
230     CommonClean(vd);
231     Direct3D11Destroy(vd);
232     free(vd->sys);
233     return VLC_EGENERIC;
234 }
235
236 static void Close(vlc_object_t *object)
237 {
238     vout_display_t * vd = (vout_display_t *)object;
239
240     Direct3D11Close(vd);
241     CommonClean(vd);
242     Direct3D11Destroy(vd);
243     free(vd->sys);
244 }
245
246 static void Prepare(vout_display_t *vd, picture_t *picture, subpicture_t *subpicture)
247 {
248     vout_display_sys_t *sys = vd->sys;
249     VLC_UNUSED(subpicture);
250     VLC_UNUSED(picture);
251
252     /* float ClearColor[4] = { 1.0f, 0.125f, 0.3f, 1.0f }; */
253     /* ID3D11DeviceContext_ClearRenderTargetView(sys->d3dcontext,sys->d3drenderTargetView, ClearColor); */
254     ID3D11DeviceContext_ClearDepthStencilView(sys->d3dcontext,sys->d3ddepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
255
256     /* Render the quad */
257     ID3D11DeviceContext_VSSetShader(sys->d3dcontext, sys->d3dvertexShader, NULL, 0);
258     ID3D11DeviceContext_PSSetShader(sys->d3dcontext, sys->d3dpixelShader, NULL, 0);
259     ID3D11DeviceContext_PSSetShaderResources(sys->d3dcontext, 0, 1, &sys->d3dresViewY);
260
261     if (sys->vlcFormat == VLC_CODEC_NV12)
262         ID3D11DeviceContext_PSSetShaderResources(sys->d3dcontext, 1, 1, &sys->d3dresViewUV);
263
264     ID3D11DeviceContext_PSSetSamplers(sys->d3dcontext, 0, 1, &sys->d3dsampState);
265     ID3D11DeviceContext_DrawIndexed(sys->d3dcontext, 6, 0, 0);
266 }
267
268 static void Display(vout_display_t *vd, picture_t *picture, subpicture_t *subpicture)
269 {
270     vout_display_sys_t *sys = vd->sys;
271
272     IDXGISwapChain_Present(sys->dxgiswapChain, 0, 0);
273
274     picture_Release(picture);
275     if (subpicture)
276         subpicture_Delete(subpicture);
277
278     CommonDisplay(vd);
279 }
280
281 #if !VLC_WINSTORE_APP
282 static HINSTANCE Direct3D11LoadShaderLibrary(void)
283 {
284     HINSTANCE instance = NULL;
285     /* d3dcompiler_47 is the latest on windows 8.1 */
286     for (int i = 47; i > 41; --i) {
287         TCHAR filename[19];
288         _sntprintf(filename, 19, TEXT("D3DCOMPILER_%d.dll"), i);
289         instance = LoadLibrary(filename);
290         if (instance) break;
291     }
292     return instance;
293 }
294 #endif
295
296 static int Direct3D11Create(vout_display_t *vd)
297 {
298
299 #if !VLC_WINSTORE_APP
300
301     HINSTANCE hd3d11_dll = LoadLibrary(TEXT("D3D11.DLL"));
302     if (!hd3d11_dll) {
303         msg_Warn(vd, "cannot load d3d11.dll, aborting");
304         return VLC_EGENERIC;
305     }
306
307 # if 0
308     HINSTANCE hdxgi_dll = LoadLibrary(TEXT("DXGI.DLL"));
309     if (!hdxgi_dll) {
310         msg_Warn(vd, "cannot load dxgi.dll, aborting");
311         return VLC_EGENERIC;
312     }
313 # endif
314
315     HINSTANCE hd3dcompiler_dll = Direct3D11LoadShaderLibrary();
316     if (!hd3dcompiler_dll) {
317         msg_Err(vd, "cannot load d3dcompiler.dll, aborting");
318         return VLC_EGENERIC;
319     }
320
321 #else
322
323     IDXGISwapChain1* dxgiswapChain  = var_InheritInteger(vd, "winrt-dxgiswapchain");
324     if (!dxgiswapChain)
325         return VLC_EGENERIC;
326     ID3D11Device* d3ddevice         = var_InheritInteger(vd, "winrt-d3ddevice");
327     if (!d3ddevice)
328         return VLC_EGENERIC;
329     ID3D11DeviceContext* d3dcontext = var_InheritInteger(vd, "winrt-d3dcontext");
330     if (!d3dcontext)
331         return VLC_EGENERIC;
332
333 #endif
334
335     vout_display_sys_t *sys = vd->sys = calloc(1, sizeof(vout_display_sys_t));
336     if (!sys)
337         return VLC_ENOMEM;
338
339 #if !VLC_WINSTORE_APP
340
341     sys->hd3d11_dll       = hd3d11_dll;
342     sys->hd3dcompiler_dll = hd3dcompiler_dll;
343
344     sys->OurD3DCompile = (void *)GetProcAddress(sys->hd3dcompiler_dll, "D3DCompile");
345     if (!sys->OurD3DCompile) {
346         msg_Err(vd, "Cannot locate reference to D3DCompile in d3dcompiler DLL");
347         return VLC_EGENERIC;
348     }
349
350 # if 0
351
352     sys->hdxgi_dll = hdxgi_dll;
353
354     /* TODO : enable all dxgi versions from 1.3 -> 1.1 */
355     PFN_CREATE_DXGI_FACTORY OurCreateDXGIFactory =
356         (void *)GetProcAddress(sys->hdxgi_dll, "CreateDXGIFactory");
357     if (!OurCreateDXGIFactory) {
358         msg_Err(vd, "Cannot locate reference to CreateDXGIFactory in dxgi DLL");
359         return VLC_EGENERIC;
360     }
361
362     /* TODO : detect the directx version supported and use IID_IDXGIFactory3 or 2 */
363     HRESULT hr = OurCreateDXGIFactory(&IID_IDXGIFactory, (void **)&sys->dxgifactory);
364     if (FAILED(hr)) {
365         msg_Err(vd, "Could not create dxgi factory. (hr=0x%lX)", hr);
366         return VLC_EGENERIC;
367     }
368
369     sys->OurD3D11CreateDeviceAndSwapChain =
370         (void *)GetProcAddress(sys->hd3d11_dll, "D3D11CreateDeviceAndSwapChain");
371     if (!sys->OurD3D11CreateDeviceAndSwapChain) {
372         msg_Err(vd, "Cannot locate reference to D3D11CreateDeviceAndSwapChain in d3d11 DLL");
373         return VLC_EGENERIC;
374     }
375
376 # else
377
378     sys->OurD3D11CreateDevice =
379         (void *)GetProcAddress(sys->hd3d11_dll, "D3D11CreateDevice");
380     if (!sys->OurD3D11CreateDevice) {
381         msg_Err(vd, "Cannot locate reference to D3D11CreateDevice in d3d11 DLL");
382         return VLC_EGENERIC;
383     }
384
385 # endif
386
387 #else
388
389     sys->dxgiswapChain = dxgiswapChain;
390     sys->d3ddevice     = d3ddevice;
391     sys->d3dcontext    = d3dcontext;
392
393 #endif
394
395     return VLC_SUCCESS;
396 }
397
398
399 static void Direct3D11Destroy(vout_display_t *vd)
400 {
401
402 #if !VLC_WINSTORE_APP
403
404     vout_display_sys_t *sys = vd->sys;
405
406 # if 0
407     if (sys->hdxgi_dll)
408         FreeLibrary(sys->hdxgi_dll);
409 # endif
410
411     if (sys->hd3d11_dll)
412         FreeLibrary(sys->hd3d11_dll);
413     if (sys->hd3dcompiler_dll)
414         FreeLibrary(sys->hd3dcompiler_dll);
415
416     /* TODO : add release of d3d11 objects here */
417
418     sys->OurD3D11CreateDevice = NULL;
419     sys->OurD3D11CreateDeviceAndSwapChain = NULL;
420     sys->OurD3DCompile = NULL;
421     sys->hdxgi_dll = NULL;
422     sys->hd3d11_dll = NULL;
423     sys->hd3dcompiler_dll = NULL;
424 #else
425
426     VLC_UNUSED(vd);
427
428 #endif
429
430 }
431
432 static int Direct3D11Open(vout_display_t *vd, video_format_t *fmt)
433 {
434     vout_display_sys_t *sys = vd->sys;
435     *fmt = vd->source;
436
437 #if !VLC_WINSTORE_APP
438
439     UINT creationFlags = 0;
440     HRESULT hr = S_OK;
441
442     static const D3D_FEATURE_LEVEL featureLevels[] =
443     {
444         D3D_FEATURE_LEVEL_11_1,
445         D3D_FEATURE_LEVEL_11_0,
446         D3D_FEATURE_LEVEL_10_1,
447         D3D_FEATURE_LEVEL_10_0,
448         D3D_FEATURE_LEVEL_9_3,
449         D3D_FEATURE_LEVEL_9_2,
450         D3D_FEATURE_LEVEL_9_1
451     };
452
453 # if !defined(NDEBUG) && defined(_MSC_VER)
454     creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
455 # endif
456
457     DXGI_SWAP_CHAIN_DESC scd;
458     memset(&scd, 0, sizeof(scd));
459     scd.BufferCount = 1;
460     scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
461     scd.SampleDesc.Count = 1;
462     scd.SampleDesc.Quality = 0;
463     scd.BufferDesc.Width = fmt->i_visible_width;
464     scd.BufferDesc.Height = fmt->i_visible_height;
465     scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
466
467 # if VLC_WINSTORE_APP
468     /* TODO : check different values for performance */
469     scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
470     scd.BufferCount = 2;
471     scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
472     scd.Flags = DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER;
473     scd.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
474     scd.Scaling = DXGI_SCALING_NONE;
475 # else
476     scd.Windowed = TRUE;
477     scd.OutputWindow = sys->hvideownd;
478 # endif
479
480 # if 0
481
482     /* TODO : list adapters for the user to choose from */
483     hr = IDXGIFactory_EnumAdapters(sys->dxgifactory, 0, &sys->dxgiadapter);
484     if (FAILED(hr)) {
485        msg_Err(vd, "Could not create find factory. (hr=0x%lX)", hr);
486        return VLC_EGENERIC;
487     }
488
489     IDXGIOutput* output;
490     hr = IDXGIAdapter_EnumOutputs(sys->dxgiadapter, 0, &output);
491     if (FAILED(hr)) {
492        msg_Err(vd, "Could not Enumerate DXGI Outputs. (hr=0x%lX)", hr);
493        return VLC_EGENERIC;
494     }
495
496     DXGI_MODE_DESC md;
497     memset(&md, 0, sizeof(md));
498     md.Width  = fmt->i_visible_width;
499     md.Height = fmt->i_visible_height;
500     md.Format = scd.BufferDesc.Format;
501     md.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
502
503     hr = IDXGIOutput_FindClosestMatchingMode(output, &md, &scd.BufferDesc, NULL);
504     if (FAILED(hr)) {
505        msg_Err(vd, "Failed to find a supported video mode. (hr=0x%lX)", hr);
506        return VLC_EGENERIC;
507     }
508
509     /* mode desc doesn't carry over the width and height*/
510     scd.BufferDesc.Width = fmt->i_visible_width;
511     scd.BufferDesc.Height = fmt->i_visible_height;
512
513     hr = D3D11CreateDeviceAndSwapChain(sys->dxgiadapter,
514                     D3D_DRIVER_TYPE_UNKNOWN, NULL, creationFlags,
515                     featureLevels, ARRAYSIZE(featureLevels),
516                     D3D11_SDK_VERSION, &scd, &sys->dxgiswapChain,
517                     &sys->d3ddevice, &sys->d3dfeaturelevel, &sys->d3dcontext);
518     if (FAILED(hr)) {
519        msg_Err(vd, "Could not Create the D3D11 device and SwapChain. (hr=0x%lX)", hr);
520        return VLC_EGENERIC;
521     }
522
523 # else
524
525     static const D3D_DRIVER_TYPE driverAttempts[] = {
526         D3D_DRIVER_TYPE_HARDWARE,
527         D3D_DRIVER_TYPE_WARP,
528         D3D_DRIVER_TYPE_REFERENCE,
529     };
530
531     for (UINT driver = 0; driver < ARRAYSIZE(driverAttempts); driver++) {
532         hr = D3D11CreateDevice(NULL, driverAttempts[driver], NULL, creationFlags,
533                     featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION,
534                     &sys->d3ddevice, &sys->d3dfeaturelevel, &sys->d3dcontext);
535         if (SUCCEEDED(hr)) break;
536     }
537
538     if (FAILED(hr)) {
539        msg_Err(vd, "Could not Create the D3D11 device. (hr=0x%lX)", hr);
540        return VLC_EGENERIC;
541     }
542
543     IDXGIDevice *pDXGIDevice = NULL;
544     hr = ID3D11Device_QueryInterface(sys->d3ddevice, &IID_IDXGIDevice, (void **)&pDXGIDevice);
545     if (FAILED(hr)) {
546        msg_Err(vd, "Could not Query DXGI Interface. (hr=0x%lX)", hr);
547        return VLC_EGENERIC;
548     }
549
550     hr = IDXGIDevice_GetAdapter(pDXGIDevice, &sys->dxgiadapter);
551     if (FAILED(hr)) {
552        msg_Err(vd, "Could not get the DXGI Adapter. (hr=0x%lX)", hr);
553        return VLC_EGENERIC;
554     }
555
556     hr = IDXGIAdapter_GetParent(sys->dxgiadapter, &IID_IDXGIFactory, (void **)&sys->dxgifactory);
557     if (FAILED(hr)) {
558        msg_Err(vd, "Could not get the DXGI Factory. (hr=0x%lX)", hr);
559        return VLC_EGENERIC;
560     }
561
562     hr = IDXGIFactory_CreateSwapChain(sys->dxgifactory, (IUnknown *)sys->d3ddevice, &scd, &sys->dxgiswapChain);
563
564     if (FAILED(hr)) {
565        msg_Err(vd, "Could not create the SwapChain. (hr=0x%lX)", hr);
566        return VLC_EGENERIC;
567     }
568
569 #  if VLC_WINSTORE_APP /* avoided until we can pass ISwapchainPanel without c++/cx mode */
570     /* TODO: figure out how to get "ISwapChainPanel ^panel" into brokenpanel in gcc */
571     ISwapChainPanel *brokenpanel;
572     ISwapChainPanelNative *panelNative;
573     hr = ISwapChainPanelNative_QueryInterface(brokenpanel, &IID_ISwapChainPanelNative, (void **)&pDXGIDevice);
574     if (FAILED(hr)) {
575        msg_Err(vd, "Could not get the Native Panel. (hr=0x%lX)", hr);
576        return VLC_EGENERIC;
577     }
578
579     hr = ISwapChainPanelNative_SetSwapChain(panelNative, sys->dxgiswapChain);
580     if (FAILED(hr)) {
581        msg_Err(vd, "Could not link the SwapChain with the Native Panel. (hr=0x%lX)", hr);
582        return VLC_EGENERIC;
583     }
584
585 #  endif
586 # endif
587 #endif
588
589     UpdateRects(vd, NULL, NULL, true);
590
591     if (Direct3D11CreateResources(vd, fmt)) {
592         msg_Err(vd, "Failed to allocate resources");
593         Direct3D11DestroyResources(vd);
594         return VLC_EGENERIC;
595     }
596
597     EventThreadUpdateTitle(sys->event, VOUT_TITLE " (Direct3D11 output)");
598
599     msg_Dbg(vd, "Direct3D11 device adapter successfully initialized");
600     return VLC_SUCCESS;
601 }
602
603 static void Direct3D11Close(vout_display_t *vd)
604 {
605     vout_display_sys_t *sys = vd->sys;
606
607     Direct3D11DestroyResources(vd);
608     ID3D11DeviceContext_Release(sys->d3dcontext);
609     ID3D11Device_Release(sys->d3ddevice);
610     msg_Dbg(vd, "Direct3D11 device adapter closed");
611 }
612
613 /* TODO : handle errors better
614    TODO : seperate out into smaller functions like createshaders */
615 static int Direct3D11CreateResources(vout_display_t *vd, video_format_t *fmt)
616 {
617     vout_display_sys_t *sys = vd->sys;
618     ID3D11Texture2D* pBackBuffer = NULL;
619     ID3D11Texture2D* pDepthStencil= NULL;
620     HRESULT hr;
621
622     fmt->i_chroma = sys->vlcFormat;
623
624     hr = IDXGISwapChain_GetBuffer(sys->dxgiswapChain, 0, &IID_ID3D11Texture2D, (LPVOID *)&pBackBuffer);
625     if (FAILED(hr)) {
626        msg_Err(vd, "Could not get the backbuffer from the Swapchain. (hr=0x%lX)", hr);
627        return VLC_EGENERIC;
628     }
629
630     hr = ID3D11Device_CreateRenderTargetView(sys->d3ddevice, (ID3D11Resource *)pBackBuffer, NULL, &sys->d3drenderTargetView);
631
632     ID3D11Texture2D_Release(pBackBuffer);
633
634     if (FAILED(hr)) {
635        msg_Err(vd, "Could not create the render view target. (hr=0x%lX)", hr);
636        return VLC_EGENERIC;
637     }
638
639     D3D11_TEXTURE2D_DESC deptTexDesc;
640     memset(&deptTexDesc, 0,sizeof(deptTexDesc));
641     deptTexDesc.ArraySize = 1;
642     deptTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
643     deptTexDesc.CPUAccessFlags = 0;
644     deptTexDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
645     deptTexDesc.Width = fmt->i_visible_width;
646     deptTexDesc.Height = fmt->i_visible_height;
647     deptTexDesc.MipLevels = 1;
648     deptTexDesc.MiscFlags = 0;
649     deptTexDesc.SampleDesc.Count = 1;
650     deptTexDesc.SampleDesc.Quality = 0;
651     deptTexDesc.Usage = D3D11_USAGE_DEFAULT;
652
653     hr = ID3D11Device_CreateTexture2D(sys->d3ddevice, &deptTexDesc, NULL, &pDepthStencil);
654
655     if (FAILED(hr)) {
656        msg_Err(vd, "Could not create the depth stencil texture. (hr=0x%lX)", hr);
657        return VLC_EGENERIC;
658     }
659
660     D3D11_DEPTH_STENCIL_VIEW_DESC depthViewDesc;
661     memset(&depthViewDesc, 0, sizeof(depthViewDesc));
662
663     depthViewDesc.Format = deptTexDesc.Format;
664     depthViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
665     depthViewDesc.Texture2D.MipSlice = 0;
666
667     hr = ID3D11Device_CreateDepthStencilView(sys->d3ddevice, (ID3D11Resource *)pDepthStencil, &depthViewDesc, &sys->d3ddepthStencilView);
668
669     ID3D11Texture2D_Release(pDepthStencil);
670
671     if (FAILED(hr)) {
672        msg_Err(vd, "Could not create the depth stencil view. (hr=0x%lX)", hr);
673        return VLC_EGENERIC;
674     }
675
676     ID3D11DeviceContext_OMSetRenderTargets(sys->d3dcontext, 1, &sys->d3drenderTargetView, sys->d3ddepthStencilView);
677
678     D3D11_VIEWPORT vp;
679     vp.Width = (FLOAT)fmt->i_visible_width;
680     vp.Height = (FLOAT)fmt->i_visible_height;
681     vp.MinDepth = 0.0f;
682     vp.MaxDepth = 1.0f;
683     vp.TopLeftX = 0;
684     vp.TopLeftY = 0;
685
686     ID3D11DeviceContext_RSSetViewports(sys->d3dcontext, 1, &vp);
687
688     ID3DBlob* pVSBlob = NULL;
689
690     /* TODO : Match the version to the D3D_FEATURE_LEVEL */
691     hr = D3DCompile(globVertexShaderDefault, strlen(globVertexShaderDefault),
692                     NULL, NULL, NULL, "VS", "vs_4_0_level_9_1", 0, 0, &pVSBlob, NULL);
693
694     if( FAILED(hr)) {
695       msg_Err(vd, "The Vertex Shader is invalid.");
696       return VLC_EGENERIC;
697     }
698
699     hr = ID3D11Device_CreateVertexShader(sys->d3ddevice, (void *)ID3D10Blob_GetBufferPointer(pVSBlob),
700                                         ID3D10Blob_GetBufferSize(pVSBlob), NULL, &sys->d3dvertexShader);
701
702     if(FAILED(hr)) {
703       ID3D11Device_Release(pVSBlob);
704       msg_Err(vd, "Failed to create the vertex shader.");
705       return VLC_EGENERIC;
706     }
707
708     D3D11_INPUT_ELEMENT_DESC layout[] = {
709     { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0},
710     { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
711     };
712
713     ID3D11InputLayout* pVertexLayout = NULL;
714     hr = ID3D11Device_CreateInputLayout(sys->d3ddevice, layout, 2, (void *)ID3D10Blob_GetBufferPointer(pVSBlob),
715                                         ID3D10Blob_GetBufferSize(pVSBlob), &pVertexLayout);
716
717     ID3D10Blob_Release(pVSBlob);
718
719     if(FAILED(hr)) {
720       msg_Err(vd, "Failed to create the vertex input layout");
721       return VLC_EGENERIC;
722     }
723
724     ID3D11DeviceContext_IASetInputLayout(sys->d3dcontext, pVertexLayout);
725
726     ID3DBlob* pPSBlob = NULL;
727
728     /* TODO : Match the version to the D3D_FEATURE_LEVEL */
729     if (sys->vlcFormat == VLC_CODEC_NV12)
730         hr = D3DCompile(globPixelShaderBiplanarYUV2RGB, strlen(globPixelShaderBiplanarYUV2RGB),
731                         NULL, NULL, NULL, "PS", "ps_4_0_level_9_1", 0, 0, &pPSBlob, NULL);
732     else
733         hr = D3DCompile(globPixelShaderDefault, strlen(globPixelShaderDefault),
734                         NULL, NULL, NULL, "PS", "ps_4_0_level_9_1", 0, 0, &pPSBlob, NULL);
735
736
737     if( FAILED(hr)) {
738       msg_Err(vd, "The Pixel Shader is invalid.");
739       return VLC_EGENERIC;
740     }
741
742     hr = ID3D11Device_CreatePixelShader(sys->d3ddevice, (void *)ID3D10Blob_GetBufferPointer(pPSBlob),
743                                         ID3D10Blob_GetBufferSize(pPSBlob), NULL, &sys->d3dpixelShader);
744
745     ID3D10Blob_Release(pPSBlob);
746
747     if(FAILED(hr)) {
748       msg_Err(vd, "Failed to create the pixel shader.");
749       return VLC_EGENERIC;
750     }
751
752     float vertices[] = {
753     -1.0f, -1.0f, -1.0f, 0.0f, 1.0f,
754      1.0f, -1.0f, -1.0f, 1.0f, 1.0f,
755      1.0f,  1.0f, -1.0f, 1.0f, 0.0f,
756     -1.0f,  1.0f, -1.0f, 0.0f, 0.0f,
757     };
758
759     D3D11_BUFFER_DESC bd;
760     memset(&bd, 0, sizeof(bd));
761     bd.Usage = D3D11_USAGE_DEFAULT;
762     bd.ByteWidth = sizeof(float) * 5 * 4;
763     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
764     bd.CPUAccessFlags = 0;
765
766     D3D11_SUBRESOURCE_DATA InitData;
767     memset(&InitData, 0, sizeof(InitData));
768     InitData.pSysMem = vertices;
769
770     ID3D11Buffer* pVertexBuffer = NULL;
771     hr = ID3D11Device_CreateBuffer(sys->d3ddevice, &bd, &InitData, &pVertexBuffer);
772
773     if(FAILED(hr)) {
774       msg_Err(vd, "Failed to create vertex buffer.");
775       return VLC_EGENERIC;
776     }
777
778     UINT stride = sizeof(float) * 5;
779     UINT offset = 0;
780     ID3D11DeviceContext_IASetVertexBuffers(sys->d3dcontext, 0, 1, &pVertexBuffer, &stride, &offset);
781
782     ID3D11Buffer_Release(pVertexBuffer);
783
784     WORD indices[] = {
785       3, 1, 0,
786       2, 1, 3,
787     };
788
789     bd.Usage = D3D11_USAGE_DEFAULT;
790     bd.ByteWidth = sizeof(WORD)*6;
791     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
792     bd.CPUAccessFlags = 0;
793     InitData.pSysMem = indices;
794
795     ID3D11Buffer* pIndexBuffer = NULL;
796     hr = ID3D11Device_CreateBuffer(sys->d3ddevice, &bd, &InitData, &pIndexBuffer);
797     if(FAILED(hr)) {
798       msg_Err(vd, "Failed to create index buffer.");
799       return VLC_EGENERIC;
800     }
801
802     ID3D11DeviceContext_IASetIndexBuffer(sys->d3dcontext, pIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
803
804     ID3D11Buffer_Release(pVertexBuffer);
805
806     ID3D11DeviceContext_IASetPrimitiveTopology(sys->d3dcontext, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
807
808     D3D11_TEXTURE2D_DESC texDesc;
809     memset(&texDesc, 0, sizeof(texDesc));
810     texDesc.Width = fmt->i_visible_width;
811     texDesc.Height = fmt->i_visible_height;
812     texDesc.MipLevels = texDesc.ArraySize = 1;
813     texDesc.Format = sys->d3dFormat;
814     texDesc.SampleDesc.Count = 1;
815     texDesc.Usage = D3D11_USAGE_DYNAMIC;
816     texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
817     texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
818     texDesc.MiscFlags = 0;
819
820     hr = ID3D11Device_CreateTexture2D(sys->d3ddevice, &texDesc, NULL, &sys->d3dtexture);
821     if (FAILED(hr)) {
822         msg_Err(vd, "Could not Create the D3d11 Texture. (hr=0x%lX)", hr);
823         return VLC_EGENERIC;
824     }
825
826     D3D11_SHADER_RESOURCE_VIEW_DESC resviewDesc;
827     memset(&resviewDesc, 0, sizeof(resviewDesc));
828     if (sys->vlcFormat == VLC_CODEC_NV12)
829         resviewDesc.Format = DXGI_FORMAT_R8_UNORM;
830     else
831         resviewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
832     resviewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
833     resviewDesc.Texture2D.MipLevels = texDesc.MipLevels;
834
835     hr = ID3D11Device_CreateShaderResourceView(sys->d3ddevice, (ID3D11Resource *)sys->d3dtexture, &resviewDesc, &sys->d3dresViewY);
836     if (FAILED(hr)) {
837         if(sys->d3dtexture) ID3D11Texture2D_Release(sys->d3dtexture);
838         msg_Err(vd, "Could not Create the Y D3d11 Texture ResourceView. (hr=0x%lX)", hr);
839         return VLC_EGENERIC;
840     }
841
842     if (sys->vlcFormat == VLC_CODEC_NV12) {
843         resviewDesc.Format = DXGI_FORMAT_R8G8_UNORM;
844         hr = ID3D11Device_CreateShaderResourceView(sys->d3ddevice, (ID3D11Resource *)sys->d3dtexture, &resviewDesc, &sys->d3dresViewUV);
845         if (FAILED(hr)) {
846             if(sys->d3dtexture) ID3D11Texture2D_Release(sys->d3dtexture);
847             msg_Err(vd, "Could not Create the UV D3d11 Texture ResourceView. (hr=0x%lX)", hr);
848             return VLC_EGENERIC;
849         }
850     }
851
852     D3D11_SAMPLER_DESC sampDesc;
853     memset(&sampDesc, 0, sizeof(sampDesc));
854     sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
855     sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
856     sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
857     sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
858     sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
859     sampDesc.MinLOD = 0;
860     sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
861
862     hr = ID3D11Device_CreateSamplerState(sys->d3ddevice, &sampDesc, &sys->d3dsampState);
863
864     if (FAILED(hr)) {
865       if(sys->d3dtexture) ID3D11Texture2D_Release(sys->d3dtexture);
866       msg_Err(vd, "Could not Create the D3d11 Sampler State. (hr=0x%lX)", hr);
867       return VLC_EGENERIC;
868     }
869
870     picture_sys_t *picsys = malloc(sizeof(*picsys));
871     if (unlikely(picsys == NULL)) {
872         if(sys->d3dtexture) ID3D11Texture2D_Release(sys->d3dtexture);
873         return VLC_ENOMEM;
874     }
875
876     picsys->texture  = sys->d3dtexture;
877     picsys->context  = sys->d3dcontext;
878
879     picture_resource_t resource = { .p_sys = picsys };
880     for (int i = 0; i < PICTURE_PLANE_MAX; i++)
881         resource.p[i].i_lines = fmt->i_visible_height / (i > 0 ? 2 : 1);
882
883     picture_t *picture = picture_NewFromResource(fmt, &resource);
884     if (!picture) {
885         if(sys->d3dtexture) ID3D11Texture2D_Release(sys->d3dtexture);
886         free(picsys);
887         return VLC_ENOMEM;
888     }
889     sys->picsys = picsys;
890
891     picture_pool_configuration_t pool_cfg;
892     memset(&pool_cfg, 0, sizeof(pool_cfg));
893     pool_cfg.picture_count = 1;
894     pool_cfg.picture       = &picture;
895     pool_cfg.lock          = Direct3D11MapTexture;
896
897     sys->pool = picture_pool_NewExtended(&pool_cfg);
898     if (!sys->pool) {
899         picture_Release(picture);
900         if(sys->d3dtexture) ID3D11Texture2D_Release(sys->d3dtexture);
901         return VLC_ENOMEM;
902     }
903
904     msg_Dbg(vd, "Direct3D11 resources created");
905     return VLC_SUCCESS;
906 }
907
908 static void Direct3D11DestroyResources(vout_display_t *vd)
909 {
910     vout_display_sys_t *sys = vd->sys;
911
912     /* TODO: Destroy Shaders? */
913     if (sys->pool) {
914         picture_sys_t *picsys = sys->picsys;
915         ID3D11Texture2D_Release(picsys->texture);
916         picture_pool_Release(sys->pool);
917     }
918     sys->pool = NULL;
919
920     msg_Dbg(vd, "Direct3D11 resources destroyed");
921 }
922
923 static int Direct3D11MapTexture(picture_t *picture)
924 {
925     D3D11_MAPPED_SUBRESOURCE mappedResource;
926     ID3D11DeviceContext_Map(picture->p_sys->context, (ID3D11Resource *)picture->p_sys->texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
927     CommonUpdatePicture(picture, NULL, mappedResource.pData, mappedResource.RowPitch);
928     ID3D11DeviceContext_Unmap(picture->p_sys->context,(ID3D11Resource *)picture->p_sys->texture, 0);
929     return VLC_SUCCESS;
930 }