d3d11: Update build-time dependency
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / d3d11 / gstd3d11window.cpp
1 /*
2  * GStreamer
3  * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include "gstd3d11window.h"
26 #include "gstd3d11pluginutils.h"
27
28 #if GST_D3D11_WINAPI_APP
29 /* workaround for GetCurrentTime collision */
30 #ifdef GetCurrentTime
31 #undef GetCurrentTime
32 #endif
33 #include <windows.ui.xaml.h>
34 #include <windows.applicationmodel.core.h>
35 #endif
36
37 #include <wrl.h>
38
39 /* *INDENT-OFF* */
40 using namespace Microsoft::WRL;
41 /* *INDENT-ON* */
42
43 GST_DEBUG_CATEGORY_EXTERN (gst_d3d11_window_debug);
44 #define GST_CAT_DEFAULT gst_d3d11_window_debug
45
46
47 enum
48 {
49   PROP_0,
50   PROP_D3D11_DEVICE,
51   PROP_FORCE_ASPECT_RATIO,
52   PROP_ENABLE_NAVIGATION_EVENTS,
53   PROP_FULLSCREEN_TOGGLE_MODE,
54   PROP_FULLSCREEN,
55   PROP_WINDOW_HANDLE,
56   PROP_RENDER_STATS,
57 };
58
59 #define DEFAULT_ENABLE_NAVIGATION_EVENTS  TRUE
60 #define DEFAULT_FORCE_ASPECT_RATIO        TRUE
61 #define DEFAULT_FULLSCREEN_TOGGLE_MODE    GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_NONE
62 #define DEFAULT_FULLSCREEN                FALSE
63 #define DEFAULT_RENDER_STATS              FALSE
64
65 enum
66 {
67   SIGNAL_KEY_EVENT,
68   SIGNAL_MOUSE_EVENT,
69   SIGNAL_LAST
70 };
71
72 static guint d3d11_window_signals[SIGNAL_LAST] = { 0, };
73
74 GType
75 gst_d3d11_window_fullscreen_toggle_mode_type (void)
76 {
77   static gsize mode_type = 0;
78
79   if (g_once_init_enter (&mode_type)) {
80     static const GFlagsValue mode_types[] = {
81       {GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_NONE,
82           "GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_NONE", "none"},
83       {GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_ALT_ENTER,
84           "GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_ALT_ENTER", "alt-enter"},
85       {GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_PROPERTY,
86           "GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_PROPERTY", "property"},
87       {0, NULL, NULL},
88     };
89     GType tmp = g_flags_register_static ("GstD3D11WindowFullscreenToggleMode",
90         mode_types);
91     g_once_init_leave (&mode_type, tmp);
92   }
93
94   return (GType) mode_type;
95 }
96
97 #define gst_d3d11_window_parent_class parent_class
98 G_DEFINE_ABSTRACT_TYPE (GstD3D11Window, gst_d3d11_window, GST_TYPE_OBJECT);
99
100 static void gst_d3d11_window_set_property (GObject * object, guint prop_id,
101     const GValue * value, GParamSpec * pspec);
102 static void gst_d3d11_window_get_property (GObject * object, guint prop_id,
103     GValue * value, GParamSpec * pspec);
104 static void gst_d3d11_window_dispose (GObject * object);
105 static GstFlowReturn gst_d3d111_window_present (GstD3D11Window * self,
106     GstBuffer * buffer, ID3D11VideoProcessorOutputView * pov,
107     ID3D11RenderTargetView * rtv);
108 static void gst_d3d11_window_on_resize_default (GstD3D11Window * window,
109     guint width, guint height);
110 static gboolean gst_d3d11_window_prepare_default (GstD3D11Window * window,
111     guint display_width, guint display_height, GstCaps * caps,
112     gboolean * video_processor_available, GError ** error);
113
114 static void
115 gst_d3d11_window_class_init (GstD3D11WindowClass * klass)
116 {
117   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
118
119   gobject_class->set_property = gst_d3d11_window_set_property;
120   gobject_class->get_property = gst_d3d11_window_get_property;
121   gobject_class->dispose = gst_d3d11_window_dispose;
122
123   klass->on_resize = GST_DEBUG_FUNCPTR (gst_d3d11_window_on_resize_default);
124   klass->prepare = GST_DEBUG_FUNCPTR (gst_d3d11_window_prepare_default);
125
126   g_object_class_install_property (gobject_class, PROP_D3D11_DEVICE,
127       g_param_spec_object ("d3d11device", "D3D11 Device",
128           "GstD3D11Device object for creating swapchain",
129           GST_TYPE_D3D11_DEVICE,
130           (GParamFlags) (G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
131               G_PARAM_STATIC_STRINGS)));
132
133   g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
134       g_param_spec_boolean ("force-aspect-ratio",
135           "Force aspect ratio",
136           "When enabled, scaling will respect original aspect ratio",
137           DEFAULT_FORCE_ASPECT_RATIO,
138           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
139
140   g_object_class_install_property (gobject_class, PROP_ENABLE_NAVIGATION_EVENTS,
141       g_param_spec_boolean ("enable-navigation-events",
142           "Enable navigation events",
143           "When enabled, signals for navigation events are emitted",
144           DEFAULT_ENABLE_NAVIGATION_EVENTS,
145           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
146
147   g_object_class_install_property (gobject_class, PROP_FULLSCREEN_TOGGLE_MODE,
148       g_param_spec_flags ("fullscreen-toggle-mode",
149           "Full screen toggle mode",
150           "Full screen toggle mode used to trigger fullscreen mode change",
151           GST_D3D11_WINDOW_TOGGLE_MODE_GET_TYPE, DEFAULT_FULLSCREEN_TOGGLE_MODE,
152           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
153
154   g_object_class_install_property (gobject_class, PROP_FULLSCREEN,
155       g_param_spec_boolean ("fullscreen",
156           "fullscreen",
157           "Ignored when \"fullscreen-toggle-mode\" does not include \"property\"",
158           DEFAULT_FULLSCREEN,
159           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
160
161   g_object_class_install_property (gobject_class, PROP_WINDOW_HANDLE,
162       g_param_spec_pointer ("window-handle",
163           "Window Handle", "External Window Handle",
164           (GParamFlags) (G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
165               G_PARAM_STATIC_STRINGS)));
166
167   d3d11_window_signals[SIGNAL_KEY_EVENT] =
168       g_signal_new ("key-event", G_TYPE_FROM_CLASS (klass),
169       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL,
170       G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_STRING);
171
172   d3d11_window_signals[SIGNAL_MOUSE_EVENT] =
173       g_signal_new ("mouse-event", G_TYPE_FROM_CLASS (klass),
174       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL,
175       G_TYPE_NONE, 4, G_TYPE_STRING, G_TYPE_INT, G_TYPE_DOUBLE, G_TYPE_DOUBLE);
176 }
177
178 static void
179 gst_d3d11_window_init (GstD3D11Window * self)
180 {
181   self->force_aspect_ratio = DEFAULT_FORCE_ASPECT_RATIO;
182   self->enable_navigation_events = DEFAULT_ENABLE_NAVIGATION_EVENTS;
183   self->fullscreen_toggle_mode = GST_D3D11_WINDOW_FULLSCREEN_TOGGLE_MODE_NONE;
184   self->fullscreen = DEFAULT_FULLSCREEN;
185   self->render_stats = DEFAULT_RENDER_STATS;
186 }
187
188 static void
189 gst_d3d11_window_set_property (GObject * object, guint prop_id,
190     const GValue * value, GParamSpec * pspec)
191 {
192   GstD3D11Window *self = GST_D3D11_WINDOW (object);
193   GstD3D11WindowClass *klass = GST_D3D11_WINDOW_GET_CLASS (object);
194
195   switch (prop_id) {
196     case PROP_D3D11_DEVICE:
197       self->device = (GstD3D11Device *) g_value_dup_object (value);
198       break;
199     case PROP_FORCE_ASPECT_RATIO:
200     {
201       self->force_aspect_ratio = g_value_get_boolean (value);
202       if (self->swap_chain)
203         klass->update_swap_chain (self);
204       break;
205     }
206     case PROP_ENABLE_NAVIGATION_EVENTS:
207       self->enable_navigation_events = g_value_get_boolean (value);
208       break;
209     case PROP_FULLSCREEN_TOGGLE_MODE:
210       self->fullscreen_toggle_mode =
211           (GstD3D11WindowFullscreenToggleMode) g_value_get_flags (value);
212       break;
213     case PROP_FULLSCREEN:
214     {
215       self->requested_fullscreen = g_value_get_boolean (value);
216       if (self->swap_chain)
217         klass->change_fullscreen_mode (self);
218       break;
219     }
220     case PROP_WINDOW_HANDLE:
221       self->external_handle = (guintptr) g_value_get_pointer (value);
222       break;
223     default:
224       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
225       break;
226   }
227 }
228
229 static void
230 gst_d3d11_window_get_property (GObject * object, guint prop_id,
231     GValue * value, GParamSpec * pspec)
232 {
233   GstD3D11Window *self = GST_D3D11_WINDOW (object);
234
235   switch (prop_id) {
236     case PROP_ENABLE_NAVIGATION_EVENTS:
237       g_value_set_boolean (value, self->enable_navigation_events);
238       break;
239     case PROP_FORCE_ASPECT_RATIO:
240       g_value_set_boolean (value, self->force_aspect_ratio);
241       break;
242     case PROP_FULLSCREEN_TOGGLE_MODE:
243       g_value_set_flags (value, self->fullscreen_toggle_mode);
244       break;
245     case PROP_FULLSCREEN:
246       g_value_set_boolean (value, self->fullscreen);
247       break;
248     default:
249       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
250       break;
251   }
252 }
253
254 static void
255 gst_d3d11_window_release_resources (GstD3D11Device * device,
256     GstD3D11Window * window)
257 {
258   GST_D3D11_CLEAR_COM (window->rtv);
259   GST_D3D11_CLEAR_COM (window->pov);
260   GST_D3D11_CLEAR_COM (window->swap_chain);
261 }
262
263 static void
264 gst_d3d11_window_dispose (GObject * object)
265 {
266   GstD3D11Window *self = GST_D3D11_WINDOW (object);
267
268   if (self->device) {
269     gst_d3d11_window_release_resources (self->device, self);
270   }
271
272   g_clear_pointer (&self->processor, gst_d3d11_video_processor_free);
273   g_clear_pointer (&self->converter, gst_d3d11_converter_free);
274   g_clear_pointer (&self->compositor, gst_d3d11_overlay_compositor_free);
275
276   gst_clear_buffer (&self->cached_buffer);
277   gst_clear_object (&self->device);
278
279   G_OBJECT_CLASS (parent_class)->dispose (object);
280 }
281
282 static void
283 gst_d3d11_window_on_resize_default (GstD3D11Window * window, guint width,
284     guint height)
285 {
286   HRESULT hr;
287   ID3D11Device *device_handle;
288   D3D11_TEXTURE2D_DESC desc;
289   DXGI_SWAP_CHAIN_DESC swap_desc;
290   ID3D11Texture2D *backbuffer = NULL;
291   GstVideoRectangle src_rect, dst_rect, rst_rect;
292   IDXGISwapChain *swap_chain;
293
294   gst_d3d11_device_lock (window->device);
295   if (!window->swap_chain)
296     goto done;
297
298   device_handle = gst_d3d11_device_get_device_handle (window->device);
299   swap_chain = window->swap_chain;
300
301   GST_D3D11_CLEAR_COM (window->rtv);
302   GST_D3D11_CLEAR_COM (window->pov);
303
304   swap_chain->GetDesc (&swap_desc);
305   hr = swap_chain->ResizeBuffers (0, width, height, window->dxgi_format,
306       swap_desc.Flags);
307   if (!gst_d3d11_result (hr, window->device)) {
308     GST_ERROR_OBJECT (window, "Couldn't resize buffers, hr: 0x%x", (guint) hr);
309     goto done;
310   }
311
312   hr = swap_chain->GetBuffer (0, IID_PPV_ARGS (&backbuffer));
313   if (!gst_d3d11_result (hr, window->device)) {
314     GST_ERROR_OBJECT (window,
315         "Cannot get backbuffer from swapchain, hr: 0x%x", (guint) hr);
316     goto done;
317   }
318
319   backbuffer->GetDesc (&desc);
320   window->surface_width = desc.Width;
321   window->surface_height = desc.Height;
322
323   {
324     dst_rect.x = 0;
325     dst_rect.y = 0;
326     dst_rect.w = window->surface_width;
327     dst_rect.h = window->surface_height;
328
329     if (window->force_aspect_ratio) {
330       src_rect.x = 0;
331       src_rect.y = 0;
332       src_rect.w = GST_VIDEO_INFO_WIDTH (&window->render_info);
333       src_rect.h = GST_VIDEO_INFO_HEIGHT (&window->render_info);
334
335       gst_video_sink_center_rect (src_rect, dst_rect, &rst_rect, TRUE);
336     } else {
337       rst_rect = dst_rect;
338     }
339   }
340
341   window->render_rect.left = rst_rect.x;
342   window->render_rect.top = rst_rect.y;
343   window->render_rect.right = rst_rect.x + rst_rect.w;
344   window->render_rect.bottom = rst_rect.y + rst_rect.h;
345
346   GST_LOG_OBJECT (window,
347       "New client area %dx%d, render rect x: %d, y: %d, %dx%d",
348       desc.Width, desc.Height, rst_rect.x, rst_rect.y, rst_rect.w, rst_rect.h);
349
350   hr = device_handle->CreateRenderTargetView (backbuffer, NULL, &window->rtv);
351   if (!gst_d3d11_result (hr, window->device)) {
352     GST_ERROR_OBJECT (window, "Cannot create render target view, hr: 0x%x",
353         (guint) hr);
354
355     goto done;
356   }
357
358   if (window->processor) {
359     D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC pov_desc;
360
361     pov_desc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D;
362     pov_desc.Texture2D.MipSlice = 0;
363
364     if (!gst_d3d11_video_processor_create_output_view (window->processor,
365             &pov_desc, backbuffer, &window->pov))
366       goto done;
367   }
368
369   window->first_present = TRUE;
370
371   /* redraw the last scene if cached buffer exits */
372   if (window->cached_buffer) {
373     gst_d3d111_window_present (window, window->cached_buffer,
374         window->pov, window->rtv);
375   }
376
377 done:
378   GST_D3D11_CLEAR_COM (backbuffer);
379
380   gst_d3d11_device_unlock (window->device);
381 }
382
383 void
384 gst_d3d11_window_on_key_event (GstD3D11Window * window, const gchar * event,
385     const gchar * key)
386 {
387   g_return_if_fail (GST_IS_D3D11_WINDOW (window));
388
389   if (!window->enable_navigation_events)
390     return;
391
392   g_signal_emit (window, d3d11_window_signals[SIGNAL_KEY_EVENT], 0, event, key);
393 }
394
395 void
396 gst_d3d11_window_on_mouse_event (GstD3D11Window * window, const gchar * event,
397     gint button, gdouble x, gdouble y)
398 {
399   g_return_if_fail (GST_IS_D3D11_WINDOW (window));
400
401   if (!window->enable_navigation_events)
402     return;
403
404   g_signal_emit (window, d3d11_window_signals[SIGNAL_MOUSE_EVENT], 0,
405       event, button, x, y);
406 }
407
408 typedef struct
409 {
410   DXGI_FORMAT dxgi_format;
411   GstVideoFormat gst_format;
412   gboolean supported;
413 } GstD3D11WindowDisplayFormat;
414
415 gboolean
416 gst_d3d11_window_prepare (GstD3D11Window * window, guint display_width,
417     guint display_height, GstCaps * caps, gboolean * video_processor_available,
418     GError ** error)
419 {
420   GstD3D11WindowClass *klass;
421
422   g_return_val_if_fail (GST_IS_D3D11_WINDOW (window), FALSE);
423
424   klass = GST_D3D11_WINDOW_GET_CLASS (window);
425   g_assert (klass->prepare != NULL);
426
427   GST_DEBUG_OBJECT (window, "Prepare window, display resolution %dx%d, caps %"
428       GST_PTR_FORMAT, display_width, display_height, caps);
429
430   return klass->prepare (window, display_width, display_height, caps,
431       video_processor_available, error);
432 }
433
434 static gboolean
435 gst_d3d11_window_prepare_default (GstD3D11Window * window, guint display_width,
436     guint display_height, GstCaps * caps, gboolean * video_processor_available,
437     GError ** error)
438 {
439   GstD3D11WindowClass *klass;
440   guint swapchain_flags = 0;
441   ID3D11Device *device_handle;
442   guint i;
443   guint num_supported_format = 0;
444   HRESULT hr;
445   UINT display_flags =
446       D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_DISPLAY;
447   UINT supported_flags = 0;
448   GstD3D11WindowDisplayFormat formats[] = {
449     {DXGI_FORMAT_R8G8B8A8_UNORM, GST_VIDEO_FORMAT_RGBA, FALSE},
450     {DXGI_FORMAT_B8G8R8A8_UNORM, GST_VIDEO_FORMAT_BGRA, FALSE},
451     {DXGI_FORMAT_R10G10B10A2_UNORM, GST_VIDEO_FORMAT_RGB10A2_LE, FALSE},
452   };
453   const GstD3D11WindowDisplayFormat *chosen_format = NULL;
454   const GstDxgiColorSpace *chosen_colorspace = NULL;
455   gboolean have_hdr10 = FALSE;
456   DXGI_COLOR_SPACE_TYPE native_colorspace_type =
457       DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
458   DXGI_HDR_METADATA_HDR10 hdr10_metadata = { 0, };
459
460   /* Step 1: Clear old resources and objects */
461   gst_clear_buffer (&window->cached_buffer);
462   g_clear_pointer (&window->processor, gst_d3d11_video_processor_free);
463   g_clear_pointer (&window->converter, gst_d3d11_converter_free);
464   g_clear_pointer (&window->compositor, gst_d3d11_overlay_compositor_free);
465
466   window->processor_in_use = FALSE;
467
468   /* Step 2: Decide display color format
469    * If upstream format is 10bits, try DXGI_FORMAT_R10G10B10A2_UNORM first
470    * Otherwise, use DXGI_FORMAT_B8G8R8A8_UNORM or DXGI_FORMAT_B8G8R8A8_UNORM
471    */
472   gst_video_info_from_caps (&window->info, caps);
473   device_handle = gst_d3d11_device_get_device_handle (window->device);
474   for (i = 0; i < G_N_ELEMENTS (formats); i++) {
475     hr = device_handle->CheckFormatSupport (formats[i].dxgi_format,
476         &supported_flags);
477     if (SUCCEEDED (hr) && (supported_flags & display_flags) == display_flags) {
478       GST_DEBUG_OBJECT (window, "Device supports format %s (DXGI_FORMAT %d)",
479           gst_video_format_to_string (formats[i].gst_format),
480           formats[i].dxgi_format);
481       formats[i].supported = TRUE;
482       num_supported_format++;
483     }
484   }
485
486   if (num_supported_format == 0) {
487     GST_ERROR_OBJECT (window, "Cannot determine render format");
488     g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_FAILED,
489         "Cannot determine render format");
490     return FALSE;
491   }
492
493   for (i = 0; i < GST_VIDEO_INFO_N_COMPONENTS (&window->info); i++) {
494     if (GST_VIDEO_INFO_COMP_DEPTH (&window->info, i) > 8) {
495       if (formats[2].supported) {
496         chosen_format = &formats[2];
497       }
498       break;
499     }
500   }
501
502   if (!chosen_format) {
503     /* prefer native format over conversion */
504     for (i = 0; i < 2; i++) {
505       if (formats[i].supported &&
506           formats[i].gst_format == GST_VIDEO_INFO_FORMAT (&window->info)) {
507         chosen_format = &formats[i];
508         break;
509       }
510     }
511
512     /* choose any color space then */
513     if (!chosen_format) {
514       for (i = 0; i < G_N_ELEMENTS (formats); i++) {
515         if (formats[i].supported) {
516           chosen_format = &formats[i];
517           break;
518         }
519       }
520     }
521   }
522
523   g_assert (chosen_format != NULL);
524
525   GST_DEBUG_OBJECT (window, "chosen render format %s (DXGI_FORMAT %d)",
526       gst_video_format_to_string (chosen_format->gst_format),
527       chosen_format->dxgi_format);
528
529   /* Step 3: Create swapchain
530    * (or reuse old swapchain if the format is not changed) */
531   window->allow_tearing = FALSE;
532
533   {
534     ComPtr < IDXGIFactory5 > factory5;
535     IDXGIFactory1 *factory_handle;
536     BOOL allow_tearing = FALSE;
537
538     factory_handle = gst_d3d11_device_get_dxgi_factory_handle (window->device);
539     hr = factory_handle->QueryInterface (IID_PPV_ARGS (&factory5));
540     if (SUCCEEDED (hr)) {
541       hr = factory5->CheckFeatureSupport (DXGI_FEATURE_PRESENT_ALLOW_TEARING,
542           (void *) &allow_tearing, sizeof (allow_tearing));
543     }
544
545     if (SUCCEEDED (hr) && allow_tearing)
546       window->allow_tearing = allow_tearing;
547   }
548
549   if (window->allow_tearing) {
550     GST_DEBUG_OBJECT (window, "device support tearning");
551     swapchain_flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
552   }
553
554   gst_d3d11_device_lock (window->device);
555   window->dxgi_format = chosen_format->dxgi_format;
556
557   klass = GST_D3D11_WINDOW_GET_CLASS (window);
558   if (!window->swap_chain &&
559       !klass->create_swap_chain (window, window->dxgi_format,
560           display_width, display_height, swapchain_flags,
561           &window->swap_chain)) {
562     GST_ERROR_OBJECT (window, "Cannot create swapchain");
563     g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_FAILED,
564         "Cannot create swapchain");
565     goto error;
566   }
567
568   /* this rect struct will be used to calculate render area */
569   window->render_rect.left = 0;
570   window->render_rect.top = 0;
571   window->render_rect.right = display_width;
572   window->render_rect.bottom = display_height;
573
574   window->input_rect.left = 0;
575   window->input_rect.top = 0;
576   window->input_rect.right = GST_VIDEO_INFO_WIDTH (&window->info);
577   window->input_rect.bottom = GST_VIDEO_INFO_HEIGHT (&window->info);
578
579   /* Step 4: Decide render color space and set it on converter/processor */
580   {
581     GstVideoMasteringDisplayInfo minfo;
582     GstVideoContentLightLevel cll;
583
584     if (gst_video_mastering_display_info_from_caps (&minfo, caps) &&
585         gst_video_content_light_level_from_caps (&cll, caps)) {
586       ComPtr < IDXGISwapChain4 > swapchain4;
587       HRESULT hr;
588
589       hr = window->swap_chain->QueryInterface (IID_PPV_ARGS (&swapchain4));
590       if (gst_d3d11_result (hr, window->device)) {
591         GST_DEBUG_OBJECT (window, "Have HDR metadata, set to DXGI swapchain");
592
593         gst_d3d11_hdr_meta_data_to_dxgi (&minfo, &cll, &hdr10_metadata);
594
595         hr = swapchain4->SetHDRMetaData (DXGI_HDR_METADATA_TYPE_HDR10,
596             sizeof (DXGI_HDR_METADATA_HDR10), &hdr10_metadata);
597         if (!gst_d3d11_result (hr, window->device)) {
598           GST_WARNING_OBJECT (window, "Couldn't set HDR metadata, hr 0x%x",
599               (guint) hr);
600         } else {
601           have_hdr10 = TRUE;
602         }
603       }
604     }
605   }
606
607   /* Step 5: Choose display color space */
608   gst_video_info_set_format (&window->render_info,
609       chosen_format->gst_format, display_width, display_height);
610
611   /* preserve upstream colorimetry */
612   window->render_info.colorimetry.primaries =
613       window->info.colorimetry.primaries;
614   window->render_info.colorimetry.transfer = window->info.colorimetry.transfer;
615   /* prefer FULL range RGB. STUDIO range doesn't seem to be well supported
616    * color space by GPUs and we don't need to preserve color range for
617    * target display color space type */
618   window->render_info.colorimetry.range = GST_VIDEO_COLOR_RANGE_0_255;
619
620   {
621     ComPtr < IDXGISwapChain3 > swapchain3;
622     HRESULT hr;
623
624     hr = window->swap_chain->QueryInterface (IID_PPV_ARGS (&swapchain3));
625
626     if (gst_d3d11_result (hr, window->device)) {
627       chosen_colorspace =
628           gst_d3d11_find_swap_chain_color_space (&window->render_info,
629           swapchain3.Get ());
630       if (chosen_colorspace) {
631         native_colorspace_type =
632             (DXGI_COLOR_SPACE_TYPE) chosen_colorspace->dxgi_color_space_type;
633         hr = swapchain3->SetColorSpace1 (native_colorspace_type);
634         if (!gst_d3d11_result (hr, window->device)) {
635           GST_WARNING_OBJECT (window, "Failed to set colorspace %d, hr: 0x%x",
636               native_colorspace_type, (guint) hr);
637           chosen_colorspace = NULL;
638           native_colorspace_type = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
639         } else {
640           GST_DEBUG_OBJECT (window,
641               "Set colorspace %d", native_colorspace_type);
642
643           /* update with selected display color space */
644           window->render_info.colorimetry.primaries =
645               chosen_colorspace->primaries;
646           window->render_info.colorimetry.transfer =
647               chosen_colorspace->transfer;
648           window->render_info.colorimetry.range = chosen_colorspace->range;
649           window->render_info.colorimetry.matrix = chosen_colorspace->matrix;
650         }
651       }
652     }
653   }
654
655   /* otherwise, use most common DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709
656    * color space */
657   if (!chosen_colorspace) {
658     GST_DEBUG_OBJECT (window, "No selected render color space, use BT709");
659     window->render_info.colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT709;
660     window->render_info.colorimetry.transfer = GST_VIDEO_TRANSFER_BT709;
661     window->render_info.colorimetry.range = GST_VIDEO_COLOR_RANGE_0_255;
662   }
663
664   if (chosen_colorspace) {
665     const GstDxgiColorSpace *in_color_space =
666         gst_d3d11_video_info_to_dxgi_color_space (&window->info);
667     const GstD3D11Format *in_format =
668         gst_d3d11_device_format_from_gst (window->device,
669         GST_VIDEO_INFO_FORMAT (&window->info));
670     gboolean hardware = FALSE;
671     GstD3D11VideoProcessor *processor = NULL;
672
673     if (in_color_space && in_format &&
674         in_format->dxgi_format != DXGI_FORMAT_UNKNOWN) {
675       g_object_get (window->device, "hardware", &hardware, NULL);
676     }
677
678     if (hardware) {
679       processor =
680           gst_d3d11_video_processor_new (window->device,
681           GST_VIDEO_INFO_WIDTH (&window->info),
682           GST_VIDEO_INFO_HEIGHT (&window->info), display_width, display_height);
683     }
684
685     if (processor) {
686       DXGI_FORMAT in_dxgi_format = in_format->dxgi_format;
687       DXGI_FORMAT out_dxgi_format = chosen_format->dxgi_format;
688       DXGI_COLOR_SPACE_TYPE in_dxgi_color_space =
689           (DXGI_COLOR_SPACE_TYPE) in_color_space->dxgi_color_space_type;
690       DXGI_COLOR_SPACE_TYPE out_dxgi_color_space = native_colorspace_type;
691
692       if (!gst_d3d11_video_processor_check_format_conversion (processor,
693               in_dxgi_format, in_dxgi_color_space, out_dxgi_format,
694               out_dxgi_color_space)) {
695         GST_DEBUG_OBJECT (window, "Conversion is not supported by device");
696         gst_d3d11_video_processor_free (processor);
697         processor = NULL;
698       } else {
699         GST_DEBUG_OBJECT (window, "video processor supports conversion");
700         gst_d3d11_video_processor_set_input_dxgi_color_space (processor,
701             in_dxgi_color_space);
702         gst_d3d11_video_processor_set_output_dxgi_color_space (processor,
703             out_dxgi_color_space);
704
705         if (have_hdr10) {
706           GST_DEBUG_OBJECT (window, "Set HDR metadata on video processor");
707           gst_d3d11_video_processor_set_input_hdr10_metadata (processor,
708               &hdr10_metadata);
709           gst_d3d11_video_processor_set_output_hdr10_metadata (processor,
710               &hdr10_metadata);
711         }
712       }
713
714       window->processor = processor;
715     }
716   }
717
718   *video_processor_available = !!window->processor;
719
720   /* configure shader even if video processor is available for fallback */
721   window->converter =
722       gst_d3d11_converter_new (window->device, &window->info,
723       &window->render_info, nullptr);
724
725   if (!window->converter) {
726     GST_ERROR_OBJECT (window, "Cannot create converter");
727     g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_FAILED,
728         "Cannot create converter");
729     goto error;
730   }
731
732   window->compositor =
733       gst_d3d11_overlay_compositor_new (window->device, &window->render_info);
734   if (!window->compositor) {
735     GST_ERROR_OBJECT (window, "Cannot create overlay compositor");
736     g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_FAILED,
737         "Cannot create overlay compositor");
738     goto error;
739   }
740   gst_d3d11_device_unlock (window->device);
741
742   /* call resize to allocated resources */
743   klass->on_resize (window, display_width, display_height);
744
745   if (window->requested_fullscreen != window->fullscreen) {
746     klass->change_fullscreen_mode (window);
747   }
748
749   GST_DEBUG_OBJECT (window, "New swap chain 0x%p created", window->swap_chain);
750
751   return TRUE;
752
753 error:
754   gst_d3d11_device_unlock (window->device);
755
756   return FALSE;
757 }
758
759 void
760 gst_d3d11_window_show (GstD3D11Window * window)
761 {
762   GstD3D11WindowClass *klass;
763
764   g_return_if_fail (GST_IS_D3D11_WINDOW (window));
765
766   klass = GST_D3D11_WINDOW_GET_CLASS (window);
767
768   if (klass->show)
769     klass->show (window);
770 }
771
772 void
773 gst_d3d11_window_set_render_rectangle (GstD3D11Window * window,
774     const GstVideoRectangle * rect)
775 {
776   GstD3D11WindowClass *klass;
777
778   g_return_if_fail (GST_IS_D3D11_WINDOW (window));
779
780   klass = GST_D3D11_WINDOW_GET_CLASS (window);
781
782   if (klass->set_render_rectangle)
783     klass->set_render_rectangle (window, rect);
784 }
785
786 void
787 gst_d3d11_window_set_title (GstD3D11Window * window, const gchar * title)
788 {
789   GstD3D11WindowClass *klass;
790
791   g_return_if_fail (GST_IS_D3D11_WINDOW (window));
792
793   klass = GST_D3D11_WINDOW_GET_CLASS (window);
794
795   if (klass->set_title)
796     klass->set_title (window, title);
797 }
798
799 static gboolean
800 gst_d3d11_window_buffer_ensure_processor_input (GstD3D11Window * self,
801     GstBuffer * buffer, ID3D11VideoProcessorInputView ** in_view)
802 {
803   GstD3D11Memory *mem;
804   ID3D11VideoProcessorInputView *piv;
805
806   if (!self->processor)
807     return FALSE;
808
809   if (gst_buffer_n_memory (buffer) != 1)
810     return FALSE;
811
812   mem = (GstD3D11Memory *) gst_buffer_peek_memory (buffer, 0);
813   piv = gst_d3d11_video_processor_get_input_view (self->processor, mem);
814   if (!piv) {
815     GST_LOG_OBJECT (self, "Failed to get processor input view");
816     return FALSE;
817   }
818
819   *in_view = piv;
820
821   return TRUE;
822 }
823
824 static gboolean
825 gst_d3d11_window_do_processor (GstD3D11Window * self,
826     ID3D11VideoProcessorInputView * piv, ID3D11VideoProcessorOutputView * pov,
827     RECT * input_rect)
828 {
829   gboolean ret;
830
831   ret = gst_d3d11_video_processor_render_unlocked (self->processor,
832       input_rect, piv, &self->render_rect, pov);
833   if (!ret) {
834     GST_ERROR_OBJECT (self, "Couldn't render to backbuffer using processor");
835   } else {
836     GST_TRACE_OBJECT (self, "Rendered using processor");
837     self->processor_in_use = TRUE;
838   }
839
840   return ret;
841 }
842
843 static gboolean
844 gst_d3d11_window_do_convert (GstD3D11Window * self,
845     ID3D11ShaderResourceView * srv[GST_VIDEO_MAX_PLANES],
846     ID3D11RenderTargetView * rtv, RECT * input_rect)
847 {
848   if (!gst_d3d11_converter_update_src_rect (self->converter, input_rect)) {
849     GST_ERROR_OBJECT (self, "Failed to update src rect");
850     return FALSE;
851   }
852
853   if (!gst_d3d11_converter_convert_unlocked (self->converter,
854           srv, &rtv, NULL, NULL)) {
855     GST_ERROR_OBJECT (self, "Couldn't render to backbuffer using converter");
856     return FALSE;
857   } else {
858     GST_TRACE_OBJECT (self, "Rendered using converter");
859   }
860
861   return TRUE;
862 }
863
864 static GstFlowReturn
865 gst_d3d111_window_present (GstD3D11Window * self, GstBuffer * buffer,
866     ID3D11VideoProcessorOutputView * pov, ID3D11RenderTargetView * rtv)
867 {
868   GstD3D11WindowClass *klass = GST_D3D11_WINDOW_GET_CLASS (self);
869   GstFlowReturn ret = GST_FLOW_OK;
870   guint present_flags = 0;
871
872   if (!buffer)
873     return GST_FLOW_OK;
874
875   {
876     GstMapInfo infos[GST_VIDEO_MAX_PLANES];
877     ID3D11ShaderResourceView *srv[GST_VIDEO_MAX_PLANES];
878     ID3D11VideoProcessorInputView *piv = NULL;
879     ID3D11Device *device_handle =
880         gst_d3d11_device_get_device_handle (self->device);
881     gboolean can_convert = FALSE;
882     gboolean can_process = FALSE;
883     gboolean convert_ret = FALSE;
884     RECT input_rect = self->input_rect;
885     GstVideoCropMeta *crop_meta;
886
887     /* Map memory in any case so that we can upload pending stage texture */
888     if (!gst_d3d11_buffer_map (buffer, device_handle, infos, GST_MAP_READ)) {
889       GST_ERROR_OBJECT (self, "Couldn't map buffer");
890       return GST_FLOW_ERROR;
891     }
892
893     can_convert = gst_d3d11_buffer_get_shader_resource_view (buffer, srv);
894     if (pov) {
895       can_process = gst_d3d11_window_buffer_ensure_processor_input (self,
896           buffer, &piv);
897     }
898
899     if (!can_convert && !can_process) {
900       GST_ERROR_OBJECT (self, "Input texture cannot be used for converter");
901       return GST_FLOW_ERROR;
902     }
903
904     crop_meta = gst_buffer_get_video_crop_meta (buffer);
905     /* Do minimal validate */
906     if (crop_meta) {
907       ID3D11Texture2D *texture = (ID3D11Texture2D *) infos[0].data;
908       D3D11_TEXTURE2D_DESC desc = { 0, };
909
910       texture->GetDesc (&desc);
911
912       if (desc.Width < crop_meta->x + crop_meta->width ||
913           desc.Height < crop_meta->y + crop_meta->height) {
914         GST_WARNING_OBJECT (self, "Invalid crop meta, ignore");
915
916         crop_meta = nullptr;
917       }
918     }
919
920     if (crop_meta) {
921       input_rect.left = crop_meta->x;
922       input_rect.right = crop_meta->x + crop_meta->width;
923       input_rect.top = crop_meta->y;
924       input_rect.bottom = crop_meta->y + crop_meta->height;
925     }
926
927     if (self->first_present) {
928       D3D11_VIEWPORT viewport;
929
930       viewport.TopLeftX = self->render_rect.left;
931       viewport.TopLeftY = self->render_rect.top;
932       viewport.Width = self->render_rect.right - self->render_rect.left;
933       viewport.Height = self->render_rect.bottom - self->render_rect.top;
934       viewport.MinDepth = 0.0f;
935       viewport.MaxDepth = 1.0f;
936       gst_d3d11_converter_update_viewport (self->converter, &viewport);
937       gst_d3d11_overlay_compositor_update_viewport (self->compositor,
938           &viewport);
939     }
940
941     /* Converter preference order
942      * 1) If this texture can be converted via processor, and we used processor
943      *    previously, use processor
944      * 2) If SRV is available, use converter
945      * 3) otherwise, use processor
946      */
947     if (can_process && self->processor_in_use) {
948       convert_ret = gst_d3d11_window_do_processor (self, piv, pov, &input_rect);
949     } else if (can_convert) {
950       convert_ret = gst_d3d11_window_do_convert (self, srv, rtv, &input_rect);
951     } else if (can_process) {
952       convert_ret = gst_d3d11_window_do_processor (self, piv, pov, &input_rect);
953     } else {
954       g_assert_not_reached ();
955       ret = GST_FLOW_ERROR;
956       goto unmap_and_out;
957     }
958
959     if (!convert_ret) {
960       ret = GST_FLOW_ERROR;
961       goto unmap_and_out;
962     }
963
964     gst_d3d11_overlay_compositor_upload (self->compositor, buffer);
965     gst_d3d11_overlay_compositor_draw_unlocked (self->compositor, &rtv);
966
967     if (self->allow_tearing && self->fullscreen) {
968       present_flags |= DXGI_PRESENT_ALLOW_TEARING;
969     }
970
971     if (klass->present)
972       ret = klass->present (self, present_flags);
973
974     self->first_present = FALSE;
975
976   unmap_and_out:
977     gst_d3d11_buffer_unmap (buffer, infos);
978   }
979
980   return ret;
981 }
982
983 GstFlowReturn
984 gst_d3d11_window_render (GstD3D11Window * window, GstBuffer * buffer)
985 {
986   GstMemory *mem;
987   GstFlowReturn ret;
988
989   g_return_val_if_fail (GST_IS_D3D11_WINDOW (window), GST_FLOW_ERROR);
990
991   if (buffer) {
992     mem = gst_buffer_peek_memory (buffer, 0);
993     if (!gst_is_d3d11_memory (mem)) {
994       GST_ERROR_OBJECT (window, "Invalid buffer");
995
996       return GST_FLOW_ERROR;
997     }
998   }
999
1000   gst_d3d11_device_lock (window->device);
1001   if (buffer)
1002     gst_buffer_replace (&window->cached_buffer, buffer);
1003
1004   ret = gst_d3d111_window_present (window, window->cached_buffer,
1005       window->pov, window->rtv);
1006   gst_d3d11_device_unlock (window->device);
1007
1008   return ret;
1009 }
1010
1011 GstFlowReturn
1012 gst_d3d11_window_render_on_shared_handle (GstD3D11Window * window,
1013     GstBuffer * buffer, HANDLE shared_handle, guint texture_misc_flags,
1014     guint64 acquire_key, guint64 release_key)
1015 {
1016   GstD3D11WindowClass *klass;
1017   GstMemory *mem;
1018   GstFlowReturn ret = GST_FLOW_OK;
1019   GstD3D11WindowSharedHandleData data = { NULL, };
1020   ID3D11VideoProcessorOutputView *pov = NULL;
1021   ID3D11RenderTargetView *rtv = NULL;
1022
1023   g_return_val_if_fail (GST_IS_D3D11_WINDOW (window), GST_FLOW_ERROR);
1024
1025   klass = GST_D3D11_WINDOW_GET_CLASS (window);
1026
1027   g_assert (klass->open_shared_handle != NULL);
1028   g_assert (klass->release_shared_handle != NULL);
1029
1030   mem = gst_buffer_peek_memory (buffer, 0);
1031   if (!gst_is_d3d11_memory (mem)) {
1032     GST_ERROR_OBJECT (window, "Invalid buffer");
1033
1034     return GST_FLOW_ERROR;
1035   }
1036
1037   data.shared_handle = shared_handle;
1038   data.texture_misc_flags = texture_misc_flags;
1039   data.acquire_key = acquire_key;
1040   data.release_key = release_key;
1041
1042   gst_d3d11_device_lock (window->device);
1043   if (!klass->open_shared_handle (window, &data)) {
1044     GST_ERROR_OBJECT (window, "Couldn't open shared handle");
1045     gst_d3d11_device_unlock (window->device);
1046     return GST_FLOW_OK;
1047   }
1048
1049   if (data.fallback_rtv) {
1050     rtv = data.fallback_rtv;
1051     pov = data.fallback_pov;
1052   } else {
1053     rtv = data.rtv;
1054     pov = data.pov;
1055   }
1056
1057   ret = gst_d3d111_window_present (window, buffer, pov, rtv);
1058
1059   klass->release_shared_handle (window, &data);
1060   gst_d3d11_device_unlock (window->device);
1061
1062   return ret;
1063 }
1064
1065 gboolean
1066 gst_d3d11_window_unlock (GstD3D11Window * window)
1067 {
1068   GstD3D11WindowClass *klass;
1069   gboolean ret = TRUE;
1070
1071   g_return_val_if_fail (GST_IS_D3D11_WINDOW (window), FALSE);
1072
1073   klass = GST_D3D11_WINDOW_GET_CLASS (window);
1074
1075   if (klass->unlock)
1076     ret = klass->unlock (window);
1077
1078   return ret;
1079 }
1080
1081 gboolean
1082 gst_d3d11_window_unlock_stop (GstD3D11Window * window)
1083 {
1084   GstD3D11WindowClass *klass;
1085   gboolean ret = TRUE;
1086
1087   g_return_val_if_fail (GST_IS_D3D11_WINDOW (window), FALSE);
1088
1089   klass = GST_D3D11_WINDOW_GET_CLASS (window);
1090
1091   if (klass->unlock_stop)
1092     ret = klass->unlock_stop (window);
1093
1094   gst_d3d11_device_lock (window->device);
1095   gst_clear_buffer (&window->cached_buffer);
1096   gst_d3d11_device_unlock (window->device);
1097
1098   return ret;
1099 }
1100
1101 void
1102 gst_d3d11_window_unprepare (GstD3D11Window * window)
1103 {
1104   GstD3D11WindowClass *klass;
1105
1106   g_return_if_fail (GST_IS_D3D11_WINDOW (window));
1107
1108   klass = GST_D3D11_WINDOW_GET_CLASS (window);
1109
1110   if (klass->unprepare)
1111     klass->unprepare (window);
1112 }
1113
1114 GstD3D11WindowNativeType
1115 gst_d3d11_window_get_native_type_from_handle (guintptr handle)
1116 {
1117   if (!handle)
1118     return GST_D3D11_WINDOW_NATIVE_TYPE_NONE;
1119
1120 #if (!GST_D3D11_WINAPI_ONLY_APP)
1121   if (IsWindow ((HWND) handle))
1122     return GST_D3D11_WINDOW_NATIVE_TYPE_HWND;
1123 #endif
1124 #if GST_D3D11_WINAPI_ONLY_APP
1125   {
1126     /* *INDENT-OFF* */
1127     ComPtr<IInspectable> window = reinterpret_cast<IInspectable*> (handle);
1128     ComPtr<ABI::Windows::UI::Core::ICoreWindow> core_window;
1129     ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> panel;
1130     /* *INDENT-ON* */
1131
1132     if (SUCCEEDED (window.As (&core_window)))
1133       return GST_D3D11_WINDOW_NATIVE_TYPE_CORE_WINDOW;
1134
1135     if (SUCCEEDED (window.As (&panel)))
1136       return GST_D3D11_WINDOW_NATIVE_TYPE_SWAP_CHAIN_PANEL;
1137   }
1138 #endif
1139
1140   return GST_D3D11_WINDOW_NATIVE_TYPE_NONE;
1141 }
1142
1143 const gchar *
1144 gst_d3d11_window_get_native_type_to_string (GstD3D11WindowNativeType type)
1145 {
1146   switch (type) {
1147     case GST_D3D11_WINDOW_NATIVE_TYPE_NONE:
1148       return "none";
1149     case GST_D3D11_WINDOW_NATIVE_TYPE_HWND:
1150       return "hwnd";
1151     case GST_D3D11_WINDOW_NATIVE_TYPE_CORE_WINDOW:
1152       return "core-window";
1153     case GST_D3D11_WINDOW_NATIVE_TYPE_SWAP_CHAIN_PANEL:
1154       return "swap-chain-panel";
1155     default:
1156       break;
1157   }
1158
1159   return "none";
1160 }