Flutter Engine
The Flutter Engine
Classes | Public Types | Public Member Functions | List of all members
flutter::Rasterizer Class Referencefinal

#include <rasterizer.h>

Inheritance diagram for flutter::Rasterizer:
flutter::SnapshotDelegate flutter::Stopwatch::RefreshRateUpdater flutter::SnapshotController::Delegate

Classes

class  Delegate
 Used to forward events from the rasterizer to interested subsystems. Currently, the shell sets itself up as the rasterizer delegate to listen for frame rasterization events. It can then forward these events to the engine. More...
 
struct  Screenshot
 A POD type used to return the screenshot data along with the size of the frame. More...
 

Public Types

enum class  MakeGpuImageBehavior { kGpu , kBitmap }
 How to handle calls to MakeSkiaGpuImage. More...
 
enum class  ScreenshotType { SkiaPicture , UncompressedImage , CompressedImage , SurfaceData }
 The type of the screenshot to obtain of the previously rendered layer tree. More...
 
enum class  ScreenshotFormat { kUnknown , kR8G8B8A8UNormInt , kB8G8R8A8UNormInt , kR16G16B16A16Float }
 

Public Member Functions

 Rasterizer (Delegate &delegate, MakeGpuImageBehavior gpu_image_behavior=MakeGpuImageBehavior::kGpu)
 Creates a new instance of a rasterizer. Rasterizers may only be created on the raster task runner. Rasterizers are currently only created by the shell (which also sets itself up as the rasterizer delegate). More...
 
 ~Rasterizer ()
 Destroys the rasterizer. This must happen on the raster task runner. All GPU resources are collected before this call returns. Any context set up by the embedder to hold these resources can be immediately collected as well. More...
 
void SetImpellerContext (std::weak_ptr< impeller::Context > impeller_context)
 
void Setup (std::unique_ptr< Surface > surface)
 Rasterizers may be created well before an on-screen surface is available for rendering. Shells usually create a rasterizer in their constructors. Once an on-screen surface is available however, one may be provided to the rasterizer using this call. No rendering may occur before this call. The surface is held till the balancing call to Rasterizer::Teardown is made. Calling a setup before tearing down the previous surface (if this is not the first time the surface has been set up) is user error. More...
 
void Teardown ()
 Releases the previously set up on-screen render surface and collects associated resources. No more rendering may occur till the next call to Rasterizer::Setup with a new render surface. Calling a teardown without a setup is user error. Calling this method multiple times is safe. More...
 
void TeardownExternalViewEmbedder ()
 Releases any resource used by the external view embedder. For example, overlay surfaces or Android views. On Android, this method post a task to the platform thread, and waits until it completes. More...
 
void NotifyLowMemoryWarning () const
 Notifies the rasterizer that there is a low memory situation and it must purge as many unnecessary resources as possible. Currently, the Skia context associated with onscreen rendering is told to free GPU resources. More...
 
fml::TaskRunnerAffineWeakPtr< RasterizerGetWeakPtr () const
 Gets a weak pointer to the rasterizer. The rasterizer may only be accessed on the raster task runner. More...
 
fml::TaskRunnerAffineWeakPtr< SnapshotDelegateGetSnapshotDelegate () const
 
void CollectView (int64_t view_id)
 Deallocate the resources for displaying a view. More...
 
flutter::LayerTreeGetLastLayerTree (int64_t view_id)
 Returns the last successfully drawn layer tree for the given view, or nullptr if there isn't any. This is useful during DrawLastLayerTrees and computing frame damage. More...
 
void DrawLastLayerTrees (std::unique_ptr< FrameTimingsRecorder > frame_timings_recorder)
 Draws the last layer trees with their last configuration. This may seem entirely redundant at first glance. After all, on surface loss and re-acquisition, the framework generates a new layer tree. Otherwise, why render the same contents to the screen again? This is used as an optimization in cases where there are external textures (video or camera streams for example) in referenced in the layer tree. These textures may be updated at a cadence different from that of the Flutter application. Flutter can re-render the layer tree with just the updated textures instead of waiting for the framework to do the work to generate the layer tree describing the same contents. More...
 
GrDirectContextGetGrContext () override
 
std::shared_ptr< flutter::TextureRegistryGetTextureRegistry () override
 Gets the registry of external textures currently in use by the rasterizer. These textures may be updated at a cadence different from that of the Flutter application. When an external texture is referenced in the Flutter layer tree, that texture is composited within the Flutter layer tree. More...
 
DrawStatus Draw (const std::shared_ptr< FramePipeline > &pipeline)
 Takes the next item from the layer tree pipeline and executes the raster thread frame workload for that pipeline item to render a frame on the on-screen surface. More...
 
Screenshot ScreenshotLastLayerTree (ScreenshotType type, bool base64_encode)
 Screenshots the last layer tree to one of the supported screenshot types and optionally Base 64 encodes that data for easier transmission and packaging (usually over the service protocol for instrumentation tools running on the host). More...
 
