Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
gpu_surface_gl_skia.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
5#include "flutter/shell/gpu/gpu_surface_gl_skia.h"
6
7#include "flutter/common/graphics/persistent_cache.h"
8#include "flutter/fml/base32.h"
9#include "flutter/fml/logging.h"
10#include "flutter/fml/size.h"
11#include "flutter/fml/trace_event.h"
12#include "flutter/shell/common/context_options.h"
13#include "flutter/shell/gpu/gpu_surface_gl_delegate.h"
25
26// These are common defines present on all OpenGL headers. However, we don't
27// want to perform GL header resolution on each platform we support. So just
28// define these upfront. It is unlikely we will need more. But, if we do, we can
29// add the same here.
30#define GPU_GL_RGBA8 0x8058
31#define GPU_GL_RGBA4 0x8056
32#define GPU_GL_RGB565 0x8D62
33
34namespace flutter {
35
36// Default maximum number of bytes of GPU memory of budgeted resources in the
37// cache.
38// The shell will dynamically increase or decrease this cache based on the
39// viewport size, unless a user has specifically requested a size on the Skia
40// system channel.
41static const size_t kGrCacheMaxByteSize = 24 * (1 << 20);
42
44 GPUSurfaceGLDelegate* delegate) {
45 auto context_switch = delegate->GLContextMakeCurrent();
46 if (!context_switch->GetResult()) {
48 << "Could not make the context current to set up the Gr context.";
49 return nullptr;
50 }
51
52 const auto options =
54
55 auto context = GrDirectContexts::MakeGL(delegate->GetGLInterface(), options);
56
57 if (!context) {
58 FML_LOG(ERROR) << "Failed to set up Skia Gr context.";
59 return nullptr;
60 }
61
62 context->setResourceCacheLimit(kGrCacheMaxByteSize);
63
65
66 return context;
67}
68
70 bool render_to_surface)
71 : GPUSurfaceGLSkia(MakeGLContext(delegate), delegate, render_to_surface) {
72 context_owner_ = true;
73}
74
76 GPUSurfaceGLDelegate* delegate,
77 bool render_to_surface)
78 : delegate_(delegate),
79 context_(gr_context),
80
81 render_to_surface_(render_to_surface),
82 weak_factory_(this) {
83 auto context_switch = delegate_->GLContextMakeCurrent();
84 if (!context_switch->GetResult()) {
86 << "Could not make the context current to set up the Gr context.";
87 return;
88 }
89
90 delegate_->GLContextClearCurrent();
91
92 valid_ = gr_context != nullptr;
93}
94
96 if (!valid_) {
97 return;
98 }
99 auto context_switch = delegate_->GLContextMakeCurrent();
100 if (!context_switch->GetResult()) {
101 FML_LOG(ERROR) << "Could not make the context current to destroy the "
102 "GrDirectContext resources.";
103 return;
104 }
105
106 onscreen_surface_ = nullptr;
107 fbo_id_ = 0;
108 if (context_owner_) {
110 }
111 context_ = nullptr;
112
113 delegate_->GLContextClearCurrent();
114}
115
116// |Surface|
118 return valid_;
119}
120
122 GrGLenum* format) {
123#define RETURN_IF_RENDERABLE(x, y) \
124 if (context->colorTypeSupportedAsSurface((x))) { \
125 *format = (y); \
126 return (x); \
127 }
132}
133
135 const SkISize& size,
136 intptr_t fbo) {
139
140 GrGLFramebufferInfo framebuffer_info = {};
141 framebuffer_info.fFBOID = static_cast<GrGLuint>(fbo);
142 framebuffer_info.fFormat = format;
143
144 auto render_target =
145 GrBackendRenderTargets::MakeGL(size.width(), // width
146 size.height(), // height
147 0, // sample count
148 0, // stencil bits
149 framebuffer_info // framebuffer info
150 );
151
154
156 context, // Gr context
157 render_target, // render target
159 color_type, // color type
160 colorspace, // colorspace
161 &surface_props // surface properties
162 );
163}
164
165bool GPUSurfaceGLSkia::CreateOrUpdateSurfaces(const SkISize& size) {
166 if (onscreen_surface_ != nullptr &&
167 size == SkISize::Make(onscreen_surface_->width(),
168 onscreen_surface_->height())) {
169 // Surface size appears unchanged. So bail.
170 return true;
171 }
172
173 // We need to do some updates.
174 TRACE_EVENT0("flutter", "UpdateSurfacesSize");
175
176 // Either way, we need to get rid of previous surface.
177 onscreen_surface_ = nullptr;
178 fbo_id_ = 0;
179
180 if (size.isEmpty()) {
181 FML_LOG(ERROR) << "Cannot create surfaces of empty size.";
182 return false;
183 }
184
185 sk_sp<SkSurface> onscreen_surface;
186
187 GLFrameInfo frame_info = {static_cast<uint32_t>(size.width()),
188 static_cast<uint32_t>(size.height())};
189 const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info);
190 onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context
191 size, // root surface size
192 fbo_info.fbo_id // window FBO ID
193 );
194
195 if (onscreen_surface == nullptr) {
196 // If the onscreen surface could not be wrapped. There is absolutely no
197 // point in moving forward.
198 FML_LOG(ERROR) << "Could not wrap onscreen surface.";
199 return false;
200 }
201
202 onscreen_surface_ = std::move(onscreen_surface);
203 fbo_id_ = fbo_info.fbo_id;
204 existing_damage_ = fbo_info.existing_damage;
205
206 return true;
207}
208
209// |Surface|
213
214// |Surface|
215std::unique_ptr<SurfaceFrame> GPUSurfaceGLSkia::AcquireFrame(
216 const SkISize& size) {
217 if (delegate_ == nullptr) {
218 return nullptr;
219 }
220 auto context_switch = delegate_->GLContextMakeCurrent();
221 if (!context_switch->GetResult()) {
223 << "Could not make the context current to acquire the frame.";
224 return nullptr;
225 }
226
227 SurfaceFrame::FramebufferInfo framebuffer_info;
228
229 // TODO(38466): Refactor GPU surface APIs take into account the fact that an
230 // external view embedder may want to render to the root surface.
231 if (!render_to_surface_) {
232 framebuffer_info.supports_readback = true;
233 return std::make_unique<SurfaceFrame>(
234 nullptr, framebuffer_info,
235 [](const SurfaceFrame& surface_frame, DlCanvas* canvas) {
236 return true;
237 },
238 size);
239 }
240
241 const auto root_surface_transformation = GetRootTransformation();
242
244 AcquireRenderSurface(size, root_surface_transformation);
245
246 if (surface == nullptr) {
247 return nullptr;
248 }
249
250 surface->getCanvas()->setMatrix(root_surface_transformation);
251 SurfaceFrame::SubmitCallback submit_callback =
252 [weak = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame,
253 DlCanvas* canvas) {
254 return weak ? weak->PresentSurface(surface_frame, canvas) : false;
255 };
256
257 framebuffer_info = delegate_->GLContextFramebufferInfo();
258 if (!framebuffer_info.existing_damage.has_value()) {
259 framebuffer_info.existing_damage = existing_damage_;
260 }
261 return std::make_unique<SurfaceFrame>(surface, framebuffer_info,
262 submit_callback, size,
263 std::move(context_switch));
264}
265
266bool GPUSurfaceGLSkia::PresentSurface(const SurfaceFrame& frame,
267 DlCanvas* canvas) {
268 if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) {
269 return false;
270 }
271
272 delegate_->GLContextSetDamageRegion(frame.submit_info().buffer_damage);
273
274 {
275 TRACE_EVENT0("flutter", "GrDirectContext::flushAndSubmit");
276 context_->flushAndSubmit();
277 }
278
279 GLPresentInfo present_info = {
280 .fbo_id = fbo_id_,
281 .frame_damage = frame.submit_info().frame_damage,
282 .presentation_time = frame.submit_info().presentation_time,
283 .buffer_damage = frame.submit_info().buffer_damage,
284 };
285 if (!delegate_->GLContextPresent(present_info)) {
286 return false;
287 }
288
289 if (delegate_->GLContextFBOResetAfterPresent()) {
290 auto current_size =
291 SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height());
292
293 GLFrameInfo frame_info = {static_cast<uint32_t>(current_size.width()),
294 static_cast<uint32_t>(current_size.height())};
295
296 // The FBO has changed, ask the delegate for the new FBO and do a surface
297 // re-wrap.
298 const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info);
299 auto new_onscreen_surface =
300 WrapOnscreenSurface(context_.get(), // GL context
301 current_size, // root surface size
302 fbo_info.fbo_id // window FBO ID
303 );
304
305 if (!new_onscreen_surface) {
306 return false;
307 }
308
309 onscreen_surface_ = std::move(new_onscreen_surface);
310 fbo_id_ = fbo_info.fbo_id;
311 existing_damage_ = fbo_info.existing_damage;
312 }
313
314 return true;
315}
316
317sk_sp<SkSurface> GPUSurfaceGLSkia::AcquireRenderSurface(
318 const SkISize& untransformed_size,
319 const SkMatrix& root_surface_transformation) {
320 const auto transformed_rect = root_surface_transformation.mapRect(
321 SkRect::MakeWH(untransformed_size.width(), untransformed_size.height()));
322
323 const auto transformed_size =
324 SkISize::Make(transformed_rect.width(), transformed_rect.height());
325
326 if (!CreateOrUpdateSurfaces(transformed_size)) {
327 return nullptr;
328 }
329
330 return onscreen_surface_;
331}
332
333// |Surface|
335 return context_.get();
336}
337
338// |Surface|
339std::unique_ptr<GLContextResult> GPUSurfaceGLSkia::MakeRenderContextCurrent() {
340 return delegate_->GLContextMakeCurrent();
341}
342
343// |Surface|
345 return delegate_->GLContextClearCurrent();
346}
347
348// |Surface|
352
353} // namespace flutter
const char * options
unsigned int GrGLuint
Definition GrGLTypes.h:113
unsigned int GrGLenum
Definition GrGLTypes.h:102
@ kBottomLeft_GrSurfaceOrigin
Definition GrTypes.h:149
SkColorType
Definition SkColorType.h:19
@ kARGB_4444_SkColorType
pixel with 4 bits for alpha, red, green, blue; in 16-bit word
Definition SkColorType.h:23
@ kRGB_565_SkColorType
pixel with 5 bits red, 6 bits green, 5 bits blue, in 16-bit word
Definition SkColorType.h:22
@ kRGBA_8888_SkColorType
pixel with 8 bits for red, green, blue, alpha; in 32-bit word
Definition SkColorType.h:24
@ kUnknown_SkColorType
uninitialized
Definition SkColorType.h:20
@ kUnknown_SkPixelGeometry
void releaseResourcesAndAbandonContext()
void flushAndSubmit(GrSyncCpu sync=GrSyncCpu::kNo)
static sk_sp< SkColorSpace > MakeSRGB()
bool mapRect(SkRect *dst, const SkRect &src, SkApplyPerspectiveClip pc=SkApplyPerspectiveClip::kYes) const
int width() const
Definition SkSurface.h:178
int height() const
Definition SkSurface.h:184
Developer-facing API for rendering anything within the engine.
Definition dl_canvas.h:37
virtual bool AllowsDrawingWhenGpuDisabled() const
virtual std::unique_ptr< GLContextResult > GLContextMakeCurrent()=0
virtual bool GLContextClearCurrent()=0
virtual bool GLContextPresent(const GLPresentInfo &present_info)=0
virtual SkMatrix GLContextSurfaceTransformation() const
virtual sk_sp< const GrGLInterface > GetGLInterface() const
virtual bool GLContextFBOResetAfterPresent() const
virtual SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const
virtual GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const =0
virtual void GLContextSetDamageRegion(const std::optional< SkIRect > &region)
GrDirectContext * GetContext() override
bool AllowsDrawingWhenGpuDisabled() const override
SkMatrix GetRootTransformation() const override
static sk_sp< GrDirectContext > MakeGLContext(GPUSurfaceGLDelegate *delegate)
GPUSurfaceGLSkia(GPUSurfaceGLDelegate *delegate, bool render_to_surface)
std::unique_ptr< GLContextResult > MakeRenderContextCurrent() override
std::unique_ptr< SurfaceFrame > AcquireFrame(const SkISize &size) override
static PersistentCache * GetCacheForProcess()
size_t PrecompileKnownSkSLs(GrDirectContext *context) const
Precompile SkSLs packaged with the application and gathered during previous runs in the given context...
std::function< bool(SurfaceFrame &surface_frame, DlCanvas *canvas)> SubmitCallback
T * get() const
Definition SkRefCnt.h:303
MockDelegate delegate_
VkSurfaceKHR surface
Definition main.cc:49
double frame
Definition examples.cpp:31
#define FML_LOG(severity)
Definition logging.h:82
#define GPU_GL_RGBA4
#define GPU_GL_RGB565
#define GPU_GL_RGBA8
#define RETURN_IF_RENDERABLE(x, y)
SK_API GrBackendRenderTarget MakeGL(int width, int height, int sampleCnt, int stencilBits, const GrGLFramebufferInfo &glInfo)
SK_API sk_sp< GrDirectContext > MakeGL()
SK_API sk_sp< SkSurface > WrapBackendRenderTarget(GrRecordingContext *context, const GrBackendRenderTarget &backendRenderTarget, GrSurfaceOrigin origin, SkColorType colorType, sk_sp< SkColorSpace > colorSpace, const SkSurfaceProps *surfaceProps, RenderTargetReleaseProc releaseProc=nullptr, ReleaseContext releaseContext=nullptr)
static SkColorType FirstSupportedColorType(GrDirectContext *context, GrGLenum *format)
GrContextOptions MakeDefaultContextOptions(ContextType type, std::optional< GrBackendApi > api)
Initializes GrContextOptions with values suitable for Flutter. The options can be further tweaked bef...
static const size_t kGrCacheMaxByteSize
static sk_sp< SkSurface > WrapOnscreenSurface(GrDirectContext *context, const SkISize &size, intptr_t fbo)
it will be possible to load the file into Perfetto s trace viewer disable asset Prevents usage of any non test fonts unless they were explicitly Loaded via prefetched default font Indicates whether the embedding started a prefetch of the default font manager before creating the engine run In non interactive keep the shell running after the Dart script has completed enable serial On low power devices with low core running concurrent GC tasks on threads can cause them to contend with the UI thread which could potentially lead to jank This option turns off all concurrent GC activities domain network JSON encoded network policy per domain This overrides the DisallowInsecureConnections switch Embedder can specify whether to allow or disallow insecure connections at a domain level old gen heap size
Definition switches.h:259
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace Enable an endless trace buffer The default is a ring buffer This is useful when very old events need to viewed For during application launch Memory usage will continue to grow indefinitely however Start app with an specific route defined on the framework flutter assets Path to the Flutter assets directory enable service port Allow the VM service to fallback to automatic port selection if binding to a specified port fails trace Trace early application lifecycle Automatically switches to an endless trace buffer trace skia Filters out all Skia trace event categories except those that are specified in this comma separated list dump skp on shader Automatically dump the skp that triggers new shader compilations This is useful for writing custom ShaderWarmUp to reduce jank By this is not enabled to reduce the overhead purge persistent Remove all existing persistent cache This is mainly for debugging purposes such as reproducing the shader compilation jank trace to Write the timeline trace to a file at the specified path The file will be in Perfetto s proto format
Definition switches.h:203
uint32_t color_type
static constexpr SkISize Make(int32_t w, int32_t h)
Definition SkSize.h:20
constexpr int32_t width() const
Definition SkSize.h:36
constexpr int32_t height() const
Definition SkSize.h:37
static constexpr SkRect MakeWH(float w, float h)
Definition SkRect.h:609
std::optional< SkIRect > existing_damage
#define ERROR(message)
#define TRACE_EVENT0(category_group, name)