summaryrefslogtreecommitdiff
path: root/ssg/src/lottie/lottieparser.cpp
blob: 53d6d970855ed207e79c2f0558ccb241c5e03efb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
#include"sgjson.h"
#include "rapidjson/document.h"
#include <iostream>
#include "lottiecomposition.h"
#include "lottiemodel.h"
#include"sgelapsedtimer.h"

//#define DEBUG_PARSER

RAPIDJSON_DIAG_PUSH
#ifdef __GNUC__
RAPIDJSON_DIAG_OFF(effc++)
#endif

// This example demonstrates JSON token-by-token parsing with an API that is
// more direct; you don't need to design your logic around a handler object and
// callbacks. Instead, you retrieve values from the JSON stream by calling
// GetInt(), GetDouble(), GetString() and GetBool(), traverse into structures
// by calling EnterObject() and EnterArray(), and skip over unwanted data by
// calling SkipValue(). When you know your JSON's structure, this can be quite
// convenient.
//
// If you aren't sure of what's next in the JSON data, you can use PeekType() and
// PeekValue() to look ahead to the next object before reading it.
//
// If you call the wrong retrieval method--e.g. GetInt when the next JSON token is
// not an int, EnterObject or EnterArray when there isn't actually an object or array
// to read--the stream parsing will end immediately and no more data will be delivered.
//
// After calling EnterObject, you retrieve keys via NextObjectKey() and values via
// the normal getters. When NextObjectKey() returns null, you have exited the
// object, or you can call SkipObject() to skip to the end of the object
// immediately. If you fetch the entire object (i.e. NextObjectKey() returned  null),
// you should not call SkipObject().
//
// After calling EnterArray(), you must alternate between calling NextArrayValue()
// to see if the array has more data, and then retrieving values via the normal
// getters. You can call SkipArray() to skip to the end of the array immediately.
// If you fetch the entire array (i.e. NextArrayValue() returned null),
// you should not call SkipArray().
//
// This parser uses in-situ strings, so the JSON buffer will be altered during the
// parse.

using namespace rapidjson;


class LookaheadParserHandler {
public:
    bool Null() { st_ = kHasNull; v_.SetNull(); return true; }
    bool Bool(bool b) { st_ = kHasBool; v_.SetBool(b); return true; }
    bool Int(int i) { st_ = kHasNumber; v_.SetInt(i); return true; }
    bool Uint(unsigned u) { st_ = kHasNumber; v_.SetUint(u); return true; }
    bool Int64(int64_t i) { st_ = kHasNumber; v_.SetInt64(i); return true; }
    bool Uint64(uint64_t u) { st_ = kHasNumber; v_.SetUint64(u); return true; }
    bool Double(double d) { st_ = kHasNumber; v_.SetDouble(d); return true; }
    bool RawNumber(const char*, SizeType, bool) { return false; }
    bool String(const char* str, SizeType length, bool) { st_ = kHasString; v_.SetString(str, length); return true; }
    bool StartObject() { st_ = kEnteringObject; return true; }
    bool Key(const char* str, SizeType length, bool) { st_ = kHasKey; v_.SetString(str, length); return true; }
    bool EndObject(SizeType) { st_ = kExitingObject; return true; }
    bool StartArray() { st_ = kEnteringArray; return true; }
    bool EndArray(SizeType) { st_ = kExitingArray; return true; }

protected:
    LookaheadParserHandler(char* str);
    void ParseNext();

protected:
    enum LookaheadParsingState {
        kInit,
        kError,
        kHasNull,
        kHasBool,
        kHasNumber,
        kHasString,
        kHasKey,
        kEnteringObject,
        kExitingObject,
        kEnteringArray,
        kExitingArray
    };

    Value v_;
    LookaheadParsingState st_;
    Reader r_;
    InsituStringStream ss_;

    static const int parseFlags = kParseDefaultFlags | kParseInsituFlag;
};

LookaheadParserHandler::LookaheadParserHandler(char* str) : v_(), st_(kInit), r_(), ss_(str) {
    r_.IterativeParseInit();
    ParseNext();
}

void LookaheadParserHandler::ParseNext() {
    if (r_.HasParseError()) {
        st_ = kError;
        return;
    }

    if (!r_.IterativeParseNext<parseFlags>(ss_, *this)) {
        sgCritical<<"Lottie file parsing error";
        RAPIDJSON_ASSERT(0);
    }
}

class LottieParser : protected LookaheadParserHandler {
public:
    LottieParser(char* str) : LookaheadParserHandler(str) {}

    bool EnterObject();
    bool EnterArray();
    const char* NextObjectKey();
    bool NextArrayValue();
    int GetInt();
    double GetDouble();
    const char* GetString();
    bool GetBool();
    void GetNull();

    void SkipObject();
    void SkipArray();
    void SkipValue();
    Value* PeekValue();
    int PeekType(); // returns a rapidjson::Type, or -1 for no value (at end of object/array)

    bool IsValid() { return st_ != kError; }