void SetNextFrameCallback (const fml::closure &callback)
 Sets a callback that will be executed when the next layer tree in rendered to the on-screen surface. This is used by embedders to listen for one time operations like listening for when the first frame is rendered so that they may hide splash screens. More...
 
void SetExternalViewEmbedder (const std::shared_ptr< ExternalViewEmbedder > &view_embedder)
 Set the External View Embedder. This is done on shell initialization. This is non-null on platforms that support embedding externally composited views. More...
 
void SetSnapshotSurfaceProducer (std::unique_ptr< SnapshotSurfaceProducer > producer)
 Set the snapshot surface producer. This is done on shell initialization. This is non-null on platforms that support taking GPU accelerated raster snapshots in the background. More...
 
flutter::CompositorContextcompositor_context ()
 Returns a pointer to the compositor context used by this rasterizer. This pointer will never be nullptr. More...
 
fml::RefPtr< fml::RasterThreadMergerGetRasterThreadMerger ()
 Returns the raster thread merger used by this rasterizer. This may be nullptr. More...
 
void SetResourceCacheMaxBytes (size_t max_bytes, bool from_user)
 Skia has no notion of time. To work around the performance implications of this, it may cache GPU resources to reference them from one frame to the next. Using this call, embedders may set the maximum bytes cached by Skia in its caches dedicated to on-screen rendering. More...
 
std::optional< size_t > GetResourceCacheMaxBytes () const
 The current value of Skia's resource cache size, if a surface is present. More...
 
void EnableThreadMergerIfNeeded ()
 Enables the thread merger if the external view embedder supports dynamic thread merging. More...
 
void DisableThreadMergerIfNeeded ()
 Disables the thread merger if the external view embedder supports dynamic thread merging. More...
 
bool IsTornDown ()
 Returns whether TearDown has been called. More...
 
std::optional< DrawSurfaceStatusGetLastDrawStatus (int64_t view_id)
 Returns the last status of drawing the specific view. More...
 
virtual std::unique_ptr< GpuImageResultMakeSkiaGpuImage (sk_sp< DisplayList > display_list, const SkImageInfo &image_info)=0
 Attempts to create a GrBackendTexture for the specified DisplayList. May result in a raster bitmap if no GPU context is available. More...
 
virtual std::shared_ptr< TextureRegistryGetTextureRegistry ()=0
 Gets the registry of external textures currently in use by the rasterizer. These textures may be updated at a cadence different from that of the Flutter application. When an external texture is referenced in the Flutter layer tree, that texture is composited within the Flutter layer tree. More...
 
virtual GrDirectContextGetGrContext ()=0
 
virtual void MakeRasterSnapshot (sk_sp< DisplayList > display_list, SkISize picture_size, std::function< void(sk_sp< DlImage >)> callback)=0
 
virtual sk_sp< DlImageMakeRasterSnapshotSync (sk_sp< DisplayList > display_list, SkISize picture_size)=0
 
virtual sk_sp< SkImageConvertToRasterImage (sk_sp< SkImage > image)=0
 
virtual void CacheRuntimeStage (const std::shared_ptr< impeller::RuntimeStage > &runtime_stage)=0
 
virtual fml::Milliseconds GetFrameBudget () const =0
 
- Public Member Functions inherited from flutter::SnapshotController::Delegate
virtual ~Delegate ()=default
 
virtual const std::unique_ptr< Surface > & GetSurface () const =0
 
virtual std::shared_ptr< impeller::AiksContextGetAiksContext () const =0
 
virtual const std::unique_ptr< SnapshotSurfaceProducer > & GetSnapshotSurfaceProducer () const =0
 
virtual std::shared_ptr< const fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const =0
 

Detailed Description

The rasterizer is a component owned by the shell that resides on the raster task runner. Each shell owns exactly one instance of a rasterizer. The rasterizer may only be created, used and collected on the raster task runner.

The rasterizer owns the instance of the currently active on-screen render surface. On this surface, it renders the contents of layer trees submitted to it by the Engine (which lives on the UI task runner).

The primary components owned by the rasterizer are the compositor context and the on-screen render surface. The compositor context has all the GPU state necessary to render frames to the render surface.

Definition at line 114 of file rasterizer.h.

Member Enumeration Documentation

◆ MakeGpuImageBehavior

How to handle calls to MakeSkiaGpuImage.

Enumerator
kGpu 

MakeSkiaGpuImage returns a GPU resident image, if possible.

kBitmap 

MakeSkiaGpuImage returns a checkerboard bitmap. This is useful in test contexts where no GPU surface is available.

Definition at line 178 of file rasterizer.h.

178 {
179 /// MakeSkiaGpuImage returns a GPU resident image, if possible.
180 kGpu,
181 /// MakeSkiaGpuImage returns a checkerboard bitmap. This is useful in test
182 /// contexts where no GPU surface is available.
183 kBitmap,
184 };

