Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
multi_frame_codec.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/multi_frame_codec.h"
6
7#include <utility>
8
9#include "flutter/fml/make_copyable.h"
10#include "flutter/lib/ui/painting/display_list_image_gpu.h"
11#include "flutter/lib/ui/painting/image.h"
12#if IMPELLER_SUPPORTS_RENDERING
13#include "flutter/lib/ui/painting/image_decoder_impeller.h"
14#endif // IMPELLER_SUPPORTS_RENDERING
15#include "third_party/dart/runtime/include/dart_api.h"
21
22namespace flutter {
23
24MultiFrameCodec::MultiFrameCodec(std::shared_ptr<ImageGenerator> generator)
25 : state_(new State(std::move(generator))) {}
26
28
29MultiFrameCodec::State::State(std::shared_ptr<ImageGenerator> generator)
30 : generator_(std::move(generator)),
31 frameCount_(generator_->GetFrameCount()),
32 repetitionCount_(generator_->GetPlayCount() ==
33 ImageGenerator::kInfinitePlayCount
34 ? -1
35 : generator_->GetPlayCount() - 1),
36 is_impeller_enabled_(UIDartState::Current()->IsImpellerEnabled()) {}
37
40 int duration,
41 const std::string& decode_error,
42 std::unique_ptr<tonic::DartPersistentValue> callback,
43 size_t trace_id) {
44 std::shared_ptr<tonic::DartState> dart_state = callback->dart_state().lock();
45 if (!dart_state) {
46 FML_DLOG(ERROR) << "Could not acquire Dart state while attempting to fire "
47 "next frame callback.";
48 return;
49 }
50 tonic::DartState::Scope scope(dart_state);
52 {tonic::ToDart(image), tonic::ToDart(duration),
53 tonic::ToDart(decode_error)});
54}
55
56std::pair<sk_sp<DlImage>, std::string>
57MultiFrameCodec::State::GetNextFrameImage(
58 fml::WeakPtr<GrDirectContext> resourceContext,
59 const std::shared_ptr<const fml::SyncSwitch>& gpu_disable_sync_switch,
60 const std::shared_ptr<impeller::Context>& impeller_context,
63 SkImageInfo info = generator_->GetInfo().makeColorType(kN32_SkColorType);
64 if (info.alphaType() == kUnpremul_SkAlphaType) {
66 info = updated;
67 }
68 if (!bitmap.tryAllocPixels(info)) {
69 std::ostringstream ostr;
70 ostr << "Failed to allocate memory for bitmap of size "
71 << info.computeMinByteSize() << "B";
72 std::string decode_error = ostr.str();
73 FML_LOG(ERROR) << decode_error;
74 return std::make_pair(nullptr, decode_error);
75 }
76
77 ImageGenerator::FrameInfo frameInfo =
78 generator_->GetFrameInfo(nextFrameIndex_);
79
80 const int requiredFrameIndex =
81 frameInfo.required_frame.value_or(SkCodec::kNoFrame);
82
83 if (requiredFrameIndex != SkCodec::kNoFrame) {
84 // We are here when the frame said |disposal_method| is
85 // `DisposalMethod::kKeep` or `DisposalMethod::kRestorePrevious` and
86 // |requiredFrameIndex| is set to ex-frame or ex-ex-frame.
87 if (!lastRequiredFrame_.has_value()) {
88 FML_DLOG(INFO)
89 << "Frame " << nextFrameIndex_ << " depends on frame "
90 << requiredFrameIndex
91 << " and no required frames are cached. Using blank slate instead.";
92 } else {
93 // Copy the previous frame's output buffer into the current frame as the
94 // starting point.
95 bitmap.writePixels(lastRequiredFrame_->pixmap());
96 if (restoreBGColorRect_.has_value()) {
97 bitmap.erase(SK_ColorTRANSPARENT, restoreBGColorRect_.value());
98 }
99 }
100 }
101
102 // Write the new frame to the output buffer. The bitmap pixels as supplied
103 // are already set in accordance with the previous frame's disposal policy.
104 if (!generator_->GetPixels(info, bitmap.getPixels(), bitmap.rowBytes(),
105 nextFrameIndex_, requiredFrameIndex)) {
106 std::ostringstream ostr;
107 ostr << "Could not getPixels for frame " << nextFrameIndex_;
108 std::string decode_error = ostr.str();
109 FML_LOG(ERROR) << decode_error;
110 return std::make_pair(nullptr, decode_error);
111 }
112
113 const bool keep_current_frame =
114 frameInfo.disposal_method == SkCodecAnimation::DisposalMethod::kKeep;
115 const bool restore_previous_frame =
116 frameInfo.disposal_method ==
118 const bool previous_frame_available = lastRequiredFrame_.has_value();
119
120 // Store the current frame in `lastRequiredFrame_` if the frame's disposal
121 // method indicates we should do so.
122 // * When the disposal method is "Keep", the stored frame should always be
123 // overwritten with the new frame we just crafted.
124 // * When the disposal method is "RestorePrevious", the previously stored
125 // frame should be retained and used as the backdrop for the next frame
126 // again. If there isn't already a stored frame, that means we haven't
127 // rendered any frames yet! When this happens, we just fall back to "Keep"
128 // behavior and store the current frame as the backdrop of the next frame.
129
130 if (keep_current_frame ||
131 (previous_frame_available && !restore_previous_frame)) {
132 // Replace the stored frame. The `lastRequiredFrame_` will get used as the
133 // starting backdrop for the next frame.
134 lastRequiredFrame_ = bitmap;
135 lastRequiredFrameIndex_ = nextFrameIndex_;
136 }
137
138 if (frameInfo.disposal_method ==
140 restoreBGColorRect_ = frameInfo.disposal_rect;
141 } else {
142 restoreBGColorRect_.reset();
143 }
144
145#if IMPELLER_SUPPORTS_RENDERING
146 if (is_impeller_enabled_) {
147 // This is safe regardless of whether the GPU is available or not because
148 // without mipmap creation there is no command buffer encoding done.
150 impeller_context, std::make_shared<SkBitmap>(bitmap),
151 std::make_shared<fml::SyncSwitch>(),
153 /*create_mips=*/false);
154 }
155#endif // IMPELLER_SUPPORTS_RENDERING
156
157 sk_sp<SkImage> skImage;
158 gpu_disable_sync_switch->Execute(
160 .SetIfTrue([&skImage, &bitmap] {
161 // Defer decoding until time of draw later on the raster thread.
162 // Can happen when GL operations are currently forbidden such as
163 // in the background on iOS.
165 })
166 .SetIfFalse([&skImage, &resourceContext, &bitmap] {
167 if (resourceContext) {
168 SkPixmap pixmap(bitmap.info(), bitmap.pixelRef()->pixels(),
169 bitmap.pixelRef()->rowBytes());
171 resourceContext.get(), pixmap, true);
172 } else {
173 // Defer decoding until time of draw later on the raster thread.
174 // Can happen when GL operations are currently forbidden such as
175 // in the background on iOS.
177 }
178 }));
179
180 return std::make_pair(DlImageGPU::Make({skImage, std::move(unref_queue)}),
181 std::string());
182}
183
184void MultiFrameCodec::State::GetNextFrameAndInvokeCallback(
185 std::unique_ptr<tonic::DartPersistentValue> callback,
186 const fml::RefPtr<fml::TaskRunner>& ui_task_runner,
187 fml::WeakPtr<GrDirectContext> resourceContext,
189 const std::shared_ptr<const fml::SyncSwitch>& gpu_disable_sync_switch,
190 size_t trace_id,
191 const std::shared_ptr<impeller::Context>& impeller_context) {
193 int duration = 0;
194 sk_sp<DlImage> dlImage;
195 std::string decode_error;
196 std::tie(dlImage, decode_error) =
197 GetNextFrameImage(std::move(resourceContext), gpu_disable_sync_switch,
198 impeller_context, std::move(unref_queue));
199 if (dlImage) {
201 image->set_image(dlImage);
202 ImageGenerator::FrameInfo frameInfo =
203 generator_->GetFrameInfo(nextFrameIndex_);
204 duration = frameInfo.duration;
205 }
206 nextFrameIndex_ = (nextFrameIndex_ + 1) % frameCount_;
207
208 // The static leak checker gets confused by the use of fml::MakeCopyable.
209 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
210 ui_task_runner->PostTask(fml::MakeCopyable(
211 [callback = std::move(callback), image = std::move(image),
212 decode_error = std::move(decode_error), duration, trace_id]() mutable {
214 std::move(callback), trace_id);
215 }));
216}
217
219 static size_t trace_counter = 1;
220 const size_t trace_id = trace_counter++;
221
222 if (!Dart_IsClosure(callback_handle)) {
223 return tonic::ToDart("Callback must be a function");
224 }
225
226 auto* dart_state = UIDartState::Current();
227
228 const auto& task_runners = dart_state->GetTaskRunners();
229
230 if (state_->frameCount_ == 0) {
231 std::string decode_error("Could not provide any frame.");
232 FML_LOG(ERROR) << decode_error;
233 task_runners.GetUITaskRunner()->PostTask(fml::MakeCopyable(
234 [trace_id, decode_error = std::move(decode_error),
235 callback = std::make_unique<tonic::DartPersistentValue>(
236 tonic::DartState::Current(), callback_handle)]() mutable {
237 InvokeNextFrameCallback(nullptr, 0, decode_error, std::move(callback),
238 trace_id);
239 }));
240 return Dart_Null();
241 }
242
243 task_runners.GetIOTaskRunner()->PostTask(fml::MakeCopyable(
244 [callback = std::make_unique<tonic::DartPersistentValue>(
245 tonic::DartState::Current(), callback_handle),
246 weak_state = std::weak_ptr<MultiFrameCodec::State>(state_), trace_id,
247 ui_task_runner = task_runners.GetUITaskRunner(),
248 io_manager = dart_state->GetIOManager()]() mutable {
249 auto state = weak_state.lock();
250 if (!state) {
251 ui_task_runner->PostTask(fml::MakeCopyable(
252 [callback = std::move(callback)]() { callback->Clear(); }));
253 return;
254 }
255 state->GetNextFrameAndInvokeCallback(
256 std::move(callback), ui_task_runner,
257 io_manager->GetResourceContext(), io_manager->GetSkiaUnrefQueue(),
258 io_manager->GetIsGpuDisabledSyncSwitch(), trace_id,
259 io_manager->GetImpellerContext());
260 }));
261
262 return Dart_Null();
263 // The static leak checker gets confused by the control flow, unique
264 // pointers and closures in this function.
265 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
266}
267
268int MultiFrameCodec::frameCount() const {
269 return state_->frameCount_;
270}
271
272int MultiFrameCodec::repetitionCount() const {
273 return state_->repetitionCount_;
274}
275
276} // namespace flutter
static void info(const char *fmt,...) SK_PRINTF_LIKE(1
Definition DM.cpp:213
kUnpremul_SkAlphaType
@ kPremul_SkAlphaType
pixel components are premultiplied by alpha
Definition SkAlphaType.h:29
constexpr SkColor SK_ColorTRANSPARENT
Definition SkColor.h:99
static constexpr int kNoFrame
Definition SkCodec.h:650
static fml::RefPtr< CanvasImage > Create()
Definition image.h:28
static sk_sp< DlImageGPU > Make(SkiaGPUObject< SkImage > image)
static std::pair< sk_sp< DlImage >, std::string > UploadTextureToStorage(const std::shared_ptr< impeller::Context > &context, std::shared_ptr< SkBitmap > bitmap, const std::shared_ptr< fml::SyncSwitch > &gpu_disabled_switch, impeller::StorageMode storage_mode, bool create_mips=true)
Create a host visible texture from the provided bitmap.
The minimal interface necessary for defining a decoder that can be used for both single and multi-fra...
MultiFrameCodec(std::shared_ptr< ImageGenerator > generator)
Dart_Handle getNextFrame(Dart_Handle args) override
static UIDartState * Current()
T * get() const
Definition weak_ptr.h:87
static DartState * Current()
Definition dart_state.cc:56
struct _Dart_Handle * Dart_Handle
Definition dart_api.h:258
DART_EXPORT Dart_Handle Dart_Null(void)
DART_EXPORT bool Dart_IsClosure(Dart_Handle object)
sk_sp< SkImage > image
Definition examples.cpp:29
double duration
Definition examples.cpp:30
AtkStateType state
FlKeyEvent uint64_t FlKeyResponderAsyncCallback callback
#define FML_DLOG(severity)
Definition logging.h:102
#define FML_LOG(severity)
Definition logging.h:82
SK_API sk_sp< SkImage > CrossContextTextureFromPixmap(GrDirectContext *context, const SkPixmap &pixmap, bool buildMips, bool limitToMaxTextureSize=false)
SK_API sk_sp< SkImage > RasterFromBitmap(const SkBitmap &bitmap)
static void InvokeNextFrameCallback(const fml::RefPtr< CanvasImage > &image, int duration, const std::string &decode_error, std::unique_ptr< tonic::DartPersistentValue > callback, size_t trace_id)
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition ref_ptr.h:256
Dart_Handle ToDart(const T &object)
Dart_Handle DartInvoke(Dart_Handle closure, std::initializer_list< Dart_Handle > args)
SkImageInfo makeAlphaType(SkAlphaType newAlphaType) const
size_t computeMinByteSize() const
SkImageInfo makeColorType(SkColorType newColorType) const
Represents the 2 code paths available when calling |SyncSwitchExecute|.
Definition sync_switch.h:35
#define ERROR(message)