    void Skip(const char *key);
    SGRect getRect();
    LottieBlendMode getBlendMode();
    CapStyle getLineCap();
    JoinStyle getLineJoin();
    LottieTrimObject::TrimType getTrimType();

    std::shared_ptr<LottieComposition> parseComposition();
    void parseLayers(LottieComposition *comp);
    std::shared_ptr<LottieObject> parseLayer();
    void parseShapesAttr(LottieLayer *layer);
    void parseObject(LottieGroupObject *parent);
    std::shared_ptr<LottieObject> parseObjectTypeAttr();
    std::shared_ptr<LottieObject> parseGroupObject();
    std::shared_ptr<LottieObject> parseRectObject();
    std::shared_ptr<LottieObject> parseEllipseObject();
    std::shared_ptr<LottieObject> parseShapeObject();

    std::shared_ptr<LottieObject> parseTransformObject();
    std::shared_ptr<LottieObject> parseFillObject();
    std::shared_ptr<LottieObject> parseGradientFillObject();
    std::shared_ptr<LottieObject> parseStrokeObject();
    std::shared_ptr<LottieObject> parseGradientStrokeObject();
    std::shared_ptr<LottieObject> parseTrimObject();
    std::shared_ptr<LottieObject> parseReapeaterObject();

    SGPointF parseInperpolatorPoint();
    void parseArrayValue(SGPointF &pt);
    void parseArrayValue(LottieColor &pt);
    void parseArrayValue(float &val);
    void parseArrayValue(int &val);
    void getValue(SGPointF &val);
    void getValue(float &val);
    void getValue(LottieColor &val);
    void getValue(int &val);
    void getValue(LottieShape &shape);
    template<typename T>
    void parseKeyFrame(LottieAnimInfo<T> &obj);
    template<typename T>
    void parseProperty(LottieAnimatable<T> &obj);

    void parseShapeKeyFrame(LottieAnimInfo<LottieShape> &obj);
    void parseShapeProperty(LottieAnimatable<LottieShape> &obj);
    void parseArrayValue(std::vector<SGPointF> &v);
protected:
    LottieComposition *compRef;
    void SkipOut(int depth);
};

bool LottieParser::EnterObject() {
    if (st_ != kEnteringObject) {
        st_  = kError;
        RAPIDJSON_ASSERT(false);
        return false;
    }

    ParseNext();
    return true;
}

bool LottieParser::EnterArray() {
    if (st_ != kEnteringArray) {
        st_  = kError;
        RAPIDJSON_ASSERT(false);
        return false;
    }

    ParseNext();
    return true;
}

const char* LottieParser::NextObjectKey() {
    if (st_ == kHasKey) {
        const char* result = v_.GetString();
        ParseNext();
        return result;
    }

    /* SPECIAL CASE
     * The parser works with a prdefined rule that it will be only
     * while (NextObjectKey()) for each object but in case of our nested group
     * object we can call multiple time NextObjectKey() while exiting the object
     * so ignore those and don't put parser in the error state.
     * */
    if (st_ == kExitingArray || st_ == kEnteringObject ) {
#ifdef DEBUG_PARSER
        sgDebug<<"Object: Exiting nested loop";
#endif
        return 0;
    }

    if (st_ != kExitingObject) {
        RAPIDJSON_ASSERT(false);
        st_ = kError;
        return 0;
    }

    ParseNext();
    return 0;
}

bool LottieParser::NextArrayValue() {
    if (st_ == kExitingArray) {
        ParseNext();
        return false;
    }

    /* SPECIAL CASE
     * same as  NextObjectKey()
     */
    if (st_ == kExitingObject) {
#ifdef DEBUG_PARSER
        sgDebug<<"Array: Exiting nested loop";
#endif
        return 0;
    }


    if (st_ == kError || st_ == kHasKey) {
        RAPIDJSON_ASSERT(false);
        st_ = kError;
        return false;
    }

    return true;
}

int LottieParser::GetInt() {
    if (st_ != kHasNumber || !v_.IsInt()) {
        st_ = kError;
        RAPIDJSON_ASSERT(false);
        return 0;
    }

    int result = v_.GetInt();
    ParseNext();
    return result;
}

double LottieParser::GetDouble() {
    if (st_ != kHasNumber) {
        st_  = kError;
        RAPIDJSON_ASSERT(false);
        return 0.;
    }

    double result = v_.GetDouble();
    ParseNext();
    return result;
}

bool LottieParser::GetBool() {
    if (st_ != kHasBool) {
        st_  = kError;
        RAPIDJSON_ASSERT(false);
        return false;
    }

    bool result = v_.GetBool();
    ParseNext();
    return result;
}

void LottieParser::GetNull() {
    if (st_ != kHasNull) {
        st_  = kError;
        return;
    }

    ParseNext();
}

const char* LottieParser::GetString() {
    if (st_ != kHasString) {
        st_  = kError;
        RAPIDJSON_ASSERT(false);
        return 0;
    }

    const char* result = v_.GetString();
    ParseNext();
    return result;
}