◆ ScreenshotFormat

Enumerator
kUnknown 
kR8G8B8A8UNormInt 
kB8G8R8A8UNormInt 
kR16G16B16A16Float 

Definition at line 383 of file rasterizer.h.

383 {
384 // Unknown format, or Skia default.
385 kUnknown,
386 // RGBA 8 bits per channel.
388 // BGRA 8 bits per channel.
390 // RGBA 16 bit floating point per channel.
392 };

◆ ScreenshotType

The type of the screenshot to obtain of the previously rendered layer tree.

Enumerator
SkiaPicture 

A format used to denote a Skia picture. A Skia picture is a serialized representation of an SkPicture that can be used to introspect the series of commands used to draw that picture.

Skia pictures are typically stored as files with the .skp extension on disk. These files may be viewed in an interactive debugger available at https://debugger.skia.org/

UncompressedImage 

A format used to denote uncompressed image data. For Skia, this format is 32 bits per pixel, 8 bits per component and denoted by the kN32_SkColorType Skia color type. For Impeller, its format is specified in Screenshot::pixel_format.

CompressedImage 

A format used to denote compressed image data. The PNG compressed container is used.

SurfaceData 

Reads the data directly from the Rasterizer's surface. The pixel format is determined from the surface. This is the only way to read wide gamut color data, but isn't supported everywhere.

Definition at line 347 of file rasterizer.h.

347 {
348 // NOLINTBEGIN(readability-identifier-naming)
349 //--------------------------------------------------------------------------
350 /// A format used to denote a Skia picture. A Skia picture is a serialized
351 /// representation of an `SkPicture` that can be used to introspect the
352 /// series of commands used to draw that picture.
353 ///
354 /// Skia pictures are typically stored as files with the .skp extension on
355 /// disk. These files may be viewed in an interactive debugger available at
356 /// https://debugger.skia.org/
357 ///
358 SkiaPicture,
359
360 //--------------------------------------------------------------------------
361 /// A format used to denote uncompressed image data. For Skia, this format
362 /// is 32 bits per pixel, 8 bits per component and
363 /// denoted by the `kN32_SkColorType ` Skia color type. For Impeller, its
364 /// format is specified in Screenshot::pixel_format.
365 ///
366 UncompressedImage,
367
368 //--------------------------------------------------------------------------
369 /// A format used to denote compressed image data. The PNG compressed
370 /// container is used.
371 ///
372 CompressedImage,
373
374 //--------------------------------------------------------------------------
375 /// Reads the data directly from the Rasterizer's surface. The pixel format
376 /// is determined from the surface. This is the only way to read wide gamut
377 /// color data, but isn't supported everywhere.
378 SurfaceData,
379 // NOLINTEND(readability-identifier-naming)
380 };

Constructor & Destructor Documentation

◆ Rasterizer()

flutter::Rasterizer::Rasterizer ( Delegate delegate,
MakeGpuImageBehavior  gpu_image_behavior = MakeGpuImageBehavior::kGpu 
)
explicit

Creates a new instance of a rasterizer. Rasterizers may only be created on the raster task runner. Rasterizers are currently only created by the shell (which also sets itself up as the rasterizer delegate).

Parameters
[in]delegateThe rasterizer delegate.
[in]gpu_image_behaviorHow to handle calls to MakeSkiaGpuImage.

Definition at line 53 of file rasterizer.cc.

55 : delegate_(delegate),
56 gpu_image_behavior_(gpu_image_behavior),
57 compositor_context_(std::make_unique<flutter::CompositorContext>(*this)),
58 snapshot_controller_(
59 SnapshotController::Make(*this, delegate.GetSettings())),
60 weak_factory_(this) {
61 FML_DCHECK(compositor_context_);
62}
static std::unique_ptr< SnapshotController > Make(const Delegate &delegate, const Settings &settings)
#define FML_DCHECK(condition)
Definition: logging.h:103

◆ ~Rasterizer()

flutter::Rasterizer::~Rasterizer ( )
default

Destroys the rasterizer. This must happen on the raster task runner. All GPU resources are collected before this call returns. Any context set up by the embedder to hold these resources can be immediately collected as well.

Member Function Documentation

◆ CollectView()

void flutter::Rasterizer::CollectView ( int64_t  view_id)

Deallocate the resources for displaying a view.

        This method must be called on the raster task runner when a
        view is removed from the engine.

        When the rasterizer is requested to draw an unrecognized view,
        it implicitly allocates necessary resources. These resources
        must be explicitly deallocated.
Parameters
[in]view_idThe ID of the view.

Definition at line 191 of file rasterizer.cc.

191 {
192 if (external_view_embedder_) {
193 external_view_embedder_->CollectView(view_id);
194 }
195 view_records_.erase(view_id);
196}

◆ compositor_context()

flutter::CompositorContext * flutter::Rasterizer::compositor_context ( )
inline

