Flutter Engine
flutter::Rasterizer Class Referencefinal

#include <rasterizer.h>

Inheritance diagram for flutter::Rasterizer:
flutter::SnapshotDelegate

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  ScreenshotType {
  ScreenshotType::SkiaPicture,
  ScreenshotType::UncompressedImage,
  ScreenshotType::CompressedImage
}
 The type of the screenshot to obtain of the previously rendered layer tree. More...
 
using LayerTreeDiscardCallback = std::function< bool(flutter::LayerTree &)>
 

Public Member Functions

 Rasterizer (Delegate &delegate)
 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 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. 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
 
flutter::LayerTreeGetLastLayerTree ()
 Sometimes, it may be necessary to render the same frame again without having to wait for the framework to build a whole new layer tree describing the same contents. One such case is when external textures (video or camera streams for example) are updated in an otherwise static layer tree. To support this use case, the rasterizer holds onto the last rendered layer tree. More...
 
void DrawLastLayerTree (std::unique_ptr< FrameTimingsRecorder > frame_timings_recorder)
 Draws a last layer tree to the render surface. 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...
 
flutter::TextureRegistryGetTextureRegistry ()
 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...
 
RasterStatus Draw (std::unique_ptr< FrameTimingsRecorder > frame_timings_recorder, std::shared_ptr< Pipeline< flutter::LayerTree >> pipeline, LayerTreeDiscardCallback discard_callback=NoDiscard)
 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...
 

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 45 of file rasterizer.h.

Member Typedef Documentation

◆ LayerTreeDiscardCallback

Member Enumeration Documentation

◆ 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. This format is 32 bits per pixel, 8 bits per component and denoted by the kN32_SkColorType Skia color type.

CompressedImage 

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

Definition at line 245 of file rasterizer.h.

245  {
246  //--------------------------------------------------------------------------
247  /// A format used to denote a Skia picture. A Skia picture is a serialized
248  /// representation of an `SkPicture` that can be used to introspect the
249  /// series of commands used to draw that picture.
250  ///
251  /// Skia pictures are typically stored as files with the .skp extension on
252  /// disk. These files may be viewed in an interactive debugger available at
253  /// https://debugger.skia.org/
254  ///
255  SkiaPicture,
256 
257  //--------------------------------------------------------------------------
258  /// A format used to denote uncompressed image data. This format
259  /// is 32 bits per pixel, 8 bits per component and
260  /// denoted by the `kN32_SkColorType ` Skia color type.
261  ///
262  UncompressedImage,
263 
264  //--------------------------------------------------------------------------
265  /// A format used to denote compressed image data. The PNG compressed
266  /// container is used.
267  ///
268  CompressedImage,
269  };

Constructor & Destructor Documentation

◆ Rasterizer()

flutter::Rasterizer::Rasterizer ( Delegate delegate)

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.

Definition at line 31 of file rasterizer.cc.

References FML_DCHECK, and ~Rasterizer().

32  : delegate_(delegate),
33  compositor_context_(std::make_unique<flutter::CompositorContext>(
34  delegate.GetFrameBudget())),
35  user_override_resource_cache_bytes_(false),
36  weak_factory_(this) {
37  FML_DCHECK(compositor_context_);
38 }
MockDelegate delegate_
#define FML_DCHECK(condition)
Definition: logging.h:86

◆ ~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.

Referenced by Rasterizer().

Member Function Documentation

◆ 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 375 of file rasterizer.h.

References delegate_, DisableThreadMergerIfNeeded(), EnableThreadMergerIfNeeded(), FML_DISALLOW_COPY_AND_ASSIGN, function, GetRasterThreadMerger(), GetResourceCacheMaxBytes(), SetResourceCacheMaxBytes(), and fml::size().

Referenced by flutter::CreateSnapshotSurface().

375  {
376  return compositor_context_.get();
377  }

◆ 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 112 of file rasterizer.cc.

References fml::RasterThreadMerger::Disable().