void LottieParser::SkipOut(int depth) {
    do {
        if (st_ == kEnteringArray || st_ == kEnteringObject) {
            ++depth;
        }
        else if (st_ == kExitingArray || st_ == kExitingObject) {
            --depth;
        }
        else if (st_ == kError) {
            RAPIDJSON_ASSERT(false);
            return;
        }

        ParseNext();
    }
    while (depth > 0);
}

void LottieParser::SkipValue() {
    SkipOut(0);
}

void LottieParser::SkipArray() {
    SkipOut(1);
}

void LottieParser::SkipObject() {
    SkipOut(1);
}

Value* LottieParser::PeekValue() {
    if (st_ >= kHasNull && st_ <= kHasKey) {
        return &v_;
    }

    return 0;
}

int LottieParser::PeekType() {
    if (st_ >= kHasNull && st_ <= kHasKey) {
        return v_.GetType();
    }

    if (st_ == kEnteringArray) {
        return kArrayType;
    }

    if (st_ == kEnteringObject) {
        return kObjectType;
    }

    return -1;
}

void LottieParser::Skip(const char *key)
{
    if (PeekType() == kArrayType) {
        EnterArray();
        SkipArray();
    } else if (PeekType() == kObjectType) {
        EnterObject();
        SkipObject();
    } else {
        SkipValue();
    }
}

LottieBlendMode
LottieParser::getBlendMode()
{
    RAPIDJSON_ASSERT(PeekType() == kNumberType);
    LottieBlendMode mode = LottieBlendMode::Normal;

    switch (GetInt()) {
    case 1:
        mode = LottieBlendMode::Multiply;
        break;
    case 2:
        mode = LottieBlendMode::Screen;
        break;
    case 3:
        mode = LottieBlendMode::OverLay;
        break;
    default:
        break;
    }
    return mode;
}
SGRect LottieParser::getRect()
{
    SGRect r;
    RAPIDJSON_ASSERT(PeekType() == kObjectType);
    EnterObject();
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "l")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            r.setLeft(GetInt());
        } else if (0 == strcmp(key, "r")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            r.setRight(GetInt());
        } else if (0 == strcmp(key, "t")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            r.setTop(GetInt());
        } else if (0 == strcmp(key, "b")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            r.setBottom(GetInt());
        } else {
            RAPIDJSON_ASSERT(false);
        }
    }
    return r;
}

std::shared_ptr<LottieComposition>
LottieParser::parseComposition()
{
    RAPIDJSON_ASSERT(PeekType() == kObjectType);
    EnterObject();
    std::shared_ptr<LottieComposition> sharedComposition = std::make_shared<LottieComposition>();
    LottieComposition *comp = sharedComposition.get();
    compRef = comp;
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "w")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            comp->mBound.setWidth(GetInt());
        } else if (0 == strcmp(key, "h")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            comp->mBound.setHeight(GetInt());
        } else if (0 == strcmp(key, "ip")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            comp->mStartFrame = GetDouble();
        } else if (0 == strcmp(key, "op")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            comp->mEndFrame = GetDouble();
        } else if (0 == strcmp(key, "fr")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            comp->mFrameRate = GetDouble();
        } else if (0 == strcmp(key, "layers")) {
            parseLayers(comp);
        } else {
#ifdef DEBUG_PARSER
            sgWarning<<"Composition Attribute Skipped : "<<key;
#endif
            Skip(key);
        }
    }
    // update the static property of Composition
    bool staticFlag = true;
    for (auto child : comp->mChildren) {
        staticFlag &= child.get()->isStatic();
    }
    comp->setStatic(staticFlag);

    return sharedComposition;
}

void LottieParser::parseLayers(LottieComposition *composition)
{
    RAPIDJSON_ASSERT(PeekType() == kArrayType);
    EnterArray();
    while (NextArrayValue()) {
        std::shared_ptr<LottieObject> layer = parseLayer();
        composition->mChildren.push_back(layer);
    }
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/layers/shape.json
 *
 */
std::shared_ptr<LottieObject>
LottieParser::parseLayer()
{
    RAPIDJSON_ASSERT(PeekType() == kObjectType);
    std::shared_ptr<LottieLayer> sharedLayer = std::make_shared<LottieLayer>();
    LottieLayer *layer = sharedLayer.get();
    EnterObject();
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "ty")) {    /* Type of layer: Shape. Value 4.*/
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mGroupType = GetInt();
        } else if (0 == strcmp(key, "ind")) { /*Layer index in AE. Used for parenting and expressions.*/
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mId = GetInt();
        } else if (0 == strcmp(key, "parent")) { /*Layer Parent. Uses "ind" of parent.*/
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mParentId = GetInt();
        }else if (0 == strcmp(key, "sr")) { // "Layer Time Stretching"
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mTimeStreatch = GetDouble();
        } else if (0 == strcmp(key, "ip")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mStartFrame = GetDouble();
        } else if (0 == strcmp(key, "op")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mEndFrame = GetDouble();
        }  else if (0 == strcmp(key, "st")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            layer->mStartTime = GetDouble();
        } else if (0 == strcmp(key, "bounds")) {
            layer->mBound = getRect();
        } else if (0 == strcmp(key, "bm")) {
            layer->mBlendMode = getBlendMode();
        } else if (0 == strcmp(key, "ks")) {
            RAPIDJSON_ASSERT(PeekType() == kObjectType);
            EnterObject();
            layer->mTransform = parseTransformObject();
        } else if (0 == strcmp(key, "shapes")) {
            parseShapesAttr(layer);
        } else {
    #ifdef DEBUG_PARSER
            sgWarning<<"Layer Attribute Skipped : "<<key;
    #endif
            Skip(key);
        }
    }
    // update the static property of layer
    bool staticFlag = true;
    for (auto child : layer->mChildren) {
        staticFlag &= child.get()->isStatic();
    }

    layer->setStatic(staticFlag &&
                     layer->mTransform->isStatic());

    return sharedLayer;
}

void LottieParser::parseShapesAttr(LottieLayer *layer)
{
    RAPIDJSON_ASSERT(PeekType() == kArrayType);
    EnterArray();
    while (NextArrayValue()) {
        parseObject(layer);
    }
}

std::shared_ptr<LottieObject>
LottieParser::parseObjectTypeAttr()
{
    RAPIDJSON_ASSERT(PeekType() == kStringType);
    const char *type = GetString();
    if (0 == strcmp(type, "gr")) {
        return parseGroupObject();
    } else if (0 == strcmp(type, "rc")) {
        return parseRectObject();
    } else if (0 == strcmp(type, "el")) {
        return parseEllipseObject();
    } else if (0 == strcmp(type, "tr")) {
        return parseTransformObject();
    } else if (0 == strcmp(type, "fl")) {
        return parseFillObject();
    } else if (0 == strcmp(type, "st")) {
        return parseStrokeObject();
    } else if (0 == strcmp(type, "sh")) {
        return parseShapeObject();
    }  else if (0 == strcmp(type, "tm")) {
        return parseTrimObject();
    } else if (0 == strcmp(type, "rp")) {
        return parseReapeaterObject();
    } else {
#ifdef DEBUG_PARSER
        sgDebug<<"The Object Type not yet handled = "<< type;
#endif
        return nullptr;
    }
}

void
LottieParser::parseObject(LottieGroupObject *parent)
{
    RAPIDJSON_ASSERT(PeekType() == kObjectType);
    EnterObject();
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "ty")) {
            auto child = parseObjectTypeAttr();
            if (child) {
                parent->mChildren.push_back(child);
            }
        } else {
            Skip(key);
        }
    }
}

std::shared_ptr<LottieObject>
LottieParser::parseGroupObject()
{
    std::shared_ptr<LottieShapeGroup> sharedGroup = std::make_shared<LottieShapeGroup>();

    LottieShapeGroup *group = sharedGroup.get();
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "it")) {
            RAPIDJSON_ASSERT(PeekType() == kArrayType);
            EnterArray();
            while (NextArrayValue()) {
                RAPIDJSON_ASSERT(PeekType() == kObjectType);
                parseObject(group);
            }
            group->mTransform = group->mChildren.back();
            group->mChildren.pop_back();
        } else {
            Skip(key);
        }
    }
    bool staticFlag = true;
    for (auto child : group->mChildren) {
        staticFlag &= child.get()->isStatic();
    }

    group->setStatic(staticFlag &&
                     group->mTransform->isStatic());

    return sharedGroup;
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/shapes/rect.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseRectObject()
{
    std::shared_ptr<LottieRectObject> sharedRect = std::make_shared<LottieRectObject>();
    LottieRectObject *obj = sharedRect.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "p")) {
            parseProperty(obj->mPos);
        } else if (0 == strcmp(key, "s")) {
            parseProperty(obj->mSize);
        } else if (0 == strcmp(key, "r")) {
            parseProperty(obj->mRound);
        }  else if (0 == strcmp(key, "d")) {
            Skip(key);
        } else {
            Skip(key);
        }
    }
    obj->setStatic(obj->mPos.isStatic() &&
                   obj->mSize.isStatic() &&
                   obj->mRound.isStatic());
    return sharedRect;
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/shapes/ellipse.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseEllipseObject()
{
    std::shared_ptr<LottieEllipseObject> sharedEllipse = std::make_shared<LottieEllipseObject>();
    LottieEllipseObject *obj = sharedEllipse.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "p")) {
            parseProperty(obj->mPos);
        } else if (0 == strcmp(key, "s")) {
            parseProperty(obj->mSize);
        } else {
            Skip(key);
        }
    }
    obj->setStatic(obj->mPos.isStatic() &&
                   obj->mSize.isStatic());
    return sharedEllipse;
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/properties/shape.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseShapeObject()
{
    std::shared_ptr<LottieShapeObject> sharedShape = std::make_shared<LottieShapeObject>();
    LottieShapeObject *obj = sharedShape.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "ks")) {
            parseShapeProperty(obj->mShape);
        }  else if (0 == strcmp(key, "closed")) {
            obj->mClosed = GetBool();
        } else {
#ifdef DEBUG_PARSER
            sgDebug<<"Shape property ignored :"<<key;
#endif
            Skip(key);
        }
    }
    obj->process();
    obj->setStatic(obj->mShape.isStatic());

    return sharedShape;
}

