1 /*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "modules/skottie/include/Skottie.h"
9
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkFontMgr.h"
13 #include "include/core/SkImage.h"
14 #include "include/core/SkPaint.h"
15 #include "include/core/SkPoint.h"
16 #include "include/core/SkStream.h"
17 #include "include/private/SkTArray.h"
18 #include "include/private/SkTPin.h"
19 #include "include/private/SkTo.h"
20 #include "modules/skottie/include/ExternalLayer.h"
21 #include "modules/skottie/include/SkottieProperty.h"
22 #include "modules/skottie/src/Composition.h"
23 #include "modules/skottie/src/SkottieJson.h"
24 #include "modules/skottie/src/SkottiePriv.h"
25 #include "modules/skottie/src/SkottieValue.h"
26 #include "modules/skottie/src/Transform.h"
27 #include "modules/skottie/src/text/TextAdapter.h"
28 #include "modules/sksg/include/SkSGInvalidationController.h"
29 #include "modules/sksg/include/SkSGOpacityEffect.h"
30 #include "modules/sksg/include/SkSGPaint.h"
31 #include "modules/sksg/include/SkSGPath.h"
32 #include "modules/sksg/include/SkSGRenderEffect.h"
33 #include "modules/sksg/include/SkSGScene.h"
34 #include "modules/sksg/include/SkSGTransform.h"
35 #include "src/core/SkTraceEvent.h"
36
37 #include <chrono>
38 #include <cmath>
39 #include <memory>
40
41 #include "stdlib.h"
42
43 namespace skottie {
44
45 namespace internal {
46
log(Logger::Level lvl,const skjson::Value * json,const char fmt[],...) const47 void AnimationBuilder::log(Logger::Level lvl, const skjson::Value* json,
48 const char fmt[], ...) const {
49 if (!fLogger) {
50 return;
51 }
52
53 char buff[1024];
54 va_list va;
55 va_start(va, fmt);
56 const auto len = vsnprintf(buff, sizeof(buff), fmt, va);
57 va_end(va);
58
59 if (len < 0) {
60 SkDebugf("!! Could not format log message !!\n");
61 return;
62 }
63
64 if (len >= SkToInt(sizeof(buff))) {
65 static constexpr char kEllipsesStr[] = "...";
66 strcpy(buff + sizeof(buff) - sizeof(kEllipsesStr), kEllipsesStr);
67 }
68
69 SkString jsonstr = json ? json->toString() : SkString();
70
71 fLogger->log(lvl, buff, jsonstr.c_str());
72 }
73
74 namespace {
75
76 class OpacityAdapter final : public DiscardableAdapterBase<OpacityAdapter, sksg::OpacityEffect> {
77 public:
OpacityAdapter(const skjson::ObjectValue & jobject,sk_sp<sksg::RenderNode> child,const AnimationBuilder & abuilder)78 OpacityAdapter(const skjson::ObjectValue& jobject,
79 sk_sp<sksg::RenderNode> child,
80 const AnimationBuilder& abuilder)
81 : INHERITED(sksg::OpacityEffect::Make(child)) {
82 this->bind(abuilder, jobject["o"], fOpacity);
83 }
84
85 private:
onSync()86 void onSync() override {
87 this->node()->setOpacity(fOpacity * 0.01f);
88 }
89
90 ScalarValue fOpacity = 100;
91
92 using INHERITED = DiscardableAdapterBase<OpacityAdapter, sksg::OpacityEffect>;
93 };
94
GetBlendMode(const skjson::ObjectValue & jobject,const AnimationBuilder * abuilder)95 static SkBlendMode GetBlendMode(const skjson::ObjectValue& jobject,
96 const AnimationBuilder* abuilder) {
97 static constexpr SkBlendMode kBlendModeMap[] = {
98 SkBlendMode::kSrcOver, // 0:'normal'
99 SkBlendMode::kMultiply, // 1:'multiply'
100 SkBlendMode::kScreen, // 2:'screen'
101 SkBlendMode::kOverlay, // 3:'overlay
102 SkBlendMode::kDarken, // 4:'darken'
103 SkBlendMode::kLighten, // 5:'lighten'
104 SkBlendMode::kColorDodge, // 6:'color-dodge'
105 SkBlendMode::kColorBurn, // 7:'color-burn'
106 SkBlendMode::kHardLight, // 8:'hard-light'
107 SkBlendMode::kSoftLight, // 9:'soft-light'
108 SkBlendMode::kDifference, // 10:'difference'
109 SkBlendMode::kExclusion, // 11:'exclusion'
110 SkBlendMode::kHue, // 12:'hue'
111 SkBlendMode::kSaturation, // 13:'saturation'
112 SkBlendMode::kColor, // 14:'color'
113 SkBlendMode::kLuminosity, // 15:'luminosity'
114 SkBlendMode::kPlus, // 16:'add'
115 };
116
117 const auto bm_index = ParseDefault<size_t>(jobject["bm"], 0);
118 if (bm_index >= SK_ARRAY_COUNT(kBlendModeMap)) {
119 abuilder->log(Logger::Level::kWarning, &jobject,
120 "Unsupported blend mode %lu\n", bm_index);
121 return SkBlendMode::kSrcOver;
122 }
123
124 return kBlendModeMap[bm_index];
125 }
126
127 } // namespace
128
attachOpacity(const skjson::ObjectValue & jobject,sk_sp<sksg::RenderNode> child_node) const129 sk_sp<sksg::RenderNode> AnimationBuilder::attachOpacity(const skjson::ObjectValue& jobject,
130 sk_sp<sksg::RenderNode> child_node) const {
131 if (!child_node)
132 return nullptr;
133
134 auto adapter = OpacityAdapter::Make(jobject, child_node, *this);
135 const auto dispatched = this->dispatchOpacityProperty(adapter->node());
136
137 if (adapter->isStatic()) {
138 adapter->seek(0);
139 if (!dispatched && adapter->node()->getOpacity() >= 1) {
140 // No obeservable effects - we can discard.
141 return child_node;
142 }
143 } else {
144 fCurrentAnimatorScope->push_back(adapter);
145 }
146
147 return adapter->node();
148 }
149
attachBlendMode(const skjson::ObjectValue & jobject,sk_sp<sksg::RenderNode> child) const150 sk_sp<sksg::RenderNode> AnimationBuilder::attachBlendMode(const skjson::ObjectValue& jobject,
151 sk_sp<sksg::RenderNode> child) const {
152 const auto bm = GetBlendMode(jobject, this);
153 if (bm != SkBlendMode::kSrcOver) {
154 fHasNontrivialBlending = true;
155 child = sksg::BlendModeEffect::Make(std::move(child), bm);
156 }
157
158 return child;
159 }
160
AnimationBuilder(sk_sp<ResourceProvider> rp,sk_sp<SkFontMgr> fontmgr,sk_sp<PropertyObserver> pobserver,sk_sp<Logger> logger,sk_sp<MarkerObserver> mobserver,sk_sp<PrecompInterceptor> pi,Animation::Builder::Stats * stats,const SkSize & comp_size,float duration,float framerate,uint32_t flags)161 AnimationBuilder::AnimationBuilder(sk_sp<ResourceProvider> rp, sk_sp<SkFontMgr> fontmgr,
162 sk_sp<PropertyObserver> pobserver, sk_sp<Logger> logger,
163 sk_sp<MarkerObserver> mobserver, sk_sp<PrecompInterceptor> pi,
164 Animation::Builder::Stats* stats,
165 const SkSize& comp_size, float duration, float framerate,
166 uint32_t flags)
167 : fResourceProvider(std::move(rp))
168 , fLazyFontMgr(std::move(fontmgr))
169 , fPropertyObserver(std::move(pobserver))
170 , fLogger(std::move(logger))
171 , fMarkerObserver(std::move(mobserver))
172 , fPrecompInterceptor(std::move(pi))
173 , fStats(stats)
174 , fCompSize(comp_size)
175 , fDuration(duration)
176 , fFrameRate(framerate)
177 , fFlags(flags)
178 , fHasNontrivialBlending(false) {}
179
parse(const skjson::ObjectValue & jroot)180 AnimationBuilder::AnimationInfo AnimationBuilder::parse(const skjson::ObjectValue& jroot) {
181 this->dispatchMarkers(jroot["markers"]);
182
183 this->parseAssets(jroot["assets"]);
184 this->parseFonts(jroot["fonts"], jroot["chars"]);
185
186 AutoScope ascope(this);
187 auto root = CompositionBuilder(*this, fCompSize, jroot).build(*this);
188
189 auto animators = ascope.release();
190 fStats->fAnimatorCount = animators.size();
191
192 return { sksg::Scene::Make(std::move(root)), std::move(animators) };
193 }
194
parseAssets(const skjson::ArrayValue * jassets)195 void AnimationBuilder::parseAssets(const skjson::ArrayValue* jassets) {
196 if (!jassets) {
197 return;
198 }
199
200 for (const skjson::ObjectValue* asset : *jassets) {
201 if (asset) {
202 fAssets.set(ParseDefault<SkString>((*asset)["id"], SkString()), { asset, false });
203 }
204 }
205 }
206
dispatchMarkers(const skjson::ArrayValue * jmarkers) const207 void AnimationBuilder::dispatchMarkers(const skjson::ArrayValue* jmarkers) const {
208 if (!fMarkerObserver || !jmarkers) {
209 return;
210 }
211
212 // For frame-number -> t conversions.
213 const auto frameRatio = 1 / (fFrameRate * fDuration);
214
215 for (const skjson::ObjectValue* m : *jmarkers) {
216 if (!m) continue;
217
218 const skjson::StringValue* name = (*m)["cm"];
219 const auto time = ParseDefault((*m)["tm"], -1.0f),
220 duration = ParseDefault((*m)["dr"], -1.0f);
221
222 if (name && time >= 0 && duration >= 0) {
223 fMarkerObserver->onMarker(
224 name->begin(),
225 // "tm" is in frames
226 time * frameRatio,
227 // ... as is "dr"
228 (time + duration) * frameRatio
229 );
230 } else {
231 this->log(Logger::Level::kWarning, m, "Ignoring unexpected marker.");
232 }
233 }
234 }
235
dispatchColorProperty(const sk_sp<sksg::Color> & c) const236 bool AnimationBuilder::dispatchColorProperty(const sk_sp<sksg::Color>& c) const {
237 bool dispatched = false;
238
239 if (fPropertyObserver) {
240 fPropertyObserver->onColorProperty(fPropertyObserverContext,
241 [&]() {
242 dispatched = true;
243 return std::make_unique<ColorPropertyHandle>(c);
244 });
245 }
246
247 return dispatched;
248 }
249
dispatchOpacityProperty(const sk_sp<sksg::OpacityEffect> & o) const250 bool AnimationBuilder::dispatchOpacityProperty(const sk_sp<sksg::OpacityEffect>& o) const {
251 bool dispatched = false;
252
253 if (fPropertyObserver) {
254 fPropertyObserver->onOpacityProperty(fPropertyObserverContext,
255 [&]() {
256 dispatched = true;
257 return std::make_unique<OpacityPropertyHandle>(o);
258 });
259 }
260
261 return dispatched;
262 }
263
dispatchTextProperty(const sk_sp<TextAdapter> & t) const264 bool AnimationBuilder::dispatchTextProperty(const sk_sp<TextAdapter>& t) const {
265 bool dispatched = false;
266
267 if (fPropertyObserver) {
268 fPropertyObserver->onTextProperty(fPropertyObserverContext,
269 [&]() {
270 dispatched = true;
271 return std::make_unique<TextPropertyHandle>(t);
272 });
273 }
274
275 return dispatched;
276 }
277
dispatchTransformProperty(const sk_sp<TransformAdapter2D> & t) const278 bool AnimationBuilder::dispatchTransformProperty(const sk_sp<TransformAdapter2D>& t) const {
279 bool dispatched = false;
280
281 if (fPropertyObserver) {
282 fPropertyObserver->onTransformProperty(fPropertyObserverContext,
283 [&]() {
284 dispatched = true;
285 return std::make_unique<TransformPropertyHandle>(t);
286 });
287 }
288
289 return dispatched;
290 }
291
updateContext(PropertyObserver * observer,const skjson::ObjectValue & obj)292 void AnimationBuilder::AutoPropertyTracker::updateContext(PropertyObserver* observer,
293 const skjson::ObjectValue& obj) {
294
295 const skjson::StringValue* name = obj["nm"];
296
297 fBuilder->fPropertyObserverContext = name ? name->begin() : nullptr;
298 }
299
300 } // namespace internal
301
log(Level,const char[],const char *)302 void Logger::log(Level, const char[], const char*) {}
303
Builder(uint32_t flags)304 Animation::Builder::Builder(uint32_t flags) : fFlags(flags) {}
305 Animation::Builder::~Builder() = default;
306
setResourceProvider(sk_sp<ResourceProvider> rp)307 Animation::Builder& Animation::Builder::setResourceProvider(sk_sp<ResourceProvider> rp) {
308 fResourceProvider = std::move(rp);
309 return *this;
310 }
311
setFontManager(sk_sp<SkFontMgr> fmgr)312 Animation::Builder& Animation::Builder::setFontManager(sk_sp<SkFontMgr> fmgr) {
313 fFontMgr = std::move(fmgr);
314 return *this;
315 }
316
setPropertyObserver(sk_sp<PropertyObserver> pobserver)317 Animation::Builder& Animation::Builder::setPropertyObserver(sk_sp<PropertyObserver> pobserver) {
318 fPropertyObserver = std::move(pobserver);
319 return *this;
320 }
321
setLogger(sk_sp<Logger> logger)322 Animation::Builder& Animation::Builder::setLogger(sk_sp<Logger> logger) {
323 fLogger = std::move(logger);
324 return *this;
325 }
326
setMarkerObserver(sk_sp<MarkerObserver> mobserver)327 Animation::Builder& Animation::Builder::setMarkerObserver(sk_sp<MarkerObserver> mobserver) {
328 fMarkerObserver = std::move(mobserver);
329 return *this;
330 }
331
setPrecompInterceptor(sk_sp<PrecompInterceptor> pi)332 Animation::Builder& Animation::Builder::setPrecompInterceptor(sk_sp<PrecompInterceptor> pi) {
333 fPrecompInterceptor = std::move(pi);
334 return *this;
335 }
336
make(SkStream * stream)337 sk_sp<Animation> Animation::Builder::make(SkStream* stream) {
338 if (!stream->hasLength()) {
339 // TODO: handle explicit buffering?
340 if (fLogger) {
341 fLogger->log(Logger::Level::kError, "Cannot parse streaming content.\n");
342 }
343 return nullptr;
344 }
345
346 auto data = SkData::MakeFromStream(stream, stream->getLength());
347 if (!data) {
348 if (fLogger) {
349 fLogger->log(Logger::Level::kError, "Failed to read the input stream.\n");
350 }
351 return nullptr;
352 }
353
354 return this->make(static_cast<const char*>(data->data()), data->size());
355 }
356
make(const char * data,size_t data_len)357 sk_sp<Animation> Animation::Builder::make(const char* data, size_t data_len) {
358 TRACE_EVENT0("skottie", TRACE_FUNC);
359
360 // Sanitize factory args.
361 class NullResourceProvider final : public ResourceProvider {
362 sk_sp<SkData> load(const char[], const char[]) const override { return nullptr; }
363 };
364 auto resolvedProvider = fResourceProvider
365 ? fResourceProvider : sk_make_sp<NullResourceProvider>();
366
367 fStats = Stats{};
368
369 fStats.fJsonSize = data_len;
370 const auto t0 = std::chrono::steady_clock::now();
371
372 const skjson::DOM dom(data, data_len);
373 if (!dom.root().is<skjson::ObjectValue>()) {
374 // TODO: more error info.
375 if (fLogger) {
376 fLogger->log(Logger::Level::kError, "Failed to parse JSON input.\n");
377 }
378 return nullptr;
379 }
380 const auto& json = dom.root().as<skjson::ObjectValue>();
381
382 const auto t1 = std::chrono::steady_clock::now();
383 fStats.fJsonParseTimeMS = std::chrono::duration<float, std::milli>{t1-t0}.count();
384
385 const auto version = ParseDefault<SkString>(json["v"], SkString());
386 const auto size = SkSize::Make(ParseDefault<float>(json["w"], 0.0f),
387 ParseDefault<float>(json["h"], 0.0f));
388 const auto fps = ParseDefault<float>(json["fr"], -1.0f),
389 inPoint = ParseDefault<float>(json["ip"], 0.0f),
390 outPoint = std::max(ParseDefault<float>(json["op"], SK_ScalarMax), inPoint),
391 duration = sk_ieee_float_divide(outPoint - inPoint, fps);
392
393 if (size.isEmpty() || version.isEmpty() || fps <= 0 ||
394 !SkScalarIsFinite(inPoint) || !SkScalarIsFinite(outPoint) || !SkScalarIsFinite(duration)) {
395 if (fLogger) {
396 const auto msg = SkStringPrintf(
397 "Invalid animation params (version: %s, size: [%f %f], frame rate: %f, "
398 "in-point: %f, out-point: %f)\n",
399 version.c_str(), size.width(), size.height(), fps, inPoint, outPoint);
400 fLogger->log(Logger::Level::kError, msg.c_str());
401 }
402 return nullptr;
403 }
404
405 SkASSERT(resolvedProvider);
406 internal::AnimationBuilder builder(std::move(resolvedProvider), fFontMgr,
407 std::move(fPropertyObserver),
408 std::move(fLogger),
409 std::move(fMarkerObserver),
410 std::move(fPrecompInterceptor),
411 &fStats, size, duration, fps, fFlags);
412 auto ainfo = builder.parse(json);
413
414 const auto t2 = std::chrono::steady_clock::now();
415 fStats.fSceneParseTimeMS = std::chrono::duration<float, std::milli>{t2-t1}.count();
416 fStats.fTotalLoadTimeMS = std::chrono::duration<float, std::milli>{t2-t0}.count();
417
418 if (!ainfo.fScene && fLogger) {
419 fLogger->log(Logger::Level::kError, "Could not parse animation.\n");
420 }
421
422 uint32_t flags = 0;
423 if (builder.hasNontrivialBlending()) {
424 flags |= Animation::Flags::kRequiresTopLevelIsolation;
425 }
426
427 return sk_sp<Animation>(new Animation(std::move(ainfo.fScene),
428 std::move(ainfo.fAnimators),
429 std::move(version),
430 size,
431 inPoint,
432 outPoint,
433 duration,
434 fps,
435 flags));
436 }
437
makeFromFile(const char path[])438 sk_sp<Animation> Animation::Builder::makeFromFile(const char path[]) {
439 const auto data = SkData::MakeFromFileName(path);
440
441 return data ? this->make(static_cast<const char*>(data->data()), data->size())
442 : nullptr;
443 }
444
Animation(std::unique_ptr<sksg::Scene> scene,std::vector<sk_sp<internal::Animator>> && animators,SkString version,const SkSize & size,double inPoint,double outPoint,double duration,double fps,uint32_t flags)445 Animation::Animation(std::unique_ptr<sksg::Scene> scene,
446 std::vector<sk_sp<internal::Animator>>&& animators,
447 SkString version, const SkSize& size,
448 double inPoint, double outPoint, double duration, double fps, uint32_t flags)
449 : fScene(std::move(scene))
450 , fAnimators(std::move(animators))
451 , fVersion(std::move(version))
452 , fSize(size)
453 , fInPoint(inPoint)
454 , fOutPoint(outPoint)
455 , fDuration(duration)
456 , fFPS(fps)
457 , fFlags(flags) {}
458
459 Animation::~Animation() = default;
460
render(SkCanvas * canvas,const SkRect * dstR) const461 void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
462 this->render(canvas, dstR, 0);
463 }
464
render(SkCanvas * canvas,const SkRect * dstR,RenderFlags renderFlags) const465 void Animation::render(SkCanvas* canvas, const SkRect* dstR, RenderFlags renderFlags) const {
466 TRACE_EVENT0("skottie", TRACE_FUNC);
467
468 if (!fScene)
469 return;
470
471 SkAutoCanvasRestore restore(canvas, true);
472
473 const SkRect srcR = SkRect::MakeSize(this->size());
474 if (dstR) {
475 canvas->concat(SkMatrix::RectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
476 }
477
478 if (!(renderFlags & RenderFlag::kDisableTopLevelClipping)) {
479 canvas->clipRect(srcR);
480 }
481
482 if ((fFlags & Flags::kRequiresTopLevelIsolation) &&
483 !(renderFlags & RenderFlag::kSkipTopLevelIsolation)) {
484 // The animation uses non-trivial blending, and needs
485 // to be rendered into a separate/transparent layer.
486 canvas->saveLayer(srcR, nullptr);
487 }
488
489 fScene->render(canvas);
490 }
491
seekFrame(double t,sksg::InvalidationController * ic)492 void Animation::seekFrame(double t, sksg::InvalidationController* ic) {
493 TRACE_EVENT0("skottie", TRACE_FUNC);
494
495 if (!fScene)
496 return;
497
498 // Per AE/Lottie semantics out_point is exclusive.
499 const auto kLastValidFrame = std::nextafterf(fOutPoint, fInPoint),
500 comp_time = SkTPin<float>(fInPoint + t, fInPoint, kLastValidFrame);
501
502 for (const auto& anim : fAnimators) {
503 anim->seek(comp_time);
504 }
505
506 fScene->revalidate(ic);
507 }
508
seekFrameTime(double t,sksg::InvalidationController * ic)509 void Animation::seekFrameTime(double t, sksg::InvalidationController* ic) {
510 this->seekFrame(t * fFPS, ic);
511 }
512
Make(const char * data,size_t length)513 sk_sp<Animation> Animation::Make(const char* data, size_t length) {
514 return Builder().make(data, length);
515 }
516
Make(SkStream * stream)517 sk_sp<Animation> Animation::Make(SkStream* stream) {
518 return Builder().make(stream);
519 }
520
MakeFromFile(const char path[])521 sk_sp<Animation> Animation::MakeFromFile(const char path[]) {
522 return Builder().makeFromFile(path);
523 }
524
525 } // namespace skottie
526