Referenced by compositor_context().

112  {
113  if (raster_thread_merger_) {
114  raster_thread_merger_->Disable();
115  }
116 }

◆ Draw()

RasterStatus flutter::Rasterizer::Draw ( std::unique_ptr< FrameTimingsRecorder frame_timings_recorder,
std::shared_ptr< Pipeline< flutter::LayerTree >>  pipeline,
LayerTreeDiscardCallback  discard_callback = NoDiscard 
)

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.
[in]discard_callbackif specified and returns true, the layer tree is discarded instead of being rendered

Definition at line 155 of file rasterizer.cc.

References fml::RasterThreadMerger::DecrementLease(), flutter::LayerTree::device_pixel_ratio(), flutter::PersistentCache::DumpSkp(), FML_DCHECK, FML_LOG, flutter::LayerTree::frame_size(), fml::TimeDelta::FromMillisecondsF(), function, flutter::FrameTimingsRecorder::GetBuildDuration(), flutter::PersistentCache::GetCacheForProcess(), flutter::Surface::GetContext(), flutter::Rasterizer::Delegate::GetFrameBudget(), flutter::Rasterizer::Delegate::GetIsGpuDisabledSyncSwitch(), flutter::Rasterizer::Delegate::GetLatestFrameTargetTime(), flutter::TaskRunners::GetRasterTaskRunner(), flutter::Rasterizer::Delegate::GetTaskRunners(), flutter::PersistentCache::IsDumpingSkp(), fml::RasterThreadMerger::IsMerged(), fml::RasterThreadMerger::IsOnRasterizingThread(), flutter::FrameTimingsRecorder::kBuildEnd, flutter::kDiscarded, flutter::kEnqueuePipeline, flutter::kFailed, flutter::kResubmit, flutter::kSkiaCleanupExpiration(), flutter::kSkipAndRetry, flutter::kSuccess, fml::kUnmergedNow, flutter::kYielded, fml::MakeCopyable(), flutter::Surface::MakeRenderContextCurrent(), flutter::MoreAvailable, fml::TimePoint::Now(), flutter::Rasterizer::Delegate::OnFrameRasterized(), fml::TaskRunner::PostTask(), flutter::FrameTimingsRecorder::RecordRasterEnd(), flutter::PersistentCache::ResetStoredNewShaders(), result, fml::TaskRunner::RunsTasksOnCurrentThread(), ScreenshotLastLayerTree(), fml::size(), SkiaPicture, flutter::PersistentCache::StoredNewShaders(), TRACE_EVENT0, TRACE_EVENT_WITH_FRAME_NUMBER, and fml::tracing::TraceEventAsyncComplete().

