ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
esp_color_correction.cpp
Go to the documentation of this file.
2
3namespace esphome::light {
4
5uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
6 if (this->gamma_table_ == nullptr)
7 return value;
8 return static_cast<uint8_t>((progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257);
9}
10
11uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
12 if (this->gamma_table_ == nullptr)
13 return value;
14 if (value == 0)
15 return 0;
16 uint16_t target = value * 257; // Scale 0-255 to 0-65535
17 uint8_t lo = gamma_table_reverse_search(this->gamma_table_, target);
18 if (lo >= 255)
19 return 255;
20 uint16_t a = progmem_read_uint16(&this->gamma_table_[lo]);
21 uint16_t b = progmem_read_uint16(&this->gamma_table_[lo + 1]);
22 return (target - a <= b - target) ? lo : lo + 1;
23}
24
26 // uncorrected = corrected^(1/gamma) / (max_brightness * local_brightness)
27 return Color(this->color_uncorrect_red(color.red), this->color_uncorrect_green(color.green),
28 this->color_uncorrect_blue(color.blue), this->color_uncorrect_white(color.white));
29}
30
31uint8_t ESPColorCorrection::color_uncorrect_channel_(uint8_t value, uint8_t max_brightness) const {
32 if (max_brightness == 0 || this->local_brightness_ == 0)
33 return 0;
34 // Use 32-bit intermediates: when max_brightness and local_brightness_ are small but non-zero,
35 // (uncorrected / max_brightness) * 255 can exceed 65535 before the std::min(255) clamp runs.
36 uint32_t uncorrected = this->gamma_uncorrect_(value) * 255UL;
37 uint32_t res = ((uncorrected / max_brightness) * 255UL) / this->local_brightness_;
38 return static_cast<uint8_t>(std::min(res, uint32_t(255)));
39}
40
41} // namespace esphome::light
uint8_t gamma_correct_(uint8_t value) const
Forward gamma: read uint16 PROGMEM table, convert to uint8.
uint8_t color_uncorrect_red(uint8_t red) const ESPHOME_ALWAYS_INLINE
uint8_t color_uncorrect_channel_(uint8_t value, uint8_t max_brightness) const
Shared body of color_uncorrect_{red,green,blue,white}.
uint8_t gamma_uncorrect_(uint8_t value) const
Reverse gamma: binary search the forward PROGMEM table.
uint8_t gamma_table_reverse_search(const uint16_t *table, uint16_t target)
Binary search a monotonically increasing uint16[256] PROGMEM table.
static float float b
uint16_t progmem_read_uint16(const uint16_t *addr)
Definition core.cpp:40
uint8_t red
Definition color.h:31
uint8_t white
Definition color.h:43
uint8_t green
Definition color.h:35
uint8_t blue
Definition color.h:39