Returns a pointer to the compositor context used by this rasterizer. This pointer will never be nullptr.

Returns
The compositor context used by this rasterizer.

Definition at line 515 of file rasterizer.h.

515 {
516 return compositor_context_.get();
517 }

◆ DisableThreadMergerIfNeeded()

void flutter::Rasterizer::DisableThreadMergerIfNeeded ( )

Disables the thread merger if the external view embedder supports dynamic thread merging.

Attention
This method is thread-safe. When the thread merger is disabled, the raster task queue will continue to run in the same thread until |EnableThreadMergerIfNeeded| is called.
See also
ExternalViewEmbedder

Definition at line 164 of file rasterizer.cc.

164 {
165 if (raster_thread_merger_) {
166 raster_thread_merger_->Disable();
167 }
168}

◆ Draw()

DrawStatus flutter::Rasterizer::Draw ( const std::shared_ptr< FramePipeline > &  pipeline)

Takes the next item from the layer tree pipeline and executes the raster thread frame workload for that pipeline item to render a frame on the on-screen surface.

Why does the draw call take a layer tree pipeline and not the layer tree directly?

The pipeline is the way book-keeping of frame workloads distributed across the multiple threads is managed. The rasterizer deals with the pipelines directly (instead of layer trees which is what it actually renders) because the pipeline consumer's workload must be accounted for within the pipeline itself. If the rasterizer took the layer tree directly, it would have to be taken out of the pipeline. That would signal the end of the frame workload and the pipeline would be ready for new frames. But the last frame has not been rendered by the frame yet! On the other hand, the pipeline must own the layer tree it renders because it keeps a reference to the last layer tree around till a new frame is rendered. So a simple reference wont work either. The Rasterizer::DoDraw method actually performs the GPU operations within the layer tree pipeline.

See also
Rasterizer::DoDraw
Parameters
[in]pipelineThe layer tree pipeline to take the next layer tree to render from.

Definition at line 245 of file rasterizer.cc.

245 {
246 TRACE_EVENT0("flutter", "GPURasterizer::Draw");
247 if (raster_thread_merger_ &&
248 !raster_thread_merger_->IsOnRasterizingThread()) {
249 // we yield and let this frame be serviced on the right thread.
251 }
252 FML_DCHECK(delegate_.GetTaskRunners()
255
256 DoDrawResult draw_result;
257 FramePipeline::Consumer consumer = [&draw_result,
258 this](std::unique_ptr<FrameItem> item) {
259 draw_result = DoDraw(std::move(item->frame_timings_recorder),
260 std::move(item->layer_tree_tasks));
261 };
262
263 PipelineConsumeResult consume_result = pipeline->Consume(consumer);
264 if (consume_result == PipelineConsumeResult::NoneAvailable) {
266 }
267 // if the raster status is to resubmit the frame, we push the frame to the
268 // front of the queue and also change the consume status to more available.
269
270 bool should_resubmit_frame = ShouldResubmitFrame(draw_result);
271 if (should_resubmit_frame) {
272 FML_CHECK(draw_result.resubmitted_item);
273 auto front_continuation = pipeline->ProduceIfEmpty();
274 PipelineProduceResult pipeline_result =
275 front_continuation.Complete(std::move(draw_result.resubmitted_item));
276 if (pipeline_result.success) {
278 }
279 } else if (draw_result.status == DoDrawStatus::kEnqueuePipeline) {
281 }
282
283 // EndFrame should perform cleanups for the external_view_embedder.
284 if (external_view_embedder_ && external_view_embedder_->GetUsedThisFrame()) {
285 external_view_embedder_->SetUsedThisFrame(false);
286 external_view_embedder_->EndFrame(should_resubmit_frame,
287 raster_thread_merger_);
288 }
289
290 // Consume as many pipeline items as possible. But yield the event loop
291 // between successive tries.
292 switch (consume_result) {
295 [weak_this = weak_factory_.GetWeakPtr(), pipeline]() {
296 if (weak_this) {
297 weak_this->Draw(pipeline);
298 }
299 });
300 break;
301 }
302 default:
303 break;
304 }
305
306 return ToDrawStatus(draw_result.status);
307}
std::function< void(ResourcePtr)> Consumer
Definition: pipeline.h:180
virtual const TaskRunners & GetTaskRunners() const =0
Task runners used by the shell.
fml::RefPtr< fml::TaskRunner > GetRasterTaskRunner() const
Definition: task_runners.cc:42
virtual void PostTask(const fml::closure &task) override
Definition: task_runner.cc:24
virtual bool RunsTasksOnCurrentThread()
Definition: task_runner.cc:43
#define FML_CHECK(condition)
Definition: logging.h:85
PipelineConsumeResult
Definition: pipeline.h:29
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:131

◆ DrawLastLayerTrees()

void flutter::Rasterizer::DrawLastLayerTrees ( std::unique_ptr< FrameTimingsRecorder frame_timings_recorder)

