Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
image_encoding_impeller.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/lib/ui/painting/image_encoding_impeller.h"
6
7#include "flutter/lib/ui/painting/image.h"
14
15namespace flutter {
16namespace {
17
18std::optional<SkColorType> ToSkColorType(impeller::PixelFormat format) {
19 switch (format) {
30 default:
31 return std::nullopt;
32 }
33}
34
35sk_sp<SkImage> ConvertBufferToSkImage(
36 const std::shared_ptr<impeller::DeviceBuffer>& buffer,
38 SkISize dimensions) {
39 SkImageInfo image_info = SkImageInfo::Make(dimensions, color_type,
42 auto func = [](void* addr, void* context) {
43 auto buffer =
44 static_cast<std::shared_ptr<impeller::DeviceBuffer>*>(context);
45 buffer->reset();
46 delete buffer;
47 };
48 auto bytes_per_pixel = image_info.bytesPerPixel();
49 bitmap.installPixels(image_info, buffer->OnGetContents(),
50 dimensions.width() * bytes_per_pixel, func,
51 new std::shared_ptr<impeller::DeviceBuffer>(buffer));
52 bitmap.setImmutable();
53
55 return raster_image;
56}
57
58[[nodiscard]] fml::Status DoConvertImageToRasterImpeller(
59 const sk_sp<DlImage>& dl_image,
60 const std::function<void(fml::StatusOr<sk_sp<SkImage>>)>& encode_task,
61 const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch,
62 const std::shared_ptr<impeller::Context>& impeller_context) {
64 is_gpu_disabled_sync_switch->Execute(
66 .SetIfTrue([&result] {
67 result =
68 fml::Status(fml::StatusCode::kUnavailable, "GPU unavailable.");
69 })
70 .SetIfFalse([&dl_image, &encode_task, &impeller_context] {
72 dl_image, encode_task, impeller_context);
73 }));
74 return result;
75}
76
77/// Same as `DoConvertImageToRasterImpeller` but it will attempt to retry the
78/// operation if `DoConvertImageToRasterImpeller` returns kUnavailable when the
79/// GPU becomes available again.
80void DoConvertImageToRasterImpellerWithRetry(
81 const sk_sp<DlImage>& dl_image,
82 std::function<void(fml::StatusOr<sk_sp<SkImage>>)>&& encode_task,
83 const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch,
84 const std::shared_ptr<impeller::Context>& impeller_context,
85 const fml::RefPtr<fml::TaskRunner>& retry_runner) {
86 fml::Status status = DoConvertImageToRasterImpeller(
87 dl_image, encode_task, is_gpu_disabled_sync_switch, impeller_context);
88 if (!status.ok()) {
89 // If the conversion failed because of the GPU is unavailable, store the
90 // task on the Context so it can be executed when the GPU becomes available.
91 if (status.code() == fml::StatusCode::kUnavailable) {
92 impeller_context->StoreTaskForGPU(
93 [dl_image, encode_task = std::move(encode_task),
94 is_gpu_disabled_sync_switch, impeller_context,
95 retry_runner]() mutable {
96 auto retry_task = [dl_image, encode_task = std::move(encode_task),
97 is_gpu_disabled_sync_switch, impeller_context] {
98 fml::Status retry_status = DoConvertImageToRasterImpeller(
99 dl_image, encode_task, is_gpu_disabled_sync_switch,
100 impeller_context);
101 if (!retry_status.ok()) {
102 // The retry failed for some reason, maybe the GPU became
103 // unavailable again. Don't retry again, just fail in this case.
104 encode_task(retry_status);
105 }
106 };
107 // If a `retry_runner` is specified, post the retry to it, otherwise
108 // execute it directly.
109 if (retry_runner) {
110 retry_runner->PostTask(retry_task);
111 } else {
112 retry_task();
113 }
114 });
115 } else {
116 // Pass on errors that are not `kUnavailable`.
117 encode_task(status);
118 }
119 }
120}
121
122} // namespace
123
125 const sk_sp<DlImage>& dl_image,
126 std::function<void(fml::StatusOr<sk_sp<SkImage>>)> encode_task,
127 const std::shared_ptr<impeller::Context>& impeller_context) {
128 auto texture = dl_image->impeller_texture();
129
130 if (impeller_context == nullptr) {
132 "Impeller context was null."));
133 return;
134 }
135
136 if (texture == nullptr) {
137 encode_task(
139 return;
140 }
141
142 auto dimensions = dl_image->dimensions();
143 auto color_type = ToSkColorType(texture->GetTextureDescriptor().format);
144
145 if (dimensions.isEmpty()) {
147 "Image dimensions were empty."));
148 return;
149 }
150
151 if (!color_type.has_value()) {
153 "Failed to get color type from pixel format."));
154 return;
155 }
156
159 buffer_desc.readback = true; // set to false for testing.
160 buffer_desc.size =
161 texture->GetTextureDescriptor().GetByteSizeOfBaseMipLevel();
162 auto buffer =
163 impeller_context->GetResourceAllocator()->CreateBuffer(buffer_desc);
164 auto command_buffer = impeller_context->CreateCommandBuffer();
165 command_buffer->SetLabel("BlitTextureToBuffer Command Buffer");
166 auto pass = command_buffer->CreateBlitPass();
167 pass->SetLabel("BlitTextureToBuffer Blit Pass");
168 pass->AddCopy(texture, buffer);
169 pass->EncodeCommands(impeller_context->GetResourceAllocator());
170 auto completion = [buffer, color_type = color_type.value(), dimensions,
171 encode_task = std::move(encode_task)](
174 encode_task(fml::Status(fml::StatusCode::kUnknown, ""));
175 return;
176 }
177 buffer->Invalidate();
178 auto sk_image = ConvertBufferToSkImage(buffer, color_type, dimensions);
179 encode_task(sk_image);
180 };
181
182 if (!impeller_context->GetCommandQueue()
183 ->Submit({command_buffer}, completion)
184 .ok()) {
185 FML_LOG(ERROR) << "Failed to submit commands.";
186 }
187}
188
190 const sk_sp<DlImage>& dl_image,
191 std::function<void(fml::StatusOr<sk_sp<SkImage>>)> encode_task,
192 const fml::RefPtr<fml::TaskRunner>& raster_task_runner,
193 const fml::RefPtr<fml::TaskRunner>& io_task_runner,
194 const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch,
195 const std::shared_ptr<impeller::Context>& impeller_context) {
196 auto original_encode_task = std::move(encode_task);
197 encode_task = [original_encode_task = std::move(original_encode_task),
198 io_task_runner](fml::StatusOr<sk_sp<SkImage>> image) mutable {
200 io_task_runner,
201 [original_encode_task = std::move(original_encode_task),
202 image = std::move(image)]() { original_encode_task(image); });
203 };
204
205 if (dl_image->owning_context() != DlImage::OwningContext::kRaster) {
206 DoConvertImageToRasterImpellerWithRetry(dl_image, std::move(encode_task),
207 is_gpu_disabled_sync_switch,
208 impeller_context,
209 /*retry_runner=*/nullptr);
210 return;
211 }
212
213 raster_task_runner->PostTask([dl_image, encode_task = std::move(encode_task),
214 io_task_runner, is_gpu_disabled_sync_switch,
215 impeller_context,
216 raster_task_runner]() mutable {
217 DoConvertImageToRasterImpellerWithRetry(
218 dl_image, std::move(encode_task), is_gpu_disabled_sync_switch,
219 impeller_context, raster_task_runner);
220 });
221}
222
224 const std::shared_ptr<impeller::Texture>& texture) {
225 const impeller::TextureDescriptor& desc = texture->GetTextureDescriptor();
226 switch (desc.format) {
227 case impeller::PixelFormat::kB10G10R10XR: // intentional_fallthrough
230 default:
231 return ColorSpace::kSRGB;
232 }
233}
234
235} // namespace flutter
@ kPremul_SkAlphaType
pixel components are premultiplied by alpha
Definition SkAlphaType.h:29
SkColorType
Definition SkColorType.h:19
@ kBGRA_8888_SkColorType
pixel with 8 bits for blue, green, red, alpha; in 32-bit word
Definition SkColorType.h:26
@ kRGBA_F16_SkColorType
pixel with half floats for red, green, blue, alpha;
Definition SkColorType.h:38
@ kBGRA_10101010_XR_SkColorType
pixel with 10 bits each for blue, green, red, alpha; in 64-bit word, extended range
Definition SkColorType.h:32
@ kRGBA_8888_SkColorType
pixel with 8 bits for red, green, blue, alpha; in 32-bit word
Definition SkColorType.h:24
@ kBGR_101010x_XR_SkColorType
pixel with 10 bits each for blue, green, red; in 32-bit word, extended range
Definition SkColorType.h:31
static int GetColorSpace(const std::shared_ptr< impeller::Texture > &texture)
static void ConvertDlImageToSkImage(const sk_sp< DlImage > &dl_image, std::function< void(fml::StatusOr< sk_sp< SkImage > >)> encode_task, const std::shared_ptr< impeller::Context > &impeller_context)
static void ConvertImageToRaster(const sk_sp< DlImage > &dl_image, std::function< void(fml::StatusOr< sk_sp< SkImage > >)> encode_task, const fml::RefPtr< fml::TaskRunner > &raster_task_runner, const fml::RefPtr< fml::TaskRunner > &io_task_runner, const std::shared_ptr< const fml::SyncSwitch > &is_gpu_disabled_sync_switch, const std::shared_ptr< impeller::Context > &impeller_context)
bool ok() const
Definition status.h:71
fml::StatusCode code() const
Definition status.h:63
static void RunNowOrPostTask(const fml::RefPtr< fml::TaskRunner > &runner, const fml::closure &task)
sk_sp< SkImage > image
Definition examples.cpp:29
GAsyncResult * result
#define FML_LOG(severity)
Definition logging.h:82
FlTexture * texture
SK_API sk_sp< SkImage > RasterFromBitmap(const SkBitmap &bitmap)
@ kExtendedSRGB
Definition image.h:18
@ kSRGB
Definition image.h:17
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 buffer
Definition switches.h:126
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
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition formats.h:100
uint32_t color_type
static size_t bytes_per_pixel(skcms_PixelFormat fmt)
Definition skcms.cc:2449
bool isEmpty() const
Definition SkSize.h:31
constexpr int32_t width() const
Definition SkSize.h:36
int bytesPerPixel() const
static SkImageInfo Make(int width, int height, SkColorType ct, SkAlphaType at)
Represents the 2 code paths available when calling |SyncSwitchExecute|.
Definition sync_switch.h:35
A lightweight object that describes the attributes of a texture that can then used an allocator to cr...
#define ERROR(message)