ESPHome 2026.10.2
Loading...
Searching...
No Matches
runtime_image.cpp
Go to the documentation of this file.
1#include "runtime_image.h"
2#include "image_decoder.h"
3#include "esphome/core/log.h"
4#include <algorithm>
5#include <cstdint>
6#include <cstring>
7#include <limits>
8
9#ifdef USE_RUNTIME_IMAGE_BMP
10#include "bmp_decoder.h"
11#endif
12#ifdef USE_RUNTIME_IMAGE_JPEG
13#include "jpeg_decoder.h"
14#endif
15#ifdef USE_RUNTIME_IMAGE_PNG
16#include "png_decoder.h"
17#endif
18#ifdef USE_RUNTIME_IMAGE_QOI
19#include "qoi_decoder.h"
20#endif
21
22namespace esphome::runtime_image {
23
24static const char *const TAG = "runtime_image";
25
26// Widest supported format is 4 bytes/pixel, so 32767 * 32767 * 4 still fits a 32-bit size_t
27static constexpr int MAX_IMAGE_DIMENSION = 32767;
28static constexpr int MAX_IMAGE_BPP = 32;
29static_assert((static_cast<uint64_t>(MAX_IMAGE_BPP) * MAX_IMAGE_DIMENSION + 7) / 8 * MAX_IMAGE_DIMENSION <=
30 std::numeric_limits<size_t>::max(),
31 "MAX_IMAGE_DIMENSION must keep the worst-case buffer size within size_t");
32
33inline bool is_color_on(const Color &color) {
34 // This produces the most accurate monochrome conversion, but is slightly slower.
35 // return (0.2125 * color.r + 0.7154 * color.g + 0.0721 * color.b) > 127;
36
37 // Approximation using fast integer computations; produces acceptable results
38 // Equivalent to 0.25 * R + 0.5 * G + 0.25 * B
39 return ((color.r >> 2) + (color.g >> 1) + (color.b >> 2)) & 0x80;
40}
41
43 image::Image *placeholder, bool is_big_endian, int fixed_width, int fixed_height)
44 : Image(nullptr, 0, 0, type, transparency),
45 format_(format),
46 fixed_width_(fixed_width),
47 fixed_height_(fixed_height),
48 placeholder_(placeholder),
49 is_big_endian_(is_big_endian) {}
50
52
53int RuntimeImage::resize(int width, int height) {
54 // Use fixed dimensions if specified (0 means auto-resize)
55 int target_width = this->fixed_width_ ? this->fixed_width_ : width;
56 int target_height = this->fixed_height_ ? this->fixed_height_ : height;
57
58 // When both fixed dimensions are set, scale uniformly to preserve aspect ratio
59 if (this->fixed_width_ && this->fixed_height_ && width > 0 && height > 0) {
60 float scale =
61 std::min(static_cast<float>(this->fixed_width_) / width, static_cast<float>(this->fixed_height_) / height);
62 target_width = static_cast<int>(width * scale);
63 target_height = static_cast<int>(height * scale);
64 }
65
66 size_t result = this->resize_buffer_(target_width, target_height);
67 if (result > 0 && this->progressive_display_) {
68 // Update display dimensions for progressive display
69 this->width_ = this->buffer_width_;
70 this->height_ = this->buffer_height_;
71 this->data_start_ = this->buffer_;
72 }
73 return result;
74}
75
76void RuntimeImage::draw_pixel(int x, int y, const Color &color) {
77 if (!this->buffer_) {
78 ESP_LOGE(TAG, "Buffer not allocated!");
79 return;
80 }
81 if (x < 0 || y < 0 || x >= this->buffer_width_ || y >= this->buffer_height_) {
82 ESP_LOGE(TAG, "Tried to paint a pixel (%d,%d) outside the image!", x, y);
83 return;
84 }
85
86 switch (this->type_) {
88 const uint32_t width_8 = ((this->buffer_width_ + 7u) / 8u) * 8u;
89 uint32_t pos = x + y * width_8;
90 auto bitno = 0x80 >> (pos % 8u);
91 pos /= 8u;
92 auto on = is_color_on(color);
93 if (this->has_transparency() && color.w < 0x80)
94 on = false;
95 if (on) {
96 this->buffer_[pos] |= bitno;
97 } else {
98 this->buffer_[pos] &= ~bitno;
99 }
100 break;
101 }
103 uint32_t pos = this->get_position_(x, y);
104 auto gray = static_cast<uint8_t>(0.2125 * color.r + 0.7154 * color.g + 0.0721 * color.b);
106 if (gray == 1) {
107 gray = 0;
108 }
109 if (color.w < 0x80) {
110 gray = 1;
111 }
113 if (color.w != 0xFF)
114 gray = color.w;
115 }
116 this->buffer_[pos] = gray;
117 break;
118 }
120 const size_t pos = (x + y * this->buffer_width_) * 2;
121 Color mapped_color = color;
122 this->map_chroma_key(mapped_color);
123 uint16_t rgb565 = display::ColorUtil::color_to_565(mapped_color);
124 if (this->is_big_endian_) {
125 this->buffer_[pos + 0] = static_cast<uint8_t>((rgb565 >> 8) & 0xFF);
126 this->buffer_[pos + 1] = static_cast<uint8_t>(rgb565 & 0xFF);
127 } else {
128 this->buffer_[pos + 0] = static_cast<uint8_t>(rgb565 & 0xFF);
129 this->buffer_[pos + 1] = static_cast<uint8_t>((rgb565 >> 8) & 0xFF);
130 }
132 const size_t alpha_pos = pos / 2 + this->buffer_width_ * this->buffer_height_ * 2;
133 this->buffer_[alpha_pos] = color.w;
134 }
135 break;
136 }
138 uint32_t pos = this->get_position_(x, y);
139 Color mapped_color = color;
140 this->map_chroma_key(mapped_color);
141 this->buffer_[pos + 0] = mapped_color.b;
142 this->buffer_[pos + 1] = mapped_color.g;
143 this->buffer_[pos + 2] = mapped_color.r;
145 this->buffer_[pos + 3] = color.w;
146 }
147 break;
148 }
149 }
150}
151
154 if (color.g == 1 && color.r == 0 && color.b == 0) {
155 color.g = 0;
156 }
157 if (color.w < 0x80) {
158 color.r = 0;
159 color.g = this->type_ == image::IMAGE_TYPE_RGB565 ? 4 : 1;
160 color.b = 0;
161 }
162 }
163}
164
165void RuntimeImage::draw(int x, int y, display::Display *display, Color color_on, Color color_off) {
166 if (this->data_start_) {
167 // If we have a complete image, use the base class draw method
168 Image::draw(x, y, display, color_on, color_off);
169 } else if (this->placeholder_) {
170 // Show placeholder while the runtime image is not available
171 this->placeholder_->draw(x, y, display, color_on, color_off);
172 }
173 // If no image is loaded and no placeholder, nothing to draw
174}
175
176bool RuntimeImage::begin_decode(size_t expected_size, ImageFormat format) {
177 if (this->is_decoding()) {
178 ESP_LOGW(TAG, "Decoding already in progress");
179 return false;
180 }
181
182 if (format == AUTO && this->format_ != AUTO) {
183 // Fall back to the configured format before the reuse check below
184 format = this->format_;
185 }
186
187 // An idle decoder for a different format cannot be reused
188 if (this->decoder_ != nullptr && this->decoder_->get_format() != format) {
189 ESP_LOGD(TAG, "Decoder format mismatch: current: %s, new: %s",
190 LOG_STR_ARG(get_format_name(this->decoder_->get_format())), LOG_STR_ARG(get_format_name(format)));
191 this->decoder_ = nullptr;
192 }
193
194 if (!this->decoder_) {
195 this->decoder_ = this->create_decoder_(format);
196 if (!this->decoder_) {
197 ESP_LOGE(TAG, "Failed to create decoder for format %s", LOG_STR_ARG(get_format_name(format)));
198 return false;
199 }
200 }
201
202 this->decoded_bytes_ = 0;
203
204 int result = this->decoder_->prepare(expected_size);
205 if (result < 0) {
206 ESP_LOGE(TAG, "Failed to prepare decoder: %d", result);
207 this->decoder_ = nullptr; // If prepare fails, a full reset is needed
208 return false;
209 }
210 return true;
211}
212
213int RuntimeImage::feed_data(uint8_t *data, size_t len) {
214 if (!this->is_decoding()) {
215 ESP_LOGE(TAG, "No decoder initialized");
216 return -1;
217 }
218
219 int consumed = this->decoder_->decode(data, len);
220 if (consumed > 0) {
221 this->decoded_bytes_ += consumed;
222 }
223
224 return consumed;
225}
226
228 if (!this->is_decoding()) {
229 return false;
230 }
231
232 // Finalize the image for display
233 if (!this->progressive_display_) {
234 // Only now make the image visible
235 this->width_ = this->buffer_width_;
236 this->height_ = this->buffer_height_;
237 this->data_start_ = this->buffer_;
238 }
239
240 // End the session; the decoder object stays warm so the next decode can
241 // reuse it (and its buffers) without churning the heap.
242 this->decoder_->reset();
243
244 ESP_LOGD(TAG, "Decoding complete: %dx%d, %zu bytes", this->width_, this->height_, this->decoded_bytes_);
245 return true;
246}
247
248bool RuntimeImage::is_decode_finished() const { return this->is_decoding() && this->decoder_->is_finished(); }
249
251 this->release_buffer_();
252 // End any active decode session; decoders free the format-specific working buffers
253 // they can (PNG), while the decoder object itself is kept warm for the next decode.
254 if (this->decoder_) {
255 this->decoder_->reset();
256 }
257}
258
260 if (this->buffer_) {
261 if (this->external_buffer_) {
262 // The caller owns this memory and goes on using it after the image lets go of it.
263 ESP_LOGV(TAG, "Letting go of the external %dx%d buffer", this->buffer_width_, this->buffer_height_);
264 this->external_buffer_ = false;
265 } else {
266 ESP_LOGV(TAG, "Releasing buffer of size %zu", this->get_buffer_size(this->buffer_width_, this->buffer_height_));
267 RAMAllocator<uint8_t> allocator;
268 allocator.deallocate(this->buffer_, this->get_buffer_size(this->buffer_width_, this->buffer_height_));
269 }
270 this->buffer_ = nullptr;
271 this->data_start_ = nullptr;
272 this->width_ = 0;
273 this->height_ = 0;
274 this->buffer_width_ = 0;
275 this->buffer_height_ = 0;
276#ifdef USE_LVGL
277 memset(&this->dsc_, 0, sizeof(this->dsc_));
278#endif
279 }
280}
281
282bool RuntimeImage::set_external_buffer(uint8_t *buffer, int width, int height) {
283 this->release_buffer_();
284 if (buffer == nullptr || this->get_buffer_size(width, height) == 0) {
285 // Keep the released state rather than remembering a buffer that cannot be decoded into: an
286 // external buffer that is never handed back would otherwise block every later allocation.
287 ESP_LOGE(TAG, "Refusing an invalid external buffer for %dx%d", width, height);
288 return false;
289 }
290 this->buffer_ = buffer;
291 this->external_buffer_ = true;
292 this->buffer_width_ = width;
293 this->buffer_height_ = height;
294 return true;
295}
296
297size_t RuntimeImage::resize_buffer_(int width, int height) {
298 size_t new_size = this->get_buffer_size(width, height);
299
300 // A buffer only ever exists with dimensions the image can decode at, so a match here means
301 // new_size is non-zero. Checking it before the invalid dimension case below lets the external
302 // buffer be let go of for every decode it cannot serve, not just for valid other dimensions.
303 if (this->buffer_ && this->buffer_width_ == width && this->buffer_height_ == height) {
304 // Buffer already allocated with correct size
305 return new_size;
306 }
307
308 if (this->external_buffer_) {
309 ESP_LOGE(TAG, "Image decoded to %dx%d, but the external buffer is %dx%d", width, height, this->buffer_width_,
310 this->buffer_height_);
311 // Let the buffer go rather than free memory that belongs to the caller. Dropping it also stops
312 // a decoder that ignores this failure from publishing a picture it never painted.
313 this->release_buffer_();
314 return 0;
315 }
316
317 if (new_size == 0) {
318 ESP_LOGE(TAG, "Refusing to allocate buffer for invalid image dimensions %dx%d", width, height);
319 return 0;
320 }
321
322 // Release old buffer if dimensions changed
323 if (this->buffer_) {
324 this->release_buffer_();
325 }
326
327 ESP_LOGD(TAG, "Allocating buffer: %dx%d, %zu bytes", width, height, new_size);
328 RAMAllocator<uint8_t> allocator;
329 this->buffer_ = allocator.allocate(new_size);
330
331 if (!this->buffer_) {
332 ESP_LOGE(TAG, "Failed to allocate %zu bytes. Largest free block: %zu", new_size,
333 allocator.get_max_free_block_size());
334 return 0;
335 }
336
337 // Clear buffer
338 memset(this->buffer_, 0, new_size);
339
340 this->buffer_width_ = width;
341 this->buffer_height_ = height;
342
343 return new_size;
344}
345
346size_t RuntimeImage::get_buffer_size(int width, int height) const {
347 // Dimensions come from a remote image header; reject absurd values so the size math cannot overflow
348 if (width <= 0 || height <= 0 || width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION) {
349 return 0;
350 }
352 // Add extra alpha channel for RGB565 with alpha
353 return static_cast<size_t>(width) * height * 3;
354 }
355 return (static_cast<size_t>(this->get_bpp()) * width + 7u) / 8u * height;
356}
357
358int RuntimeImage::get_position_(int x, int y) const { return (x + y * this->buffer_width_) * this->get_bpp() / 8; }
359
360std::unique_ptr<ImageDecoder> RuntimeImage::create_decoder_(ImageFormat format) {
361 ESP_LOGV(TAG, "Creating decoder for format %s", LOG_STR_ARG(get_format_name(format)));
362 switch (format) {
363#ifdef USE_RUNTIME_IMAGE_BMP
364 case BMP:
365 return make_unique<BmpDecoder>(this);
366#endif
367#ifdef USE_RUNTIME_IMAGE_JPEG
368 case JPEG:
369 return make_unique<JpegDecoder>(this);
370#endif
371#ifdef USE_RUNTIME_IMAGE_PNG
372 case PNG:
373 return make_unique<PngDecoder>(this);
374#endif
375#ifdef USE_RUNTIME_IMAGE_QOI
376 case QOI:
377 return make_unique<QoiDecoder>(this);
378#endif
379 case AUTO:
380 ESP_LOGE(TAG, "Image format could not be determined; set `format:` explicitly in the configuration");
381 return nullptr;
382 default:
383 ESP_LOGE(TAG, "Unsupported image format: %s", LOG_STR_ARG(get_format_name(format)));
384 return nullptr;
385 }
386}
387
388} // namespace esphome::runtime_image
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2231
void deallocate(T *p, size_t n)
Definition helpers.h:2288
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:2336
T * allocate(size_t n)
Definition helpers.h:2258
static uint16_t color_to_565(Color color, ColorOrder color_order=ColorOrder::COLOR_ORDER_RGB)
const uint8_t * data_start_
Definition image.h:54
int get_bpp() const
Definition image.h:33
bool has_transparency() const
Definition image.h:40
ImageType type_
Definition image.h:53
ImageType get_type() const
Definition image.cpp:212
Transparency transparency_
Definition image.h:55
lv_img_dsc_t dsc_
Definition image.h:58
void draw(int x, int y, display::Display *display, Color color_on, Color color_off) override
Definition image.cpp:8
bool begin_decode(size_t expected_size=0, ImageFormat format=AUTO)
Begin decoding an image.
bool is_decoding() const
Check if decoding is currently in progress.
bool is_big_endian_
Whether the image is stored in big-endian format.
void draw(int x, int y, display::Display *display, Color color_on, Color color_off) override
size_t get_buffer_size(int width, int height) const
Get the buffer size in bytes needed for a picture of the given dimensions.
int buffer_width_
Actual width of the current image.
bool end_decode()
Complete the decoding process.
int get_position_(int x, int y) const
Get the position in the buffer for a pixel.
const int fixed_height_
Fixed height requested on configuration, or 0 if not specified.
void release_buffer_()
Release only the image buffer without resetting the decoder.
int resize(int width, int height)
Resize the image buffer to the requested dimensions.
int feed_data(uint8_t *data, size_t len)
Feed data to the decoder.
const int fixed_width_
Fixed width requested on configuration, or 0 if not specified.
bool is_decode_finished() const
Check if the decoder has finished processing all data.
void release()
Release the image buffer and free its memory, ending any decode session.
image::Image * placeholder_
Placeholder image to show when the runtime image is not available.
RuntimeImage(ImageFormat format, image::ImageType type, image::Transparency transparency, image::Image *placeholder=nullptr, bool is_big_endian=false, int fixed_width=0, int fixed_height=0)
Construct a new RuntimeImage object.
const ImageFormat format_
The image format this RuntimeImage is configured to decode.
size_t resize_buffer_(int width, int height)
Resize the image buffer to the requested dimensions.
std::unique_ptr< ImageDecoder > decoder_
void draw_pixel(int x, int y, const Color &color)
std::unique_ptr< ImageDecoder > create_decoder_(ImageFormat format)
Create decoder instance for the requested format.
int buffer_height_
Actual height of the current image.
bool set_external_buffer(uint8_t *buffer, int width, int height)
Decode into a buffer the caller owns, instead of one allocated here.
bool external_buffer_
Whether buffer_ belongs to the caller, so it must not be freed or resized here.
uint16_t type
uint32_t buffer
Definition gif.cpp:50
const char * format
@ TRANSPARENCY_ALPHA_CHANNEL
Definition image.h:21
@ TRANSPARENCY_CHROMA_KEY
Definition image.h:20
@ IMAGE_TYPE_GRAYSCALE
Definition image.h:13
@ IMAGE_TYPE_BINARY
Definition image.h:12
@ IMAGE_TYPE_RGB565
Definition image.h:15
@ IMAGE_TYPE_RGB
Definition image.h:14
bool is_color_on(const Color &color)
ImageFormat
Image format types that can be decoded dynamically.
@ AUTO
Format is supplied per decode, e.g.
const LogString * get_format_name(ImageFormat format)
Human-readable name for a format; "UNKNOWN" if not recognized.
const void size_t len
Definition hal.h:64
size_t size_t pos
Definition helpers.h:1186
static void uint32_t
uint8_t w
Definition color.h:42
uint8_t g
Definition color.h:34
uint8_t b
Definition color.h:38
uint8_t r
Definition color.h:30
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6