Draws the last layer trees with their last configuration. This may seem entirely redundant at first glance. After all, on surface loss and re-acquisition, the framework generates a new layer tree. Otherwise, why render the same contents to the screen again? This is used as an optimization in cases where there are external textures (video or camera streams for example) in referenced in the layer tree. These textures may be updated at a cadence different from that of the Flutter application. Flutter can re-render the layer tree with just the updated textures instead of waiting for the framework to do the work to generate the layer tree describing the same contents.

Calling this method clears all last layer trees (GetLastLayerTree).

Definition at line 218 of file rasterizer.cc.

219 {
220 if (!surface_) {
221 return;
222 }
223 std::vector<std::unique_ptr<LayerTreeTask>> tasks;
224 for (auto& [view_id, view_record] : view_records_) {
225 if (view_record.last_successful_task) {
226 tasks.push_back(std::move(view_record.last_successful_task));
227 }
228 }
229 if (tasks.empty()) {
230 return;
231 }
232
233 DoDrawResult result =
234 DrawToSurfaces(*frame_timings_recorder, std::move(tasks));
235
236 // EndFrame should perform cleanups for the external_view_embedder.
237 if (external_view_embedder_ && external_view_embedder_->GetUsedThisFrame()) {
238 bool should_resubmit_frame = ShouldResubmitFrame(result);
239 external_view_embedder_->SetUsedThisFrame(false);
240 external_view_embedder_->EndFrame(should_resubmit_frame,
241 raster_thread_merger_);
242 }
243}
GAsyncResult * result

◆ EnableThreadMergerIfNeeded()

void flutter::Rasterizer::EnableThreadMergerIfNeeded ( )

Enables the thread merger if the external view embedder supports dynamic thread merging.

Attention
This method is thread-safe. When the thread merger is enabled, the raster task queue can run in the platform thread at any time.
See also
ExternalViewEmbedder

Definition at line 158 of file rasterizer.cc.

158 {
159 if (raster_thread_merger_) {
160 raster_thread_merger_->Enable();
161 }
162}

◆ GetGrContext()

GrDirectContext * flutter::Rasterizer::GetGrContext ( )
overridevirtual

Implements flutter::SnapshotDelegate.

Definition at line 202 of file rasterizer.cc.

202 {
203 return surface_ ? surface_->GetContext() : nullptr;
204}

◆ GetLastDrawStatus()

std::optional< DrawSurfaceStatus > flutter::Rasterizer::GetLastDrawStatus ( int64_t  view_id)

Returns the last status of drawing the specific view.

        This method is used only in unit tests.

Definition at line 148 of file rasterizer.cc.

149 {
150 auto found = view_records_.find(view_id);
151 if (found != view_records_.end()) {
152 return found->second.last_draw_status;
153 } else {
154 return std::optional<DrawSurfaceStatus>();
155 }
156}

◆ GetLastLayerTree()

flutter::LayerTree * flutter::Rasterizer::GetLastLayerTree ( int64_t  view_id)

Returns the last successfully drawn layer tree for the given view, or nullptr if there isn't any. This is useful during DrawLastLayerTrees and computing frame damage.

Bug:
https://github.com/flutter/flutter/issues/33939
Returns
A pointer to the last layer or nullptr if this rasterizer has never rendered a frame to the given view.

Definition at line 206 of file rasterizer.cc.

206 {
207 auto found = view_records_.find(view_id);
208 if (found == view_records_.end()) {
209 return nullptr;
210 }
211 auto& last_task = found->second.last_successful_task;
212 if (last_task == nullptr) {
213 return nullptr;
214 }
215 return last_task->layer_tree.get();
216}

◆ GetRasterThreadMerger()

fml::RefPtr< fml::RasterThreadMerger > flutter::Rasterizer::GetRasterThreadMerger ( )

Returns the raster thread merger used by this rasterizer. This may be nullptr.

Returns
The raster thread merger used by this rasterizer.

Definition at line 1099 of file rasterizer.cc.

1099 {
1100 return raster_thread_merger_;
1101}

◆ GetResourceCacheMaxBytes()

std::optional< size_t > flutter::Rasterizer::GetResourceCacheMaxBytes ( ) const

The current value of Skia's resource cache size, if a surface is present.

Attention
This cache does not describe the entirety of GPU resources that may be cached. The RasterCache also holds very large GPU resources.
See also
RasterCache
Returns
The size of Skia's resource cache, if available.

Definition at line 1140 of file rasterizer.cc.

1140 {
1141#if SLIMPELLER
1142 return std::nullopt;
1143#else // SLIMPELLER
1144 if (!surface_) {
1145 return std::nullopt;
1146 }
1147 GrDirectContext* context = surface_->GetContext();
1148 if (context) {
1149 return context->getResourceCacheLimit();
1150 }
1151 return std::nullopt;
1152#endif // SLIMPELLER
1153}
size_t getResourceCacheLimit() const

