Application Lifecycle and Threading
This document is the application-facing contract for starting, updating, synchronizing and stopping an ESP-GSP UI on ESP-IDF.
Recommended API layers
Section titled “Recommended API layers”Use the narrowest layer that fits the application:
- Include the generated
<symbol>_gsp.hbundle header. - Start from
gsp_<symbol>_config(). - Use generated
gsp_<scene>_<object>_*()functions for named controls. - Use
esp_gsp_on_event()with the generated scene event decoder. - Use the generic image, canvas, list or navigation APIs only when the generated object API does not cover the operation.
The bind, stable-key/property and raw widget/template APIs remain available for compatibility, editors and data-driven bridges. They are not separate application startup paths.
Load a UI bundle independently of firmware
Section titled “Load a UI bundle independently of firmware”For a first USB upload on an ESP32-P4, ESP32-S3 or ESP32-S31 display board, follow the device live reload example.
Once the firmware includes a bundle loader, you can change layouts, styles and declarative animations by repacking the scenes. New native C callbacks still require a firmware build. From the repository root, this command packs the 1024×600 Hello World scene for an ESP32-P4 RGB565 display.
gspc pack examples/usage/hello_world/scenes/hello_1024.json \ --profile config/profiles/esp32p4_rgb565.yaml --deployable -o hello.gspb- Deliver
hello.gspbusing the application’s USB receiver or storage reader. The application also manages any flash partitions, authentication and rollback. - Include
esp_gsp_deployable.hand open the complete, 64-byte-aligned buffer withesp_gsp_deployable_bundle_open(data, size, true, &bundle)to verify its CRC. Useesp_gsp_deployable_bundle_make_config(bundle, &config)to obtain the configuration foresp_gsp_esp_lcd_start(). - Keep the buffer immutable and the bundle handle open for the life of the UI.
After the UI is destroyed, call
esp_gsp_deployable_bundle_close(bundle), then release the buffer.
To reuse a C callback across UI versions, keep its authored name and use
esp_gsp_deployable_bundle_action_key() to map each scene’s action ID to that stable key.
To replace a temporary UI on an existing LCD session, match its logical width,
height and pixel format and use esp_gsp_esp_lcd_replace_on_session_prepared_ex().
Check the session outcome before releasing the previous bundle.
See suspend, replace and resume.
Configuration lifetime
Section titled “Configuration lifetime”gsp_<symbol>_config() initializes esp_gsp_config_t.struct_size, the
embedded bundle and every generated component directory. Applications that
construct the configuration manually should start from
ESP_GSP_CONFIG_INIT().
The ESP-LCD adapter configuration should start from
ESP_GSP_ESP_LCD_CONFIG_INIT():
esp_gsp_config_t app_config = gsp_bundle_config();
esp_gsp_esp_lcd_config_t lcd_config = ESP_GSP_ESP_LCD_CONFIG_INIT();lcd_config.display = display;lcd_config.touch = touch;
esp_gsp_handle_t ui;ESP_ERROR_CHECK(esp_gsp_esp_lcd_start( &app_config, &lcd_config, &ui));The runtime also accepts a zero struct_size from aggregate-zero initialized
configurations. A nonzero size must match the public structure used by the
current component.
Keep bundle bytes, generated component directories, optional outline-font bytes,
borrowed font catalogs and their backing data valid for the life of the UI.
For a standalone UI, this includes the call to esp_gsp_stop() until it succeeds.
Treat compiled bundle bytes as immutable. Startup may reuse successful CRC checks for scenes and shared embedded images and fonts within that load; structure and bounds checks still run. Verification results are not retained across UI instances, and external font catalogs are checked separately.
Submission and committed state
Section titled “Submission and committed state”ESP-IDF acceleration is shared by UI instances. The first active reference sets its policy; later references retain that policy and keep the backend alive. Use matching acceleration settings across simultaneous instances. Release all instances before changing the shared policy; a failed startup does not change the policy of an existing instance.
State setters are asynchronous on ESP-IDF:
application task -> command queue -> render task -> state commit -> renderA successful setter confirms command admission. The render task commits queued
changes and schedules the resulting redraws. The normal queue admission wait is bounded; queue
pressure is returned as ESP_GSP_ERR_TIMEOUT.
Getters read the committed state of the current scene. A setter followed immediately by a getter from another task may still observe the previous value.
Use esp_gsp_component_set_many() or
esp_gsp_component_set_properties() when related scalar properties must
become visible atomically.
Synchronization fence
Section titled “Synchronization fence”esp_gsp_flush(ui, timeout_ms) is a low-frequency fence. It waits until
commands submitted before the call have been applied and the display backend
has completed the following render attempt.
Use it for deterministic tests, screenshots or an orderly state boundary:
ESP_ERROR_CHECK(gsp_dashboard_load_set_value(ui, 80));ESP_ERROR_CHECK(esp_gsp_flush(ui, 250));Do not put esp_gsp_flush() in an animation or telemetry loop. It preserves
the asynchronous setter model and is invalid from render- or decode-task callbacks.
Portable apps without an asynchronous platform adapter already apply commands
directly, so the fence completes immediately. Render failures remain available
through esp_gsp_render_error_stats(); the fence reports synchronization
status, not the render result. A timeout does not cancel a fence that was
already accepted by the command queue.
A background image replacement can still be decoding when the fence completes.
Wait for its image-completion callback to report GSP_OK before using a flush
to synchronize a capture of that replacement.
Callback contexts
Section titled “Callback contexts”The following callbacks run on the render task and must stay short and non-blocking:
- application events registered with
esp_gsp_on_event(); - framework timers;
- list row binders and scroll callbacks;
- image completion callbacks that complete on the render task;
- canvas release callbacks.
Generated setters may be called from these callbacks; the render task applies
them directly. Canvas direct-draw callbacks are the exception: they run inside
an active renderer frame, so APIs that change GSP state return
ESP_GSP_ERR_INVALID_STATE. Do not wait for esp_gsp_flush() or call
esp_gsp_stop() from render- or decode-task callbacks. Defer shutdown and
blocking work to an application task; direct-draw state changes must also be
deferred until the draw callback has returned.
Image decode completion may also run on the decode task. Completion and release callbacks must not assume application-task context.
Replacing or resuming a temporary app waits for its active decode and source release before destroying the app. Keep these callbacks short; this wait does not hold the render task’s cache lock.
Image and canvas ownership
Section titled “Image and canvas ownership”esp_gsp_set_image()copies the encoded input before returning.esp_gsp_set_image_borrowed()borrows the input until its release callback.esp_gsp_set_image_owned()takes malloc-compatible storage after a successful submission.esp_gsp_set_image_ex()selects COPY, BORROW or TAKE explicitly.- Canvas frames remain borrowed until their release callbacks run.
- A Canvas direct-draw callback runs synchronously in render-task context. Its surface pointer is valid only during that call and must not be retained. It must fill every supplied region and keep partitioned calls for one repaint visually coherent.
A borrowed or taken payload is held while its image is the one on screen, not merely until it decodes: under memory pressure the cache may drop the decoded pixels and decode again from the encoded bytes. The release therefore lands when the next image for that bind is adopted, or at shutdown. Budget for that published payload plus accepted replacements still queued, decoding or awaiting publication. Cancellation can also retain a payload until an in-flight decode releases it. Reuse each borrowed buffer only after its own release callback.
A bind keeps showing its current image for the whole time a replacement is decoding, and keeps it if that decode fails. An update is visible in one step or not at all, so applications never need to pre-load a placeholder to avoid a flash.
If a borrowed or TAKE submission returns an error immediately, ownership remains with the caller and no later release callback follows.
esp_gsp_canvas_stop() is asynchronous. Wait for esp_gsp_flush() to succeed
before freeing the direct-draw callback context. Borrowed frames can be reused
or freed after their release callbacks run.
List binding lifetime
Section titled “List binding lifetime”Bind each logical List or Wheel once and retain the returned handle for the life of the UI instance. A binding persists across scene changes: the runtime parks its rows while the owning scene or PageFlow page is hidden, then reactivates them when it becomes visible again.
Do not call esp_gsp_list_bind_component() from every scene-ready event.
Repeated binding allocates another entry from the configured list pool
(CONFIG_ESP_GSP_MAX_LISTS, default 0/AUTO from bundled bindings) and eventually returns
ESP_GSP_LIST_NONE. Use esp_gsp_list_set_total() when the item count changes
and esp_gsp_list_refresh() when visible row data changes. The current API has
no unbind operation; all bindings are released by esp_gsp_stop().
Shutdown
Section titled “Shutdown”Call esp_gsp_stop() from an application task. It requests render-task
shutdown, drains display callbacks, stops background decode and releases the
UI instance. It can return ESP_GSP_ERR_TIMEOUT; the handle remains owned by
the application and shutdown may be retried.
After esp_gsp_stop() succeeds, the handle and every framework-owned callback
registration are invalid.
Pause and resume the same application
Section titled “Pause and resume the same application”esp_gsp_esp_lcd_pause() pauses the active UI and waits for the presenter
fences without destroying the application. Keep its pause token and resume
that exact app with esp_gsp_esp_lcd_resume_paused(); this also applies to a
temporary app on a retained hub session.
On ESP_ERR_TIMEOUT, continue using the original UI. out_pause is NULL.
If pause returns ESP_ERR_NOT_FINISHED, rollback failed and out_pause
contains a valid token for retrying resume_paused(). This is not a successful
display handoff: transfer/present fences may still be outstanding, so do not
give the display to another producer. Other pause failures do not transfer a
token. A failed resume keeps the token and original app alive for retry;
successful resume consumes it. Keep borrowed resources alive throughout.
ESP-IDF Light-sleep
Section titled “ESP-IDF Light-sleep”Call esp_gsp_esp_lcd_set_event_driven_idle(ui, true) after startup to let
an idle UI wait for commands, input or its next deadline. Active animation,
polling touch and display retries keep their service cadence. The application
owns ESP-IDF power management and hardware wakeup sources.
For application-managed standby, serialize the following operations from the application task.
- Quiesce application-owned producers and storage I/O, then call
esp_gsp_esp_lcd_prepare_sleep(). The token retains the scene and control state while GSP drains its renderer, decoder, presenter and accelerator. - To release a panel or touch controller, call
esp_gsp_esp_lcd_detach_paused()before the BSP tears down those handles. The owner of a borrowed presenter stops and releases it. - Restore any powered-down resource readers. Reinitialize the display and
call
esp_gsp_esp_lcd_rebind_paused()if detached.esp_gsp_esp_lcd_resume_paused()restores the same UI and forces a full redraw. Useesp_gsp_esp_lcd_resume_paused_prepared()to register a frame completion request before that redraw.
prepare_sleep() certifies standby readiness on ESP_OK. On
ESP_ERR_NOT_FINISHED, retain the token and retry resume. Send UI commands
again after resume succeeds and consumes the token. A partial detach needs
the same token and hardware for a detach retry. Detach cancels pending
confirmations for the old display. A failed first redraw can repeat the
prepared callback on retry, so register callbacks and timers idempotently.
The application owns standby wake deadlines. Each overdue UI timer fires
once after resume and then follows its normal period. The ESP32-P4 standby
example was verified with esp_display_present 1.2.4. Use 1.2.4 or later to
recover partial updates after a cancelled frame or rejected panel submission.
- Configure the board’s Light-sleep wake source separately from
touch_wake_from_isr, which notifies the application when an attached touch controller interrupts. To consume the wake touch, clear the controller report and wait for release before resuming the UI. A detached or unpowered controller needs a wake path supplied by the BSP. - The ESP32-S3 ESP-IDF RGB panel driver holds a PM lock while the panel exists. Detach GSP, delete the RGB panel in the BSP, and rebuild it on wake. Turning off the backlight leaves the lock held.
- Streamed fonts and EAF4 playback need the original mount and open files to remain valid across standby. Close the streams before remounting. A paused UI still borrows its streamed fonts. If the board powers off their storage, use fonts loaded into memory or stop the UI before remounting.
See the Light-sleep example for retained QSPI and rebuilt MIPI-DSI displays.
Suspend and temporary applications
Section titled “Suspend and temporary applications”The ESP-LCD adapter can retain one hub UI and its LCD render task while a temporary bundle uses the same display host:
hub -> suspend -> session -> start temporary app -> stop app and resume hubCall esp_gsp_esp_lcd_suspend() from an application task. On success the hub
runtime, scene and component state remain owned by the returned session, while
decoded image surfaces are released. Do not submit work through the suspended
hub handle.
Before esp_gsp_esp_lcd_start_on_session*(), an application needing more memory
can explicitly call esp_gsp_esp_lcd_trim_session(session, timeout_ms, &released_bytes) on the suspended session. Use esp_gsp_esp_lcd_trim_paused()
for a Pause Token. This releases only the inactive viewport snapshot atlas;
UI state, fonts, borrowed sources and display buffers remain owned as before.
Without this call, the existing cache-reuse policy is unchanged. The optional
byte count excludes allocator overhead and does not guarantee a contiguous
allocation of that size elsewhere.
Trim executes on the paused render task after Presenter and accelerator fences.
Failure retains the atlas and token for retry or resume; ESP_ERR_NOT_FINISHED
means accelerator reads could not be confirmed complete. timeout_ms bounds the
Presenter wait, not dispatch or accelerator synchronization. Serialize lifecycle
calls from an application task. Resume still uses the original API, redraws a
full first frame, and later gestures recapture their snapshots normally.
If suspend returns ESP_ERR_NOT_FINISHED, its rollback could not restore the
hub and out_session still receives a valid session with no temporary app.
Retain that token and retry esp_gsp_esp_lcd_resume(session, NULL, &hub), or
destroy the session. Other suspend errors do not transfer a session.
esp_gsp_esp_lcd_start_on_session() requires a bundle with the same logical
width, height and pixel format as the retained display. On success it returns
the temporary app handle. App creation, compatibility or activation failure
attempts to restore the hub. Successful recovery consumes the session and
returns the original startup error. ESP_ERR_NOT_FINISHED means hub recovery
also failed: the session remains valid with no temporary app, for resume with
app = NULL or destruction, and out_gsp is NULL. Initial pointer/session-state validation errors
leave the session unchanged.
The resident render task keeps its original stack allocation. An app requiring
more stack is rejected with ESP_ERR_INVALID_SIZE; size the hub’s
task_stack_size for the most demanding temporary app before creating the
session. Dynamic fonts and vectors can require at least 32 KiB in standard
builds. Changing a temporary app’s configuration cannot enlarge the retained
task; see stack budgets.
Pass that exact temporary app handle to esp_gsp_esp_lcd_resume(). The call
stops the temporary app, resumes the retained hub, schedules a full first
frame and consumes the session on success.
Use the session resume/replace APIs for the temporary app;
esp_gsp_stop() rejects that handle because it shares the hub’s runtime.
A resume failure while pausing the temporary app leaves that app alive. If it
was destroyed but hub recovery failed, resume returns ESP_ERR_NOT_FINISHED;
out_hub is NULL. Retry with app = NULL, not the destroyed handle. Replacement startup follows
the same recovery and token rules as start_on_session().
For reliable error ownership use the _ex session operations. Legacy
replace_on_session_prepared() can return the same error and NULL new-App
output when pausing the old App fails, or when starting the replacement fails
and the SDK restores the Hub. Those cases have different App/Token lifetimes.
Initialize esp_gsp_esp_lcd_session_result_t with
ESP_GSP_ESP_LCD_SESSION_RESULT_INIT() and pass the address of your owned
Session pointer. _ex sets that pointer to NULL exactly when the Token is
consumed. result.outcome distinguishes unchanged inputs, a retained previous
App, a started new App, an empty retained Session and a resumed Hub. app and
hub provide the handles appropriate to that outcome; UNCHANGED preserves
input lifetimes and does not make NULL output handles evidence of destruction.
On APP_RETAINED keep the old App’s callback contexts. After replacement reaches
APP_STARTED, EMPTY or HUB_RESUMED, a supplied old temporary GSP App is destroyed;
keep the newly started App’s contexts on APP_STARTED. An empty Session retries
through esp_gsp_esp_lcd_resume_ex(&session, NULL, &hub, &result). A resumed Hub
remains alive even though its Session Token was consumed; do not release its
borrowed sources until the normal stop contract completes.
stage and operation_error identify the primary failure. recovery_error
retains the raw automatic Hub-recovery error after start/replace failure; it is
ESP_OK when no recovery was attempted. Results describe lifetimes and runtime
activation, not physical presentation. Serialize lifecycle calls as before.
Wrong result struct_size is rejected before effects and leaves result intact;
use the initializer and do not interpret a stale result after a size rejection.
If no temporary app is active, esp_gsp_esp_lcd_session_destroy() destroys
the suspended hub and display host instead of resuming them. A session with an
active temporary app cannot be destroyed.
Destroy consumes the session only on success. A failure retains its resources
for another destroy attempt; once destruction has been requested, do not start
or resume an app on that session. Keep borrowed assets and display resources
alive until destruction succeeds.
Target-frame completion
Section titled “Target-frame completion”Use Target-frame Update Receipts to distinguish accepted, applied, rendered, transferred and hardware-confirmed updates. For static stack analysis of application-owned tasks, see Compiler Stack Evidence.
Component timelines
Section titled “Component timelines”Add timelines at the scene root to coordinate writable properties of named
components. A timeline can be a multi-keyframe animation (duration_ms > 0) or
an instant pose (duration_ms omitted or 0, using value on each track).
{ "timelines": { "idle": { "duration_ms": 1200, "auto_play": true, "loop": true, "alternate": true, "tracks": [ {"target": "claw", "property": "rotation", "interpolation": "ease_in_out", "keyframes": [{"time_ms": 0, "value": -10}, {"time_ms": 1200, "value": 15}]} ] }, "react": { "duration_ms": 400, "tracks": [ {"target": "claw", "property": "rotation", "interpolation": "ease_out", "keyframes": [ {"time_ms": 0, "value": 0}, {"time_ms": 200, "value": 45, "interpolation": "step"}, {"time_ms": 400, "value": 10} ]}, {"target": "marker", "property": "visible", "keyframes": [{"time_ms": 0, "value": false}, {"time_ms": 200, "value": true}]} ] }, "pose_rest": { "tracks": [ {"target": "claw", "property": "rotation", "value": 0}, {"target": "marker", "property": "visible", "value": false} ] } }}GSPC resolves the targets and validates their authored property types and bounds.
The generated *.api.json lists each object’s properties, including their
timeline_writable flag and limits. Image scale tracks accept float factors
such as 1.0 or 1.5. Each track
starts at zero milliseconds with strictly increasing key times, and the final
value holds until the clip ends. Numbers and colors support step, linear,
ease_in, ease_out, ease_in_out, cubic_bezier (with bezier: [x1, y1, x2, y2]),
ease_out_back, and ease_in_out_back at both track and per-keyframe levels;
boolean, visibility and pose tracks use step. Multiple auto_play clips in
one scene must drive disjoint properties.
Trigger clips declaratively from widget events or scene actions with
"action": "timeline_play" (optional "loop", "mask_conflicts"),
"timeline_pause", "timeline_resume", "timeline_stop", or
"timeline_seek" ("position_ms"), passing "timeline": "<name>". From C,
prefer the generated <scene>_actions.h wrappers
(gsp_<scene>_timeline_<name>_play(), _play_ex(), _apply(), _seek(),
_pause(), _resume(), _stop(), _get_state()), or call
esp_gsp_timeline_*() directly. Subscribe to lifecycle transitions (STARTED,
LOOPED, COMPLETED, PAUSED, STOPPED, DISPLACED) with
esp_gsp_on_timeline_event() to chain follow-up actions cleanly on completion.
Concurrent clips drive disjoint properties in parallel. By default, starting,
resuming or seeking a clip pauses overlapping playing clips; set
mask_conflicts = true in esp_gsp_timeline_play_options_t (or in a
timeline_play action) to mute only the overlapping tracks so unrelated parts
keep animating. Direct application writes or single-property animations to a
driven property automatically yield only that track, and timelines cancel
conflicting single-property animations when they take ownership. A scene change
resets outgoing timelines, discards pending events, and starts auto_play
clips in the incoming scene. Stopping leaves the current property values
visible.
Timelines require matched compiler and runtime builds (GSB 2.24). Each scene supports up to 64 clips and 128 tracks per clip, with at most 65,535 tracks and 65,535 keys in its compiled tables. Playback uses the UI clock and existing property transactions, allocating player state and a reusable transaction buffer once at startup when the bundle contains timelines. Moving bitmap parts use the same tracks as SVG parts; profile animation-heavy artwork on the target display path.
Soft transitions, spring follow-through, additive layers, and 2D rigs
Section titled “Soft transitions, spring follow-through, additive layers, and 2D rigs”For organic character motion without hard snaps:
- Cross-fade transitions (
blend_ms): set"blend_ms": 180on a clip (or passblend_msinesp_gsp_timeline_play_options_t) to blend smoothly from current property values into the incoming clip (even on zero-duration poses).esp_gsp_timeline_seek()always lands immediately without blending. - Second-order spring-damper (
spring): add"spring": {"freq_hz": 3.0, "damping_ratio": 0.55}(or explicit{"stiffness": ..., "damping": ...}) on any numeric track for soft inertia, overshoot, and natural settle on hair, tails, or limb tips. - Additive layers (
"additive": true): store signed relative offsets (such as subtle breathing or head sway) that compose on top of active base clips without displacing them; stopping an additive clip cleanly restores the base pose. - Orthogonal rotation precision, filtering & native auto-trim: set
"rotation_precision": "deci_deg"on animagefor 0.1-degree precision at full nearest-neighbor speed (zero per-pixel penalty), and opt into"rotation_filter": "bilinear"on key parts where soft anti-aliased edges are desired ("smooth_rotation": trueenables both). Combine"fit": "native"with"trim_transparent": trueon rotating sprites or rig parts sogspcautomatically trims empty transparent borders at compile time, computes the rotation envelope from the rig joint sweep, compensatespivot, and enables tight oriented dirty-rect tracking at runtime. - 2D articulated rigs (
rigs): declare hierarchical joints with custompivot, parentoffset,rotationlimits, optional joint-level"spring": {"freq_hz": 3.0, "damping_ratio": 0.4, "follow_parent": 0.5}, and declarativeconstraints("kind": "couple"for weighted joint coupling,"kind": "aim"for shared Look-At orientation, and"kind": "look_at_x"/"look_at_y"targeting"property": "rotation" | "x" | "y"for 2.5D multi-layer parallax and eye tracking) at the scene root. Joint springs use unconditionally stable implicit integration and add frame-rate-consistent parent-motion inertia to secondary parts such as hair or tails. GSPC auto-promotes bound target parts, compiles topologically sortedrig_joints, groups constraints by target, and exposes each joint’srotation(in 0.1-degree units; authored in degrees in timelines) as a normal component property. The runtime solves 2D forward kinematics once per frame and providesesp_gsp_rig_get_joint_world(),esp_gsp_rig_solve_ik_2bone(), target-space smoothed stateful IK (esp_gsp_rig_set_ik_2bone()/esp_gsp_rig_release_ik_2bone()), and shared Look-At control (esp_gsp_rig_set_look_at()/esp_gsp_rig_clear_look_at()).
Seeking a clip samples its keyed joint rotations immediately. Other joint springs, IK and look-at controllers continue at their current rates, including when application input drives an appearance-only clip.
A joint owns its target object’s x, y, and optional rotation. Read these
to inspect the solved pose and animate the joint to change it. In the generated
*.api.json, each driven property names its joint in derived_from_joint.
Independent properties such as opacity and vector morph remain available on the image.
A couple constraint reads the source joint’s committed local rotation (after
property and timeline updates, before constraints, IK, and joint springs).
Two joints can drive each other this way in the same frame. The result is
independent of the order of the joint declarations. For a child that should
inherit a solved parent transform, use parent.
Inspect a compiled bundle with gspc bundle-info ui.gspb --format json.
Each scene’s motion counts its encoded tracks, keys, spring tracks, joints,
IK parent/child pairs and constraints. The bundle’s motion_capacity counts
the elements reserved by one UI instance, taking each buffer’s maximum across
its scenes. Static bundles reserve zero motion slots. Each clip, including a pose, has a player slot. If any scene uses
track springs, the lookup map spans the largest track table. FK update capacity
counts the actual output properties. Stateful IK reserves one controller per
eligible parent/child pair up to eight, including pairs selected later through
the C API. Each joint embeds one spring state and each IK or look-at controller
embeds two. Keys and constraints are read directly from the bundle. Use the
target build to convert element counts to bytes.