ESPHome 2026.9.0-dev
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: %d, new: %d", this->decoder_->get_format(), format);
190 this->decoder_ = nullptr;
191 }
192
193 if (!this->decoder_) {
194 this->decoder_ = this->create_decoder_(format);
195 if (!this->decoder_) {
196 ESP_LOGE(TAG, "Failed to create decoder for format %d", format);
197 return false;
198 }
199 }
200
201 this->decoded_bytes_ = 0;
202
203 int result = this->decoder_->prepare(expected_size);
204 if (result < 0) {
205 ESP_LOGE(TAG, "Failed to prepare decoder: %d", result);
206 this->decoder_ = nullptr; // If prepare fails, a full reset is needed
207 return false;
208 }
209 return true;
210}
211
212int RuntimeImage::feed_data(uint8_t *data, size_t len) {
213 if (!this->is_decoding()) {
214 ESP_LOGE(TAG, "No decoder initialized");
215 return -1;
216 }
217
218 int consumed = this->decoder_->decode(data, len);
219 if (consumed > 0) {
220 this->decoded_bytes_ += consumed;
221 }
222
223 return consumed;
224}
225
227 if (!this->is_decoding()) {
228 return false;
229 }
230
231 // Finalize the image for display
232 if (!this->progressive_display_) {
233 // Only now make the image visible
234 this->width_ = this->buffer_width_;
235 this->height_ = this->buffer_height_;
236 this->data_start_ = this->buffer_;
237 }
238
239 // End the session; the decoder object stays warm so the next decode can
240 // reuse it (and its buffers) without churning the heap.
241 this->decoder_->reset();
242
243 ESP_LOGD(TAG, "Decoding complete: %dx%d, %zu bytes", this->width_, this->height_, this->decoded_bytes_);
244 return true;
245}
246
247bool RuntimeImage::is_decode_finished() const { return this->is_decoding() && this->decoder_->is_finished(); }
248
250 this->release_buffer_();
251 // End any active decode session; decoders free the format-specific working buffers
252 // they can (PNG), while the decoder object itself is kept warm for the next decode.
253 if (this->decoder_) {
254 this->decoder_->reset();
255 }
256}
257
259 if (this->buffer_) {
260 if (this->external_buffer_) {
261 // The caller owns this memory and goes on using it after the image lets go of it.
262 ESP_LOGV(TAG, "Letting go of the external %dx%d buffer", this->buffer_width_, this->buffer_height_);
263 this->external_buffer_ = false;
264 } else {
265 ESP_LOGV(TAG, "Releasing buffer of size %zu", this->get_buffer_size(this->buffer_width_, this->buffer_height_));
266 RAMAllocator<uint8_t> allocator;
267 allocator.deallocate(this->buffer_, this->get_buffer_size(this->buffer_width_, this->buffer_height_));
268 }
269 this->buffer_ = nullptr;
270 this->data_start_ = nullptr;
271 this->width_ = 0;
272 this->height_ = 0;
273 this->buffer_width_ = 0;
274 this->buffer_height_ = 0;
275#ifdef USE_LVGL
276 memset(&this->dsc_, 0, sizeof(this->dsc_));
277#endif
278 }
279}
280
281bool RuntimeImage::set_external_buffer(uint8_t *buffer, int width, int height) {
282 this->release_buffer_();
283 if (buffer == nullptr || this->get_buffer_size(width, height) == 0) {
284 // Keep the released state rather than remembering a buffer that cannot be decoded into: an
285 // external buffer that is never handed back would otherwise block every later allocation.
286 ESP_LOGE(TAG, "Refusing an invalid external buffer for %dx%d", width, height);
287 return false;
288 }
289 this->buffer_ = buffer;
290 this->external_buffer_ = true;
291 this->buffer_width_ = width;
292 this->buffer_height_ = height;
293 return true;
294}
295
296size_t RuntimeImage::resize_buffer_(int width, int height) {
297 size_t new_size = this->get_buffer_size(width, height);
298
299 // A buffer only ever exists with dimensions the image can decode at, so a match here means
300 // new_size is non-zero. Checking it before the invalid dimension case below lets the external
301 // buffer be let go of for every decode it cannot serve, not just for valid other dimensions.
302 if (this->buffer_ && this->buffer_width_ == width && this->buffer_height_ == height) {
303 // Buffer already allocated with correct size
304 return new_size;
305 }
306
307 if (this->external_buffer_) {
308 ESP_LOGE(TAG, "Image decoded to %dx%d, but the external buffer is %dx%d", width, height, this->buffer_width_,
309 this->buffer_height_);
310 // Let the buffer go rather than free memory that belongs to the caller. Dropping it also stops
311 // a decoder that ignores this failure from publishing a picture it never painted.
312 this->release_buffer_();
313 return 0;
314 }
315
316 if (new_size == 0) {
317 ESP_LOGE(TAG, "Refusing to allocate buffer for invalid image dimensions %dx%d", width, height);
318 return 0;
319 }
320
321 // Release old buffer if dimensions changed
322 if (this->buffer_) {
323 this->release_buffer_();
324 }
325
326 ESP_LOGD(TAG, "Allocating buffer: %dx%d, %zu bytes", width, height, new_size);
327 RAMAllocator<uint8_t> allocator;
328 this->buffer_ = allocator.allocate(new_size);
329
330 if (!this->buffer_) {
331 ESP_LOGE(TAG, "Failed to allocate %zu bytes. Largest free block: %zu", new_size,
332 allocator.get_max_free_block_size());
333 return 0;
334 }
335
336 // Clear buffer
337 memset(this->buffer_, 0, new_size);
338
339 this->buffer_width_ = width;
340 this->buffer_height_ = height;
341
342 return new_size;
343}
344
345size_t RuntimeImage::get_buffer_size(int width, int height) const {
346 // Dimensions come from a remote image header; reject absurd values so the size math cannot overflow
347 if (width <= 0 || height <= 0 || width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION) {
348 return 0;
349 }
351 // Add extra alpha channel for RGB565 with alpha
352 return static_cast<size_t>(width) * height * 3;
353 }
354 return (static_cast<size_t>(this->get_bpp()) * width + 7u) / 8u * height;
355}
356
357int RuntimeImage::get_position_(int x, int y) const { return (x + y * this->buffer_width_) * this->get_bpp() / 8; }
358
359std::unique_ptr<ImageDecoder> RuntimeImage::create_decoder_(ImageFormat format) {
360 ESP_LOGV(TAG, "Creating decoder for format %d", format);
361 switch (format) {
362#ifdef USE_RUNTIME_IMAGE_BMP
363 case BMP:
364 return make_unique<BmpDecoder>(this);
365#endif
366#ifdef USE_RUNTIME_IMAGE_JPEG
367 case JPEG:
368 return make_unique<JpegDecoder>(this);
369#endif
370#ifdef USE_RUNTIME_IMAGE_PNG
371 case PNG:
372 return make_unique<PngDecoder>(this);
373#endif
374#ifdef USE_RUNTIME_IMAGE_QOI
375 case QOI:
376 return make_unique<QoiDecoder>(this);
377#endif
378 case AUTO:
379 ESP_LOGE(TAG, "Image format could not be determined; set `format:` explicitly in the configuration");
380 return nullptr;
381 default:
382 ESP_LOGE(TAG, "Unsupported image format: %d", format);
383 return nullptr;
384 }
385}
386
387} // namespace esphome::runtime_image
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2107
void deallocate(T *p, size_t n)
Definition helpers.h:2164
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:2192
T * allocate(size_t n)
Definition helpers.h:2134
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:214
Transparency transparency_
Definition image.h:55
lv_img_dsc_t dsc_
Definition image.h:59
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
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 void size_t len
Definition hal.h:64
size_t size_t pos
Definition helpers.h:1092
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