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,sk_sp<ExpressionManager> expressionmgr,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 sk_sp<ExpressionManager> expressionmgr,
165 Animation::Builder::Stats* stats,
166 const SkSize& comp_size, float duration, float framerate,
167 uint32_t flags)
168 : fResourceProvider(std::move(rp))
169 , fLazyFontMgr(std::move(fontmgr))
170 , fPropertyObserver(std::move(pobserver))
171 , fLogger(std::move(logger))
172 , fMarkerObserver(std::move(mobserver))
173 , fPrecompInterceptor(std::move(pi))
174 , fExpressionManager(std::move(expressionmgr))
175 , fStats(stats)
176 , fCompSize(comp_size)
177 , fDuration(duration)
178 , fFrameRate(framerate)
179 , fFlags(flags)
180 , fHasNontrivialBlending(false) {}
181
parse(const skjson::ObjectValue & jroot)182 AnimationBuilder::AnimationInfo AnimationBuilder::parse(const skjson::ObjectValue& jroot) {
183 this->dispatchMarkers(jroot["markers"]);
184
185 this->parseAssets(jroot["assets"]);
186 this->parseFonts(jroot["fonts"], jroot["chars"]);
187
188 AutoScope ascope(this);
189 AutoPropertyTracker apt(this, jroot, PropertyObserver::NodeType::COMPOSITION);
190 auto root = CompositionBuilder(*this, fCompSize, jroot).build(*this);
191
192 auto animators = ascope.release();
193 fStats->fAnimatorCount = animators.size();
194
195 return { sksg::Scene::Make(std::move(root)), std::move(animators) };
196 }
197
parseAssets(const skjson::ArrayValue * jassets)198 void AnimationBuilder::parseAssets(const skjson::ArrayValue* jassets) {
199 if (!jassets) {
200 return;
201 }
202
203 for (const skjson::ObjectValue* asset : *jassets) {
204 if (asset) {
205 fAssets.set(ParseDefault<SkString>((*asset)["id"], SkString()), { asset, false });
206 }
207 }
208 }
209
dispatchMarkers(const skjson::ArrayValue * jmarkers) const210 void AnimationBuilder::dispatchMarkers(const skjson::ArrayValue* jmarkers) const {
211 if (!fMarkerObserver || !jmarkers) {
212 return;
213 }
214
215 // For frame-number -> t conversions.
216 const auto frameRatio = 1 / (fFrameRate * fDuration);
217
218 for (const skjson::ObjectValue* m : *jmarkers) {
219 if (!m) continue;
220
221 const skjson::StringValue* name = (*m)["cm"];
222 const auto time = ParseDefault((*m)["tm"], -1.0f),
223 duration = ParseDefault((*m)["dr"], -1.0f);
224
225 if (name && time >= 0 && duration >= 0) {
226 fMarkerObserver->onMarker(
227 name->begin(),
228 // "tm" is in frames
229 time * frameRatio,
230 // ... as is "dr"
231 (time + duration) * frameRatio
232 );
233 } else {
234 this->log(Logger::Level::kWarning, m, "Ignoring unexpected marker.");
235 }
236 }
237 }
238
dispatchColorProperty(const sk_sp<sksg::Color> & c) const239 bool AnimationBuilder::dispatchColorProperty(const sk_sp<sksg::Color>& c) const {
240 bool dispatched = false;
241
242 if (fPropertyObserver) {
243 fPropertyObserver->onColorProperty(fPropertyObserverContext,
244 [&]() {
245 dispatched = true;
246 return std::make_unique<ColorPropertyHandle>(c);
247 });
248 }
249
250 return dispatched;
251 }
252
dispatchOpacityProperty(const sk_sp<sksg::OpacityEffect> & o) const253 bool AnimationBuilder::dispatchOpacityProperty(const sk_sp<sksg::OpacityEffect>& o) const {
254 bool dispatched = false;
255
256 if (fPropertyObserver) {
257 fPropertyObserver->onOpacityProperty(fPropertyObserverContext,
258 [&]() {
259 dispatched = true;
260 return std::make_unique<OpacityPropertyHandle>(o);
261 });
262 }
263
264 return dispatched;
265 }
266
dispatchTextProperty(const sk_sp<TextAdapter> & t) const267 bool AnimationBuilder::dispatchTextProperty(const sk_sp<TextAdapter>& t) const {
268 bool dispatched = false;
269
270 if (fPropertyObserver) {
271 fPropertyObserver->onTextProperty(fPropertyObserverContext,
272 [&]() {
273 dispatched = true;
274 return std::make_unique<TextPropertyHandle>(t);
275 });
276 }
277
278 return dispatched;
279 }
280
dispatchTransformProperty(const sk_sp<TransformAdapter2D> & t) const281 bool AnimationBuilder::dispatchTransformProperty(const sk_sp<TransformAdapter2D>& t) const {
282 bool dispatched = false;
283
284 if (fPropertyObserver) {
285 fPropertyObserver->onTransformProperty(fPropertyObserverContext,
286 [&]() {
287 dispatched = true;
288 return std::make_unique<TransformPropertyHandle>(t);
289 });
290 }
291
292 return dispatched;
293 }
294
expression_manager() const295 sk_sp<ExpressionManager> AnimationBuilder::expression_manager() const {
296 return fExpressionManager;
297 }
298
updateContext(PropertyObserver * observer,const skjson::ObjectValue & obj)299 void AnimationBuilder::AutoPropertyTracker::updateContext(PropertyObserver* observer,
300 const skjson::ObjectValue& obj) {
301
302 const skjson::StringValue* name = obj["nm"];
303
304 fBuilder->fPropertyObserverContext = name ? name->begin() : nullptr;
305 }
306
307 } // namespace internal
308
log(Level,const char[],const char *)309 void Logger::log(Level, const char[], const char*) {}
310
Builder(uint32_t flags)311 Animation::Builder::Builder(uint32_t flags) : fFlags(flags) {}
312 Animation::Builder::~Builder() = default;
313
setResourceProvider(sk_sp<ResourceProvider> rp)314 Animation::Builder& Animation::Builder::setResourceProvider(sk_sp<ResourceProvider> rp) {
315 fResourceProvider = std::move(rp);
316 return *this;
317 }
318
setFontManager(sk_sp<SkFontMgr> fmgr)319 Animation::Builder& Animation::Builder::setFontManager(sk_sp<SkFontMgr> fmgr) {
320 fFontMgr = std::move(fmgr);
321 return *this;
322 }
323
setPropertyObserver(sk_sp<PropertyObserver> pobserver)324 Animation::Builder& Animation::Builder::setPropertyObserver(sk_sp<PropertyObserver> pobserver) {
325 fPropertyObserver = std::move(pobserver);
326 return *this;
327 }
328
setLogger(sk_sp<Logger> logger)329 Animation::Builder& Animation::Builder::setLogger(sk_sp<Logger> logger) {
330 fLogger = std::move(logger);
331 return *this;
332 }
333
setMarkerObserver(sk_sp<MarkerObserver> mobserver)334 Animation::Builder& Animation::Builder::setMarkerObserver(sk_sp<MarkerObserver> mobserver) {
335 fMarkerObserver = std::move(mobserver);
336 return *this;
337 }
338
setPrecompInterceptor(sk_sp<PrecompInterceptor> pi)339 Animation::Builder& Animation::Builder::setPrecompInterceptor(sk_sp<PrecompInterceptor> pi) {
340 fPrecompInterceptor = std::move(pi);
341 return *this;
342 }
343
setExpressionManager(sk_sp<ExpressionManager> em)344 Animation::Builder& Animation::Builder::setExpressionManager(sk_sp<ExpressionManager> em) {
345 fExpressionManager = std::move(em);
346 return *this;
347 }
348
make(SkStream * stream)349 sk_sp<Animation> Animation::Builder::make(SkStream* stream) {
350 if (!stream->hasLength()) {
351 // TODO: handle explicit buffering?
352 if (fLogger) {
353 fLogger->log(Logger::Level::kError, "Cannot parse streaming content.\n");
354 }
355 return nullptr;
356 }
357
358 auto data = SkData::MakeFromStream(stream, stream->getLength());
359 if (!data) {
360 if (fLogger) {
361 fLogger->log(Logger::Level::kError, "Failed to read the input stream.\n");
362 }
363 return nullptr;
364 }
365
366 return this->make(static_cast<const char*>(data->data()), data->size());
367 }
368
make(const char * data,size_t data_len)369 sk_sp<Animation> Animation::Builder::make(const char* data, size_t data_len) {
370 TRACE_EVENT0("skottie", TRACE_FUNC);
371
372 // Sanitize factory args.
373 class NullResourceProvider final : public ResourceProvider {
374 sk_sp<SkData> load(const char[], const char[]) const override { return nullptr; }
375 };
376 auto resolvedProvider = fResourceProvider
377 ? fResourceProvider : sk_make_sp<NullResourceProvider>();
378
379 fStats = Stats{};
380
381 fStats.fJsonSize = data_len;
382 const auto t0 = std::chrono::steady_clock::now();
383
384 const skjson::DOM dom(data, data_len);
385 if (!dom.root().is<skjson::ObjectValue>()) {
386 // TODO: more error info.
387 if (fLogger) {
388 fLogger->log(Logger::Level::kError, "Failed to parse JSON input.\n");
389 }
390 return nullptr;
391 }
392 const auto& json = dom.root().as<skjson::ObjectValue>();
393
394 const auto t1 = std::chrono::steady_clock::now();
395 fStats.fJsonParseTimeMS = std::chrono::duration<float, std::milli>{t1-t0}.count();
396
397 const auto version = ParseDefault<SkString>(json["v"], SkString());
398 const auto size = SkSize::Make(ParseDefault<float>(json["w"], 0.0f),
399 ParseDefault<float>(json["h"], 0.0f));
400 const auto fps = ParseDefault<float>(json["fr"], -1.0f),
401 inPoint = ParseDefault<float>(json["ip"], 0.0f),
402 outPoint = std::max(ParseDefault<float>(json["op"], SK_ScalarMax), inPoint),
403 duration = sk_ieee_float_divide(outPoint - inPoint, fps);
404
405 if (size.isEmpty() || version.isEmpty() || fps <= 0 ||
406 !SkScalarIsFinite(inPoint) || !SkScalarIsFinite(outPoint) || !SkScalarIsFinite(duration)) {
407 if (fLogger) {
408 const auto msg = SkStringPrintf(
409 "Invalid animation params (version: %s, size: [%f %f], frame rate: %f, "
410 "in-point: %f, out-point: %f)\n",
411 version.c_str(), size.width(), size.height(), fps, inPoint, outPoint);
412 fLogger->log(Logger::Level::kError, msg.c_str());
413 }
414 return nullptr;
415 }
416
417 SkASSERT(resolvedProvider);
418 internal::AnimationBuilder builder(std::move(resolvedProvider), fFontMgr,
419 std::move(fPropertyObserver),
420 std::move(fLogger),
421 std::move(fMarkerObserver),
422 std::move(fPrecompInterceptor),
423 std::move(fExpressionManager),
424 &fStats, size, duration, fps, fFlags);
425 auto ainfo = builder.parse(json);
426
427 const auto t2 = std::chrono::steady_clock::now();
428 fStats.fSceneParseTimeMS = std::chrono::duration<float, std::milli>{t2-t1}.count();
429 fStats.fTotalLoadTimeMS = std::chrono::duration<float, std::milli>{t2-t0}.count();
430
431 if (!ainfo.fScene && fLogger) {
432 fLogger->log(Logger::Level::kError, "Could not parse animation.\n");
433 }
434
435 uint32_t flags = 0;
436 if (builder.hasNontrivialBlending()) {
437 flags |= Animation::Flags::kRequiresTopLevelIsolation;
438 }
439
440 return sk_sp<Animation>(new Animation(std::move(ainfo.fScene),
441 std::move(ainfo.fAnimators),
442 std::move(version),
443 size,
444 inPoint,
445 outPoint,
446 duration,
447 fps,
448 flags));
449 }
450
makeFromFile(const char path[])451 sk_sp<Animation> Animation::Builder::makeFromFile(const char path[]) {
452 const auto data = SkData::MakeFromFileName(path);
453
454 return data ? this->make(static_cast<const char*>(data->data()), data->size())
455 : nullptr;
456 }
457
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)458 Animation::Animation(std::unique_ptr<sksg::Scene> scene,
459 std::vector<sk_sp<internal::Animator>>&& animators,
460 SkString version, const SkSize& size,
461 double inPoint, double outPoint, double duration, double fps, uint32_t flags)
462 : fScene(std::move(scene))
463 , fAnimators(std::move(animators))
464 , fVersion(std::move(version))
465 , fSize(size)
466 , fInPoint(inPoint)
467 , fOutPoint(outPoint)
468 , fDuration(duration)
469 , fFPS(fps)
470 , fFlags(flags) {}
471
472 Animation::~Animation() = default;
473
render(SkCanvas * canvas,const SkRect * dstR) const474 void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
475 this->render(canvas, dstR, 0);
476 }
477
render(SkCanvas * canvas,const SkRect * dstR,RenderFlags renderFlags) const478 void Animation::render(SkCanvas* canvas, const SkRect* dstR, RenderFlags renderFlags) const {
479 TRACE_EVENT0("skottie", TRACE_FUNC);
480
481 if (!fScene)
482 return;
483
484 SkAutoCanvasRestore restore(canvas, true);
485
486 const SkRect srcR = SkRect::MakeSize(this->size());
487 if (dstR) {
488 canvas->concat(SkMatrix::RectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
489 }
490
491 if (!(renderFlags & RenderFlag::kDisableTopLevelClipping)) {
492 canvas->clipRect(srcR);
493 }
494
495 if ((fFlags & Flags::kRequiresTopLevelIsolation) &&
496 !(renderFlags & RenderFlag::kSkipTopLevelIsolation)) {
497 // The animation uses non-trivial blending, and needs
498 // to be rendered into a separate/transparent layer.
499 canvas->saveLayer(srcR, nullptr);
500 }
501
502 fScene->render(canvas);
503 }
504
seekFrame(double t,sksg::InvalidationController * ic)505 void Animation::seekFrame(double t, sksg::InvalidationController* ic) {
506 TRACE_EVENT0("skottie", TRACE_FUNC);
507
508 if (!fScene)
509 return;
510
511 // Per AE/Lottie semantics out_point is exclusive.
512 const auto kLastValidFrame = std::nextafterf(fOutPoint, fInPoint),
513 comp_time = SkTPin<float>(fInPoint + t, fInPoint, kLastValidFrame);
514
515 for (const auto& anim : fAnimators) {
516 anim->seek(comp_time);
517 }
518
519 fScene->revalidate(ic);
520 }
521
seekFrameTime(double t,sksg::InvalidationController * ic)522 void Animation::seekFrameTime(double t, sksg::InvalidationController* ic) {
523 this->seekFrame(t * fFPS, ic);
524 }
525
Make(const char * data,size_t length)526 sk_sp<Animation> Animation::Make(const char* data, size_t length) {
527 return Builder().make(data, length);
528 }
529
Make(SkStream * stream)530 sk_sp<Animation> Animation::Make(SkStream* stream) {
531 return Builder().make(stream);
532 }
533
MakeFromFile(const char path[])534 sk_sp<Animation> Animation::MakeFromFile(const char path[]) {
535 return Builder().makeFromFile(path);
536 }
537
538 } // namespace skottie
539