158  {
159  TRACE_EVENT_WITH_FRAME_NUMBER(frame_timings_recorder, "flutter",
160  "GPURasterizer::Draw");
161  if (raster_thread_merger_ &&
162  !raster_thread_merger_->IsOnRasterizingThread()) {
163  // we yield and let this frame be serviced on the right thread.
164  return RasterStatus::kYielded;
165  }
166  FML_DCHECK(delegate_.GetTaskRunners()
167  .GetRasterTaskRunner()
168  ->RunsTasksOnCurrentThread());
169 
170  std::unique_ptr<FrameTimingsRecorder> resubmit_recorder =
171  frame_timings_recorder->CloneUntil(
173 
174  RasterStatus raster_status = RasterStatus::kFailed;
176  [&](std::unique_ptr<LayerTree> layer_tree) {
177  if (discard_callback(*layer_tree.get())) {
178  raster_status = RasterStatus::kDiscarded;
179  } else {
180  raster_status =
181  DoDraw(std::move(frame_timings_recorder), std::move(layer_tree));
182  }
183  };
184 
185  PipelineConsumeResult consume_result = pipeline->Consume(consumer);
186  // if the raster status is to resubmit the frame, we push the frame to the
187  // front of the queue and also change the consume status to more available.
188 
189  auto should_resubmit_frame = raster_status == RasterStatus::kResubmit ||
190  raster_status == RasterStatus::kSkipAndRetry;
191  if (should_resubmit_frame) {
192  auto front_continuation = pipeline->ProduceIfEmpty();
193  bool result =
194  front_continuation.Complete(std::move(resubmitted_layer_tree_));
195  if (result) {
196  consume_result = PipelineConsumeResult::MoreAvailable;
197  }
198  } else if (raster_status == RasterStatus::kEnqueuePipeline) {
199  consume_result = PipelineConsumeResult::MoreAvailable;
200  }
201 
202  // EndFrame should perform cleanups for the external_view_embedder.
203  if (surface_ && external_view_embedder_) {
204  external_view_embedder_->EndFrame(should_resubmit_frame,
205  raster_thread_merger_);
206  }
207 
208  // Consume as many pipeline items as possible. But yield the event loop
209  // between successive tries.
210  switch (consume_result) {
212  delegate_.GetTaskRunners().GetRasterTaskRunner()->PostTask(
214  [weak_this = weak_factory_.GetWeakPtr(), pipeline,
215  resubmit_recorder = std::move(resubmit_recorder),
216  discard_callback = std::move(discard_callback)]() mutable {
217  if (weak_this) {
218  weak_this->Draw(std::move(resubmit_recorder), pipeline,
219  std::move(discard_callback));
220  }
221  }));
222  break;
223  }
224  default:
225  break;
226  }
227 
228  return raster_status;
229 }
PipelineConsumeResult
Definition: pipeline.h:19
MockDelegate delegate_
#define FML_DCHECK(condition)
Definition: logging.h:86
GAsyncResult * result
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
#define TRACE_EVENT_WITH_FRAME_NUMBER(recorder, category_group, name)
Definition: frame_timings.h:16
std::function< void(ResourcePtr)> Consumer
Definition: pipeline.h:136

◆ DrawLastLayerTree()

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

Draws a last layer tree to the render surface. 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.

Definition at line 145 of file rasterizer.cc.

References fml::TimePoint::Now().

146  {
147  if (!last_layer_tree_ || !surface_) {
148  return;
149  }
150  frame_timings_recorder->RecordRasterStart(
151  fml::TimePoint::Now(), &compositor_context_->raster_cache());
152  DrawToSurface(*frame_timings_recorder, *last_layer_tree_);
153 }
static TimePoint Now()
Definition: time_point.cc:39

◆ 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 106 of file rasterizer.cc.

References fml::RasterThreadMerger::Enable().

Referenced by compositor_context().

106  {
107  if (raster_thread_merger_) {
108  raster_thread_merger_->Enable();
109  }
110 }

◆ GetLastLayerTree()

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

Sometimes, it may be necessary to render the same frame again without having to wait for the framework to build a whole new layer tree describing the same contents. One such case is when external textures (video or camera streams for example) are updated in an otherwise static layer tree. To support this use case, the rasterizer holds onto the last rendered layer tree.

Returns
A pointer to the last layer or nullptr if this rasterizer has never rendered a frame.

Definition at line 141 of file rasterizer.cc.

Referenced by ScreenshotLastLayerTree().

141  {
142  return last_layer_tree_.get();
143 }

◆ 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 746 of file rasterizer.cc.

References callback.

Referenced by compositor_context().

746  {
747  return raster_thread_merger_;
748 }

◆ 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 787 of file rasterizer.cc.

Referenced by compositor_context().

787  {
788  if (!surface_) {
789  return std::nullopt;
790  }
791  GrDirectContext* context = surface_->GetContext();
792  if (context) {
793  size_t max_bytes;
794  context->getResourceCacheLimits(nullptr, &max_bytes);
795  return max_bytes;
796  }
797  return std::nullopt;
798 }

◆ GetSnapshotDelegate()

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

Definition at line 46 of file rasterizer.cc.

47  {
48  return weak_factory_.GetWeakPtr();
49 }

◆ GetTextureRegistry()

flutter::TextureRegistry * flutter::Rasterizer::GetTextureRegistry ( )

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.

Definition at line 137 of file rasterizer.cc.

137  {
138  return &compositor_context_->texture_registry();
139 }

◆ 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 42 of file rasterizer.cc.

42  {
43  return weak_factory_.GetWeakPtr();
44 }

◆ 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 118 of file rasterizer.cc.

References FML_DLOG.

118  {
119  if (!surface_) {
120  FML_DLOG(INFO)
121  << "Rasterizer::NotifyLowMemoryWarning called with no surface.";
122  return;
123  }
124  auto context = surface_->GetContext();
125  if (!context) {
126  FML_DLOG(INFO)
127  << "Rasterizer::NotifyLowMemoryWarning called with no GrContext.";
128  return;
129  }
130  auto context_switch = surface_->MakeRenderContextCurrent();
131  if (!context_switch->GetResult()) {
132  return;
133  }
134  context->performDeferredCleanup(std::chrono::milliseconds(0));
135 }
#define FML_DLOG(severity)
Definition: logging.h:85

◆ 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 689 of file rasterizer.cc.

References CompressedImage, FML_LOG, flutter::LayerTree::frame_size(), GetLastLayerTree(), flutter::ScreenshotLayerTreeAsPicture(), SkiaPicture, and UncompressedImage.

Referenced by Draw().

691  {
692  auto* layer_tree = GetLastLayerTree();
693  if (layer_tree == nullptr) {
694  FML_LOG(ERROR) << "Last layer tree was null when screenshotting.";
695  return {};
696  }
697 
698  sk_sp<SkData> data = nullptr;
699 
700  GrDirectContext* surface_context =
701  surface_ ? surface_->GetContext() : nullptr;
702 
703  switch (type) {
705  data = ScreenshotLayerTreeAsPicture(layer_tree, *compositor_context_);
706  break;
708  data = ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_,
709  surface_context, false);
710  break;
712  data = ScreenshotLayerTreeAsImage(layer_tree, *compositor_context_,
713  surface_context, true);
714  break;
715  }
716 
717  if (data == nullptr) {
718  FML_LOG(ERROR) << "Screenshot data was null.";
719  return {};
720  }
721 
722  if (base64_encode) {
723  size_t b64_size = SkBase64::Encode(data->data(), data->size(), nullptr);
724  auto b64_data = SkData::MakeUninitialized(b64_size);
725  SkBase64::Encode(data->data(), data->size(), b64_data->writable_data());
726  return Rasterizer::Screenshot{b64_data, layer_tree->frame_size()};
727  }
728 
729  return Rasterizer::Screenshot{data, layer_tree->frame_size()};
730 }
KeyCallType type
#define FML_LOG(severity)
Definition: logging.h:65
static sk_sp< SkData > ScreenshotLayerTreeAsPicture(flutter::LayerTree *tree, flutter::CompositorContext &compositor_context)
Definition: rasterizer.cc:573
flutter::LayerTree * GetLastLayerTree()
Sometimes, it may be necessary to render the same frame again without having to wait for the framewor...
Definition: rasterizer.cc:141

◆ 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 736 of file rasterizer.cc.

737  {
738  external_view_embedder_ = view_embedder;
739 }

◆ 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 732 of file rasterizer.cc.

References callback.

732  {
733  next_frame_callback_ = callback;
734 }
FlKeyEvent 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 760 of file rasterizer.cc.

Referenced by compositor_context(), and Setup().

760  {
761  user_override_resource_cache_bytes_ |= from_user;
762 
763  if (!from_user && user_override_resource_cache_bytes_) {
764  // We should not update the setting here if a user has explicitly set a
765  // value for this over the flutter/skia channel.
766  return;
767  }
768 
769  max_cache_bytes_ = max_bytes;
770  if (!surface_) {
771  return;
772  }
773 
774  GrDirectContext* context = surface_->GetContext();
775  if (context) {
776  auto context_switch = surface_->MakeRenderContextCurrent();
777  if (!context_switch->GetResult()) {
778  return;
779  }
780 
781  int max_resources;
782  context->getResourceCacheLimits(&max_resources, nullptr);
783  context->setResourceCacheLimits(max_resources, max_bytes);
784  }
785 }