◆ GetSnapshotDelegate()

fml::TaskRunnerAffineWeakPtr< SnapshotDelegate > flutter::Rasterizer::GetSnapshotDelegate ( ) const

Definition at line 70 of file rasterizer.cc.

71 {
72 return weak_factory_.GetWeakPtr();
73}

◆ GetTextureRegistry()

std::shared_ptr< flutter::TextureRegistry > flutter::Rasterizer::GetTextureRegistry ( )
overridevirtual

Gets the registry of external textures currently in use by the rasterizer. These textures may be updated at a cadence different from that of the Flutter application. When an external texture is referenced in the Flutter layer tree, that texture is composited within the Flutter layer tree.

Returns
A pointer to the external texture registry.

Implements flutter::SnapshotDelegate.

Definition at line 198 of file rasterizer.cc.

198 {
199 return compositor_context_->texture_registry();
200}

◆ GetWeakPtr()

fml::TaskRunnerAffineWeakPtr< Rasterizer > flutter::Rasterizer::GetWeakPtr ( ) const

Gets a weak pointer to the rasterizer. The rasterizer may only be accessed on the raster task runner.

Returns
The weak pointer to the rasterizer.

Definition at line 66 of file rasterizer.cc.

66 {
67 return weak_factory_.GetWeakPtr();
68}

◆ IsTornDown()

bool flutter::Rasterizer::IsTornDown ( )

Returns whether TearDown has been called.

        This method is used only in unit tests.

Definition at line 144 of file rasterizer.cc.

144 {
145 return is_torn_down_;
146}

◆ NotifyLowMemoryWarning()

void flutter::Rasterizer::NotifyLowMemoryWarning ( ) const

Notifies the rasterizer that there is a low memory situation and it must purge as many unnecessary resources as possible. Currently, the Skia context associated with onscreen rendering is told to free GPU resources.

Definition at line 170 of file rasterizer.cc.

170 {
171#if !SLIMPELLER
172 if (!surface_) {
173 FML_DLOG(INFO)
174 << "Rasterizer::NotifyLowMemoryWarning called with no surface.";
175 return;
176 }
177 auto context = surface_->GetContext();
178 if (!context) {
179 FML_DLOG(INFO)
180 << "Rasterizer::NotifyLowMemoryWarning called with no GrContext.";
181 return;
182 }
183 auto context_switch = surface_->MakeRenderContextCurrent();
184 if (!context_switch->GetResult()) {
185 return;
186 }
187 context->performDeferredCleanup(std::chrono::milliseconds(0));
188#endif // !SLIMPELLER
189}
#define FML_DLOG(severity)
Definition: logging.h:102

◆ ScreenshotLastLayerTree()

Rasterizer::Screenshot flutter::Rasterizer::ScreenshotLastLayerTree ( Rasterizer::ScreenshotType  type,
bool  base64_encode 
)

Screenshots the last layer tree to one of the supported screenshot types and optionally Base 64 encodes that data for easier transmission and packaging (usually over the service protocol for instrumentation tools running on the host).

Parameters
[in]typeThe type of the screenshot to gather.
[in]base64_encodeWhether Base 64 encoding must be applied to the data after a screenshot has been captured.
Returns
A non-empty screenshot if one could be captured. A screenshot capture may fail if there were no layer trees previously rendered by this rasterizer, or, due to an unspecified internal error. Internal error will be logged to the console.

Definition at line 1020 of file rasterizer.cc.

