ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
jpeg_decoder.cpp
Go to the documentation of this file.
1#include "jpeg_decoder.h"
2#ifdef USE_RUNTIME_IMAGE_JPEG
3
9#include "esphome/core/log.h"
10
11ESPHOME_LOG_TAG(TAG, "image_decoder.jpeg");
12
13namespace esphome::runtime_image {
14
15void JpegDecoder::draw_rgb565(int x, int y, int w, int h, const uint8_t *pixels) {
16 if (pixels == nullptr) {
17 return;
18 }
19 uint8_t *const buffer = this->image_buffer_();
20 const uint32_t buffer_width = this->image_->get_buffer_width();
21 // JPEGDEC gives little-endian words; a big-endian image stores the high byte first
22 const uint8_t first = this->image_is_big_endian_() ? 1 : 0;
23 for (int source_y = 0; source_y < h; source_y++) {
24 const int absolute_y = y + source_y;
25 if (absolute_y < 0 || absolute_y >= this->draw_height_) {
26 continue;
27 }
28 const uint16_t y1 = this->y_boundaries_[absolute_y];
29 const uint16_t y2 = this->y_boundaries_[absolute_y + 1];
30 for (int source_x = 0; source_x < w; source_x++) {
31 const int absolute_x = x + source_x;
32 if (absolute_x < 0 || absolute_x >= this->draw_width_) {
33 continue;
34 }
35 const uint16_t x1 = this->x_boundaries_[absolute_x];
36 const uint16_t x2 = this->x_boundaries_[absolute_x + 1];
37 const uint8_t *pixel = pixels + (source_y * w + source_x) * 2;
38 for (uint16_t destination_y = y1; destination_y < y2; destination_y++) {
39 uint8_t *destination = buffer + (destination_y * buffer_width + x1) * 2;
40 for (uint16_t destination_x = x1; destination_x < x2; destination_x++) {
41 destination[0] = pixel[first];
42 destination[1] = pixel[1 - first];
43 destination += 2;
44 }
45 }
46 }
47 }
48}
49
56static int draw_callback(JPEGDRAW *jpeg) {
57 JpegDecoder *decoder = (JpegDecoder *) jpeg->pUser;
58
59 if (decoder == nullptr) {
60 ESP_LOGE(TAG, "Decoder pointer is null!");
61 return 0;
62 }
63
64 // Very big images take long to decode, so feed the watchdog as the decode goes
66 if (decoder->uses_direct_rgb565()) {
67 decoder->draw_rgb565(jpeg->x, jpeg->y, jpeg->iWidth, jpeg->iHeight,
68 reinterpret_cast<const uint8_t *>(jpeg->pPixels));
69 return 1;
70 }
71 size_t position = 0;
72 size_t height = static_cast<size_t>(jpeg->iHeight);
73 size_t width = static_cast<size_t>(jpeg->iWidth);
74 for (size_t y = 0; y < height; y++) {
75 for (size_t x = 0; x < width; x++) {
76 auto rg = decode_value(jpeg->pPixels[position++]);
77 auto ba = decode_value(jpeg->pPixels[position++]);
78 Color color(rg[1], rg[0], ba[1], ba[0]);
79
80 decoder->draw(jpeg->x + x, jpeg->y + y, 1, 1, color);
81 }
82 }
83 return 1;
84}
85
87 : ImageDecoder(image, JPEG), jpeg_(RAMAllocator<JPEGDEC>().make_unique()) {
88 if (this->jpeg_ == nullptr) {
89 ESP_LOGE(TAG, "Failed to allocate memory for the JPEG decoder");
90 }
91}
92
93int JpegDecoder::prepare(size_t expected_size) {
94 // Check before the base prepare() so a failure never leaves an active session
95 if (this->jpeg_ == nullptr) {
96 ESP_LOGE(TAG, "JPEG decoder engine not initialized!");
98 }
99 return ImageDecoder::prepare(expected_size);
100}
101
102int HOT JpegDecoder::decode(uint8_t *buffer, size_t size) {
103 if (this->jpeg_ == nullptr) {
104 ESP_LOGE(TAG, "JPEG decoder engine not initialized!");
106 }
107 // JPEG decoder requires complete data
108 // If we know the expected size, wait for it
110 ESP_LOGV(TAG, "Download not complete. Size: %zu/%zu", size, this->expected_size_);
111 return 0;
112 }
113
114 // If size unknown, try to decode what has arrived. JPEGDEC usually fails on an incomplete baseline image, but draws
115 // the scans that arrived of an incomplete progressive image and reports success, so any data after that cannot open.
116
117 if (!this->jpeg_->openRAM(buffer, size, draw_callback)) {
118 ESP_LOGE(TAG, "Could not open image for decoding: %d", this->jpeg_->getLastError());
120 }
121 const int err = this->start_();
122 if (err != 0)
123 return err;
124 // Row by row rather than with decode(): a progressive image decodes all its scans before the first draw callback
125 if (!this->jpeg_->decodeBegin(0, 0, this->scale_option_()))
126 return this->fail_();
127 int result;
128 while ((result = this->jpeg_->decodeRows(1)) == JPEG_DECODE_MORE)
130 if (result != 1)
131 return this->fail_();
132 this->decoded_bytes_ = size;
133 this->jpeg_->close();
134 return size;
135}
136
138 auto jpeg_type = this->jpeg_->getJPEGType();
139 if (jpeg_type == JPEG_MODE_INVALID) {
140 ESP_LOGE(TAG, "Unsupported JPEG image");
142 }
143 ESP_LOGD(TAG, "Image size: %d x %d, bpp: %d", this->jpeg_->getWidth(), this->jpeg_->getHeight(),
144 this->jpeg_->getBpp());
145
146 this->jpeg_->setUserPointer(this);
147 const int width = this->jpeg_->getWidth();
148 const int height = this->jpeg_->getHeight();
149 // The tables for drawing are only built once the decoded size is known, below
150 if (!this->resize_image_(width, height)) {
152 }
153 // JPEGDEC can decode at 1/2, 1/4 or 1/8 size for much less work. Use the smallest size that still has at least as
154 // many pixels as the buffer, so a large image shown small is not decoded in full only to be thrown away.
155 const int buffer_width = this->image_->get_buffer_width();
156 const int buffer_height = this->image_->get_buffer_height();
157 this->scale_ = 1;
158 while (this->scale_ < JPEG_SCALE_EIGHTH && width / (this->scale_ * 2) >= buffer_width &&
159 height / (this->scale_ * 2) >= buffer_height) {
160 this->scale_ *= 2;
161 }
162 const int decoded_width = (width + this->scale_ - 1) / this->scale_;
163 const int decoded_height = (height + this->scale_ - 1) / this->scale_;
164 if (this->scale_ != 1) {
165 ESP_LOGD(TAG, "Decoding at 1/%d size, %d x %d", this->scale_, decoded_width, decoded_height);
166 }
167 this->prepare_draw_(decoded_width, decoded_height);
168 if (this->direct_rgb565_) {
169 // JPEGDEC's RGB565_BIG_ENDIAN output is not byte swapped on every build (the x86 host build
170 // returns little-endian words for it), so the byte order is applied in draw_rgb565 instead
171 this->jpeg_->setPixelType(RGB565_LITTLE_ENDIAN);
172 } else {
173 this->jpeg_->setPixelType(RGB8888);
174 }
175 return 0;
176}
177
179 const bool read_failed = this->source_ != nullptr && this->source_failed_;
180 const int error = this->jpeg_->getLastError();
181 this->jpeg_->close();
182 this->source_ = nullptr;
183 if (read_failed) {
184 ESP_LOGE(TAG, "Reading the image failed");
185 return DECODE_ERROR_READ;
186 }
187 ESP_LOGE(TAG, "Error while decoding: %d", error);
188 switch (error) {
189 case JPEG_ERROR_MEMORY:
191 case JPEG_UNSUPPORTED_FEATURE:
193 case JPEG_INVALID_FILE:
194 case JPEG_INVALID_PARAMETER:
196 case JPEG_DECODE_ERROR:
197 default:
199 }
200}
201
203 // A decode from a source that was given up part way still has the image open
204 if (this->source_ != nullptr) {
205 this->jpeg_->close();
206 this->source_ = nullptr;
207 }
209}
210
211int32_t JpegDecoder::source_read(JPEGFILE *file, uint8_t *buf, int32_t len) {
212 auto *decoder = static_cast<JpegDecoder *>(file->fHandle);
213 const int32_t n = decoder->source_->read(buf, len);
214 if (n < 0) {
215 // JPEGDEC has no way to report a failed read, so remember it and give it no data
216 decoder->source_failed_ = true;
217 return 0;
218 }
219 file->iPos += n;
220 return n;
221}
222
223int32_t JpegDecoder::source_seek(JPEGFILE *file, int32_t position) {
224 auto *decoder = static_cast<JpegDecoder *>(file->fHandle);
226 decoder->source_failed_ = true;
227 return file->iPos;
228 }
229 file->iPos = position;
230 return position;
231}
232
234 if (this->jpeg_ == nullptr) {
235 ESP_LOGE(TAG, "JPEG decoder engine not initialized!");
237 }
238 if (this->expected_size_ == 0 || this->expected_size_ > INT32_MAX) {
239 ESP_LOGE(TAG, "Image size %zu cannot be read from a source", this->expected_size_);
241 }
242 if (!source->seek(0)) {
243 ESP_LOGE(TAG, "Could not read the image");
244 return DECODE_ERROR_READ;
245 }
246 this->source_ = source;
247 this->source_failed_ = false;
248 if (!this->jpeg_->open(this, this->expected_size_, source_close, source_read, source_seek, draw_callback)) {
249 // The caller may recover, for example by reading the whole image first, so it reports the failure
250 ESP_LOGD(TAG, "Could not open image for decoding: %d", this->jpeg_->getLastError());
251 this->source_ = nullptr;
253 }
254 const int err = this->start_();
255 if (err != 0) {
256 this->jpeg_->close();
257 this->source_ = nullptr;
258 return err;
259 }
260 if (!this->jpeg_->decodeBegin(0, 0, this->scale_option_()))
261 return this->fail_();
262 return 0;
263}
264
266 if (this->source_ == nullptr)
268 const int result = this->jpeg_->decodeRows(1);
269 // JPEGDEC may decode on with the missing data, so check the read before its result
270 if (this->source_failed_)
271 return this->fail_();
272 if (result == JPEG_DECODE_MORE)
273 return DECODE_STEP_MORE;
274 if (result == JPEG_DECODE_NEED_DATA)
276 if (result == 0)
277 return this->fail_();
278 this->decoded_bytes_ = this->expected_size_;
279 this->jpeg_->close();
280 this->source_ = nullptr;
281 return DECODE_STEP_DONE;
282}
283
284} // namespace esphome::runtime_image
285
286#endif // USE_RUNTIME_IMAGE_JPEG
uint8_t h
Definition bl0906.h:2
void feed_wdt_if_watched()
Feed from code that may run off the loop task (a long download or image decode): on ESP32 only a task...
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2670
Input that a decoder reads itself as it goes, so the whole image never has to be in memory at once.
virtual int32_t read(uint8_t *buf, uint32_t len)=0
Read up to len bytes at the current position.
virtual bool seek(uint32_t position)=0
Move to a position counted from the start. Returns false on error.
Class to abstract decoding different image formats.
FixedVector< uint16_t > x_boundaries_
void prepare_draw_(int width, int height)
Draw a source of width x height over the whole buffer from now on.
virtual void reset()
Reset the decoder state, ending any decoding session.
bool resize_image_(int width, int height)
Resize the image for a width x height source, without preparing to draw. prepare_draw_() must follow.
uint8_t * image_buffer_() const
The image's pixel buffer, for decoders that write their output straight into it.
FixedVector< uint16_t > y_boundaries_
virtual int prepare(size_t expected_size)
Initialize the decoder, starting a new decoding session.
Image decoder specialization for JPEG images.
RAMUniquePtr< JPEGDEC > jpeg_
About 18 KB of decoder state: PSRAM first, nullptr if out of memory.
int prepare(size_t expected_size) override
int begin_source(DecodeSource *source) override
void draw_rgb565(int x, int y, int w, int h, const uint8_t *pixels)
int start_()
Set up an opened image for decoding. Returns 0, or a DecodeError.
static int32_t source_read(JPEGFILE *file, uint8_t *buf, int32_t len)
JpegDecoder(RuntimeImage *image)
Construct a new JPEG Decoder object.
int fail_()
The DecodeError for a failed read of the source or JPEGDEC's last error, closing the image.
int HOT decode(uint8_t *buffer, size_t size) override
int HOT decode_step() override
Decodes one row of MCUs (8 or 16 pixel rows), or waits part way through one for more of the source.
static int32_t source_seek(JPEGFILE *file, int32_t position)
static void source_close(void *handle)
A dynamic image that can be loaded and decoded at runtime.
float position
Definition cover.h:0
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, "image_decoder.jpeg")
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:1285
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6
esp_err_t result