◆ 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 741 of file rasterizer.cc.

742  {
743  snapshot_surface_producer_ = std::move(producer);
744 }

◆ 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 51 of file rasterizer.cc.

References fml::RasterThreadMerger::CreateOrShareThreadMerger(), flutter::Rasterizer::Delegate::GetParentRasterThreadMerger(), flutter::TaskRunners::GetPlatformTaskRunner(), flutter::TaskRunners::GetRasterTaskRunner(), fml::TaskRunner::GetTaskQueueId(), flutter::Rasterizer::Delegate::GetTaskRunners(), fml::RasterThreadMerger::SetMergeUnmergeCallback(), and SetResourceCacheMaxBytes().

51  {
52  surface_ = std::move(surface);
53 
54  if (max_cache_bytes_.has_value()) {
55  SetResourceCacheMaxBytes(max_cache_bytes_.value(),
56  user_override_resource_cache_bytes_);
57  }
58 
59  auto context_switch = surface_->MakeRenderContextCurrent();
60  if (context_switch->GetResult()) {
61  compositor_context_->OnGrContextCreated();
62  }
63 
64  if (external_view_embedder_ &&
65  external_view_embedder_->SupportsDynamicThreadMerging() &&
66  !raster_thread_merger_) {
67  const auto platform_id =
68  delegate_.GetTaskRunners().GetPlatformTaskRunner()->GetTaskQueueId();
69  const auto gpu_id =
70  delegate_.GetTaskRunners().GetRasterTaskRunner()->GetTaskQueueId();
72  delegate_.GetParentRasterThreadMerger(), platform_id, gpu_id);
73  }
74  if (raster_thread_merger_) {
75  raster_thread_merger_->SetMergeUnmergeCallback([=]() {
76  // Clear the GL context after the thread configuration has changed.
77  if (surface_) {
78  surface_->ClearRenderContext();
79  }
80  });
81  }
82 }
static fml::RefPtr< fml::RasterThreadMerger > CreateOrShareThreadMerger(const fml::RefPtr< fml::RasterThreadMerger > &parent_merger, TaskQueueId platform_id, TaskQueueId raster_id)
MockDelegate delegate_
void SetMergeUnmergeCallback(const fml::closure &callback)
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:760

◆ 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.

Definition at line 84 of file rasterizer.cc.

References FML_DCHECK, fml::RefPtr< T >::get(), fml::RasterThreadMerger::IsEnabled(), fml::RasterThreadMerger::IsMerged(), fml::RasterThreadMerger::SetMergeUnmergeCallback(), and fml::RasterThreadMerger::UnMergeNowIfLastOne().

84  {
85  auto context_switch =
86  surface_ ? surface_->MakeRenderContextCurrent() : nullptr;
87  if (context_switch && context_switch->GetResult()) {
88  compositor_context_->OnGrContextDestroyed();
89  }
90 
91  surface_.reset();
92  last_layer_tree_.reset();
93 
94  if (raster_thread_merger_.get() != nullptr &&
95  raster_thread_merger_.get()->IsMerged()) {
96  FML_DCHECK(raster_thread_merger_->IsEnabled());
97  raster_thread_merger_->UnMergeNowIfLastOne();
98  raster_thread_merger_->SetMergeUnmergeCallback(nullptr);
99  }
100 
101  if (external_view_embedder_) {
102  external_view_embedder_->Teardown();
103  }
104 }
#define FML_DCHECK(condition)
Definition: logging.h:86
void SetMergeUnmergeCallback(const fml::closure &callback)
T * get() const
Definition: ref_ptr.h:112

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