Flutter Windows Embedder
manager.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
6 
7 #include <string_view>
8 #include <vector>
9 
10 #include "flutter/fml/logging.h"
12 
13 namespace flutter {
14 namespace egl {
15 
16 namespace {
17 
18 // Returns whether |extensions|, a space delimited extension list, contains
19 // |name| as a whole entry.
20 bool HasExtension(std::string_view extensions, std::string_view name) {
21  for (size_t start = 0; start <= extensions.size();) {
22  const size_t space = extensions.find(' ', start);
23  const size_t end =
24  space == std::string_view::npos ? extensions.size() : space;
25  if (extensions.substr(start, end - start) == name) {
26  return true;
27  }
28  if (space == std::string_view::npos) {
29  break;
30  }
31  start = space + 1;
32  }
33  return false;
34 }
35 
36 // If |max_feature_level| is set, appends attributes that limit ANGLE's D3D11
37 // device to at most that feature level.
38 void AppendMaxFeatureLevel(std::optional<D3DFeatureLevel> max_feature_level,
39  std::vector<EGLint>& attributes) {
40  if (!max_feature_level.has_value()) {
41  return;
42  }
43  attributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE);
44  attributes.push_back(static_cast<EGLint>(max_feature_level->major));
45  attributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE);
46  attributes.push_back(static_cast<EGLint>(max_feature_level->minor));
47 
48  // ANGLE caches displays per process, keyed on a fixed set of attributes
49  // that does not include the feature level cap. Add a key based on the
50  // feature level to prevent incorrect cache hits for displays that have
51  // different feature levels.
52  attributes.push_back(EGL_PLATFORM_ANGLE_DISPLAY_KEY_ANGLE);
53  attributes.push_back(static_cast<EGLint>(max_feature_level->major * 10 +
54  max_feature_level->minor));
55 }
56 
57 } // namespace
58 
59 int Manager::instance_count_ = 0;
60 
61 std::unique_ptr<Manager> Manager::Create(
62  GpuPreference gpu_preference,
63  bool allow_inverted_surface,
64  std::optional<D3DFeatureLevel> max_feature_level) {
65  std::unique_ptr<Manager> manager;
66  manager.reset(
67  new Manager(gpu_preference, allow_inverted_surface, max_feature_level));
68  if (!manager->IsValid()) {
69  return nullptr;
70  }
71  return std::move(manager);
72 }
73 
75  bool allow_inverted_surface,
76  std::optional<D3DFeatureLevel> max_feature_level) {
77  ++instance_count_;
78 
79  if (!InitializeDisplay(gpu_preference, allow_inverted_surface,
81  return;
82  }
83 
84  if (!InitializeConfig()) {
85  return;
86  }
87 
88  if (!InitializeContexts()) {
89  return;
90  }
91 
92  is_valid_ = true;
93 }
94 
96  CleanUp();
97  --instance_count_;
98 }
99 
100 bool Manager::InitializeDisplay(
101  GpuPreference gpu_preference,
102  bool allow_inverted_surface,
103  std::optional<D3DFeatureLevel> max_feature_level) {
104  // If the request for a low power GPU is provided,
105  // we will attempt to select GPU explicitly, via ANGLE extension
106  // that allows to specify the GPU to use via LUID.
107  std::optional<LUID> luid = std::nullopt;
108  switch (gpu_preference) {
110  luid = GetLowPowerGpuLuid();
111  break;
113  luid = GetHighPerformanceGpuLuid();
114  break;
116  break;
117  }
118 
119  // EGL_ANGLE_surface_orientation and EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE
120  // are mutually exclusive on ANGLE's D3D11 backend: the orientation extension
121  // is only advertised when present path fast is off, and SwapChain11 asserts
122  // that a non-default orientation is never combined with it.
123  //
124  // Both avoid ANGLE's intermediate offscreen texture, so they are equivalent
125  // in terms of allocations and presentation. They differ in how the default
126  // framebuffer's Y axis is handled. Present path fast preserves OpenGL's
127  // bottom-left origin and compensates by flipping, which forces any blit into
128  // the swapchain through a full-screen shader pass because D3D11 cannot flip
129  // during a copy. The inverted orientation instead exposes the D3D
130  // backbuffer's top-left origin directly, so an unflipped blit can be a plain
131  // copy or multisample resolve.
132  const bool request_present_path_fast = !allow_inverted_surface;
133 
134  // Builds the preferred display attributes, which request ANGLE's D3D11
135  // renderer. eglInitialize will only succeed with these attributes if the
136  // hardware supports D3D11 Feature Level 10_0+.
137  auto build_d3d11_attributes = [&](bool with_luid) {
138  std::vector<EGLint> attributes = {
139  EGL_PLATFORM_ANGLE_TYPE_ANGLE,
140  EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
141 
142  // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that will
143  // enable ANGLE to automatically call the IDXGIDevice3::Trim method on
144  // behalf of the application when it gets suspended.
145  EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE,
146  EGL_TRUE,
147  };
148 
149  if (request_present_path_fast) {
150  // This extension allows angle to render directly on a D3D swapchain
151  // in the correct orientation on D3D11.
152  attributes.push_back(EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE);
153  attributes.push_back(EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE);
154  }
155 
156  if (with_luid) {
157  // Specify the LUID of the GPU to use.
158  attributes.push_back(EGL_PLATFORM_ANGLE_D3D_LUID_HIGH_ANGLE);
159  attributes.push_back(static_cast<EGLint>(luid->HighPart));
160  attributes.push_back(EGL_PLATFORM_ANGLE_D3D_LUID_LOW_ANGLE);
161  attributes.push_back(static_cast<EGLint>(luid->LowPart));
162  }
163 
164  AppendMaxFeatureLevel(max_feature_level, attributes);
165 
166  attributes.push_back(EGL_NONE);
167  return attributes;
168  };
169 
170  // These are preferred display attributes and request ANGLE's D3D11
171  // renderer (use only in case of valid LUID returned from above).
172  const std::vector<EGLint> d3d11_display_attributes_with_luid =
173  luid.has_value() ? build_d3d11_attributes(/*with_luid=*/true)
174  : std::vector<EGLint>{};
175 
176  const std::vector<EGLint> d3d11_display_attributes =
177  build_d3d11_attributes(/*with_luid=*/false);
178 
179  // These are used to request ANGLE's D3D11 renderer, with D3D11 Feature
180  // Level 9_3.
181  const EGLint d3d11_fl_9_3_display_attributes[] = {
182  EGL_PLATFORM_ANGLE_TYPE_ANGLE,
183  EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
184  EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE,
185  9,
186  EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE,
187  3,
188  EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE,
189  EGL_TRUE,
190  EGL_NONE,
191  };
192 
193  // These attributes request D3D11 WARP (software rendering fallback) in case
194  // hardware-backed D3D11 is unavailable.
195  std::vector<EGLint> d3d11_warp_display_attributes = {
196  EGL_PLATFORM_ANGLE_TYPE_ANGLE,
197  EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
198  EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE,
199  EGL_TRUE,
200  };
201  AppendMaxFeatureLevel(max_feature_level, d3d11_warp_display_attributes);
202  d3d11_warp_display_attributes.push_back(EGL_NONE);
203 
204  std::vector<const EGLint*> display_attributes_configs;
205 
206  if (luid) {
207  // If LUID value is present, obtain an adapter with that luid.
208  display_attributes_configs.push_back(
209  d3d11_display_attributes_with_luid.data());
210  }
211  display_attributes_configs.push_back(d3d11_display_attributes.data());
212  display_attributes_configs.push_back(d3d11_fl_9_3_display_attributes);
213  display_attributes_configs.push_back(d3d11_warp_display_attributes.data());
214 
215  PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT =
216  reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
217  ::eglGetProcAddress("eglGetPlatformDisplayEXT"));
218  if (!egl_get_platform_display_EXT) {
219  LogEGLError("eglGetPlatformDisplayEXT not available");
220  return false;
221  }
222 
223  // Attempt to initialize ANGLE's renderer in order of: D3D11, D3D11 Feature
224  // Level 9_3 and finally D3D11 WARP.
225  for (auto config : display_attributes_configs) {
226  bool is_last = (config == display_attributes_configs.back());
227 
228  display_ = egl_get_platform_display_EXT(EGL_PLATFORM_ANGLE_ANGLE,
229  EGL_DEFAULT_DISPLAY, config);
230 
231  if (display_ == EGL_NO_DISPLAY) {
232  if (is_last) {
233  LogEGLError("Failed to get a compatible EGLdisplay");
234  return false;
235  }
236 
237  // Try the next config.
238  continue;
239  }
240 
241  if (::eglInitialize(display_, nullptr, nullptr) == EGL_FALSE) {
242  if (is_last) {
243  LogEGLError("Failed to initialize EGL via ANGLE");
244  return false;
245  }
246 
247  // Try the next config.
248  continue;
249  }
250 
251  if (allow_inverted_surface) {
252  const char* extensions = ::eglQueryString(display_, EGL_EXTENSIONS);
253  if (extensions != nullptr &&
254  HasExtension(extensions, "EGL_ANGLE_surface_orientation")) {
255  surface_orientation_ = EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE;
256  } else {
257  // Rendering stays correct because |surface_origin_is_top_left| will
258  // report the default bottom-left origin, but the swapchain blit will
259  // go through ANGLE's full-screen shader pass.
260  FML_LOG(WARNING) << "EGL_ANGLE_surface_orientation is unavailable. "
261  "Falling back to a bottom-left surface origin.";
262  }
263  }
264 
265  return true;
266  }
267 
268  FML_UNREACHABLE();
269 }
270 
271 bool Manager::InitializeConfig() {
272  const EGLint config_attributes[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8,
273  EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8,
274  EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8,
275  EGL_NONE};
276 
277  EGLint num_config = 0;
278 
279  EGLBoolean result =
280  ::eglChooseConfig(display_, config_attributes, &config_, 1, &num_config);
281 
282  if (result == EGL_TRUE && num_config > 0) {
283  return true;
284  }
285 
286  LogEGLError("Failed to choose EGL config");
287  return false;
288 }
289 
290 bool Manager::InitializeContexts() {
291  const EGLint gles3_context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 3,
292  EGL_NONE};
293  const EGLint gles2_context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2,
294  EGL_NONE};
295 
296  // Attempt to create an OpenGL ES 3.0 context first (which enables UBOs and
297  // other modern GLES3 features on ANGLE), falling back to OpenGL ES 2.0.
298  const EGLint* context_attributes = gles3_context_attributes;
299  EGLContext render_context =
300  ::eglCreateContext(display_, config_, EGL_NO_CONTEXT, context_attributes);
301  if (render_context == EGL_NO_CONTEXT) {
302  // Clear out lingering error.
303  ::eglGetError();
304  context_attributes = gles2_context_attributes;
305  render_context = ::eglCreateContext(display_, config_, EGL_NO_CONTEXT,
306  context_attributes);
307  }
308 
309  if (render_context == EGL_NO_CONTEXT) {
310  LogEGLError("Failed to create EGL render context");
311  return false;
312  }
313 
314  auto const resource_context =
315  ::eglCreateContext(display_, config_, render_context, context_attributes);
316  if (resource_context == EGL_NO_CONTEXT) {
317  LogEGLError("Failed to create EGL resource context");
318  return false;
319  }
320 
321  render_context_ = std::make_unique<Context>(display_, render_context);
322  resource_context_ = std::make_unique<Context>(display_, resource_context);
323  return true;
324 }
325 
326 bool Manager::InitializeDevice() {
327  const auto query_display_attrib_EXT =
328  reinterpret_cast<PFNEGLQUERYDISPLAYATTRIBEXTPROC>(
329  ::eglGetProcAddress("eglQueryDisplayAttribEXT"));
330  const auto query_device_attrib_EXT =
331  reinterpret_cast<PFNEGLQUERYDEVICEATTRIBEXTPROC>(
332  ::eglGetProcAddress("eglQueryDeviceAttribEXT"));
333 
334  if (query_display_attrib_EXT == nullptr ||
335  query_device_attrib_EXT == nullptr) {
336  return false;
337  }
338 
339  EGLAttrib egl_device = 0;
340  EGLAttrib angle_device = 0;
341 
342  auto result = query_display_attrib_EXT(display_, EGL_DEVICE_EXT, &egl_device);
343  if (result != EGL_TRUE) {
344  return false;
345  }
346 
347  result = query_device_attrib_EXT(reinterpret_cast<EGLDeviceEXT>(egl_device),
348  EGL_D3D11_DEVICE_ANGLE, &angle_device);
349  if (result != EGL_TRUE) {
350  return false;
351  }
352 
353  resolved_device_ = reinterpret_cast<ID3D11Device*>(angle_device);
354  return true;
355 }
356 
357 void Manager::CleanUp() {
358  EGLBoolean result = EGL_FALSE;
359 
360  // Needs to be reset before destroying the contexts.
361  resolved_device_.Reset();
362 
363  // Needs to be reset before destroying the EGLDisplay.
364  render_context_.reset();
365  resource_context_.reset();
366 
367  if (display_ != EGL_NO_DISPLAY) {
368  // Display is reused between instances so only terminate display
369  // if destroying last instance
370  if (instance_count_ == 1) {
371  ::eglTerminate(display_);
372  }
373  display_ = EGL_NO_DISPLAY;
374  }
375 }
376 
377 bool Manager::IsValid() const {
378  return is_valid_;
379 }
380 
382  return surface_orientation_ == EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE;
383 }
384 
385 std::unique_ptr<WindowSurface> Manager::CreateWindowSurface(HWND hwnd,
386  size_t width,
387  size_t height) {
388  if (!hwnd || !is_valid_) {
389  return nullptr;
390  }
391 
392  // Disable ANGLE's automatic surface resizing and provide an explicit size.
393  // The surface will need to be destroyed and re-created if the HWND is
394  // resized.
395  std::vector<EGLint> surface_attributes = {
396  EGL_FIXED_SIZE_ANGLE, EGL_TRUE, EGL_WIDTH,
397  static_cast<EGLint>(width), EGL_HEIGHT, static_cast<EGLint>(height),
398  };
399 
400  if (surface_orientation_ != 0) {
401  surface_attributes.push_back(EGL_SURFACE_ORIENTATION_ANGLE);
402  surface_attributes.push_back(surface_orientation_);
403  }
404 
405  surface_attributes.push_back(EGL_NONE);
406 
407  auto const surface = ::eglCreateWindowSurface(
408  display_, config_, static_cast<EGLNativeWindowType>(hwnd),
409  surface_attributes.data());
410  if (surface == EGL_NO_SURFACE) {
411  LogEGLError("Surface creation failed.");
412  return nullptr;
413  }
414 
415  return std::make_unique<WindowSurface>(display_, render_context_->GetHandle(),
416  surface, width, height);
417 }
418 
420  return ::eglGetCurrentContext() != EGL_NO_CONTEXT;
421 }
422 
423 EGLSurface Manager::CreateSurfaceFromHandle(EGLenum handle_type,
424  EGLClientBuffer handle,
425  const EGLint* attributes) const {
426  return ::eglCreatePbufferFromClientBuffer(display_, handle_type, handle,
427  config_, attributes);
428 }
429 
430 bool Manager::GetDevice(ID3D11Device** device) {
431  if (!resolved_device_) {
432  if (!InitializeDevice()) {
433  return false;
434  }
435  }
436 
437  resolved_device_.CopyTo(device);
438  return (resolved_device_ != nullptr);
439 }
440 
442  return render_context_.get();
443 }
444 
446  return resource_context_.get();
447 }
448 
449 std::optional<LUID> Manager::GetGpuLuidByPreference(
450  DXGI_GPU_PREFERENCE preference) {
451  Microsoft::WRL::ComPtr<IDXGIFactory1> factory1;
452  HRESULT hr = ::CreateDXGIFactory1(IID_PPV_ARGS(&factory1));
453  if (FAILED(hr)) {
454  return std::nullopt;
455  }
456 
457  Microsoft::WRL::ComPtr<IDXGIFactory6> factory6;
458  hr = factory1->QueryInterface(IID_PPV_ARGS(&factory6));
459  if (FAILED(hr)) {
460  // No support for IDXGIFactory6, so we will not use the selected GPU.
461  // We will follow with the default ANGLE selection.
462  return std::nullopt;
463  }
464 
465  Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
466  hr = factory6->EnumAdapterByGpuPreference(0, preference,
467  IID_PPV_ARGS(&adapter));
468  if (FAILED(hr) || !adapter) {
469  return std::nullopt;
470  }
471 
472  // Get the LUID of the adapter.
473  DXGI_ADAPTER_DESC desc;
474  hr = adapter->GetDesc(&desc);
475  if (FAILED(hr)) {
476  return std::nullopt;
477  }
478 
479  return desc.AdapterLuid;
480 }
481 
482 std::optional<LUID> Manager::GetLowPowerGpuLuid() {
483  return GetGpuLuidByPreference(DXGI_GPU_PREFERENCE_MINIMUM_POWER);
484 }
485 
486 std::optional<LUID> Manager::GetHighPerformanceGpuLuid() {
487  return GetGpuLuidByPreference(DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE);
488 }
489 
490 } // namespace egl
491 } // namespace flutter
virtual Context * resource_context() const
Definition: manager.cc:445
static std::unique_ptr< Manager > Create(GpuPreference gpu_preference, bool allow_inverted_surface, std::optional< D3DFeatureLevel > max_feature_level=std::nullopt)
Definition: manager.cc:61
virtual ~Manager()
Definition: manager.cc:95
virtual bool surface_origin_is_top_left() const
Definition: manager.cc:381
bool HasContextCurrent()
Definition: manager.cc:419
EGLSurface CreateSurfaceFromHandle(EGLenum handle_type, EGLClientBuffer handle, const EGLint *attributes) const
Definition: manager.cc:423
static std::optional< LUID > GetLowPowerGpuLuid()
Definition: manager.cc:482
virtual Context * render_context() const
Definition: manager.cc:441
static std::optional< LUID > GetHighPerformanceGpuLuid()
Definition: manager.cc:486
virtual std::unique_ptr< WindowSurface > CreateWindowSurface(HWND hwnd, size_t width, size_t height)
Definition: manager.cc:385
bool GetDevice(ID3D11Device **device)
Definition: manager.cc:430
Manager(GpuPreference gpu_preference, bool allow_inverted_surface, std::optional< D3DFeatureLevel > max_feature_level=std::nullopt)
Definition: manager.cc:74
bool IsValid() const
Definition: manager.cc:377
const char * name
std::optional< egl::D3DFeatureLevel > max_feature_level
void LogEGLError(std::string_view message)
Log the last EGL error with an error message.
Definition: egl.cc:55