1022 {
1023 if (delegate_.GetSettings().enable_impeller &&
1025 FML_DCHECK(false);
1026 FML_LOG(ERROR) << "Last layer tree cannot be screenshotted as a "
1027 "SkiaPicture when using Impeller.";
1028 return {};
1029 }
1030 // TODO(dkwingsmt): Support screenshotting all last layer trees
1031 // when the shell protocol supports multi-views.
1032 // https://github.com/flutter/flutter/issues/135534
1033 // https://github.com/flutter/flutter/issues/135535
1034 auto* layer_tree = GetLastLayerTree(kFlutterImplicitViewId);
1035 if (layer_tree == nullptr) {
1036 FML_LOG(ERROR) << "Last layer tree was null when screenshotting.";
1037 return {};
1038 }
1039
1040 std::pair<sk_sp<SkData>, ScreenshotFormat> data{nullptr,
1042 std::string format;
1043
1044 switch (type) {
1046 format = "ScreenshotType::SkiaPicture";
1047 data.first =
1048 ScreenshotLayerTreeAsPicture(layer_tree, *compositor_context_);
1049 break;
1051 format = "ScreenshotType::UncompressedImage";
1052 data =
1053 ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_, false);
1054 break;
1056 format = "ScreenshotType::CompressedImage";
1057 data = ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_, true);
1058 break;
1060 Surface::SurfaceData surface_data = surface_->GetSurfaceData();
1061 format = surface_data.pixel_format;
1062 data.first = surface_data.data;
1063 break;
1064 }
1065 }
1066
1067 if (data.first == nullptr) {
1068 FML_LOG(ERROR) << "Screenshot data was null.";
1069 return {};
1070 }
1071
1072 if (base64_encode) {
1073 size_t b64_size = Base64::EncodedSize(data.first->size());
1074 auto b64_data = SkData::MakeUninitialized(b64_size);
1075 Base64::Encode(data.first->data(), data.first->size(),
1076 b64_data->writable_data());
1077 return Rasterizer::Screenshot{b64_data, layer_tree->frame_size(), format,
1078 data.second};
1079 }
1080
1081 return Rasterizer::Screenshot{data.first, layer_tree->frame_size(), format,
1082 data.second};
1083}
GLenum type
static sk_sp< SkData > MakeUninitialized(size_t length)
Definition: SkData.cpp:116
virtual const Settings & GetSettings() const =0
flutter::LayerTree * GetLastLayerTree(int64_t view_id)
Returns the last successfully drawn layer tree for the given view, or nullptr if there isn't any....
Definition: rasterizer.cc:206
#define FML_LOG(severity)
Definition: logging.h:82
constexpr int64_t kFlutterImplicitViewId
Definition: constants.h:35
static sk_sp< SkData > ScreenshotLayerTreeAsPicture(flutter::LayerTree *tree, flutter::CompositorContext &compositor_context)
Definition: rasterizer.cc:823
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot data
Definition: switches.h:41
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
static size_t Encode(const void *src, size_t length, void *dst)
Definition: base64.cc:118
static size_t EncodedSize(size_t srcDataLength)
Definition: base64.h:33
bool enable_impeller
Definition: settings.h:229
#define ERROR(message)
Definition: elf_loader.cc:260

◆ SetExternalViewEmbedder()

void flutter::Rasterizer::SetExternalViewEmbedder ( const std::shared_ptr< ExternalViewEmbedder > &  view_embedder)

Set the External View Embedder. This is done on shell initialization. This is non-null on platforms that support embedding externally composited views.

Parameters
[in]view_embedderThe external view embedder object.

Definition at line 1089 of file rasterizer.cc.

1090 {
1091 external_view_embedder_ = view_embedder;
1092}

◆ SetImpellerContext()

void flutter::Rasterizer::SetImpellerContext ( std::weak_ptr< impeller::Context impeller_context)

Definition at line 75 of file rasterizer.cc.

76 {
77 impeller_context_ = std::move(impeller_context);
78}

◆ SetNextFrameCallback()

void flutter::Rasterizer::SetNextFrameCallback ( const fml::closure callback)

Sets a callback that will be executed when the next layer tree in rendered to the on-screen surface. This is used by embedders to listen for one time operations like listening for when the first frame is rendered so that they may hide splash screens.

The callback is only executed once and dropped on the GPU thread when executed (lambda captures must be able to deal with the threading repercussions of this behavior).

Parameters
[in]callbackThe callback to execute when the next layer tree is rendered on-screen.

Definition at line 1085 of file rasterizer.cc.

1085 {
1086 next_frame_callback_ = callback;
1087}
FlKeyEvent uint64_t FlKeyResponderAsyncCallback callback

◆ SetResourceCacheMaxBytes()

void flutter::Rasterizer::SetResourceCacheMaxBytes ( size_t  max_bytes,
bool  from_user 
)

Skia has no notion of time. To work around the performance implications of this, it may cache GPU resources to reference them from one frame to the next. Using this call, embedders may set the maximum bytes cached by Skia in its caches dedicated to on-screen rendering.

Attention
This cache setting will be invalidated when the surface is torn down via Rasterizer::Teardown. This call must be made again with new limits after surface re-acquisition.
This cache does not describe the entirety of GPU resources that may be cached. The RasterCache also holds very large GPU resources.
See also
RasterCache
Parameters
[in]max_bytesThe maximum byte size of resource that may be cached for GPU rendering.
[in]from_userWhether this request was from user code, e.g. via the flutter/skia message channel, in which case it should not be overridden by the platform.

Definition at line 1113 of file rasterizer.cc.

1113 {
1114#if !SLIMPELLER
1115 user_override_resource_cache_bytes_ |= from_user;
1116
1117 if (!from_user && user_override_resource_cache_bytes_) {
1118 // We should not update the setting here if a user has explicitly set a
1119 // value for this over the flutter/skia channel.
1120 return;
1121 }
1122
1123 max_cache_bytes_ = max_bytes;
1124 if (!surface_) {
1125 return;
1126 }
1127
1128 GrDirectContext* context = surface_->GetContext();
1129 if (context) {
1130 auto context_switch = surface_->MakeRenderContextCurrent();
1131 if (!context_switch->GetResult()) {
1132 return;
1133 }
1134
1135 context->setResourceCacheLimit(max_bytes);
1136 }
1137#endif // !SLIMPELLER
1138}
void setResourceCacheLimit(size_t maxResourceBytes)

