/** * @file lottie_player.c * @brief Lightweight Lottie animation player implementation for LVGL on ESP32 * * This implementation provides a minimal Lottie JSON parser and renderer * optimized for simple shape-based animations. It supports: * - Rounded rectangle shapes * - Position, size, and corner radius animation * - Keyframe interpolation with bezier easing * - Solid color fills * - Natural blink mode with random intervals * * The parser extracts only the data needed for rendering, minimizing memory * usage on resource-constrained embedded systems. */ #include "ui/lottie_player.h" #include "cJSON.h" #include "esp_heap_caps.h" #include "esp_log.h" #include "esp_random.h" #include "esp_timer.h" #include #include #include static const char *TAG = "lottie_player"; // ---------------------------------------------------------------------------- // Internal Type Definitions // ---------------------------------------------------------------------------- /** * Keyframe data structure for animated properties */ typedef struct { float time; float value[2]; float inTangent[2]; float outTangent[2]; bool hold; } LottieKeyframe; /** * Animated property that can have keyframes or static value */ typedef struct { bool animated; float staticValue[2]; LottieKeyframe keyframes[LOTTIE_MAX_KEYFRAMES]; uint8_t keyframeCount; } LottieProperty; /** * Rounded rectangle shape definition */ typedef struct { LottieProperty position; LottieProperty size; LottieProperty cornerRadius; lv_color_t fillColor; uint8_t fillOpacity; bool valid; } LottieRoundedRect; /** * Layer in the animation */ typedef struct { int index; int parent; int type; LottieProperty position; LottieProperty anchor; LottieRoundedRect shapes[LOTTIE_MAX_SHAPES]; uint8_t shapeCount; bool valid; } LottieLayer; /** * Main player state structure */ struct lottie_player_t { // Animation metadata uint16_t width; uint16_t height; float framerate; uint32_t totalFrames; uint32_t inPoint; uint32_t outPoint; // Layers LottieLayer layers[LOTTIE_MAX_LAYERS]; uint8_t layerCount; // Playback state float currentFrame; bool playing; bool loop; int64_t startTimeUs; // Natural blink mode bool naturalBlinkMode; lv_timer_t *blinkTimer; // LVGL objects lv_obj_t *canvas; lv_color_t *canvasBuffer; lv_timer_t *animTimer; }; // ---------------------------------------------------------------------------- // Forward Declarations // ---------------------------------------------------------------------------- static void parseAnimation(lottie_player_handle_t handle, const cJSON *root); static void parseLayers(lottie_player_handle_t handle, const cJSON *layers); static void parseLayer(LottieLayer *layer, const cJSON *json); static void parseShapes(LottieLayer *layer, const cJSON *shapes); static void parseProperty(LottieProperty *prop, const cJSON *json); static float interpolateProperty(const LottieProperty *prop, float frame, int index); static void renderFrame(lottie_player_handle_t handle); static void animTimerCallback(lv_timer_t *timer); static void blinkTimerCallback(lv_timer_t *timer); static void scheduleNextBlink(lottie_player_handle_t handle); static float bezierInterpolate(float t, float p0, float p1, float p2, float p3); static LottieLayer *getLayerByIndex(lottie_player_handle_t handle, int index); static void getLayerTransform(lottie_player_handle_t handle, LottieLayer *layer, float frame, float *offsetX, float *offsetY); static void drawRoundedRect(lottie_player_handle_t handle, lv_coord_t x, lv_coord_t y, lv_coord_t w, lv_coord_t h, lv_coord_t radius, lv_color_t color); // ---------------------------------------------------------------------------- // Public API Implementation // ---------------------------------------------------------------------------- lottie_player_handle_t lottieCreateFromData(lv_obj_t *parent, const char *jsonData) { if (!parent || !jsonData) { ESP_LOGE(TAG, "Invalid parameters"); return NULL; } // Parse JSON cJSON *root = cJSON_Parse(jsonData); if (!root) { ESP_LOGE(TAG, "Failed to parse JSON: %s", cJSON_GetErrorPtr()); return NULL; } // Allocate player structure lottie_player_handle_t handle = calloc(1, sizeof(struct lottie_player_t)); if (!handle) { ESP_LOGE(TAG, "Failed to allocate player"); cJSON_Delete(root); return NULL; } // Set defaults handle->playing = false; handle->loop = true; handle->currentFrame = 0; // Parse animation data parseAnimation(handle, root); cJSON_Delete(root); // Validate parsed data if (handle->width == 0 || handle->height == 0 || handle->totalFrames == 0) { ESP_LOGE(TAG, "Invalid animation data"); free(handle); return NULL; } ESP_LOGI(TAG, "Parsed animation: %dx%d, %lu frames at %.1f fps", handle->width, handle->height, (unsigned long)handle->totalFrames, handle->framerate); ESP_LOGI(TAG, "Loaded %d layers", handle->layerCount); // Allocate canvas buffer (prefer SPIRAM for large buffers) size_t bufSize = handle->width * handle->height * sizeof(lv_color_t); handle->canvasBuffer = heap_caps_malloc(bufSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); if (!handle->canvasBuffer) { handle->canvasBuffer = malloc(bufSize); } if (!handle->canvasBuffer) { ESP_LOGE(TAG, "Failed to allocate canvas buffer (%u bytes)", (unsigned)bufSize); free(handle); return NULL; } // Create LVGL canvas handle->canvas = lv_canvas_create(parent); lv_canvas_set_buffer(handle->canvas, handle->canvasBuffer, handle->width, handle->height, LV_IMG_CF_TRUE_COLOR); lv_obj_center(handle->canvas); // Speed up animation for snappier blinks (2x speed) handle->framerate *= 2.0f; // Create animation timer handle->animTimer = lv_timer_create(animTimerCallback, LOTTIE_TIMER_PERIOD_MS, handle); lv_timer_pause(handle->animTimer); // Enable natural blink mode by default handle->naturalBlinkMode = true; handle->loop = false; // Show idle state (last frame = eyes open) handle->currentFrame = handle->totalFrames - 1; renderFrame(handle); // Schedule first blink with random delay uint32_t initialDelay = LOTTIE_BLINK_MIN_MS + (esp_random() % (LOTTIE_BLINK_MAX_MS - LOTTIE_BLINK_MIN_MS)); handle->blinkTimer = lv_timer_create(blinkTimerCallback, initialDelay, handle); lv_timer_set_repeat_count(handle->blinkTimer, 1); ESP_LOGI(TAG, "Natural blink mode enabled, first blink in %lu ms", (unsigned long)initialDelay); return handle; } void lottiePlay(lottie_player_handle_t handle) { if (!handle) return; int64_t frameOffsetUs = (int64_t)(handle->currentFrame / handle->framerate * 1000000.0f); handle->startTimeUs = esp_timer_get_time() - frameOffsetUs; handle->playing = true; lv_timer_resume(handle->animTimer); } void lottiePause(lottie_player_handle_t handle) { if (!handle) return; handle->playing = false; lv_timer_pause(handle->animTimer); } void lottieStop(lottie_player_handle_t handle) { if (!handle) return; handle->playing = false; handle->currentFrame = 0; lv_timer_pause(handle->animTimer); renderFrame(handle); } void lottieSetLoop(lottie_player_handle_t handle, bool loop) { if (!handle) return; handle->loop = loop; } bool lottieIsPlaying(lottie_player_handle_t handle) { if (!handle) return false; return handle->playing; } uint32_t lottieGetCurrentFrame(lottie_player_handle_t handle) { if (!handle) return 0; return (uint32_t)handle->currentFrame; } uint32_t lottieGetTotalFrames(lottie_player_handle_t handle) { if (!handle) return 0; return handle->totalFrames; } void lottieSetFrame(lottie_player_handle_t handle, uint32_t frame) { if (!handle) return; if (frame >= handle->totalFrames) { frame = handle->totalFrames - 1; } handle->currentFrame = (float)frame; renderFrame(handle); } void lottieDestroy(lottie_player_handle_t handle) { if (!handle) return; if (handle->animTimer) { lv_timer_del(handle->animTimer); } if (handle->blinkTimer) { lv_timer_del(handle->blinkTimer); } if (handle->canvas) { lv_obj_del(handle->canvas); } if (handle->canvasBuffer) { free(handle->canvasBuffer); } free(handle); ESP_LOGI(TAG, "Lottie player destroyed"); } // ---------------------------------------------------------------------------- // JSON Parsing Implementation // ---------------------------------------------------------------------------- static void parseAnimation(lottie_player_handle_t handle, const cJSON *root) { cJSON *item; item = cJSON_GetObjectItem(root, "w"); if (item && cJSON_IsNumber(item)) { handle->width = (uint16_t)item->valueint; } item = cJSON_GetObjectItem(root, "h"); if (item && cJSON_IsNumber(item)) { handle->height = (uint16_t)item->valueint; } item = cJSON_GetObjectItem(root, "fr"); if (item && cJSON_IsNumber(item)) { handle->framerate = (float)item->valuedouble; } item = cJSON_GetObjectItem(root, "ip"); if (item && cJSON_IsNumber(item)) { handle->inPoint = (uint32_t)item->valueint; } item = cJSON_GetObjectItem(root, "op"); if (item && cJSON_IsNumber(item)) { handle->outPoint = (uint32_t)item->valueint; } handle->totalFrames = handle->outPoint - handle->inPoint; item = cJSON_GetObjectItem(root, "layers"); if (item && cJSON_IsArray(item)) { parseLayers(handle, item); } } static void parseLayers(lottie_player_handle_t handle, const cJSON *layers) { int count = cJSON_GetArraySize(layers); if (count > LOTTIE_MAX_LAYERS) { ESP_LOGW(TAG, "Truncating %d layers to %d", count, LOTTIE_MAX_LAYERS); count = LOTTIE_MAX_LAYERS; } handle->layerCount = 0; for (int i = 0; i < count; i++) { cJSON *layerJson = cJSON_GetArrayItem(layers, i); if (layerJson) { LottieLayer *layer = &handle->layers[handle->layerCount]; memset(layer, 0, sizeof(LottieLayer)); layer->parent = -1; parseLayer(layer, layerJson); if (layer->valid) { handle->layerCount++; } } } } static void parseLayer(LottieLayer *layer, const cJSON *json) { cJSON *item; item = cJSON_GetObjectItem(json, "ind"); if (item && cJSON_IsNumber(item)) { layer->index = item->valueint; } item = cJSON_GetObjectItem(json, "ty"); if (item && cJSON_IsNumber(item)) { layer->type = item->valueint; } item = cJSON_GetObjectItem(json, "parent"); if (item && cJSON_IsNumber(item)) { layer->parent = item->valueint; } cJSON *ks = cJSON_GetObjectItem(json, "ks"); if (ks) { item = cJSON_GetObjectItem(ks, "p"); if (item) { parseProperty(&layer->position, item); } item = cJSON_GetObjectItem(ks, "a"); if (item) { parseProperty(&layer->anchor, item); } } if (layer->type == 4) { item = cJSON_GetObjectItem(json, "shapes"); if (item && cJSON_IsArray(item)) { parseShapes(layer, item); } } layer->valid = true; } static void parseShapes(LottieLayer *layer, const cJSON *shapes) { int count = cJSON_GetArraySize(shapes); layer->shapeCount = 0; // Pass 1: Find fill color lv_color_t fillColor = lv_color_white(); uint8_t fillOpacity = 100; bool fillFound = false; for (int i = 0; i < count; i++) { cJSON *shape = cJSON_GetArrayItem(shapes, i); if (!shape) continue; cJSON *ty = cJSON_GetObjectItem(shape, "ty"); if (!ty || !cJSON_IsString(ty)) continue; const char *type = ty->valuestring; if (strcmp(type, "fl") == 0) { cJSON *c = cJSON_GetObjectItem(shape, "c"); if (c) { cJSON *k = cJSON_GetObjectItem(c, "k"); if (k && cJSON_IsArray(k) && cJSON_GetArraySize(k) >= 3) { float r = (float)cJSON_GetArrayItem(k, 0)->valuedouble; float g = (float)cJSON_GetArrayItem(k, 1)->valuedouble; float b = (float)cJSON_GetArrayItem(k, 2)->valuedouble; fillColor = lv_color_make((uint8_t)(r * 255), (uint8_t)(g * 255), (uint8_t)(b * 255)); fillFound = true; } } cJSON *o = cJSON_GetObjectItem(shape, "o"); if (o) { cJSON *k = cJSON_GetObjectItem(o, "k"); if (k && cJSON_IsNumber(k)) { fillOpacity = (uint8_t)k->valueint; } } break; } } if (!fillFound) { ESP_LOGW(TAG, "No fill found for layer, using default white"); } // Pass 2: Parse shapes for (int i = 0; i < count && layer->shapeCount < LOTTIE_MAX_SHAPES; i++) { cJSON *shape = cJSON_GetArrayItem(shapes, i); if (!shape) continue; cJSON *ty = cJSON_GetObjectItem(shape, "ty"); if (!ty || !cJSON_IsString(ty)) continue; const char *type = ty->valuestring; if (strcmp(type, "rc") == 0) { LottieRoundedRect *rect = &layer->shapes[layer->shapeCount]; memset(rect, 0, sizeof(LottieRoundedRect)); cJSON *p = cJSON_GetObjectItem(shape, "p"); if (p) parseProperty(&rect->position, p); cJSON *s = cJSON_GetObjectItem(shape, "s"); if (s) parseProperty(&rect->size, s); cJSON *r = cJSON_GetObjectItem(shape, "r"); if (r) parseProperty(&rect->cornerRadius, r); rect->fillColor = fillColor; rect->fillOpacity = fillOpacity; rect->valid = true; layer->shapeCount++; } } } static void parseProperty(LottieProperty *prop, const cJSON *json) { memset(prop, 0, sizeof(LottieProperty)); cJSON *a = cJSON_GetObjectItem(json, "a"); cJSON *k = cJSON_GetObjectItem(json, "k"); if (!k) return; if (a && cJSON_IsNumber(a) && a->valueint == 1) { prop->animated = true; if (cJSON_IsArray(k)) { int count = cJSON_GetArraySize(k); if (count > LOTTIE_MAX_KEYFRAMES) { count = LOTTIE_MAX_KEYFRAMES; } for (int i = 0; i < count; i++) { cJSON *kf = cJSON_GetArrayItem(k, i); if (!kf) continue; LottieKeyframe *keyframe = &prop->keyframes[prop->keyframeCount]; cJSON *t = cJSON_GetObjectItem(kf, "t"); if (t && cJSON_IsNumber(t)) { keyframe->time = (float)t->valuedouble; } cJSON *h = cJSON_GetObjectItem(kf, "h"); if (h && cJSON_IsNumber(h)) { keyframe->hold = h->valueint == 1; } cJSON *s = cJSON_GetObjectItem(kf, "s"); if (s && cJSON_IsArray(s)) { int vcount = cJSON_GetArraySize(s); for (int v = 0; v < vcount && v < 2; v++) { cJSON *val = cJSON_GetArrayItem(s, v); if (val && cJSON_IsNumber(val)) { keyframe->value[v] = (float)val->valuedouble; } } } cJSON *inTan = cJSON_GetObjectItem(kf, "i"); if (inTan) { cJSON *x = cJSON_GetObjectItem(inTan, "x"); cJSON *y = cJSON_GetObjectItem(inTan, "y"); if (x && cJSON_IsArray(x) && cJSON_GetArraySize(x) > 0) { keyframe->inTangent[0] = (float)cJSON_GetArrayItem(x, 0)->valuedouble; } else if (x && cJSON_IsNumber(x)) { keyframe->inTangent[0] = (float)x->valuedouble; } if (y && cJSON_IsArray(y) && cJSON_GetArraySize(y) > 0) { keyframe->inTangent[1] = (float)cJSON_GetArrayItem(y, 0)->valuedouble; } else if (y && cJSON_IsNumber(y)) { keyframe->inTangent[1] = (float)y->valuedouble; } } cJSON *outTan = cJSON_GetObjectItem(kf, "o"); if (outTan) { cJSON *x = cJSON_GetObjectItem(outTan, "x"); cJSON *y = cJSON_GetObjectItem(outTan, "y"); if (x && cJSON_IsArray(x) && cJSON_GetArraySize(x) > 0) { keyframe->outTangent[0] = (float)cJSON_GetArrayItem(x, 0)->valuedouble; } else if (x && cJSON_IsNumber(x)) { keyframe->outTangent[0] = (float)x->valuedouble; } if (y && cJSON_IsArray(y) && cJSON_GetArraySize(y) > 0) { keyframe->outTangent[1] = (float)cJSON_GetArrayItem(y, 0)->valuedouble; } else if (y && cJSON_IsNumber(y)) { keyframe->outTangent[1] = (float)y->valuedouble; } } prop->keyframeCount++; } } } else { prop->animated = false; if (cJSON_IsArray(k)) { int count = cJSON_GetArraySize(k); for (int i = 0; i < count && i < 2; i++) { cJSON *val = cJSON_GetArrayItem(k, i); if (val && cJSON_IsNumber(val)) { prop->staticValue[i] = (float)val->valuedouble; } } } else if (cJSON_IsNumber(k)) { prop->staticValue[0] = (float)k->valuedouble; } } } // ---------------------------------------------------------------------------- // Animation Interpolation // ---------------------------------------------------------------------------- static float bezierInterpolate(float t, float p0, float p1, float p2, float p3) { float u = 1.0f - t; float tt = t * t; float uu = u * u; float uuu = uu * u; float ttt = tt * t; float result = uuu * p0; result += 3.0f * uu * t * p1; result += 3.0f * u * tt * p2; result += ttt * p3; return result; } static float interpolateProperty(const LottieProperty *prop, float frame, int index) { if (!prop->animated) { return prop->staticValue[index]; } if (prop->keyframeCount == 0) { return 0.0f; } const LottieKeyframe *prev = NULL; const LottieKeyframe *next = NULL; for (int i = 0; i < prop->keyframeCount; i++) { if (prop->keyframes[i].time <= frame) { prev = &prop->keyframes[i]; } if (prop->keyframes[i].time >= frame && next == NULL) { next = &prop->keyframes[i]; } } if (!prev) { return prop->keyframes[0].value[index]; } if (!next || prev == next) { return prev->value[index]; } if (prev->hold) { return prev->value[index]; } float duration = next->time - prev->time; if (duration <= 0) { return prev->value[index]; } float t = (frame - prev->time) / duration; if (prev->outTangent[0] != 0 || prev->outTangent[1] != 0 || next->inTangent[0] != 0 || next->inTangent[1] != 0) { t = bezierInterpolate(t, 0.0f, prev->outTangent[1], next->inTangent[1], 1.0f); t = fmaxf(0.0f, fminf(1.0f, t)); } return prev->value[index] + t * (next->value[index] - prev->value[index]); } // ---------------------------------------------------------------------------- // Rendering // ---------------------------------------------------------------------------- static LottieLayer *getLayerByIndex(lottie_player_handle_t handle, int index) { for (int i = 0; i < handle->layerCount; i++) { if (handle->layers[i].index == index) { return &handle->layers[i]; } } return NULL; } static void getLayerTransform(lottie_player_handle_t handle, LottieLayer *layer, float frame, float *offsetX, float *offsetY) { *offsetX = 0; *offsetY = 0; LottieLayer *current = layer; while (current) { float posX = interpolateProperty(¤t->position, frame, 0); float posY = interpolateProperty(¤t->position, frame, 1); float ancX = interpolateProperty(¤t->anchor, frame, 0); float ancY = interpolateProperty(¤t->anchor, frame, 1); *offsetX += posX - ancX; *offsetY += posY - ancY; if (current->parent >= 0) { current = getLayerByIndex(handle, current->parent); } else { current = NULL; } } } static void drawRoundedRect(lottie_player_handle_t handle, lv_coord_t x, lv_coord_t y, lv_coord_t w, lv_coord_t h, lv_coord_t radius, lv_color_t color) { lv_draw_rect_dsc_t rectDsc; lv_draw_rect_dsc_init(&rectDsc); rectDsc.bg_color = color; rectDsc.bg_opa = LV_OPA_COVER; rectDsc.radius = radius; rectDsc.border_width = 0; lv_canvas_draw_rect(handle->canvas, x - w / 2, y - h / 2, w, h, &rectDsc); } static void renderFrame(lottie_player_handle_t handle) { static bool firstFrameLogged = false; lv_canvas_fill_bg(handle->canvas, lv_color_black(), LV_OPA_COVER); float frame = handle->currentFrame + handle->inPoint; // Render layers in reverse order (last layer = bottom) for (int i = handle->layerCount - 1; i >= 0; i--) { LottieLayer *layer = &handle->layers[i]; if (!layer->valid || layer->type != 4) { continue; } float offsetX = 0, offsetY = 0; getLayerTransform(handle, layer, frame, &offsetX, &offsetY); for (int s = 0; s < layer->shapeCount; s++) { LottieRoundedRect *rect = &layer->shapes[s]; if (!rect->valid) continue; float px = interpolateProperty(&rect->position, frame, 0); float py = interpolateProperty(&rect->position, frame, 1); float w = interpolateProperty(&rect->size, frame, 0); float h = interpolateProperty(&rect->size, frame, 1); float r = interpolateProperty(&rect->cornerRadius, frame, 0); px += offsetX; py += offsetY; if (!firstFrameLogged) { ESP_LOGI(TAG, "Layer %d shape %d: pos=(%.1f,%.1f) size=(%.1f,%.1f)", layer->index, s, px, py, w, h); } if (w > 0 && h > 0) { drawRoundedRect(handle, (lv_coord_t)px, (lv_coord_t)py, (lv_coord_t)w, (lv_coord_t)h, (lv_coord_t)r, rect->fillColor); } } } if (!firstFrameLogged) { firstFrameLogged = true; } lv_obj_invalidate(handle->canvas); } // ---------------------------------------------------------------------------- // Timer Callbacks // ---------------------------------------------------------------------------- static void animTimerCallback(lv_timer_t *timer) { lottie_player_handle_t handle = (lottie_player_handle_t)timer->user_data; if (!handle || !handle->playing) { return; } int64_t nowUs = esp_timer_get_time(); int64_t elapsedUs = nowUs - handle->startTimeUs; float elapsedSec = (float)elapsedUs / 1000000.0f; float frame = elapsedSec * handle->framerate; if (frame >= handle->totalFrames) { if (handle->loop) { float cycles = frame / handle->totalFrames; int fullCycles = (int)cycles; handle->startTimeUs += (int64_t)(fullCycles * handle->totalFrames / handle->framerate * 1000000.0f); frame = frame - (fullCycles * handle->totalFrames); } else { ESP_LOGI(TAG, "Blink animation complete"); handle->playing = false; lv_timer_pause(handle->animTimer); handle->currentFrame = handle->totalFrames - 1; renderFrame(handle); if (handle->naturalBlinkMode) { scheduleNextBlink(handle); } return; } } handle->currentFrame = frame; renderFrame(handle); } static void scheduleNextBlink(lottie_player_handle_t handle) { if (!handle || !handle->naturalBlinkMode) { return; } uint32_t delayMs = LOTTIE_BLINK_MIN_MS + (esp_random() % (LOTTIE_BLINK_MAX_MS - LOTTIE_BLINK_MIN_MS)); handle->blinkTimer = lv_timer_create(blinkTimerCallback, delayMs, handle); lv_timer_set_repeat_count(handle->blinkTimer, 1); } static void blinkTimerCallback(lv_timer_t *timer) { lottie_player_handle_t handle = (lottie_player_handle_t)timer->user_data; if (handle) { handle->blinkTimer = NULL; } if (!handle || !handle->naturalBlinkMode) { return; } ESP_LOGI(TAG, "Blink triggered"); handle->currentFrame = 0; lottiePlay(handle); }