/** * @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; /** * Cached shape bounds for dirty rect optimization */ typedef struct { lv_coord_t x1, y1, x2, y2; // Bounding box corners bool valid; } ShapeBounds; // Maximum cached shapes for dirty rect tracking #define LOTTIE_MAX_CACHED_SHAPES (LOTTIE_MAX_LAYERS * LOTTIE_MAX_SHAPES) /** * Main player state structure */ struct lottie_player_t { // Animation metadata uint16_t width; uint16_t height; float framerate; float nativeFramerate; // Original framerate from JSON 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; // Dirty rect optimization - cache previous frame shape bounds ShapeBounds prevBounds[LOTTIE_MAX_CACHED_SHAPES]; int prevBoundsCount; bool firstRender; // Skip dirty optimization on first frame }; // ---------------------------------------------------------------------------- // 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; handle->firstRender = true; handle->prevBoundsCount = 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; } void lottieDisableNaturalBlink(lottie_player_handle_t handle) { if (!handle) return; // Delete the blink timer if it exists if (handle->blinkTimer) { lv_timer_del(handle->blinkTimer); handle->blinkTimer = NULL; } handle->naturalBlinkMode = false; ESP_LOGI(TAG, "Natural blink mode disabled"); } void lottiePauseNaturalBlink(lottie_player_handle_t handle) { if (!handle || !handle->blinkTimer) return; lv_timer_pause(handle->blinkTimer); ESP_LOGI(TAG, "Natural blink timer paused"); } void lottieResumeNaturalBlink(lottie_player_handle_t handle) { if (!handle || !handle->blinkTimer) return; lv_timer_resume(handle->blinkTimer); ESP_LOGI(TAG, "Natural blink timer resumed"); } 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 lottieSetSpeed(lottie_player_handle_t handle, float speed) { if (!handle || speed <= 0) return; // Use native framerate as base and apply speed multiplier handle->framerate = handle->nativeFramerate * speed; ESP_LOGI(TAG, "Playback speed set to %.1fx (%.1f fps)", speed, handle->framerate); } 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; handle->nativeFramerate = handle->framerate; // Store native before any modifications } 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) { float frame = handle->currentFrame + handle->inPoint; // Combined dirty area for partial invalidation lv_area_t dirtyArea; bool hasDirty = false; // Helper macro to expand dirty area (parameters named differently to avoid // conflict) #define EXPAND_DIRTY(_ax1, _ay1, _ax2, _ay2) \ do { \ if (!hasDirty) { \ dirtyArea.x1 = (_ax1); \ dirtyArea.y1 = (_ay1); \ dirtyArea.x2 = (_ax2); \ dirtyArea.y2 = (_ay2); \ hasDirty = true; \ } else { \ if ((_ax1) < dirtyArea.x1) \ dirtyArea.x1 = (_ax1); \ if ((_ay1) < dirtyArea.y1) \ dirtyArea.y1 = (_ay1); \ if ((_ax2) > dirtyArea.x2) \ dirtyArea.x2 = (_ax2); \ if ((_ay2) > dirtyArea.y2) \ dirtyArea.y2 = (_ay2); \ } \ } while (0) // Collect current frame shape bounds ShapeBounds currBounds[LOTTIE_MAX_CACHED_SHAPES]; int currCount = 0; // First pass: calculate all current shape bounds 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 || currCount >= LOTTIE_MAX_CACHED_SHAPES) continue; float px = interpolateProperty(&rect->position, frame, 0) + offsetX; float py = interpolateProperty(&rect->position, frame, 1) + offsetY; float w = interpolateProperty(&rect->size, frame, 0); float h = interpolateProperty(&rect->size, frame, 1); if (w > 0 && h > 0) { currBounds[currCount].x1 = (lv_coord_t)(px - w / 2); currBounds[currCount].y1 = (lv_coord_t)(py - h / 2); currBounds[currCount].x2 = (lv_coord_t)(px + w / 2); currBounds[currCount].y2 = (lv_coord_t)(py + h / 2); currBounds[currCount].valid = true; currCount++; } } } // On first render, do full clear and full invalidate if (handle->firstRender) { lv_canvas_fill_bg(handle->canvas, lv_color_black(), LV_OPA_COVER); handle->firstRender = false; lv_obj_invalidate(handle->canvas); // Cache bounds for next frame for (int i = 0; i < currCount && i < LOTTIE_MAX_CACHED_SHAPES; i++) { handle->prevBounds[i] = currBounds[i]; } handle->prevBoundsCount = currCount; // Draw shapes 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) + offsetX; float py = interpolateProperty(&rect->position, frame, 1) + offsetY; float w = interpolateProperty(&rect->size, frame, 0); float h = interpolateProperty(&rect->size, frame, 1); float r = interpolateProperty(&rect->cornerRadius, frame, 0); 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); } } } return; } // Clear previous shape positions and track dirty areas lv_draw_rect_dsc_t clearDsc; lv_draw_rect_dsc_init(&clearDsc); clearDsc.bg_color = lv_color_black(); clearDsc.bg_opa = LV_OPA_COVER; clearDsc.radius = 0; clearDsc.border_width = 0; for (int i = 0; i < handle->prevBoundsCount; i++) { if (!handle->prevBounds[i].valid) continue; ShapeBounds *prev = &handle->prevBounds[i]; // Check if shape moved bool needsClear = true; if (i < currCount && currBounds[i].valid) { ShapeBounds *curr = &currBounds[i]; if (prev->x1 == curr->x1 && prev->y1 == curr->y1 && prev->x2 == curr->x2 && prev->y2 == curr->y2) { needsClear = false; // Shape didn't move } } if (needsClear) { lv_coord_t pw = prev->x2 - prev->x1; lv_coord_t ph = prev->y2 - prev->y1; if (pw > 0 && ph > 0) { lv_canvas_draw_rect(handle->canvas, prev->x1, prev->y1, pw, ph, &clearDsc); EXPAND_DIRTY(prev->x1, prev->y1, prev->x2, prev->y2); } } } // Draw current shapes and track dirty areas int shapeIdx = 0; 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) + offsetX; float py = interpolateProperty(&rect->position, frame, 1) + offsetY; float w = interpolateProperty(&rect->size, frame, 0); float h = interpolateProperty(&rect->size, frame, 1); float r = interpolateProperty(&rect->cornerRadius, frame, 0); if (w > 0 && h > 0) { lv_coord_t cx1 = (lv_coord_t)(px - w / 2); lv_coord_t cy1 = (lv_coord_t)(py - h / 2); lv_coord_t cx2 = (lv_coord_t)(px + w / 2); lv_coord_t cy2 = (lv_coord_t)(py + h / 2); drawRoundedRect(handle, (lv_coord_t)px, (lv_coord_t)py, (lv_coord_t)w, (lv_coord_t)h, (lv_coord_t)r, rect->fillColor); // Check if this shape moved from previous position if (shapeIdx < handle->prevBoundsCount && handle->prevBounds[shapeIdx].valid) { ShapeBounds *prev = &handle->prevBounds[shapeIdx]; if (cx1 != prev->x1 || cy1 != prev->y1 || cx2 != prev->x2 || cy2 != prev->y2) { EXPAND_DIRTY(cx1, cy1, cx2, cy2); } } else { // New shape EXPAND_DIRTY(cx1, cy1, cx2, cy2); } } shapeIdx++; } } // Cache current bounds for next frame for (int i = 0; i < currCount && i < LOTTIE_MAX_CACHED_SHAPES; i++) { handle->prevBounds[i] = currBounds[i]; } handle->prevBoundsCount = currCount; // Partial invalidation - only refresh the dirty area via DMA if (hasDirty) { // Clamp to canvas bounds if (dirtyArea.x1 < 0) dirtyArea.x1 = 0; if (dirtyArea.y1 < 0) dirtyArea.y1 = 0; if (dirtyArea.x2 >= handle->width) dirtyArea.x2 = handle->width - 1; if (dirtyArea.y2 >= handle->height) dirtyArea.y2 = handle->height - 1; lv_obj_invalidate_area(handle->canvas, &dirtyArea); } #undef EXPAND_DIRTY } // ---------------------------------------------------------------------------- // 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); }