LottieTrimObject::TrimType
LottieParser::getTrimType()
{
    RAPIDJSON_ASSERT(PeekType() == kNumberType);
    switch (GetInt()) {
    case 1:
        return LottieTrimObject::TrimType::Simultaneously;
        break;
    case 2:
        return LottieTrimObject::TrimType::Individually;
        break;
    default:
        RAPIDJSON_ASSERT(0);
        break;
    }
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/shapes/trim.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseTrimObject()
{
    std::shared_ptr<LottieTrimObject> sharedTrim = std::make_shared<LottieTrimObject>();
    LottieTrimObject *obj = sharedTrim.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "s")) {
            parseProperty(obj->mStart);
        } else if (0 == strcmp(key, "e")) {
            parseProperty(obj->mEnd);
        } else if (0 == strcmp(key, "o")) {
            parseProperty(obj->mOffset);
        }  else if (0 == strcmp(key, "m")) {
            obj->mTrimType = getTrimType();
        } else {
#ifdef DEBUG_PARSER
            sgDebug<<"Trim property ignored :"<<key;
#endif
            Skip(key);
        }
    }
    obj->setStatic(obj->mStart.isStatic() &&
                   obj->mEnd.isStatic() &&
                   obj->mOffset.isStatic());

    return sharedTrim;
}

std::shared_ptr<LottieObject>
LottieParser::parseReapeaterObject()
{
    std::shared_ptr<LottieRepeaterObject> sharedRepeater = std::make_shared<LottieRepeaterObject>();
    LottieRepeaterObject *obj = sharedRepeater.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "c")) {
            parseProperty(obj->mCopies);
        } else if (0 == strcmp(key, "o")) {
            parseProperty(obj->mOffset);
        } else if (0 == strcmp(key, "tr")) {
            obj->mTransform = parseTransformObject();
        } else {
#ifdef DEBUG_PARSER
            sgDebug<<"Repeater property ignored :"<<key;
#endif
            Skip(key);
        }
    }
    obj->setStatic(obj->mCopies.isStatic() &&
                   obj->mOffset.isStatic() &&
                   obj->mTransform->isStatic());

    return sharedRepeater;
}


/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/shapes/transform.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseTransformObject()
{
    std::shared_ptr<LottieTransform> sharedTransform = std::make_shared<LottieTransform>();
    LottieTransform *obj = sharedTransform.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "a")) {
            parseProperty(obj->mAnchor);
        } else if (0 == strcmp(key, "p")) {
            parseProperty(obj->mPosition);
        } else if (0 == strcmp(key, "r")) {
            parseProperty(obj->mRotation);
        } else if (0 == strcmp(key, "s")) {
            parseProperty(obj->mScale);
        } else if (0 == strcmp(key, "sk")) {
            parseProperty(obj->mSkew);
        }  else if (0 == strcmp(key, "sa")) {
            parseProperty(obj->mSkewAxis);
        } else if (0 == strcmp(key, "o")) {
            parseProperty(obj->mOpacity);
        } else {
            Skip(key);
        }
    }
    obj->setStatic(obj->mAnchor.isStatic() &&
                   obj->mPosition.isStatic() &&
                   obj->mRotation.isStatic() &&
                   obj->mScale.isStatic() &&
                   obj->mSkew.isStatic() &&
                   obj->mSkewAxis.isStatic() &&
                   obj->mOpacity.isStatic() );

    return sharedTransform;
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/shapes/fill.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseFillObject()
{
    std::shared_ptr<LottieFillObject> sharedFill = std::make_shared<LottieFillObject>();
    LottieFillObject *obj = sharedFill.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "c")) {
            parseProperty(obj->mColor);
        } else if (0 == strcmp(key, "o")) {
            parseProperty(obj->mOpacity);
        } else if (0 == strcmp(key, "fillEnabled")) {
            obj->mEnabled = GetBool();
        } else {
#ifdef DEBUG_PARSER
            sgWarning<<"Fill property skipped = "<<key;
#endif
            Skip(key);
        }
    }
    obj->setStatic(obj->mColor.isStatic() &&
                   obj->mOpacity.isStatic());

    return sharedFill;
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/helpers/lineCap.json
 */
CapStyle LottieParser::getLineCap()
{
    RAPIDJSON_ASSERT(PeekType() == kNumberType);
    switch (GetInt()) {
    case 1:
        return CapStyle::Flat;
        break;
    case 2:
        return CapStyle::Round;
        break;
    default:
        return CapStyle::Square;
        break;
    }
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/helpers/lineJoin.json
 */
JoinStyle LottieParser::getLineJoin()
{
    RAPIDJSON_ASSERT(PeekType() == kNumberType);
    switch (GetInt()) {
    case 1:
        return JoinStyle::Miter;
        break;
    case 2:
        return JoinStyle::Round;
        break;
    default:
        return JoinStyle::Bevel;
        break;
    }
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/shapes/stroke.json
 */
std::shared_ptr<LottieObject>
LottieParser::parseStrokeObject()
{
    std::shared_ptr<LottieStrokeObject> sharedStroke = std::make_shared<LottieStrokeObject>();
    LottieStrokeObject *obj = sharedStroke.get();

    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "c")) {
            parseProperty(obj->mColor);
        } else if (0 == strcmp(key, "o")) {
            parseProperty(obj->mOpacity);
        } else if (0 == strcmp(key, "w")) {
            parseProperty(obj->mWidth);
        } else if (0 == strcmp(key, "fillEnabled")) {
            obj->mEnabled = GetBool();
        } else if (0 == strcmp(key, "lc")) {
            obj->mCapStyle = getLineCap();
        } else if (0 == strcmp(key, "lj")) {
            obj->mJoinStyle = getLineJoin();
        } else if (0 == strcmp(key, "ml")) {
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            obj->mMeterLimit = GetDouble();
        } else {
#ifdef DEBUG_PARSER
            sgWarning<<"Stroke property skipped = "<<key;
#endif
            Skip(key);
        }
    }
    obj->setStatic(obj->mColor.isStatic() &&
                   obj->mOpacity.isStatic() &&
                   obj->mWidth.isStatic());

    return sharedStroke;
}

void LottieParser::parseArrayValue(LottieColor &color)
{
    float val[4];
    int i=0;
    while (NextArrayValue()) {
        val[i++] = GetDouble();
    }

    color.r = val[0];
    color.g = val[1];
    color.b = val[2];
}

void LottieParser::parseArrayValue(SGPointF &pt)
{
    float val[4];
    int i=0;
    while (NextArrayValue()) {
        val[i++] = GetDouble();
    }
    pt.setX(val[0]);
    pt.setY(val[1]);
}

void LottieParser::parseArrayValue(float &val)
{
    val = GetDouble();
}

void LottieParser::parseArrayValue(int &val)
{
    val = GetInt();
}

void LottieParser::parseArrayValue(std::vector<SGPointF> &v)
{
    RAPIDJSON_ASSERT(PeekType() == kArrayType);
    EnterArray();
    while (NextArrayValue()) {
        RAPIDJSON_ASSERT(PeekType() == kArrayType);
        EnterArray();
        while (NextArrayValue()) {
            v.push_back(SGPointF(GetDouble(), GetDouble()));
        }
    }
}

void LottieParser::getValue(SGPointF &pt)
{
    float val[4];
    int i=0;
    RAPIDJSON_ASSERT(PeekType() == kArrayType);
    EnterArray();
    while (NextArrayValue()) {
        val[i++] = GetDouble();
    }
    pt.setX(val[0]);
    pt.setY(val[1]);
}

void LottieParser::getValue(float &val)
{
    RAPIDJSON_ASSERT(PeekType() == kArrayType);
    EnterArray();
    while (NextArrayValue()) {
        val = GetDouble();
    }
}

void LottieParser::getValue(LottieColor &color)
{
    float val[4];
    int i=0;
    RAPIDJSON_ASSERT(PeekType() == kArrayType);
    EnterArray();
    while (NextArrayValue()) {
        val[i++] = GetDouble();
    }
    color.r = val[0];
    color.g = val[1];
    color.b = val[2];
}

void LottieParser::getValue(int &val)
{
    RAPIDJSON_ASSERT(PeekType() == kNumberType);
    val = GetInt();
}

void LottieParser::getValue(LottieShape &obj)
{
    /*
     * The shape object could be wrapped by a array
     * if its part of the keyframe object
     */
    bool arrayWrapper = (PeekType() == kArrayType);
    if (arrayWrapper)
         EnterArray();

    RAPIDJSON_ASSERT(PeekType() == kObjectType);
    EnterObject();
    // make sure the shared_ptr is valid.
    if (!obj.mShapeData)
        obj.mShapeData = std::make_shared<LottieShapeData>();//(new LottieShapeData());
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "i")) {
            parseArrayValue(obj.mShapeData.get()->mInPoint);
        } else if (0 == strcmp(key, "o")) {
            parseArrayValue(obj.mShapeData.get()->mOutPoint);
        } else if (0 == strcmp(key, "v")) {
            parseArrayValue(obj.mShapeData.get()->mVertices);
        } else {
            RAPIDJSON_ASSERT(0);
            Skip(nullptr);
        }
    }
    // exit properly from the array
    if (arrayWrapper)
        NextArrayValue();
}

SGPointF
LottieParser::parseInperpolatorPoint()
{
    SGPointF cp;
    RAPIDJSON_ASSERT(PeekType() == kObjectType);
    EnterObject();
    while(const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "x")) {
            if (PeekType() == kNumberType) {
                cp.setX(GetDouble());
            } else {
                RAPIDJSON_ASSERT(PeekType() == kArrayType);
                EnterArray();
                while (NextArrayValue()) {
                    cp.setX(GetDouble());
                }
            }
        }
        if (0 == strcmp(key, "y")) {
            if (PeekType() == kNumberType) {
                cp.setY(GetDouble());
            } else {
                RAPIDJSON_ASSERT(PeekType() == kArrayType);
                EnterArray();
                while (NextArrayValue()) {
                    cp.setY(GetDouble());
                }
            }
        }
    }
    return cp;
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/properties/multiDimensionalKeyframed.json
 */
template<typename T>
void LottieParser::parseKeyFrame(LottieAnimInfo<T> &obj)
{
    EnterObject();
    LottieKeyFrame<T> keyframe;
    SGPointF inTangent;
    SGPointF outTangent;
    const char *interpolatorKey = nullptr;
     while (const char* key = NextObjectKey()) {
         if (0 == strcmp(key, "i")) {
             inTangent = parseInperpolatorPoint();
         } else if (0 == strcmp(key, "o")) {
             outTangent = parseInperpolatorPoint();
         } else if (0 == strcmp(key, "n")) {
             if (PeekType() == kStringType) {
                interpolatorKey = GetString();
             } else {
                RAPIDJSON_ASSERT(PeekType() == kArrayType);
                EnterArray();
                while (NextArrayValue()) {
                    RAPIDJSON_ASSERT(PeekType() == kStringType);
                    interpolatorKey = GetString();
                }
             }
             continue;
         } else if (0 == strcmp(key, "t")) {
             keyframe.mStartFrame = GetDouble();
         } else if (0 == strcmp(key, "s")) {
             getValue(keyframe.mStartValue);
             continue;
         } else if (0 == strcmp(key, "e")) {
             getValue(keyframe.mEndValue);
             continue;
         } else if (0 == strcmp(key, "ti")) {
             keyframe.mPathKeyFrame = true;
             getValue(keyframe.mInTangent);
             continue;
         } else if (0 == strcmp(key, "to")) {
             keyframe.mPathKeyFrame = true;
             getValue(keyframe.mOutTangent);
             continue;
         } else {
#ifdef DEBUG_PARSER
             sgDebug<<"key frame property skipped = "<<key;
#endif
             Skip(key);
         }
     }

     if (!obj.mKeyFrames.empty()) {
         // update the endFrame value of current keyframe
         obj.mKeyFrames.back().mEndFrame = keyframe.mStartFrame;
     }

     // Try to find the interpolator from cache
     if (interpolatorKey) {
         auto search = compRef->mInterpolatorCache.find(interpolatorKey);
         if (search != compRef->mInterpolatorCache.end()) {
             keyframe.mInterpolator = search->second;
         } else {
             keyframe.mInterpolator = std::make_shared<LottieInterpolater>();
             keyframe.mInterpolator.get()->mInTangent = inTangent;
             keyframe.mInterpolator.get()->mOutTangent = outTangent;
             compRef->mInterpolatorCache[interpolatorKey] = keyframe.mInterpolator;
         }
     } else {
         /* this is the last key frame just skip it  */
         return;
     }
   obj.mKeyFrames.push_back(keyframe);
}

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/properties/shapeKeyframed.json
 */

/*
 * https://github.com/airbnb/lottie-web/blob/master/docs/json/properties/shape.json
 */
void
LottieParser::parseShapeProperty(LottieAnimatable<LottieShape> &obj)
{
    EnterObject();
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "k")) {
            if (PeekType() == kArrayType) {
                EnterArray();
                while (NextArrayValue()) {
                    RAPIDJSON_ASSERT(PeekType() == kObjectType);
                    if (!obj.mAnimInfo)
                        obj.mAnimInfo = std::make_shared<LottieAnimInfo<LottieShape>>();
                    parseKeyFrame(*obj.mAnimInfo.get());
                }
            } else {
                getValue(obj.mValue);
            }
        } else {
#ifdef DEBUG_PARSER
            sgDebug<<"shape property ignored = "<<key;
#endif
            Skip(nullptr);
        }
    }
}

/*
 * https://github.com/airbnb/lottie-web/tree/master/docs/json/properties
 */
template<typename T>
void LottieParser::parseProperty(LottieAnimatable<T> &obj)
{
    EnterObject();
    while (const char* key = NextObjectKey()) {
        if (0 == strcmp(key, "k")) {
            if (PeekType() == kNumberType) {
                /*single value property with no animation*/
                parseArrayValue(obj.mValue);
            } else {
                RAPIDJSON_ASSERT(PeekType() == kArrayType);
                EnterArray();
                while (NextArrayValue()) {
                    /* property with keyframe info*/
                    if (PeekType() == kObjectType) {
                        if (!obj.mAnimInfo)
                            obj.mAnimInfo = std::make_shared<LottieAnimInfo<T>>();
                        parseKeyFrame(*obj.mAnimInfo.get());
                    } else {
                        /* Read before modifying.
                         * as there is no way of knowing if the
                         * value of the array is either array of numbers
                         * or array of object without entering the array
                         * thats why this hack is there
                         */
                        RAPIDJSON_ASSERT(PeekType() == kNumberType);
                        /*multi value property with no animation*/
                        parseArrayValue(obj.mValue);
                        /*break here as we already reached end of array*/
                        break;
                    }
                }
            }
        }  else if (0 == strcmp(key, "ix")){
            RAPIDJSON_ASSERT(PeekType() == kNumberType);
            obj.mPropertyIndex = GetInt();
        } else {
            Skip(key);
        }
    }
}

class LottieObjectInspector : public LottieObjectVisitor
{
public:
    void visit(LottieComposition *obj) {
        sgDebug<<"[COMP: START: static: "<<obj->isStatic()<<"[{ stFm endFm fmRate } { "<<obj->mStartFrame<<" "<<obj->mEndFrame<<" }]";
    }
    void visit(LottieLayer *obj) {
        sgDebug<<"[LAYER: "<<"type: "<<obj->mGroupType<<" id: "<<obj->mId<<" parent: "<<obj->mParentId
               <<" static:"<<obj->isStatic()<<"[{ stFm endFm stTm tmStrch } { "
               <<obj->mStartFrame<<" "<<obj->mEndFrame<<" "<<obj->mStartTime<<" "<<obj->mTimeStreatch <<" }]";
    }
    void visit(LottieTransform *t) {
        sgDebug<<"[TRANSFORM: static: "<<t->isStatic()<<" ]";
    }
    void visit(LottieShapeGroup *o) {
        sgDebug<<"[SHAPEGROP: START :   static: "<<o->isStatic()<<" ]";
    }
    void visit(LottieShapeObject *s) {
        sgDebug<<"[SHAPE: static: "<<s->isStatic()<<" pthOps: "<<s->mPathOperations.size()<<" pntOps: "<<s->mPaintOperations.size()<<" ]";
    }
    void visit(LottieRectObject *r) {
        sgDebug<<"[RECT:  static: "<<r->isStatic()<<" pthOps: "<<r->mPathOperations.size()<<" pntOps: "<<r->mPaintOperations.size()<<" ]";
    }
    void visit(LottieEllipseObject *e) {
        sgDebug<<"[ELLIPSE: static: "<<e->isStatic()<<" pthOps: "<<e->mPathOperations.size()<<" pntOps: "<<e->mPaintOperations.size()<<" ]";
    }
    void visit(LottieTrimObject *t) {
        sgDebug<<"[TRIM: static: "<<t->isStatic()<<" ]";
    }
    void visit(LottieRepeaterObject *r) {
        sgDebug<<"[REPEATER: static: "<<r->isStatic()<<" ]";
    }
    void visit(LottieFillObject *f) {
        sgDebug<<"[FILL: static: "<<f->isStatic()<<" ]";
    }
    void visit(LottieStrokeObject *s) {
        sgDebug<<"[STROKE: static: "<<s->isStatic()<<" ]";
    }
    void visitChildren(LottieGroupObject *obj) {
        for(auto child :obj->mChildren)
            child.get()->accept(this);
        switch (obj->type()) {
        case LottieObject::Type::Layer:
            sgDebug<<"[LAYER End ]";
            break;
        case LottieObject::Type::ShapeGroup:
            sgDebug<<"[SHAPEGROUP End ]";
            break;
        case LottieObject::Type::Composition:
            sgDebug<<"[COMP End ]";
            break;
        case LottieObject::Type::Repeater:
            sgDebug<<"[REPEATER End ]";
            break;
        default:
            break;
        }
    }
};

SGJson::SGJson(const char *data)
{
    SGElapsedTimer t;
    t.start();
    LottieParser r(const_cast<char *>(data));

    std::shared_ptr<LottieComposition> comp = r.parseComposition();
//#ifdef DEBUG_PARSER
    sgDebug<<"*******  Before processing *************\n";
    sgDebug<<" ";

    LottieObjectInspector inspector;
    comp.get()->accept(&inspector);
//#endif
    comp.get()->processPathOperatorObjects();
    comp.get()->processPaintOperatorObjects();
    comp.get()->processRepeaterObjects();

//#ifdef DEBUG_PARSER
    sgDebug<<" ";
    sgDebug<<"********  After Processing **********\n";
    comp.get()->accept(&inspector);
//#endif
    sgDebug<<" ";
    sgCritical<<"Parsing time = "<<t.elapsed()<<" ms";
}

RAPIDJSON_DIAG_POP