◆ SetSnapshotSurfaceProducer()

void flutter::Rasterizer::SetSnapshotSurfaceProducer ( std::unique_ptr< SnapshotSurfaceProducer producer)

Set the snapshot surface producer. This is done on shell initialization. This is non-null on platforms that support taking GPU accelerated raster snapshots in the background.

Parameters
[in]producerA surface producer for raster snapshotting when the onscreen surface is not available.

Definition at line 1094 of file rasterizer.cc.

1095 {
1096 snapshot_surface_producer_ = std::move(producer);
1097}

◆ Setup()

void flutter::Rasterizer::Setup ( std::unique_ptr< Surface surface)

Rasterizers may be created well before an on-screen surface is available for rendering. Shells usually create a rasterizer in their constructors. Once an on-screen surface is available however, one may be provided to the rasterizer using this call. No rendering may occur before this call. The surface is held till the balancing call to Rasterizer::Teardown is made. Calling a setup before tearing down the previous surface (if this is not the first time the surface has been set up) is user error.

See also
Rasterizer::Teardown
Parameters
[in]surfaceThe on-screen render surface.

Definition at line 80 of file rasterizer.cc.

80 {
81 surface_ = std::move(surface);
82
83 if (max_cache_bytes_.has_value()) {
84 SetResourceCacheMaxBytes(max_cache_bytes_.value(),
85 user_override_resource_cache_bytes_);
86 }
87
88 auto context_switch = surface_->MakeRenderContextCurrent();
89 if (context_switch->GetResult()) {
90 compositor_context_->OnGrContextCreated();
91 }
92
93 if (external_view_embedder_ &&
94 external_view_embedder_->SupportsDynamicThreadMerging() &&
95 !raster_thread_merger_) {
96 const auto platform_id =
98 const auto gpu_id =
101 delegate_.GetParentRasterThreadMerger(), platform_id, gpu_id);
102 }
103 if (raster_thread_merger_) {
104 raster_thread_merger_->SetMergeUnmergeCallback([this]() {
105 // Clear the GL context after the thread configuration has changed.
106 if (surface_) {
107 surface_->ClearRenderContext();
108 }
109 });
110 }
111}
virtual const fml::RefPtr< fml::RasterThreadMerger > GetParentRasterThreadMerger() const =0
The raster thread merger from parent shell's rasterizer.
void SetResourceCacheMaxBytes(size_t max_bytes, bool from_user)
Skia has no notion of time. To work around the performance implications of this, it may cache GPU res...
Definition: rasterizer.cc:1113
fml::RefPtr< fml::TaskRunner > GetPlatformTaskRunner() const
Definition: task_runners.cc:30
static fml::RefPtr< fml::RasterThreadMerger > CreateOrShareThreadMerger(const fml::RefPtr< fml::RasterThreadMerger > &parent_merger, TaskQueueId platform_id, TaskQueueId raster_id)
void SetMergeUnmergeCallback(const fml::closure &callback)
virtual TaskQueueId GetTaskQueueId()
Definition: task_runner.cc:38
VkSurfaceKHR surface
Definition: main.cc:49

◆ Teardown()

void flutter::Rasterizer::Teardown ( )

Releases the previously set up on-screen render surface and collects associated resources. No more rendering may occur till the next call to Rasterizer::Setup with a new render surface. Calling a teardown without a setup is user error. Calling this method multiple times is safe.

Definition at line 119 of file rasterizer.cc.

119 {
120 is_torn_down_ = true;
121 if (surface_) {
122 auto context_switch = surface_->MakeRenderContextCurrent();
123 if (context_switch->GetResult()) {
124 compositor_context_->OnGrContextDestroyed();
125#if !SLIMPELLER
126 if (auto* context = surface_->GetContext()) {
127 context->purgeUnlockedResources(GrPurgeResourceOptions::kAllResources);
128 }
129#endif // !SLIMPELLER
130 }
131 surface_.reset();
132 }
133
134 view_records_.clear();
135
136 if (raster_thread_merger_.get() != nullptr &&
137 raster_thread_merger_.get()->IsMerged()) {
138 FML_DCHECK(raster_thread_merger_->IsEnabled());
139 raster_thread_merger_->UnMergeNowIfLastOne();
140 raster_thread_merger_->SetMergeUnmergeCallback(nullptr);
141 }
142}
T * get() const
Definition: ref_ptr.h:116

◆ TeardownExternalViewEmbedder()

void flutter::Rasterizer::TeardownExternalViewEmbedder ( )

Releases any resource used by the external view embedder. For example, overlay surfaces or Android views. On Android, this method post a task to the platform thread, and waits until it completes.

Definition at line 113 of file rasterizer.cc.

113 {
114 if (external_view_embedder_) {
115 external_view_embedder_->Teardown();
116 }
117}

The documentation for this class was generated from the following files: