From 498dd76730469cf3bde53851a4908c52c569b60b Mon Sep 17 00:00:00 2001 From: Christian Schwinne Date: Mon, 26 Jun 2023 18:16:38 +0200 Subject: [PATCH 01/34] Decouple segment led buffer from global led buffer --- wled00/FX.h | 11 +++++----- wled00/FX_fcn.cpp | 51 ++++++++++++++++++++++------------------------- wled00/cfg.cpp | 4 ++-- wled00/set.cpp | 2 +- wled00/xml.cpp | 2 +- 5 files changed, 34 insertions(+), 36 deletions(-) diff --git a/wled00/FX.h b/wled00/FX.h index 19b1fc4a..059bf820 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -380,7 +380,6 @@ typedef struct Segment { uint16_t aux1; // custom var byte* data; // effect data pointer CRGB* leds; // local leds[] array (may be a pointer to global) - static CRGB *_globalLeds; // global leds[] array static uint16_t maxWidth, maxHeight; // these define matrix width & height (max. segment dimensions) private: @@ -487,7 +486,7 @@ typedef struct Segment { //if (leds) Serial.printf(" [%u]", length()*sizeof(CRGB)); //Serial.println(); //#endif - if (!Segment::_globalLeds && leds) free(leds); + if (leds) free(leds); if (name) delete[] name; if (_t) delete _t; deallocateData(); @@ -497,7 +496,7 @@ typedef struct Segment { Segment& operator= (Segment &&orig) noexcept; // move assignment #ifdef WLED_DEBUG - size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0) + (!Segment::_globalLeds && leds?sizeof(CRGB)*length():0); } + size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0) + (leds?sizeof(CRGB)*length():0); } #endif inline bool getOption(uint8_t n) const { return ((options >> n) & 0x01); } @@ -710,7 +709,7 @@ class WS2812FX { // 96 bytes panel.clear(); #endif customPalettes.clear(); - if (useLedsArray && Segment::_globalLeds) free(Segment::_globalLeds); + if (_globalLedBuffer) free(_globalLedBuffer); } static WS2812FX* getInstance(void) { return instance; } @@ -758,7 +757,7 @@ class WS2812FX { // 96 bytes // return true if the strip is being sent pixel updates isUpdating(void), deserializeMap(uint8_t n=0), - useLedsArray = false; + useGlobalLedBuffer = false; inline bool isServicing(void) { return _isServicing; } inline bool hasWhiteChannel(void) {return _hasWhiteChannel;} @@ -905,6 +904,8 @@ class WS2812FX { // 96 bytes uint8_t _segment_index; uint8_t _mainSegment; + static uint32_t *_globalLedBuffer; // global leds[] array + void estimateCurrentAndLimitBri(void); }; diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 50d3f2f4..181819e6 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -74,7 +74,6 @@ // Segment class implementation /////////////////////////////////////////////////////////////////////////////// uint16_t Segment::_usedSegmentData = 0U; // amount of RAM all segments use for their data[] -CRGB *Segment::_globalLeds = nullptr; uint16_t Segment::maxWidth = DEFAULT_LED_COUNT; uint16_t Segment::maxHeight = 1; @@ -86,11 +85,11 @@ Segment::Segment(const Segment &orig) { data = nullptr; _dataLen = 0; _t = nullptr; - if (leds && !Segment::_globalLeds) leds = nullptr; + leds = nullptr; if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } - if (orig.leds && !Segment::_globalLeds) { leds = (CRGB*)malloc(sizeof(CRGB)*length()); if (leds) memcpy(leds, orig.leds, sizeof(CRGB)*length()); } + if (orig.leds) { leds = (CRGB*)malloc(sizeof(CRGB)*length()); if (leds) memcpy(leds, orig.leds, sizeof(CRGB)*length()); } } // move constructor @@ -111,7 +110,7 @@ Segment& Segment::operator= (const Segment &orig) { // clean destination if (name) delete[] name; if (_t) delete _t; - if (leds && !Segment::_globalLeds) free(leds); + if (leds) free(leds); deallocateData(); // copy source memcpy((void*)this, (void*)&orig, sizeof(Segment)); @@ -120,12 +119,12 @@ Segment& Segment::operator= (const Segment &orig) { data = nullptr; _dataLen = 0; _t = nullptr; - if (!Segment::_globalLeds) leds = nullptr; + leds = nullptr; // copy source data if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } - if (orig.leds && !Segment::_globalLeds) { leds = (CRGB*)malloc(sizeof(CRGB)*length()); if (leds) memcpy(leds, orig.leds, sizeof(CRGB)*length()); } + if (orig.leds) { leds = (CRGB*)malloc(sizeof(CRGB)*length()); if (leds) memcpy(leds, orig.leds, sizeof(CRGB)*length()); } } return *this; } @@ -137,7 +136,7 @@ Segment& Segment::operator= (Segment &&orig) noexcept { if (name) delete[] name; // free old name deallocateData(); // free old runtime data if (_t) delete _t; - if (leds && !Segment::_globalLeds) free(leds); + if (leds) free(leds); memcpy((void*)this, (void*)&orig, sizeof(Segment)); orig.name = nullptr; orig.data = nullptr; @@ -183,7 +182,7 @@ void Segment::deallocateData() { */ void Segment::resetIfRequired() { if (reset) { - if (leds && !Segment::_globalLeds) { free(leds); leds = nullptr; } + if (leds) { free(leds); leds = nullptr; } //if (transitional && _t) { transitional = false; delete _t; _t = nullptr; } deallocateData(); next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; @@ -193,19 +192,16 @@ void Segment::resetIfRequired() { void Segment::setUpLeds() { // deallocation happens in resetIfRequired() as it is called when segment changes or in destructor - if (Segment::_globalLeds) - #ifndef WLED_DISABLE_2D - leds = &Segment::_globalLeds[start + startY*Segment::maxWidth]; - #else - leds = &Segment::_globalLeds[start]; - #endif - else if (leds == nullptr && length() > 0) { //softhack007 quickfix - avoid malloc(0) which is undefined behaviour (should not happen, but i've seen it) + if (WS2812FX::_globalLedBuffer) return; // TODO optional seg buffer for FX without lossy restore due to opacity + + // no global buffer + if (leds == nullptr && length() > 0) { //softhack007 quickfix - avoid malloc(0) which is undefined behaviour (should not happen, but i've seen it) //#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_PSRAM) //if (psramFound()) // leds = (CRGB*)ps_malloc(sizeof(CRGB)*length()); // softhack007 disabled; putting leds into psram leads to horrible slowdown on WROVER boards //else //#endif - leds = (CRGB*)malloc(sizeof(CRGB)*length()); + leds = (CRGB*)malloc(sizeof(CRGB)*length()); } } @@ -1062,22 +1058,22 @@ void WS2812FX::finalizeInit(void) Segment::maxHeight = 1; } - //initialize leds array. TBD: realloc if nr of leds change - if (Segment::_globalLeds) { - purgeSegments(true); - free(Segment::_globalLeds); - Segment::_globalLeds = nullptr; + // initialize leds array + if (_globalLedBuffer) { + //purgeSegments(true); + free(_globalLedBuffer); + _globalLedBuffer = nullptr; } - if (useLedsArray) { - size_t arrSize = sizeof(CRGB) * getLengthTotal(); + if (useGlobalLedBuffer) { + size_t arrSize = sizeof(uint32_t) * getLengthTotal(); // softhack007 disabled; putting leds into psram leads to horrible slowdown on WROVER boards (see setUpLeds()) //#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_PSRAM) //if (psramFound()) - // Segment::_globalLeds = (CRGB*) ps_malloc(arrSize); + // Segment::_globalLedBuffer = (CRGB*) ps_malloc(arrSize); //else //#endif - Segment::_globalLeds = (CRGB*) malloc(arrSize); - memset(Segment::_globalLeds, 0, arrSize); + _globalLedBuffer = (uint32_t*) malloc(arrSize); + memset(_globalLedBuffer, 0, arrSize); } //segments are created in makeAutoSegments(); @@ -1604,7 +1600,7 @@ void WS2812FX::printSize() { DEBUG_PRINTF("Data: %d*%d=%uB\n", sizeof(const char *), _modeData.size(), (_modeData.capacity()*sizeof(const char *))); DEBUG_PRINTF("Map: %d*%d=%uB\n", sizeof(uint16_t), (int)customMappingSize, customMappingSize*sizeof(uint16_t)); size = getLengthTotal(); - if (useLedsArray) DEBUG_PRINTF("Buffer: %d*%u=%uB\n", sizeof(CRGB), size, size*sizeof(CRGB)); + if (useGlobalLedBuffer) DEBUG_PRINTF("Buffer: %d*%u=%uB\n", sizeof(CRGB), size, size*sizeof(CRGB)); } #endif @@ -1707,6 +1703,7 @@ bool WS2812FX::deserializeMap(uint8_t n) { WS2812FX* WS2812FX::instance = nullptr; +uint32_t* WS2812FX::_globalLedBuffer = nullptr; const char JSON_mode_names[] PROGMEM = R"=====(["FX names moved"])====="; const char JSON_palette_names[] PROGMEM = R"=====([ diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index 15ef0e1f..5b0fbd5f 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -90,7 +90,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { CJSON(strip.cctBlending, hw_led[F("cb")]); Bus::setCCTBlend(strip.cctBlending); strip.setTargetFps(hw_led["fps"]); //NOP if 0, default 42 FPS - CJSON(strip.useLedsArray, hw_led[F("ld")]); + CJSON(strip.useGlobalLedBuffer, hw_led[F("ld")]); #ifndef WLED_DISABLE_2D // 2D Matrix Settings @@ -706,7 +706,7 @@ void serializeConfig() { hw_led[F("cb")] = strip.cctBlending; hw_led["fps"] = strip.getTargetFps(); hw_led[F("rgbwm")] = Bus::getGlobalAWMode(); // global auto white mode override - hw_led[F("ld")] = strip.useLedsArray; + hw_led[F("ld")] = strip.useGlobalLedBuffer; #ifndef WLED_DISABLE_2D // 2D Matrix Settings diff --git a/wled00/set.cpp b/wled00/set.cpp index 588ae0cd..30d499d6 100644 --- a/wled00/set.cpp +++ b/wled00/set.cpp @@ -91,7 +91,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage) Bus::setCCTBlend(strip.cctBlending); Bus::setGlobalAWMode(request->arg(F("AW")).toInt()); strip.setTargetFps(request->arg(F("FR")).toInt()); - strip.useLedsArray = request->hasArg(F("LD")); + strip.useGlobalLedBuffer = request->hasArg(F("LD")); bool busesChanged = false; for (uint8_t s = 0; s < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; s++) { diff --git a/wled00/xml.cpp b/wled00/xml.cpp index e9eb8dd0..8057aac7 100644 --- a/wled00/xml.cpp +++ b/wled00/xml.cpp @@ -404,7 +404,7 @@ void getSettingsJS(byte subPage, char* dest) sappend('v',SET_F("CB"),strip.cctBlending); sappend('v',SET_F("FR"),strip.getTargetFps()); sappend('v',SET_F("AW"),Bus::getGlobalAWMode()); - sappend('c',SET_F("LD"),strip.useLedsArray); + sappend('c',SET_F("LD"),strip.useGlobalLedBuffer); for (uint8_t s=0; s < busses.getNumBusses(); s++) { Bus* bus = busses.getBus(s); From f6e86bfcf8a174278cd4990b3a68f932b9245f19 Mon Sep 17 00:00:00 2001 From: Christian Schwinne Date: Mon, 26 Jun 2023 22:12:32 +0200 Subject: [PATCH 02/34] First global buffer iteration --- wled00/FX.h | 5 +- wled00/FX_fcn.cpp | 36 +++++++++--- wled00/bus_manager.cpp | 4 +- wled00/bus_manager.h | 12 ++++ wled00/bus_wrapper.h | 130 ++++++++++++++++++++--------------------- 5 files changed, 111 insertions(+), 76 deletions(-) diff --git a/wled00/FX.h b/wled00/FX.h index 059bf820..6b312a21 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -677,6 +677,7 @@ class WS2812FX { // 96 bytes // true private variables _length(DEFAULT_LED_COUNT), _brightness(DEFAULT_BRIGHTNESS), + _renderBrightness(0), _transitionDur(750), _targetFps(WLED_FPS), _frametime(FRAMETIME_FIXED), @@ -875,7 +876,7 @@ class WS2812FX { // 96 bytes private: uint16_t _length; - uint8_t _brightness; + uint8_t _brightness, _renderBrightness; uint16_t _transitionDur; uint8_t _targetFps; @@ -906,7 +907,7 @@ class WS2812FX { // 96 bytes static uint32_t *_globalLedBuffer; // global leds[] array - void + uint8_t estimateCurrentAndLimitBri(void); }; diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 181819e6..90a28554 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1102,8 +1102,12 @@ void WS2812FX::service() { // last condition ensures all solid segments are updated at the same time if(nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC)) { - if (seg.grouping == 0) seg.grouping = 1; //sanity check - doShow = true; + if (seg.grouping == 0) seg.grouping = 1; // sanity check + if (!doShow) { + busses.setBrightness(_brightness); // bus luminance must be set before FX using setPixelColor() + _renderBrightness = _brightness; // save in case brightness gets changed while FX is calculated + doShow = true; + } uint16_t delay = FRAMETIME; if (!seg.freeze) { //only run effect function if not frozen @@ -1142,13 +1146,18 @@ void IRAM_ATTR WS2812FX::setPixelColor(int i, uint32_t col) { if (i < customMappingSize) i = customMappingTable[i]; if (i >= _length) return; - busses.setPixelColor(i, col); + if (_globalLedBuffer) { + _globalLedBuffer[i] = col; + } else { + busses.setPixelColor(i, col); + } } uint32_t WS2812FX::getPixelColor(uint16_t i) { if (i < customMappingSize) i = customMappingTable[i]; if (i >= _length) return 0; + if (_globalLedBuffer) return _globalLedBuffer[i]; return busses.getPixelColor(i); } @@ -1164,7 +1173,7 @@ uint32_t WS2812FX::getPixelColor(uint16_t i) #define MA_FOR_ESP 100 //how much mA does the ESP use (Wemos D1 about 80mA, ESP32 about 120mA) //you can set it to 0 if the ESP is powered by USB and the LEDs by external -void WS2812FX::estimateCurrentAndLimitBri() { +uint8_t WS2812FX::estimateCurrentAndLimitBri() { //power limit calculation //each LED can draw up 195075 "power units" (approx. 53mA) //one PU is the power it takes to have 1 channel 1 step brighter per brightness step @@ -1180,7 +1189,7 @@ void WS2812FX::estimateCurrentAndLimitBri() { if (ablMilliampsMax < 150 || actualMilliampsPerLed == 0) { //0 mA per LED and too low numbers turn off calculation currentMilliamps = 0; busses.setBrightness(_brightness); - return; + return _brightness; } uint16_t pLen = getLengthPhysical(); @@ -1219,13 +1228,14 @@ void WS2812FX::estimateCurrentAndLimitBri() { uint32_t powerSum0 = powerSum; powerSum *= _brightness; + uint8_t newBri = _brightness; if (powerSum > powerBudget) //scale brightness down to stay in current limit { float scale = (float)powerBudget / (float)powerSum; uint16_t scaleI = scale * 255; uint8_t scaleB = (scaleI > 255) ? 255 : scaleI; - uint8_t newBri = scale8(_brightness, scaleB); + newBri = scale8(_brightness, scaleB); busses.setBrightness(newBri); //to keep brightness uniform, sets virtual busses too currentMilliamps = (powerSum0 * newBri) / puPerMilliamp; } else { @@ -1234,6 +1244,7 @@ void WS2812FX::estimateCurrentAndLimitBri() { } currentMilliamps += MA_FOR_ESP; //add power of ESP back to estimate currentMilliamps += pLen; //add standby power back to estimate + return newBri; } void WS2812FX::show(void) { @@ -1242,7 +1253,16 @@ void WS2812FX::show(void) { show_callback callback = _callback; if (callback) callback(); - estimateCurrentAndLimitBri(); + uint8_t busBrightness = estimateCurrentAndLimitBri(); + + if (_globalLedBuffer) { // copy data from buffer to bus + for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, _globalLedBuffer[i]); + } else { + // if brightness changed since last show, must set everything again to update to new luminance + if (_renderBrightness != busBrightness) { + for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, busses.getPixelColor(i)); // LOSSY and slow! + } + } // some buses send asynchronously and this method will return before // all of the data has been sent. @@ -1254,6 +1274,7 @@ void WS2812FX::show(void) { if (diff > 0) fpsCurr = 1000 / diff; _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; _lastShow = now; + _renderBrightness = _brightness; } /** @@ -1321,6 +1342,7 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) { if (direct) { // would be dangerous if applied immediately (could exceed ABL), but will not output until the next show() busses.setBrightness(b); + _renderBrightness = b; } else { unsigned long t = millis(); if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) show(); //apply brightness change immediately if no refresh soon diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 4b96060e..729393cb 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -172,7 +172,7 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint16_t pOld = pix; pix = IC_INDEX_WS2812_1CH_3X(pix); - uint32_t c = PolyBus::getPixelColor(_busPtr, _iType, pix, co); + uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co)); switch (pOld % 3) { // get only the single channel case 0: c = RGBW32(G(c), G(c), G(c), G(c)); break; case 1: c = RGBW32(R(c), R(c), R(c), R(c)); break; @@ -180,7 +180,7 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { } return c; } - return PolyBus::getPixelColor(_busPtr, _iType, pix, co); + return restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co)); } uint8_t BusDigital::getPins(uint8_t* pinArray) { diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index b6d79d07..fd5d8651 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -223,6 +223,18 @@ class BusDigital : public Bus { uint16_t _frequencykHz = 0U; void * _busPtr = nullptr; const ColorOrderMap &_colorOrderMap; + + inline uint32_t restoreColorLossy(uint32_t c) { + if (_bri == 255) return c; + uint8_t* chan = (uint8_t*) &c; + + for (uint8_t i=0; i<4; i++) + { + uint16_t val = chan[i]; + chan[i] = (val << 8) / (_bri + 1); + } + return c; + } }; diff --git a/wled00/bus_wrapper.h b/wled00/bus_wrapper.h index dce23478..0314a793 100644 --- a/wled00/bus_wrapper.h +++ b/wled00/bus_wrapper.h @@ -810,97 +810,97 @@ class PolyBus { switch (busType) { case I_NONE: break; #ifdef ESP8266 - case I_8266_U0_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U0_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U0_400_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_400_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_400_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_400_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U0_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U0_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U0_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U0_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_U1_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_DM_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_8266_BB_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifdef ARDUINO_ARCH_ESP32 - case I_32_RN_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; #endif -// case I_32_BB_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; +// case I_32_BB_NEO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_RN_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; #endif -// case I_32_BB_NEO_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; +// case I_32_BB_NEO_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_RN_400_3: (static_cast(busPtr))->SetLuminance(b); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_400_3: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_400_3: (static_cast(busPtr))->SetLuminance(b); break; #endif -// case I_32_BB_400_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; +// case I_32_BB_400_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_RN_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_RN_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_I0_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_I0_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_TM1_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_I1_TM2_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_TM1_4: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_I1_TM2_3: (static_cast(busPtr))->SetLuminance(b); break; #endif - case I_32_RN_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; #endif -// case I_32_BB_UCS_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; +// case I_32_BB_UCS_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_32_RN_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; #endif -// case I_32_BB_UCS_4: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; +// case I_32_BB_UCS_4: (static_cast(busPtr))->SetLuminance(b); break; #endif - case I_HS_DOT_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_DOT_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_LPD_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_LPD_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_LPO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_LPO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_WS1_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_WS1_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_P98_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_P98_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_HS_DOT_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_SS_DOT_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_HS_LPD_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_SS_LPD_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_HS_LPO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_SS_LPO_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_HS_WS1_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_SS_WS1_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_HS_P98_3: (static_cast(busPtr))->SetLuminance(b); break; + case I_SS_P98_3: (static_cast(busPtr))->SetLuminance(b); break; } }; static uint32_t getPixelColor(void* busPtr, uint8_t busType, uint16_t pix, uint8_t co) { @@ -1209,4 +1209,4 @@ class PolyBus { } }; -#endif +#endif \ No newline at end of file From 61ba16b7799c5d674affdc4c7618f40d9abd526f Mon Sep 17 00:00:00 2001 From: Christian Schwinne Date: Tue, 27 Jun 2023 00:38:30 +0200 Subject: [PATCH 03/34] Global buffer and ABL fixes --- wled00/FX_fcn.cpp | 13 +++++++++++-- wled00/bus_manager.cpp | 1 + wled00/bus_manager.h | 4 +++- wled00/cfg.cpp | 9 +++++++-- wled00/data/settings_leds.htm | 2 +- wled00/wled.cpp | 9 +++++++-- 6 files changed, 30 insertions(+), 8 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 90a28554..206e626f 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1209,7 +1209,13 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { uint16_t len = bus->getLength(); uint32_t busPowerSum = 0; for (uint_fast16_t i = 0; i < len; i++) { //sum up the usage of each LED - uint32_t c = bus->getPixelColor(i); + uint32_t c = 0; + if (_globalLedBuffer) + { + c = _globalLedBuffer[bus->getStart() + i]; + } else { + c = bus->getPixelColor(i); + } byte r = R(c), g = G(c), b = B(c), w = W(c); if(useWackyWS2815PowerModel) { //ignore white component on WS2815 power calculation @@ -1253,6 +1259,7 @@ void WS2812FX::show(void) { show_callback callback = _callback; if (callback) callback(); + Bus::setRestoreBri(_renderBrightness); uint8_t busBrightness = estimateCurrentAndLimitBri(); if (_globalLedBuffer) { // copy data from buffer to bus @@ -1260,7 +1267,8 @@ void WS2812FX::show(void) { } else { // if brightness changed since last show, must set everything again to update to new luminance if (_renderBrightness != busBrightness) { - for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, busses.getPixelColor(i)); // LOSSY and slow! + for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, busses.getPixelColor(i)); // LOSSLESS due to trick (but still slow!) + Bus::setRestoreBri(busBrightness); } } @@ -1343,6 +1351,7 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) { // would be dangerous if applied immediately (could exceed ABL), but will not output until the next show() busses.setBrightness(b); _renderBrightness = b; + Bus::setRestoreBri(b); } else { unsigned long t = millis(); if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) show(); //apply brightness change immediately if no refresh soon diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 729393cb..4b75baad 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -563,3 +563,4 @@ uint16_t BusManager::getTotalLength() { int16_t Bus::_cct = -1; uint8_t Bus::_cctBlend = 0; uint8_t Bus::_gAWM = 255; +uint8_t Bus::_restaurationBri = 255; diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index fd5d8651..8740a9a2 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -154,6 +154,7 @@ class Bus { inline uint8_t getAutoWhiteMode() { return _autoWhiteMode; } inline static void setGlobalAWMode(uint8_t m) { if (m < 5) _gAWM = m; else _gAWM = AW_GLOBAL_DISABLED; } inline static uint8_t getGlobalAWMode() { return _gAWM; } + inline static void setRestoreBri(uint8_t b) { _restaurationBri = b; } bool reversed = false; @@ -168,6 +169,7 @@ class Bus { static uint8_t _gAWM; static int16_t _cct; static uint8_t _cctBlend; + static uint8_t _restaurationBri; // previous brightness used as setPixelColor was called. Used for lossy restoration uint32_t autoWhiteCalc(uint32_t c); }; @@ -231,7 +233,7 @@ class BusDigital : public Bus { for (uint8_t i=0; i<4; i++) { uint16_t val = chan[i]; - chan[i] = (val << 8) / (_bri + 1); + chan[i] = ((val << 8) + _restaurationBri) / (_restaurationBri + 1); //adding _bri slighly improves recovery / stops degradation on re-scale } return c; } diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index 5b0fbd5f..bc63f811 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -134,7 +134,8 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { if (fromFS || !ins.isNull()) { uint8_t s = 0; // bus iterator if (fromFS) busses.removeAll(); // can't safely manipulate busses directly in network callback - uint32_t mem = 0; + uint32_t mem = 0, globalBufMem = 0; + uint16_t maxlen = 0; bool busesChanged = false; for (JsonObject elm : ins) { if (s >= WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES) break; @@ -162,7 +163,11 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { if (fromFS) { BusConfig bc = BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz); mem += BusManager::memUsage(bc); - if (mem <= MAX_LED_MEMORY) if (busses.add(bc) == -1) break; // finalization will be done in WLED::beginStrip() + if (strip.useGlobalLedBuffer && start + length > maxlen) { + maxlen = start + length; + globalBufMem = maxlen * 4; + } + if (mem + globalBufMem <= MAX_LED_MEMORY) if (busses.add(bc) == -1) break; // finalization will be done in WLED::beginStrip() } else { if (busConfigs[s] != nullptr) delete busConfigs[s]; busConfigs[s] = new BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode); diff --git a/wled00/data/settings_leds.htm b/wled00/data/settings_leds.htm index 9f822294..11a34493 100644 --- a/wled00/data/settings_leds.htm +++ b/wled00/data/settings_leds.htm @@ -141,7 +141,7 @@ let len = parseInt(d.getElementsByName("LC"+n)[0].value); len += parseInt(d.getElementsByName("SL"+n)[0].value); // skipped LEDs are allocated too let dbl = 0; - if (d.Sf.LD.checked) dbl = len * 3; // double buffering + if (d.Sf.LD.checked) dbl = len * 4; // double buffering if (t < 32) { if (t==26 || t==29) len *= 2; // 16 bit LEDs if (maxM < 10000 && d.getElementsByName("L0"+n)[0].value == 3) { //8266 DMA uses 5x the mem diff --git a/wled00/wled.cpp b/wled00/wled.cpp index 6866a692..cd027c06 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -151,11 +151,16 @@ void WLED::loop() DEBUG_PRINTLN(F("Re-init busses.")); bool aligned = strip.checkSegmentAlignment(); //see if old segments match old bus(ses) busses.removeAll(); - uint32_t mem = 0; + uint32_t mem = 0, globalBufMem = 0; + uint16_t maxlen = 0; for (uint8_t i = 0; i < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; i++) { if (busConfigs[i] == nullptr) break; mem += BusManager::memUsage(*busConfigs[i]); - if (mem <= MAX_LED_MEMORY) { + if (strip.useGlobalLedBuffer && busConfigs[i]->start + busConfigs[i]->count > maxlen) { + maxlen = busConfigs[i]->start + busConfigs[i]->count; + globalBufMem = maxlen * 4; + } + if (mem + globalBufMem <= MAX_LED_MEMORY) { busses.add(*busConfigs[i]); } delete busConfigs[i]; busConfigs[i] = nullptr; From fa9b151c3682b66b2cf650f3030c23cd3f02d5eb Mon Sep 17 00:00:00 2001 From: Christian Schwinne Date: Tue, 27 Jun 2023 01:57:05 +0200 Subject: [PATCH 04/34] Slightly more efficient buffer copy to busses --- wled00/FX.cpp | 1 - wled00/FX_fcn.cpp | 3 ++- wled00/bus_manager.cpp | 11 ++++++++++- wled00/bus_manager.h | 4 +++- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/wled00/FX.cpp b/wled00/FX.cpp index ff69e439..5c0aa546 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -289,7 +289,6 @@ uint16_t mode_dynamic(void) { if (!SEGENV.allocateData(SEGLEN)) return mode_static(); //allocation failed if(SEGENV.call == 0) { - //SEGMENT.setUpLeds(); //lossless getPixelColor() //SEGMENT.fill(BLACK); for (int i = 0; i < SEGLEN; i++) SEGENV.data[i] = random8(); } diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 206e626f..dbe35a8c 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1263,7 +1263,8 @@ void WS2812FX::show(void) { uint8_t busBrightness = estimateCurrentAndLimitBri(); if (_globalLedBuffer) { // copy data from buffer to bus - for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, _globalLedBuffer[i]); + //for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, _globalLedBuffer[i]); + busses.setColorsFromBuffer(_globalLedBuffer); } else { // if brightness changed since last show, must set everything again to update to new luminance if (_renderBrightness != busBrightness) { diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 4b75baad..001ac1d4 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -506,7 +506,7 @@ void BusManager::setStatusPixel(uint32_t c) { } } -void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c, int16_t cct) { +void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c) { for (uint8_t i = 0; i < numBusses; i++) { Bus* b = busses[i]; uint16_t bstart = b->getStart(); @@ -515,6 +515,15 @@ void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c, int16_t cct) } } +void BusManager::setColorsFromBuffer(uint32_t* buf) { + for (uint8_t i = 0; i < numBusses; i++) { + Bus* b = busses[i]; + uint16_t bstart = b->getStart(); + for (uint16_t pix = 0; pix < b->getLength(); pix++) + busses[i]->setPixelColor(pix, buf[bstart + pix]); + } +} + void BusManager::setBrightness(uint8_t b) { for (uint8_t i = 0; i < numBusses; i++) { busses[i]->setBrightness(b); diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 8740a9a2..e550440a 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -357,7 +357,9 @@ class BusManager { void setStatusPixel(uint32_t c); - void setPixelColor(uint16_t pix, uint32_t c, int16_t cct=-1); + void setPixelColor(uint16_t pix, uint32_t c); + + void setColorsFromBuffer(uint32_t* buf); void setBrightness(uint8_t b); From 272f96b40558bffad51bf87b941828bceb70e3de Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Fri, 30 Jun 2023 21:12:59 +0200 Subject: [PATCH 05/34] Double buffering at bus level. --- wled00/FX.h | 19 ++--- wled00/FX_2Dfcn.cpp | 4 - wled00/FX_fcn.cpp | 106 ++++----------------------- wled00/bus_manager.cpp | 163 +++++++++++++++++++++++++++-------------- wled00/bus_manager.h | 21 ++++-- wled00/bus_wrapper.h | 118 +++++++++++++++++++++++++++-- wled00/cfg.cpp | 6 +- wled00/set.cpp | 2 +- wled00/wled.cpp | 2 +- wled00/wled.h | 15 ++-- wled00/xml.cpp | 2 +- 11 files changed, 266 insertions(+), 192 deletions(-) diff --git a/wled00/FX.h b/wled00/FX.h index 6b312a21..f5e7a4e3 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -379,7 +379,6 @@ typedef struct Segment { uint16_t aux0; // custom var uint16_t aux1; // custom var byte* data; // effect data pointer - CRGB* leds; // local leds[] array (may be a pointer to global) static uint16_t maxWidth, maxHeight; // these define matrix width & height (max. segment dimensions) private: @@ -462,7 +461,6 @@ typedef struct Segment { aux0(0), aux1(0), data(nullptr), - leds(nullptr), _capabilities(0), _dataLen(0), _t(nullptr) @@ -483,10 +481,8 @@ typedef struct Segment { //Serial.print(F("Destroying segment:")); //if (name) Serial.printf(" %s (%p)", name, name); //if (data) Serial.printf(" %d (%p)", (int)_dataLen, data); - //if (leds) Serial.printf(" [%u]", length()*sizeof(CRGB)); //Serial.println(); //#endif - if (leds) free(leds); if (name) delete[] name; if (_t) delete _t; deallocateData(); @@ -496,7 +492,7 @@ typedef struct Segment { Segment& operator= (Segment &&orig) noexcept; // move assignment #ifdef WLED_DEBUG - size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0) + (leds?sizeof(CRGB)*length():0); } + size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0); } #endif inline bool getOption(uint8_t n) const { return ((options >> n) & 0x01); } @@ -537,7 +533,7 @@ typedef struct Segment { * Safe to call from interrupts and network requests. */ inline void markForReset(void) { reset = true; } // setOption(SEG_OPTION_RESET, true) - void setUpLeds(void); // set up leds[] array for loseless getPixelColor() + inline void setUpLeds(void) {} // legacy filler (should be removed) // transition functions void startTransition(uint16_t dur); // transition has to start before actual segment values change @@ -578,7 +574,7 @@ typedef struct Segment { uint16_t virtualHeight(void) const; uint16_t nrOfVStrips(void) const; #ifndef WLED_DISABLE_2D - uint16_t XY(uint16_t x, uint16_t y); // support function to get relative index within segment (for leds[]) + uint16_t XY(uint16_t x, uint16_t y); // support function to get relative index within segment void setPixelColorXY(int x, int y, uint32_t c); // set relative pixel within segment with color void setPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { setPixelColorXY(x, y, RGBW32(r,g,b,w)); } // automatically inline void setPixelColorXY(int x, int y, CRGB c) { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); } // automatically inline @@ -677,7 +673,6 @@ class WS2812FX { // 96 bytes // true private variables _length(DEFAULT_LED_COUNT), _brightness(DEFAULT_BRIGHTNESS), - _renderBrightness(0), _transitionDur(750), _targetFps(WLED_FPS), _frametime(FRAMETIME_FIXED), @@ -710,7 +705,6 @@ class WS2812FX { // 96 bytes panel.clear(); #endif customPalettes.clear(); - if (_globalLedBuffer) free(_globalLedBuffer); } static WS2812FX* getInstance(void) { return instance; } @@ -757,8 +751,7 @@ class WS2812FX { // 96 bytes hasCCTBus(void), // return true if the strip is being sent pixel updates isUpdating(void), - deserializeMap(uint8_t n=0), - useGlobalLedBuffer = false; + deserializeMap(uint8_t n=0); inline bool isServicing(void) { return _isServicing; } inline bool hasWhiteChannel(void) {return _hasWhiteChannel;} @@ -876,7 +869,7 @@ class WS2812FX { // 96 bytes private: uint16_t _length; - uint8_t _brightness, _renderBrightness; + uint8_t _brightness; uint16_t _transitionDur; uint8_t _targetFps; @@ -905,8 +898,6 @@ class WS2812FX { // 96 bytes uint8_t _segment_index; uint8_t _mainSegment; - static uint32_t *_globalLedBuffer; // global leds[] array - uint8_t estimateCurrentAndLimitBri(void); }; diff --git a/wled00/FX_2Dfcn.cpp b/wled00/FX_2Dfcn.cpp index f4dac68d..5a5720b3 100644 --- a/wled00/FX_2Dfcn.cpp +++ b/wled00/FX_2Dfcn.cpp @@ -199,8 +199,6 @@ void /*IRAM_ATTR*/ Segment::setPixelColorXY(int x, int y, uint32_t col) if (Segment::maxHeight==1) return; // not a matrix set-up if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return; // if pixel would fall out of virtual segment just exit - if (leds) leds[XY(x,y)] = col; - uint8_t _bri_t = currentBri(on ? opacity : 0); if (_bri_t < 255) { byte r = scale8(R(col), _bri_t); @@ -286,8 +284,6 @@ void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa) // returns RGBW values of pixel uint32_t Segment::getPixelColorXY(uint16_t x, uint16_t y) { - int i = XY(x,y); - if (leds) return RGBW32(leds[i].r, leds[i].g, leds[i].b, 0); if (reverse ) x = virtualWidth() - x - 1; if (reverse_y) y = virtualHeight() - y - 1; if (transpose) { uint16_t t = x; x = y; y = t; } // swap X & Y if segment transposed diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index dbe35a8c..e0f132cd 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -85,11 +85,9 @@ Segment::Segment(const Segment &orig) { data = nullptr; _dataLen = 0; _t = nullptr; - leds = nullptr; if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } - if (orig.leds) { leds = (CRGB*)malloc(sizeof(CRGB)*length()); if (leds) memcpy(leds, orig.leds, sizeof(CRGB)*length()); } } // move constructor @@ -100,7 +98,6 @@ Segment::Segment(Segment &&orig) noexcept { orig.data = nullptr; orig._dataLen = 0; orig._t = nullptr; - orig.leds = nullptr; } // copy assignment @@ -110,7 +107,6 @@ Segment& Segment::operator= (const Segment &orig) { // clean destination if (name) delete[] name; if (_t) delete _t; - if (leds) free(leds); deallocateData(); // copy source memcpy((void*)this, (void*)&orig, sizeof(Segment)); @@ -119,12 +115,10 @@ Segment& Segment::operator= (const Segment &orig) { data = nullptr; _dataLen = 0; _t = nullptr; - leds = nullptr; // copy source data if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } - if (orig.leds) { leds = (CRGB*)malloc(sizeof(CRGB)*length()); if (leds) memcpy(leds, orig.leds, sizeof(CRGB)*length()); } } return *this; } @@ -136,13 +130,11 @@ Segment& Segment::operator= (Segment &&orig) noexcept { if (name) delete[] name; // free old name deallocateData(); // free old runtime data if (_t) delete _t; - if (leds) free(leds); memcpy((void*)this, (void*)&orig, sizeof(Segment)); orig.name = nullptr; orig.data = nullptr; orig._dataLen = 0; orig._t = nullptr; - orig.leds = nullptr; } return *this; } @@ -182,29 +174,12 @@ void Segment::deallocateData() { */ void Segment::resetIfRequired() { if (reset) { - if (leds) { free(leds); leds = nullptr; } - //if (transitional && _t) { transitional = false; delete _t; _t = nullptr; } deallocateData(); next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; reset = false; // setOption(SEG_OPTION_RESET, false); } } -void Segment::setUpLeds() { - // deallocation happens in resetIfRequired() as it is called when segment changes or in destructor - if (WS2812FX::_globalLedBuffer) return; // TODO optional seg buffer for FX without lossy restore due to opacity - - // no global buffer - if (leds == nullptr && length() > 0) { //softhack007 quickfix - avoid malloc(0) which is undefined behaviour (should not happen, but i've seen it) - //#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_PSRAM) - //if (psramFound()) - // leds = (CRGB*)ps_malloc(sizeof(CRGB)*length()); // softhack007 disabled; putting leds into psram leads to horrible slowdown on WROVER boards - //else - //#endif - leds = (CRGB*)malloc(sizeof(CRGB)*length()); - } -} - CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) { static unsigned long _lastPaletteChange = 0; // perhaps it should be per segment static CRGBPalette16 randomPalette = CRGBPalette16(DEFAULT_COLOR); @@ -617,8 +592,6 @@ void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col) } #endif - if (leds) leds[i] = col; - uint16_t len = length(); uint8_t _bri_t = currentBri(on ? opacity : 0); if (_bri_t < 255) { @@ -718,8 +691,6 @@ uint32_t Segment::getPixelColor(int i) } #endif - if (leds) return RGBW32(leds[i].r, leds[i].g, leds[i].b, 0); - if (reverse) i = virtualLength() - i - 1; i *= groupLength(); i += start; @@ -1058,24 +1029,6 @@ void WS2812FX::finalizeInit(void) Segment::maxHeight = 1; } - // initialize leds array - if (_globalLedBuffer) { - //purgeSegments(true); - free(_globalLedBuffer); - _globalLedBuffer = nullptr; - } - if (useGlobalLedBuffer) { - size_t arrSize = sizeof(uint32_t) * getLengthTotal(); - // softhack007 disabled; putting leds into psram leads to horrible slowdown on WROVER boards (see setUpLeds()) - //#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_PSRAM) - //if (psramFound()) - // Segment::_globalLedBuffer = (CRGB*) ps_malloc(arrSize); - //else - //#endif - _globalLedBuffer = (uint32_t*) malloc(arrSize); - memset(_globalLedBuffer, 0, arrSize); - } - //segments are created in makeAutoSegments(); DEBUG_PRINTLN(F("Loading custom palettes")); loadCustomPalettes(); // (re)load all custom palettes @@ -1103,11 +1056,10 @@ void WS2812FX::service() { if(nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC)) { if (seg.grouping == 0) seg.grouping = 1; // sanity check - if (!doShow) { - busses.setBrightness(_brightness); // bus luminance must be set before FX using setPixelColor() - _renderBrightness = _brightness; // save in case brightness gets changed while FX is calculated +// if (!doShow) { +// busses.setBrightness(_brightness); // bus luminance must be set before FX using setPixelColor() doShow = true; - } +// } uint16_t delay = FRAMETIME; if (!seg.freeze) { //only run effect function if not frozen @@ -1146,18 +1098,13 @@ void IRAM_ATTR WS2812FX::setPixelColor(int i, uint32_t col) { if (i < customMappingSize) i = customMappingTable[i]; if (i >= _length) return; - if (_globalLedBuffer) { - _globalLedBuffer[i] = col; - } else { - busses.setPixelColor(i, col); - } + busses.setPixelColor(i, col); } uint32_t WS2812FX::getPixelColor(uint16_t i) { if (i < customMappingSize) i = customMappingTable[i]; if (i >= _length) return 0; - if (_globalLedBuffer) return _globalLedBuffer[i]; return busses.getPixelColor(i); } @@ -1188,7 +1135,6 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { if (ablMilliampsMax < 150 || actualMilliampsPerLed == 0) { //0 mA per LED and too low numbers turn off calculation currentMilliamps = 0; - busses.setBrightness(_brightness); return _brightness; } @@ -1209,15 +1155,14 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { uint16_t len = bus->getLength(); uint32_t busPowerSum = 0; for (uint_fast16_t i = 0; i < len; i++) { //sum up the usage of each LED - uint32_t c = 0; - if (_globalLedBuffer) - { - c = _globalLedBuffer[bus->getStart() + i]; - } else { - c = bus->getPixelColor(i); - } + uint32_t c = bus->getPixelColor(i); byte r = R(c), g = G(c), b = B(c), w = W(c); - + if (useGlobalLedBuffer) { + r = scale8(r, _brightness); + g = scale8(g, _brightness); + b = scale8(b, _brightness); + w = scale8(w, _brightness); + } if(useWackyWS2815PowerModel) { //ignore white component on WS2815 power calculation busPowerSum += (MAX(MAX(r,g),b)) * 3; } else { @@ -1232,22 +1177,14 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { powerSum += busPowerSum; } - uint32_t powerSum0 = powerSum; - powerSum *= _brightness; uint8_t newBri = _brightness; - - if (powerSum > powerBudget) //scale brightness down to stay in current limit - { + if (powerSum > powerBudget) {//scale brightness down to stay in current limit float scale = (float)powerBudget / (float)powerSum; uint16_t scaleI = scale * 255; uint8_t scaleB = (scaleI > 255) ? 255 : scaleI; newBri = scale8(_brightness, scaleB); - busses.setBrightness(newBri); //to keep brightness uniform, sets virtual busses too - currentMilliamps = (powerSum0 * newBri) / puPerMilliamp; - } else { - currentMilliamps = powerSum / puPerMilliamp; - busses.setBrightness(_brightness); } + currentMilliamps = (powerSum * newBri) / puPerMilliamp; currentMilliamps += MA_FOR_ESP; //add power of ESP back to estimate currentMilliamps += pLen; //add standby power back to estimate return newBri; @@ -1259,19 +1196,8 @@ void WS2812FX::show(void) { show_callback callback = _callback; if (callback) callback(); - Bus::setRestoreBri(_renderBrightness); uint8_t busBrightness = estimateCurrentAndLimitBri(); - - if (_globalLedBuffer) { // copy data from buffer to bus - //for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, _globalLedBuffer[i]); - busses.setColorsFromBuffer(_globalLedBuffer); - } else { - // if brightness changed since last show, must set everything again to update to new luminance - if (_renderBrightness != busBrightness) { - for (uint16_t i = 0; i < _length; i++) busses.setPixelColor(i, busses.getPixelColor(i)); // LOSSLESS due to trick (but still slow!) - Bus::setRestoreBri(busBrightness); - } - } + busses.setBrightness(busBrightness); // some buses send asynchronously and this method will return before // all of the data has been sent. @@ -1283,7 +1209,6 @@ void WS2812FX::show(void) { if (diff > 0) fpsCurr = 1000 / diff; _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; _lastShow = now; - _renderBrightness = _brightness; } /** @@ -1351,8 +1276,6 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) { if (direct) { // would be dangerous if applied immediately (could exceed ABL), but will not output until the next show() busses.setBrightness(b); - _renderBrightness = b; - Bus::setRestoreBri(b); } else { unsigned long t = millis(); if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) show(); //apply brightness change immediately if no refresh soon @@ -1735,7 +1658,6 @@ bool WS2812FX::deserializeMap(uint8_t n) { WS2812FX* WS2812FX::instance = nullptr; -uint32_t* WS2812FX::_globalLedBuffer = nullptr; const char JSON_mode_names[] PROGMEM = R"=====(["FX names moved"])====="; const char JSON_palette_names[] PROGMEM = R"=====([ diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 001ac1d4..a3807dbe 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -91,6 +91,11 @@ uint32_t Bus::autoWhiteCalc(uint32_t c) { return RGBW32(r, g, b, w); } +uint8_t *Bus::allocData(size_t size) { + if (_data) free(_data); // should not happen, but for safety + return _data = (uint8_t *)(size>0 ? calloc(size, sizeof(uint8_t)) : nullptr); +} + BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bus(bc.type, bc.start, bc.autoWhite), _colorOrderMap(com) { if (!IS_DIGITAL(bc.type) || !bc.count) return; @@ -107,22 +112,57 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bu reversed = bc.reversed; _needsRefresh = bc.refreshReq || bc.type == TYPE_TM1814; _skip = bc.skipAmount; //sacrificial pixels - _len = bc.count + _skip; + _len = bc.count; + _colorOrder = bc.colorOrder; _iType = PolyBus::getI(bc.type, _pins, nr); if (_iType == I_NONE) return; + if (useGlobalLedBuffer && !allocData(_len * (hasWhite() + 3*hasRGB()))) return; //warning: hardcoded channel count uint16_t lenToCreate = _len; - if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus - _busPtr = PolyBus::create(_iType, _pins, lenToCreate, nr, _frequencykHz); + if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus + _busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz); _valid = (_busPtr != nullptr); - _colorOrder = bc.colorOrder; DEBUG_PRINTF("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u)\n", _valid?"S":"Uns", nr, _len, bc.type, _pins[0],_pins[1],_iType); } void BusDigital::show() { - PolyBus::show(_busPtr, _iType); + if (!_valid) return; + PolyBus::setBrightness(_busPtr, _iType, _bri); + if (useGlobalLedBuffer) { + size_t channels = hasWhite() + 3*hasRGB(); + for (size_t i=0; i<_len; i++) { + size_t offset = i*channels; + uint8_t co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder); + uint32_t c; + if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs (_len is always a multiple of 3) + switch (i%3) { + case 0: c = RGBW32(_data[offset] , _data[offset+1], _data[offset+2], 0); break; + case 1: c = RGBW32(_data[offset-1], _data[offset] , _data[offset+1], 0); break; + case 2: c = RGBW32(_data[offset-2], _data[offset-1], _data[offset] , 0); break; + } + } else { + c = RGBW32(_data[offset],_data[offset+1],_data[offset+2],(hasWhite()?_data[offset+3]:0)); + } + uint16_t pix = i; + if (reversed) pix = _len - pix -1; + else pix += _skip; + PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); + } + PolyBus::show(_busPtr, _iType); + } else { + PolyBus::applyPostAdjustments(_busPtr, _iType); + PolyBus::show(_busPtr, _iType); + // now restore (as close as possible) previous colors + // warning: this may not be the best idea as the buffer may still be in use + for (size_t i=0; i<_len; i++) { + uint8_t co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder); + setPixelColor(i, restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, i, co), _bri)); + } + } + PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness } bool BusDigital::canShow() { + if (!_valid) return true; return PolyBus::canShow(_busPtr, _iType); } @@ -130,57 +170,81 @@ void BusDigital::setBrightness(uint8_t b) { //Fix for turning off onboard LED breaking bus #ifdef LED_BUILTIN if (_bri == 0 && b > 0) { - if (_pins[0] == LED_BUILTIN || _pins[1] == LED_BUILTIN) PolyBus::begin(_busPtr, _iType, _pins); + if (_pins[0] == LED_BUILTIN || _pins[1] == LED_BUILTIN) reinit(); } #endif Bus::setBrightness(b); - PolyBus::setBrightness(_busPtr, _iType, b); } //If LEDs are skipped, it is possible to use the first as a status LED. //TODO only show if no new show due in the next 50ms void BusDigital::setStatusPixel(uint32_t c) { - if (_skip && canShow()) { + if (_valid && _skip && canShow()) { PolyBus::setPixelColor(_busPtr, _iType, 0, c, _colorOrderMap.getPixelColorOrder(_start, _colorOrder)); PolyBus::show(_busPtr, _iType); } } void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { - if (_type == TYPE_SK6812_RGBW || _type == TYPE_TM1814 || _type == TYPE_WS2812_1CH_X3) c = autoWhiteCalc(c); + if (!_valid) return; + if (hasWhite()) c = autoWhiteCalc(c); if (_cct >= 1900) c = colorBalanceFromKelvin(_cct, c); //color correction from CCT - if (reversed) pix = _len - pix -1; - else pix += _skip; - uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); - if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs - uint16_t pOld = pix; - pix = IC_INDEX_WS2812_1CH_3X(pix); - uint32_t cOld = PolyBus::getPixelColor(_busPtr, _iType, pix, co); - switch (pOld % 3) { // change only the single channel (TODO: this can cause loss because of get/set) - case 0: c = RGBW32(R(cOld), W(c) , B(cOld), 0); break; - case 1: c = RGBW32(W(c) , G(cOld), B(cOld), 0); break; - case 2: c = RGBW32(R(cOld), G(cOld), W(c) , 0); break; + if (useGlobalLedBuffer) { + size_t channels = hasWhite() + 3*hasRGB(); + size_t offset = pix*channels; + if (hasRGB()) { + _data[offset++] = R(c); + _data[offset++] = G(c); + _data[offset++] = B(c); } + if (hasWhite()) _data[offset] = W(c); + } else { + if (reversed) pix = _len - pix -1; + else pix += _skip; + uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); + if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs + uint16_t pOld = pix; + pix = IC_INDEX_WS2812_1CH_3X(pix); + uint32_t cOld = PolyBus::getPixelColor(_busPtr, _iType, pix, co); + switch (pOld % 3) { // change only the single channel (TODO: this can cause loss because of get/set) + case 0: c = RGBW32(R(cOld), W(c) , B(cOld), 0); break; + case 1: c = RGBW32(W(c) , G(cOld), B(cOld), 0); break; + case 2: c = RGBW32(R(cOld), G(cOld), W(c) , 0); break; + } + } + PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); } - PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); } uint32_t BusDigital::getPixelColor(uint16_t pix) { - if (reversed) pix = _len - pix -1; - else pix += _skip; - uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); - if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs - uint16_t pOld = pix; - pix = IC_INDEX_WS2812_1CH_3X(pix); - uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co)); - switch (pOld % 3) { // get only the single channel - case 0: c = RGBW32(G(c), G(c), G(c), G(c)); break; - case 1: c = RGBW32(R(c), R(c), R(c), R(c)); break; - case 2: c = RGBW32(B(c), B(c), B(c), B(c)); break; + if (!_valid) return 0; + if (useGlobalLedBuffer) { + size_t channels = hasWhite() + 3*hasRGB(); + size_t offset = pix*channels; + uint32_t c; + if (!hasRGB()) { + c = RGBW32(_data[offset], _data[offset], _data[offset], _data[offset]); + } else { + c = RGBW32(_data[offset], _data[offset+1], _data[offset+2], hasWhite() ? _data[offset+3] : 0); } return c; + } else { + if (reversed) pix = _len - pix -1; + else pix += _skip; + uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); + if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs + uint16_t pOld = pix; + pix = IC_INDEX_WS2812_1CH_3X(pix); + uint32_t c = PolyBus::getPixelColor(_busPtr, _iType, pix, co); + switch (pOld % 3) { // get only the single channel + case 0: c = RGBW32(G(c), G(c), G(c), G(c)); break; + case 1: c = RGBW32(R(c), R(c), R(c), R(c)); break; + case 2: c = RGBW32(B(c), B(c), B(c), B(c)); break; + } + return c; + } + return PolyBus::getPixelColor(_busPtr, _iType, pix, co); } - return restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co)); } uint8_t BusDigital::getPins(uint8_t* pinArray) { @@ -196,6 +260,7 @@ void BusDigital::setColorOrder(uint8_t colorOrder) { } void BusDigital::reinit() { + if (!_valid) return; PolyBus::begin(_busPtr, _iType, _pins); } @@ -205,6 +270,7 @@ void BusDigital::cleanup() { _iType = I_NONE; _valid = false; _busPtr = nullptr; + if (useGlobalLedBuffer) freeData(); pinManager.deallocatePin(_pins[1], PinOwner::BusDigital); pinManager.deallocatePin(_pins[0], PinOwner::BusDigital); } @@ -229,7 +295,7 @@ BusPwm::BusPwm(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { for (uint8_t i = 0; i < numPins; i++) { uint8_t currentPin = bc.pins[i]; if (!pinManager.allocatePin(currentPin, true, PinOwner::BusPwm)) { - deallocatePins(); return; + deallocatePins(); return; } _pins[i] = currentPin; //store only after allocatePin() succeeds #ifdef ESP8266 @@ -240,6 +306,7 @@ BusPwm::BusPwm(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { #endif } reversed = bc.reversed; + _data = _pwmdata; // avoid malloc() and use stack _valid = true; } @@ -353,6 +420,7 @@ BusOnOff::BusOnOff(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { _pin = currentPin; //store only after allocatePin() succeeds pinMode(_pin, OUTPUT); reversed = bc.reversed; + _data = &_onoffdata; // avoid malloc() and use stack _valid = true; } @@ -363,18 +431,17 @@ void BusOnOff::setPixelColor(uint16_t pix, uint32_t c) { uint8_t g = G(c); uint8_t b = B(c); uint8_t w = W(c); - - _data = bool(r|g|b|w) && bool(_bri) ? 0xFF : 0; + _data[0] = bool(r|g|b|w) && bool(_bri) ? 0xFF : 0; } uint32_t BusOnOff::getPixelColor(uint16_t pix) { if (!_valid) return 0; - return RGBW32(_data, _data, _data, _data); + return RGBW32(_data[0], _data[0], _data[0], _data[0]); } void BusOnOff::show() { if (!_valid) return; - digitalWrite(_pin, reversed ? !(bool)_data : (bool)_data); + digitalWrite(_pin, reversed ? !(bool)_data[0] : (bool)_data[0]); } uint8_t BusOnOff::getPins(uint8_t* pinArray) { @@ -401,13 +468,10 @@ BusNetwork::BusNetwork(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { break; } _UDPchannels = _rgbw ? 4 : 3; - _data = (byte *)malloc(bc.count * _UDPchannels); - if (_data == nullptr) return; - memset(_data, 0, bc.count * _UDPchannels); _len = bc.count; _client = IPAddress(bc.pins[0],bc.pins[1],bc.pins[2],bc.pins[3]); _broadcastLock = false; - _valid = true; + _valid = (allocData(_len * _UDPchannels) != nullptr); } void BusNetwork::setPixelColor(uint16_t pix, uint32_t c) { @@ -424,7 +488,7 @@ void BusNetwork::setPixelColor(uint16_t pix, uint32_t c) { uint32_t BusNetwork::getPixelColor(uint16_t pix) { if (!_valid || pix >= _len) return 0; uint16_t offset = pix * _UDPchannels; - return RGBW32(_data[offset], _data[offset+1], _data[offset+2], _rgbw ? (_data[offset+3] << 24) : 0); + return RGBW32(_data[offset], _data[offset+1], _data[offset+2], (_rgbw ? _data[offset+3] : 0)); } void BusNetwork::show() { @@ -444,8 +508,7 @@ uint8_t BusNetwork::getPins(uint8_t* pinArray) { void BusNetwork::cleanup() { _type = I_NONE; _valid = false; - if (_data != nullptr) free(_data); - _data = nullptr; + freeData(); } @@ -515,15 +578,6 @@ void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c) { } } -void BusManager::setColorsFromBuffer(uint32_t* buf) { - for (uint8_t i = 0; i < numBusses; i++) { - Bus* b = busses[i]; - uint16_t bstart = b->getStart(); - for (uint16_t pix = 0; pix < b->getLength(); pix++) - busses[i]->setPixelColor(pix, buf[bstart + pix]); - } -} - void BusManager::setBrightness(uint8_t b) { for (uint8_t i = 0; i < numBusses; i++) { busses[i]->setBrightness(b); @@ -572,4 +626,3 @@ uint16_t BusManager::getTotalLength() { int16_t Bus::_cct = -1; uint8_t Bus::_cctBlend = 0; uint8_t Bus::_gAWM = 255; -uint8_t Bus::_restaurationBri = 255; diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index e550440a..8e78310b 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -18,6 +18,10 @@ #define IC_INDEX_WS2812_2CH_3X(i) ((i)*2/3) #define WS2812_2CH_3X_SPANS_2_ICS(i) ((i)&0x01) // every other LED zone is on two different ICs +// flag for using double buffering in BusDigital +extern bool useGlobalLedBuffer; + + //temporary struct for passing bus configuration to bus struct BusConfig { uint8_t type; @@ -54,6 +58,7 @@ struct BusConfig { } }; + // Defines an LED Strip and its color ordering. struct ColorOrderMapEntry { uint16_t start; @@ -87,12 +92,14 @@ struct ColorOrderMap { ColorOrderMapEntry _mappings[WLED_MAX_COLOR_ORDER_MAPPINGS]; }; + //parent class of BusDigital, BusPwm, and BusNetwork class Bus { public: Bus(uint8_t type, uint16_t start, uint8_t aw) : _bri(255) , _len(1) + , _data(nullptr) // keep data access consistent across all types of buses , _valid(false) , _needsRefresh(false) { @@ -154,7 +161,6 @@ class Bus { inline uint8_t getAutoWhiteMode() { return _autoWhiteMode; } inline static void setGlobalAWMode(uint8_t m) { if (m < 5) _gAWM = m; else _gAWM = AW_GLOBAL_DISABLED; } inline static uint8_t getGlobalAWMode() { return _gAWM; } - inline static void setRestoreBri(uint8_t b) { _restaurationBri = b; } bool reversed = false; @@ -163,15 +169,17 @@ class Bus { uint8_t _bri; uint16_t _start; uint16_t _len; + uint8_t *_data; bool _valid; bool _needsRefresh; uint8_t _autoWhiteMode; static uint8_t _gAWM; static int16_t _cct; static uint8_t _cctBlend; - static uint8_t _restaurationBri; // previous brightness used as setPixelColor was called. Used for lossy restoration uint32_t autoWhiteCalc(uint32_t c); + uint8_t *allocData(size_t size = 1); + void freeData() { if (_data) free(_data); _data = nullptr; } }; @@ -226,7 +234,7 @@ class BusDigital : public Bus { void * _busPtr = nullptr; const ColorOrderMap &_colorOrderMap; - inline uint32_t restoreColorLossy(uint32_t c) { + inline uint32_t restoreColorLossy(uint32_t c, uint8_t _restaurationBri) { if (_bri == 255) return c; uint8_t* chan = (uint8_t*) &c; @@ -265,7 +273,7 @@ class BusPwm : public Bus { private: uint8_t _pins[5] = {255, 255, 255, 255, 255}; - uint8_t _data[5] = {0}; + uint8_t _pwmdata[5] = {0}; #ifdef ARDUINO_ARCH_ESP32 uint8_t _ledcStart = 255; #endif @@ -297,7 +305,7 @@ class BusOnOff : public Bus { private: uint8_t _pin = 255; - uint8_t _data = 0; + uint8_t _onoffdata = 0; }; @@ -337,7 +345,6 @@ class BusNetwork : public Bus { uint8_t _UDPchannels; bool _rgbw; bool _broadcastLock; - byte *_data; }; @@ -359,8 +366,6 @@ class BusManager { void setPixelColor(uint16_t pix, uint32_t c); - void setColorsFromBuffer(uint32_t* buf); - void setBrightness(uint8_t b); void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); diff --git a/wled00/bus_wrapper.h b/wled00/bus_wrapper.h index 0314a793..9807c54b 100644 --- a/wled00/bus_wrapper.h +++ b/wled00/bus_wrapper.h @@ -280,6 +280,7 @@ class PolyBus { #endif if (clock_kHz) dotStar_strip->SetMethodSettings(NeoSpiSettings((uint32_t)clock_kHz*1000)); } + // Begin & initialize the PixelSettings for TM1814 strips. template static void beginTM1814(void* busPtr) { @@ -288,6 +289,7 @@ class PolyBus { // Max current for each LED (22.5 mA). tm1814_strip->SetPixelSettings(NeoTm1814Settings(/*R*/225, /*G*/225, /*B*/225, /*W*/225)); } + static void begin(void* busPtr, uint8_t busType, uint8_t* pins, uint16_t clock_kHz = 0U) { switch (busType) { case I_NONE: break; @@ -390,7 +392,8 @@ class PolyBus { case I_SS_WS1_3: (static_cast(busPtr))->Begin(); break; case I_SS_P98_3: (static_cast(busPtr))->Begin(); break; } - }; + } + static void* create(uint8_t busType, uint8_t* pins, uint16_t len, uint8_t channel, uint16_t clock_kHz = 0U) { void* busPtr = nullptr; switch (busType) { @@ -491,7 +494,8 @@ class PolyBus { } begin(busPtr, busType, pins, clock_kHz); return busPtr; - }; + } + static void show(void* busPtr, uint8_t busType) { switch (busType) { case I_NONE: break; @@ -588,7 +592,8 @@ class PolyBus { case I_HS_P98_3: (static_cast(busPtr))->Show(); break; case I_SS_P98_3: (static_cast(busPtr))->Show(); break; } - }; + } + static bool canShow(void* busPtr, uint8_t busType) { switch (busType) { case I_NONE: return true; @@ -685,7 +690,8 @@ class PolyBus { case I_SS_P98_3: return (static_cast(busPtr))->CanShow(); break; } return true; - }; + } + static void setPixelColor(void* busPtr, uint8_t busType, uint16_t pix, uint32_t c, uint8_t co) { uint8_t r = c >> 16; uint8_t g = c >> 8; @@ -805,7 +811,8 @@ class PolyBus { case I_HS_P98_3: (static_cast(busPtr))->SetPixelColor(pix, RgbColor(col)); break; case I_SS_P98_3: (static_cast(busPtr))->SetPixelColor(pix, RgbColor(col)); break; } - }; + } + static void setBrightness(void* busPtr, uint8_t busType, uint8_t b) { switch (busType) { case I_NONE: break; @@ -902,7 +909,106 @@ class PolyBus { case I_HS_P98_3: (static_cast(busPtr))->SetLuminance(b); break; case I_SS_P98_3: (static_cast(busPtr))->SetLuminance(b); break; } - }; + } + + static void applyPostAdjustments(void* busPtr, uint8_t busType) { + switch (busType) { + case I_NONE: break; + #ifdef ESP8266 + case I_8266_U0_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U0_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_U1_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_DM_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_8266_BB_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifdef ARDUINO_ARCH_ESP32 + case I_32_RN_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #ifndef WLED_NO_I2S0_PIXELBUS + case I_32_I0_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifndef WLED_NO_I2S1_PIXELBUS + case I_32_I1_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif +// case I_32_BB_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #ifndef WLED_NO_I2S0_PIXELBUS + case I_32_I0_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifndef WLED_NO_I2S1_PIXELBUS + case I_32_I1_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif +// case I_32_BB_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #ifndef WLED_NO_I2S0_PIXELBUS + case I_32_I0_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifndef WLED_NO_I2S1_PIXELBUS + case I_32_I1_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif +// case I_32_BB_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #ifndef WLED_NO_I2S0_PIXELBUS + case I_32_I0_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I0_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifndef WLED_NO_I2S1_PIXELBUS + case I_32_I1_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_I1_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + case I_32_RN_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #ifndef WLED_NO_I2S0_PIXELBUS + case I_32_I0_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifndef WLED_NO_I2S1_PIXELBUS + case I_32_I1_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif +// case I_32_BB_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_32_RN_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #ifndef WLED_NO_I2S0_PIXELBUS + case I_32_I0_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + #ifndef WLED_NO_I2S1_PIXELBUS + case I_32_I1_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif +// case I_32_BB_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; + #endif + case I_HS_DOT_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_SS_DOT_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_HS_LPD_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_SS_LPD_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_HS_LPO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_SS_LPO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_HS_WS1_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_SS_WS1_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_HS_P98_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + case I_SS_P98_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; + } + } + static uint32_t getPixelColor(void* busPtr, uint8_t busType, uint16_t pix, uint8_t co) { RgbwColor col(0,0,0,0); switch (busType) { diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index bc63f811..6c2e9422 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -90,7 +90,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { CJSON(strip.cctBlending, hw_led[F("cb")]); Bus::setCCTBlend(strip.cctBlending); strip.setTargetFps(hw_led["fps"]); //NOP if 0, default 42 FPS - CJSON(strip.useGlobalLedBuffer, hw_led[F("ld")]); + CJSON(useGlobalLedBuffer, hw_led[F("ld")]); #ifndef WLED_DISABLE_2D // 2D Matrix Settings @@ -163,7 +163,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { if (fromFS) { BusConfig bc = BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz); mem += BusManager::memUsage(bc); - if (strip.useGlobalLedBuffer && start + length > maxlen) { + if (useGlobalLedBuffer && start + length > maxlen) { maxlen = start + length; globalBufMem = maxlen * 4; } @@ -711,7 +711,7 @@ void serializeConfig() { hw_led[F("cb")] = strip.cctBlending; hw_led["fps"] = strip.getTargetFps(); hw_led[F("rgbwm")] = Bus::getGlobalAWMode(); // global auto white mode override - hw_led[F("ld")] = strip.useGlobalLedBuffer; + hw_led[F("ld")] = useGlobalLedBuffer; #ifndef WLED_DISABLE_2D // 2D Matrix Settings diff --git a/wled00/set.cpp b/wled00/set.cpp index 30d499d6..3420f22c 100644 --- a/wled00/set.cpp +++ b/wled00/set.cpp @@ -91,7 +91,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage) Bus::setCCTBlend(strip.cctBlending); Bus::setGlobalAWMode(request->arg(F("AW")).toInt()); strip.setTargetFps(request->arg(F("FR")).toInt()); - strip.useGlobalLedBuffer = request->hasArg(F("LD")); + useGlobalLedBuffer = request->hasArg(F("LD")); bool busesChanged = false; for (uint8_t s = 0; s < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; s++) { diff --git a/wled00/wled.cpp b/wled00/wled.cpp index cd027c06..86d14d6a 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -156,7 +156,7 @@ void WLED::loop() for (uint8_t i = 0; i < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; i++) { if (busConfigs[i] == nullptr) break; mem += BusManager::memUsage(*busConfigs[i]); - if (strip.useGlobalLedBuffer && busConfigs[i]->start + busConfigs[i]->count > maxlen) { + if (useGlobalLedBuffer && busConfigs[i]->start + busConfigs[i]->count > maxlen) { maxlen = busConfigs[i]->start + busConfigs[i]->count; globalBufMem = maxlen * 4; } diff --git a/wled00/wled.h b/wled00/wled.h index 6cae6a8a..7fc3ba86 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -8,7 +8,7 @@ */ // version code in format yymmddb (b = daily build) -#define VERSION 2306240 +#define VERSION 23062490 //uncomment this if you have a "my_config.h" file you'd like to use //#define WLED_USE_MY_CONFIG @@ -331,12 +331,13 @@ WLED_GLOBAL byte bootPreset _INIT(0); // save preset to load //if true, a segment per bus will be created on boot and LED settings save //if false, only one segment spanning the total LEDs is created, //but not on LED settings save if there is more than one segment currently -WLED_GLOBAL bool autoSegments _INIT(false); -WLED_GLOBAL bool correctWB _INIT(false); // CCT color correction of RGB color -WLED_GLOBAL bool cctFromRgb _INIT(false); // CCT is calculated from RGB instead of using seg.cct -WLED_GLOBAL bool gammaCorrectCol _INIT(true ); // use gamma correction on colors -WLED_GLOBAL bool gammaCorrectBri _INIT(false); // use gamma correction on brightness -WLED_GLOBAL float gammaCorrectVal _INIT(2.8f); // gamma correction value +WLED_GLOBAL bool autoSegments _INIT(false); +WLED_GLOBAL bool useGlobalLedBuffer _INIT(true); +WLED_GLOBAL bool correctWB _INIT(false); // CCT color correction of RGB color +WLED_GLOBAL bool cctFromRgb _INIT(false); // CCT is calculated from RGB instead of using seg.cct +WLED_GLOBAL bool gammaCorrectCol _INIT(true); // use gamma correction on colors +WLED_GLOBAL bool gammaCorrectBri _INIT(false); // use gamma correction on brightness +WLED_GLOBAL float gammaCorrectVal _INIT(2.8f); // gamma correction value WLED_GLOBAL byte col[] _INIT_N(({ 255, 160, 0, 0 })); // current RGB(W) primary color. col[] should be updated if you want to change the color. WLED_GLOBAL byte colSec[] _INIT_N(({ 0, 0, 0, 0 })); // current RGB(W) secondary color diff --git a/wled00/xml.cpp b/wled00/xml.cpp index 8057aac7..12fc9717 100644 --- a/wled00/xml.cpp +++ b/wled00/xml.cpp @@ -404,7 +404,7 @@ void getSettingsJS(byte subPage, char* dest) sappend('v',SET_F("CB"),strip.cctBlending); sappend('v',SET_F("FR"),strip.getTargetFps()); sappend('v',SET_F("AW"),Bus::getGlobalAWMode()); - sappend('c',SET_F("LD"),strip.useGlobalLedBuffer); + sappend('c',SET_F("LD"),useGlobalLedBuffer); for (uint8_t s=0; s < busses.getNumBusses(); s++) { Bus* bus = busses.getBus(s); From 858b57d77a58c1c09585abf650b4e186310e9dd6 Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Sat, 1 Jul 2023 21:48:30 +0200 Subject: [PATCH 06/34] Return of local leds[] --- wled00/FX.h | 7 +++++-- wled00/FX_2Dfcn.cpp | 3 +++ wled00/FX_fcn.cpp | 28 ++++++++++++++++++++++++++++ wled00/bus_manager.cpp | 13 +++---------- 4 files changed, 39 insertions(+), 12 deletions(-) diff --git a/wled00/FX.h b/wled00/FX.h index f5e7a4e3..f58f2524 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -379,6 +379,7 @@ typedef struct Segment { uint16_t aux0; // custom var uint16_t aux1; // custom var byte* data; // effect data pointer + uint32_t* leds; // local leds[] array (may be a pointer to global) static uint16_t maxWidth, maxHeight; // these define matrix width & height (max. segment dimensions) private: @@ -461,6 +462,7 @@ typedef struct Segment { aux0(0), aux1(0), data(nullptr), + leds(nullptr), _capabilities(0), _dataLen(0), _t(nullptr) @@ -485,6 +487,7 @@ typedef struct Segment { //#endif if (name) delete[] name; if (_t) delete _t; + if (leds) free(leds); deallocateData(); } @@ -492,7 +495,7 @@ typedef struct Segment { Segment& operator= (Segment &&orig) noexcept; // move assignment #ifdef WLED_DEBUG - size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0); } + size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0) + (leds?sizeof(CRGB)*length():0); } #endif inline bool getOption(uint8_t n) const { return ((options >> n) & 0x01); } @@ -533,7 +536,7 @@ typedef struct Segment { * Safe to call from interrupts and network requests. */ inline void markForReset(void) { reset = true; } // setOption(SEG_OPTION_RESET, true) - inline void setUpLeds(void) {} // legacy filler (should be removed) + void setUpLeds(void); // local double buffer/lossless getPixelColor() // transition functions void startTransition(uint16_t dur); // transition has to start before actual segment values change diff --git a/wled00/FX_2Dfcn.cpp b/wled00/FX_2Dfcn.cpp index 5a5720b3..45238824 100644 --- a/wled00/FX_2Dfcn.cpp +++ b/wled00/FX_2Dfcn.cpp @@ -199,6 +199,8 @@ void /*IRAM_ATTR*/ Segment::setPixelColorXY(int x, int y, uint32_t col) if (Segment::maxHeight==1) return; // not a matrix set-up if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return; // if pixel would fall out of virtual segment just exit + if (leds) leds[XY(x,y)] = col; + uint8_t _bri_t = currentBri(on ? opacity : 0); if (_bri_t < 255) { byte r = scale8(R(col), _bri_t); @@ -284,6 +286,7 @@ void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa) // returns RGBW values of pixel uint32_t Segment::getPixelColorXY(uint16_t x, uint16_t y) { + if (leds) return leds[XY(x,y)]; if (reverse ) x = virtualWidth() - x - 1; if (reverse_y) y = virtualHeight() - y - 1; if (transpose) { uint16_t t = x; x = y; y = t; } // swap X & Y if segment transposed diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index e0f132cd..7c97c9b6 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -85,9 +85,11 @@ Segment::Segment(const Segment &orig) { data = nullptr; _dataLen = 0; _t = nullptr; + leds = nullptr; if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } + if (orig.leds) { leds = (uint32_t*)malloc(sizeof(uint32_t)*length()); if (leds) memcpy(leds, orig.leds, sizeof(uint32_t)*length()); } } // move constructor @@ -98,6 +100,7 @@ Segment::Segment(Segment &&orig) noexcept { orig.data = nullptr; orig._dataLen = 0; orig._t = nullptr; + orig.leds = nullptr; } // copy assignment @@ -107,6 +110,7 @@ Segment& Segment::operator= (const Segment &orig) { // clean destination if (name) delete[] name; if (_t) delete _t; + if (leds) free(leds); deallocateData(); // copy source memcpy((void*)this, (void*)&orig, sizeof(Segment)); @@ -115,10 +119,12 @@ Segment& Segment::operator= (const Segment &orig) { data = nullptr; _dataLen = 0; _t = nullptr; + leds = nullptr; // copy source data if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } + if (orig.leds) { leds = (uint32_t*)malloc(sizeof(uint32_t)*length()); if (leds) memcpy(leds, orig.leds, sizeof(uint32_t)*length()); } } return *this; } @@ -128,6 +134,7 @@ Segment& Segment::operator= (Segment &&orig) noexcept { //DEBUG_PRINTLN(F("-- Moving segment --")); if (this != &orig) { if (name) delete[] name; // free old name + if (leds) free(leds); deallocateData(); // free old runtime data if (_t) delete _t; memcpy((void*)this, (void*)&orig, sizeof(Segment)); @@ -135,6 +142,7 @@ Segment& Segment::operator= (Segment &&orig) noexcept { orig.data = nullptr; orig._dataLen = 0; orig._t = nullptr; + orig.leds = nullptr; } return *this; } @@ -174,12 +182,28 @@ void Segment::deallocateData() { */ void Segment::resetIfRequired() { if (reset) { + if (leds) { free(leds); leds = nullptr; } deallocateData(); next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; reset = false; // setOption(SEG_OPTION_RESET, false); } } +void Segment::setUpLeds() { + // deallocation happens in resetIfRequired() as it is called when segment changes or in destructor + if (useGlobalLedBuffer) return; // TODO optional seg buffer for FX without lossy restore due to opacity + + // no global buffer + if (leds == nullptr && length() > 0) { //softhack007 quickfix - avoid malloc(0) which is undefined behaviour (should not happen, but i've seen it) + //#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_PSRAM) + //if (psramFound()) + // leds = (CRGB*)ps_malloc(sizeof(CRGB)*length()); // softhack007 disabled; putting leds into psram leads to horrible slowdown on WROVER boards + //else + //#endif + leds = (uint32_t *)calloc(length(), sizeof(uint32_t)); + } +} + CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) { static unsigned long _lastPaletteChange = 0; // perhaps it should be per segment static CRGBPalette16 randomPalette = CRGBPalette16(DEFAULT_COLOR); @@ -592,6 +616,8 @@ void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col) } #endif + if (leds) leds[i] = col; + uint16_t len = length(); uint8_t _bri_t = currentBri(on ? opacity : 0); if (_bri_t < 255) { @@ -691,6 +717,8 @@ uint32_t Segment::getPixelColor(int i) } #endif + if (leds) return leds[i]; + if (reverse) i = virtualLength() - i - 1; i *= groupLength(); i += start; diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index a3807dbe..822b527b 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -147,18 +147,11 @@ void BusDigital::show() { else pix += _skip; PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); } - PolyBus::show(_busPtr, _iType); } else { PolyBus::applyPostAdjustments(_busPtr, _iType); - PolyBus::show(_busPtr, _iType); - // now restore (as close as possible) previous colors - // warning: this may not be the best idea as the buffer may still be in use - for (size_t i=0; i<_len; i++) { - uint8_t co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder); - setPixelColor(i, restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, i, co), _bri)); - } } - PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness + PolyBus::show(_busPtr, _iType); + PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) } bool BusDigital::canShow() { @@ -243,7 +236,7 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { } return c; } - return PolyBus::getPixelColor(_busPtr, _iType, pix, co); + return restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co), _bri); } } From c9ef034ab856e3b1d188b61d08d47bd7cc229ca0 Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Sun, 2 Jul 2023 13:43:29 +0200 Subject: [PATCH 07/34] Build bump/fix --- wled00/wled.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wled00/wled.h b/wled00/wled.h index 7fc3ba86..2d6d5b54 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -8,7 +8,7 @@ */ // version code in format yymmddb (b = daily build) -#define VERSION 23062490 +#define VERSION 2307020 //uncomment this if you have a "my_config.h" file you'd like to use //#define WLED_USE_MY_CONFIG From 66616e1cab422a06fd4d0baf5b7b447dd94df4bd Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Mon, 3 Jul 2023 21:13:01 +0200 Subject: [PATCH 08/34] Some timings added. --- wled00/FX_fcn.cpp | 11 +++++++++++ wled00/bus_manager.cpp | 35 ++++++++++++++++++++++------------- wled00/bus_manager.h | 14 ++++++++------ 3 files changed, 41 insertions(+), 19 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 7c97c9b6..e3256134 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1219,6 +1219,9 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { } void WS2812FX::show(void) { + static unsigned long sumMicros = 0, sumCurrent = 0; + static size_t calls = 0; + unsigned long microsStart = micros(); // avoid race condition, caputre _callback value show_callback callback = _callback; @@ -1226,6 +1229,7 @@ void WS2812FX::show(void) { uint8_t busBrightness = estimateCurrentAndLimitBri(); busses.setBrightness(busBrightness); + sumCurrent += micros() - microsStart; // some buses send asynchronously and this method will return before // all of the data has been sent. @@ -1237,6 +1241,13 @@ void WS2812FX::show(void) { if (diff > 0) fpsCurr = 1000 / diff; _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; _lastShow = now; + + sumMicros += micros() - microsStart; + if (++calls == 100) { + DEBUG_PRINTF("show calls: %d micros: %lu avg: %lu (current: %lu avg: %lu)\n", calls, sumMicros, sumMicros/calls, sumCurrent, sumCurrent/calls); + sumMicros = sumCurrent = 0; + calls = 0; + } } /** diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 822b527b..4883fff1 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -116,7 +116,7 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bu _colorOrder = bc.colorOrder; _iType = PolyBus::getI(bc.type, _pins, nr); if (_iType == I_NONE) return; - if (useGlobalLedBuffer && !allocData(_len * (hasWhite() + 3*hasRGB()))) return; //warning: hardcoded channel count + if (useGlobalLedBuffer && !allocData(_len * (Bus::hasWhite(_type) + 3*Bus::hasRGB(_type)))) return; //warning: hardcoded channel count uint16_t lenToCreate = _len; if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus _busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz); @@ -126,9 +126,12 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bu void BusDigital::show() { if (!_valid) return; + static unsigned long sumMicros = 0; + static size_t calls = 0; + unsigned long microsStart = micros(); PolyBus::setBrightness(_busPtr, _iType, _bri); if (useGlobalLedBuffer) { - size_t channels = hasWhite() + 3*hasRGB(); + size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); for (size_t i=0; i<_len; i++) { size_t offset = i*channels; uint8_t co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder); @@ -140,7 +143,7 @@ void BusDigital::show() { case 2: c = RGBW32(_data[offset-2], _data[offset-1], _data[offset] , 0); break; } } else { - c = RGBW32(_data[offset],_data[offset+1],_data[offset+2],(hasWhite()?_data[offset+3]:0)); + c = RGBW32(_data[offset],_data[offset+1],_data[offset+2],(Bus::hasWhite(_type)?_data[offset+3]:0)); } uint16_t pix = i; if (reversed) pix = _len - pix -1; @@ -152,6 +155,12 @@ void BusDigital::show() { } PolyBus::show(_busPtr, _iType); PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) + sumMicros += micros() - microsStart; + if (++calls == 100) { + DEBUG_PRINTF("Bus calls: %d micros: %lu avg: %lu\n", calls, sumMicros, sumMicros/calls); + sumMicros = 0; + calls = 0; + } } bool BusDigital::canShow() { @@ -172,25 +181,25 @@ void BusDigital::setBrightness(uint8_t b) { //If LEDs are skipped, it is possible to use the first as a status LED. //TODO only show if no new show due in the next 50ms void BusDigital::setStatusPixel(uint32_t c) { - if (_valid && _skip && canShow()) { + if (_valid && _skip) { PolyBus::setPixelColor(_busPtr, _iType, 0, c, _colorOrderMap.getPixelColorOrder(_start, _colorOrder)); - PolyBus::show(_busPtr, _iType); + if (canShow()) PolyBus::show(_busPtr, _iType); } } void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { if (!_valid) return; - if (hasWhite()) c = autoWhiteCalc(c); + if (Bus::hasWhite(_type)) c = autoWhiteCalc(c); if (_cct >= 1900) c = colorBalanceFromKelvin(_cct, c); //color correction from CCT if (useGlobalLedBuffer) { - size_t channels = hasWhite() + 3*hasRGB(); + size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); size_t offset = pix*channels; - if (hasRGB()) { + if (Bus::hasRGB(_type)) { _data[offset++] = R(c); _data[offset++] = G(c); _data[offset++] = B(c); } - if (hasWhite()) _data[offset] = W(c); + if (Bus::hasWhite(_type)) _data[offset] = W(c); } else { if (reversed) pix = _len - pix -1; else pix += _skip; @@ -212,13 +221,13 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { uint32_t BusDigital::getPixelColor(uint16_t pix) { if (!_valid) return 0; if (useGlobalLedBuffer) { - size_t channels = hasWhite() + 3*hasRGB(); + size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); size_t offset = pix*channels; uint32_t c; - if (!hasRGB()) { + if (!Bus::hasRGB(_type)) { c = RGBW32(_data[offset], _data[offset], _data[offset], _data[offset]); } else { - c = RGBW32(_data[offset], _data[offset+1], _data[offset+2], hasWhite() ? _data[offset+3] : 0); + c = RGBW32(_data[offset], _data[offset+1], _data[offset+2], Bus::hasWhite(_type) ? _data[offset+3] : 0); } return c; } else { @@ -469,7 +478,7 @@ BusNetwork::BusNetwork(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { void BusNetwork::setPixelColor(uint16_t pix, uint32_t c) { if (!_valid || pix >= _len) return; - if (hasWhite()) c = autoWhiteCalc(c); + if (_rgbw) c = autoWhiteCalc(c); if (_cct >= 1900) c = colorBalanceFromKelvin(_cct, c); //color correction from CCT uint16_t offset = pix * _UDPchannels; _data[offset] = R(c); diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 8e78310b..bb5df68e 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -130,20 +130,22 @@ class Bus { inline bool isOffRefreshRequired() { return _needsRefresh; } bool containsPixel(uint16_t pix) { return pix >= _start && pix < _start+_len; } - virtual bool hasRGB() { - if ((_type >= TYPE_WS2812_1CH && _type <= TYPE_WS2812_WWA) || _type == TYPE_ANALOG_1CH || _type == TYPE_ANALOG_2CH || _type == TYPE_ONOFF) return false; + virtual bool hasRGB(void) { return Bus::hasRGB(_type); } + static bool hasRGB(uint8_t type) { + if ((type >= TYPE_WS2812_1CH && type <= TYPE_WS2812_WWA) || type == TYPE_ANALOG_1CH || type == TYPE_ANALOG_2CH || type == TYPE_ONOFF) return false; return true; } - virtual bool hasWhite() { return Bus::hasWhite(_type); } + virtual bool hasWhite(void) { return Bus::hasWhite(_type); } static bool hasWhite(uint8_t type) { if ((type >= TYPE_WS2812_1CH && type <= TYPE_WS2812_WWA) || type == TYPE_SK6812_RGBW || type == TYPE_TM1814) return true; // digital types with white channel if (type > TYPE_ONOFF && type <= TYPE_ANALOG_5CH && type != TYPE_ANALOG_3CH) return true; // analog types with white channel if (type == TYPE_NET_DDP_RGBW) return true; // network types with white channel return false; } - virtual bool hasCCT() { - if (_type == TYPE_WS2812_2CH_X3 || _type == TYPE_WS2812_WWA || - _type == TYPE_ANALOG_2CH || _type == TYPE_ANALOG_5CH) return true; + virtual bool hasCCT(void) { return Bus::hasCCT(_type); } + static bool hasCCT(uint8_t type) { + if (type == TYPE_WS2812_2CH_X3 || type == TYPE_WS2812_WWA || + type == TYPE_ANALOG_2CH || type == TYPE_ANALOG_5CH) return true; return false; } static void setCCT(uint16_t cct) { From 8831c76fb42c02fed6227cc05fe9cd262b860cec Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Tue, 4 Jul 2023 16:22:19 +0200 Subject: [PATCH 09/34] restoreColorLossy small optimization minor optimizations that give up to 10% speedup in my tests * use "fast" integer types (where possible) * replaced _bri with _restaurationBri (no use of globals) --- wled00/bus_manager.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index bb5df68e..e9d773d6 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -236,13 +236,13 @@ class BusDigital : public Bus { void * _busPtr = nullptr; const ColorOrderMap &_colorOrderMap; - inline uint32_t restoreColorLossy(uint32_t c, uint8_t _restaurationBri) { - if (_bri == 255) return c; + inline uint32_t restoreColorLossy(uint32_t c, uint_fast8_t _restaurationBri) { + if (_restaurationBri == 255) return c; uint8_t* chan = (uint8_t*) &c; - for (uint8_t i=0; i<4; i++) + for (uint_fast8_t i=0; i<4; i++) { - uint16_t val = chan[i]; + uint_fast16_t val = chan[i]; chan[i] = ((val << 8) + _restaurationBri) / (_restaurationBri + 1); //adding _bri slighly improves recovery / stops degradation on re-scale } return c; From 45a0061660692c25f9231d4e2ba55d0eb894a060 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Wed, 5 Jul 2023 14:26:09 +0200 Subject: [PATCH 10/34] reverting _restaurationBri change see previous discussion --- wled00/bus_manager.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index e9d773d6..fe9690c7 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -237,7 +237,7 @@ class BusDigital : public Bus { const ColorOrderMap &_colorOrderMap; inline uint32_t restoreColorLossy(uint32_t c, uint_fast8_t _restaurationBri) { - if (_restaurationBri == 255) return c; + if (_bri == 255) return c; uint8_t* chan = (uint8_t*) &c; for (uint_fast8_t i=0; i<4; i++) @@ -404,4 +404,4 @@ class BusManager { return j; } }; -#endif \ No newline at end of file +#endif From ad825b80b019577144e774447808b63dc5778f4f Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Wed, 5 Jul 2023 17:16:54 +0200 Subject: [PATCH 11/34] Added a few debug timings. --- wled00/wled.cpp | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/wled00/wled.cpp b/wled00/wled.cpp index 86d14d6a..8f80b89f 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -35,12 +35,19 @@ void WLED::reset() void WLED::loop() { #ifdef WLED_DEBUG + static unsigned serviceCount = 0; static unsigned long maxUsermodMillis = 0; - static uint16_t avgUsermodMillis = 0; + static size_t avgUsermodMillis = 0; static unsigned long maxStripMillis = 0; - static uint16_t avgStripMillis = 0; + static size_t avgStripMillis = 0; + static size_t avgHandlingMillis = 0; + static size_t avgHandling2Millis = 0; + static size_t avgHandling3Millis = 0; #endif + #ifdef WLED_DEBUG + unsigned long handlingMillis = millis(); + #endif handleTime(); #ifndef WLED_DISABLE_INFRARED handleIR(); // 2nd call to function needed for ESP32 to return valid results -- should be good for ESP8266, too @@ -53,6 +60,10 @@ void WLED::loop() #ifdef WLED_ENABLE_DMX handleDMX(); #endif + #ifdef WLED_DEBUG + handlingMillis = millis() - handlingMillis; + avgHandlingMillis += handlingMillis; + #endif userLoop(); #ifdef WLED_DEBUG @@ -65,6 +76,9 @@ void WLED::loop() if (usermodMillis > maxUsermodMillis) maxUsermodMillis = usermodMillis; #endif + #ifdef WLED_DEBUG + unsigned long handling2Millis = millis(); + #endif yield(); handleIO(); #ifndef WLED_DISABLE_INFRARED @@ -73,6 +87,10 @@ void WLED::loop() #ifndef WLED_DISABLE_ALEXA handleAlexa(); #endif + #ifdef WLED_DEBUG + handling2Millis = millis() - handling2Millis; + avgHandling2Millis += handling2Millis; + #endif if (doCloseFile) { closeFile(); @@ -146,7 +164,7 @@ void WLED::loop() //LED settings have been saved, re-init busses //This code block causes severe FPS drop on ESP32 with the original "if (busConfigs[0] != nullptr)" conditional. Investigate! - if (doInitBusses) { + if (busConfigs[0] != nullptr) { doInitBusses = false; DEBUG_PRINTLN(F("Re-init busses.")); bool aligned = strip.checkSegmentAlignment(); //see if old segments match old bus(ses) @@ -177,9 +195,16 @@ void WLED::loop() yield(); if (doSerializeConfig) serializeConfig(); + #ifdef WLED_DEBUG + unsigned long handling3Millis = millis(); + #endif yield(); handleWs(); handleStatusLED(); + #ifdef WLED_DEBUG + handling3Millis = millis() - handling3Millis; + avgHandling3Millis += handling3Millis; + #endif // DEBUG serial logging (every 30s) #ifdef WLED_DEBUG @@ -207,6 +232,9 @@ void WLED::loop() DEBUG_PRINT(F("Loops/sec: ")); DEBUG_PRINTLN(loops / 30); DEBUG_PRINT(F("UM time[ms]: ")); DEBUG_PRINT(avgUsermodMillis/loops); DEBUG_PRINT("/");DEBUG_PRINTLN(maxUsermodMillis); DEBUG_PRINT(F("Strip time[ms]: ")); DEBUG_PRINT(avgStripMillis/loops); DEBUG_PRINT("/"); DEBUG_PRINTLN(maxStripMillis); + DEBUG_PRINT(F("Handling 1 time[ms]: ")); DEBUG_PRINTLN(avgHandlingMillis/loops); + DEBUG_PRINT(F("Handling 2 time[ms]: ")); DEBUG_PRINTLN(avgHandling2Millis/loops); + DEBUG_PRINT(F("Handling 3 time[ms]: ")); DEBUG_PRINTLN(avgHandling3Millis/loops); } strip.printSize(); loops = 0; @@ -214,6 +242,9 @@ void WLED::loop() maxStripMillis = 0; avgUsermodMillis = 0; avgStripMillis = 0; + avgHandlingMillis = 0; + avgHandling2Millis = 0; + avgHandling3Millis = 0; debugTime = millis(); } loops++; From 59a144baedf47a9e5ccd8479b92a18f643ce0bd9 Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Wed, 5 Jul 2023 23:57:46 +0200 Subject: [PATCH 12/34] Disable global buffer on ESP8266 by default Remove global dependency from Bus class and subclasses Remove timings --- wled00/FX_fcn.cpp | 6 ++++++ wled00/bus_manager.cpp | 15 ++++++++++----- wled00/bus_manager.h | 8 +++++--- wled00/cfg.cpp | 4 ++-- wled00/set.cpp | 2 +- wled00/wled.cpp | 31 ------------------------------- wled00/wled.h | 8 ++++++-- 7 files changed, 30 insertions(+), 44 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index e3256134..3c009592 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1219,9 +1219,11 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { } void WS2812FX::show(void) { + #ifdef WLED_DEBUG static unsigned long sumMicros = 0, sumCurrent = 0; static size_t calls = 0; unsigned long microsStart = micros(); + #endif // avoid race condition, caputre _callback value show_callback callback = _callback; @@ -1229,7 +1231,9 @@ void WS2812FX::show(void) { uint8_t busBrightness = estimateCurrentAndLimitBri(); busses.setBrightness(busBrightness); + #ifdef WLED_DEBUG sumCurrent += micros() - microsStart; + #endif // some buses send asynchronously and this method will return before // all of the data has been sent. @@ -1242,12 +1246,14 @@ void WS2812FX::show(void) { _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; _lastShow = now; + #ifdef WLED_DEBUG sumMicros += micros() - microsStart; if (++calls == 100) { DEBUG_PRINTF("show calls: %d micros: %lu avg: %lu (current: %lu avg: %lu)\n", calls, sumMicros, sumMicros/calls, sumCurrent, sumCurrent/calls); sumMicros = sumCurrent = 0; calls = 0; } + #endif } /** diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 4883fff1..24c2ea40 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -116,7 +116,8 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bu _colorOrder = bc.colorOrder; _iType = PolyBus::getI(bc.type, _pins, nr); if (_iType == I_NONE) return; - if (useGlobalLedBuffer && !allocData(_len * (Bus::hasWhite(_type) + 3*Bus::hasRGB(_type)))) return; //warning: hardcoded channel count + if (bc.doubleBuffer && !allocData(_len * (Bus::hasWhite(_type) + 3*Bus::hasRGB(_type)))) return; //warning: hardcoded channel count + buffering = bc.doubleBuffer; uint16_t lenToCreate = _len; if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus _busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz); @@ -126,11 +127,13 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bu void BusDigital::show() { if (!_valid) return; + #ifdef WLED_DEBUG static unsigned long sumMicros = 0; static size_t calls = 0; unsigned long microsStart = micros(); + #endif PolyBus::setBrightness(_busPtr, _iType, _bri); - if (useGlobalLedBuffer) { + if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); for (size_t i=0; i<_len; i++) { size_t offset = i*channels; @@ -155,12 +158,14 @@ void BusDigital::show() { } PolyBus::show(_busPtr, _iType); PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) + #ifdef WLED_DEBUG sumMicros += micros() - microsStart; if (++calls == 100) { DEBUG_PRINTF("Bus calls: %d micros: %lu avg: %lu\n", calls, sumMicros, sumMicros/calls); sumMicros = 0; calls = 0; } + #endif } bool BusDigital::canShow() { @@ -191,7 +196,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { if (!_valid) return; if (Bus::hasWhite(_type)) c = autoWhiteCalc(c); if (_cct >= 1900) c = colorBalanceFromKelvin(_cct, c); //color correction from CCT - if (useGlobalLedBuffer) { + if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); size_t offset = pix*channels; if (Bus::hasRGB(_type)) { @@ -220,7 +225,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { uint32_t BusDigital::getPixelColor(uint16_t pix) { if (!_valid) return 0; - if (useGlobalLedBuffer) { + if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); size_t offset = pix*channels; uint32_t c; @@ -272,7 +277,7 @@ void BusDigital::cleanup() { _iType = I_NONE; _valid = false; _busPtr = nullptr; - if (useGlobalLedBuffer) freeData(); + if (_data != nullptr) freeData(); pinManager.deallocatePin(_pins[1], PinOwner::BusDigital); pinManager.deallocatePin(_pins[0], PinOwner::BusDigital); } diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index fe9690c7..7f138cc0 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -34,10 +34,11 @@ struct BusConfig { uint8_t autoWhite; uint8_t pins[5] = {LEDPIN, 255, 255, 255, 255}; uint16_t frequency; - BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U) { + bool doubleBuffer; + BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, bool dblBfr=false) { refreshReq = (bool) GET_BIT(busType,7); type = busType & 0x7F; // bit 7 may be/is hacked to include refresh info (1=refresh in off state, 0=no refresh) - count = len; start = pstart; colorOrder = pcolorOrder; reversed = rev; skipAmount = skip; autoWhite = aw; frequency = clock_kHz; + count = len; start = pstart; colorOrder = pcolorOrder; reversed = rev; skipAmount = skip; autoWhite = aw; frequency = clock_kHz; doubleBuffer = dblBfr; uint8_t nPins = 1; if (type >= TYPE_NET_DDP_RGB && type < 96) nPins = 4; //virtual network bus. 4 "pins" store IP address else if (type > 47) nPins = 2; @@ -181,7 +182,7 @@ class Bus { uint32_t autoWhiteCalc(uint32_t c); uint8_t *allocData(size_t size = 1); - void freeData() { if (_data) free(_data); _data = nullptr; } + void freeData() { if (_data != nullptr) free(_data); _data = nullptr; } }; @@ -235,6 +236,7 @@ class BusDigital : public Bus { uint16_t _frequencykHz = 0U; void * _busPtr = nullptr; const ColorOrderMap &_colorOrderMap; + bool buffering = false; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop inline uint32_t restoreColorLossy(uint32_t c, uint_fast8_t _restaurationBri) { if (_bri == 255) return c; diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index 6c2e9422..6730fe5f 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -161,7 +161,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { ledType |= refresh << 7; // hack bit 7 to indicate strip requires off refresh uint8_t AWmode = elm[F("rgbwm")] | autoWhiteMode; if (fromFS) { - BusConfig bc = BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz); + BusConfig bc = BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, useGlobalLedBuffer); mem += BusManager::memUsage(bc); if (useGlobalLedBuffer && start + length > maxlen) { maxlen = start + length; @@ -170,7 +170,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { if (mem + globalBufMem <= MAX_LED_MEMORY) if (busses.add(bc) == -1) break; // finalization will be done in WLED::beginStrip() } else { if (busConfigs[s] != nullptr) delete busConfigs[s]; - busConfigs[s] = new BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode); + busConfigs[s] = new BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, useGlobalLedBuffer); busesChanged = true; } s++; diff --git a/wled00/set.cpp b/wled00/set.cpp index 3420f22c..fb3e40c2 100644 --- a/wled00/set.cpp +++ b/wled00/set.cpp @@ -153,7 +153,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage) // actual finalization is done in WLED::loop() (removing old busses and adding new) // this may happen even before this loop is finished so we do "doInitBusses" after the loop if (busConfigs[s] != nullptr) delete busConfigs[s]; - busConfigs[s] = new BusConfig(type, pins, start, length, colorOrder | (channelSwap<<4), request->hasArg(cv), skip, awmode, freqHz); + busConfigs[s] = new BusConfig(type, pins, start, length, colorOrder | (channelSwap<<4), request->hasArg(cv), skip, awmode, freqHz, useGlobalLedBuffer); busesChanged = true; } //doInitBusses = busesChanged; // we will do that below to ensure all input data is processed diff --git a/wled00/wled.cpp b/wled00/wled.cpp index 8f80b89f..83a79358 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -35,19 +35,12 @@ void WLED::reset() void WLED::loop() { #ifdef WLED_DEBUG - static unsigned serviceCount = 0; static unsigned long maxUsermodMillis = 0; static size_t avgUsermodMillis = 0; static unsigned long maxStripMillis = 0; static size_t avgStripMillis = 0; - static size_t avgHandlingMillis = 0; - static size_t avgHandling2Millis = 0; - static size_t avgHandling3Millis = 0; #endif - #ifdef WLED_DEBUG - unsigned long handlingMillis = millis(); - #endif handleTime(); #ifndef WLED_DISABLE_INFRARED handleIR(); // 2nd call to function needed for ESP32 to return valid results -- should be good for ESP8266, too @@ -60,10 +53,6 @@ void WLED::loop() #ifdef WLED_ENABLE_DMX handleDMX(); #endif - #ifdef WLED_DEBUG - handlingMillis = millis() - handlingMillis; - avgHandlingMillis += handlingMillis; - #endif userLoop(); #ifdef WLED_DEBUG @@ -76,9 +65,6 @@ void WLED::loop() if (usermodMillis > maxUsermodMillis) maxUsermodMillis = usermodMillis; #endif - #ifdef WLED_DEBUG - unsigned long handling2Millis = millis(); - #endif yield(); handleIO(); #ifndef WLED_DISABLE_INFRARED @@ -87,10 +73,6 @@ void WLED::loop() #ifndef WLED_DISABLE_ALEXA handleAlexa(); #endif - #ifdef WLED_DEBUG - handling2Millis = millis() - handling2Millis; - avgHandling2Millis += handling2Millis; - #endif if (doCloseFile) { closeFile(); @@ -195,16 +177,9 @@ void WLED::loop() yield(); if (doSerializeConfig) serializeConfig(); - #ifdef WLED_DEBUG - unsigned long handling3Millis = millis(); - #endif yield(); handleWs(); handleStatusLED(); - #ifdef WLED_DEBUG - handling3Millis = millis() - handling3Millis; - avgHandling3Millis += handling3Millis; - #endif // DEBUG serial logging (every 30s) #ifdef WLED_DEBUG @@ -232,9 +207,6 @@ void WLED::loop() DEBUG_PRINT(F("Loops/sec: ")); DEBUG_PRINTLN(loops / 30); DEBUG_PRINT(F("UM time[ms]: ")); DEBUG_PRINT(avgUsermodMillis/loops); DEBUG_PRINT("/");DEBUG_PRINTLN(maxUsermodMillis); DEBUG_PRINT(F("Strip time[ms]: ")); DEBUG_PRINT(avgStripMillis/loops); DEBUG_PRINT("/"); DEBUG_PRINTLN(maxStripMillis); - DEBUG_PRINT(F("Handling 1 time[ms]: ")); DEBUG_PRINTLN(avgHandlingMillis/loops); - DEBUG_PRINT(F("Handling 2 time[ms]: ")); DEBUG_PRINTLN(avgHandling2Millis/loops); - DEBUG_PRINT(F("Handling 3 time[ms]: ")); DEBUG_PRINTLN(avgHandling3Millis/loops); } strip.printSize(); loops = 0; @@ -242,9 +214,6 @@ void WLED::loop() maxStripMillis = 0; avgUsermodMillis = 0; avgStripMillis = 0; - avgHandlingMillis = 0; - avgHandling2Millis = 0; - avgHandling3Millis = 0; debugTime = millis(); } loops++; diff --git a/wled00/wled.h b/wled00/wled.h index 2d6d5b54..28b11a06 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -8,7 +8,7 @@ */ // version code in format yymmddb (b = daily build) -#define VERSION 2307020 +#define VERSION 2307050 //uncomment this if you have a "my_config.h" file you'd like to use //#define WLED_USE_MY_CONFIG @@ -332,7 +332,11 @@ WLED_GLOBAL byte bootPreset _INIT(0); // save preset to load //if false, only one segment spanning the total LEDs is created, //but not on LED settings save if there is more than one segment currently WLED_GLOBAL bool autoSegments _INIT(false); -WLED_GLOBAL bool useGlobalLedBuffer _INIT(true); +#ifdef ESP8266 +WLED_GLOBAL bool useGlobalLedBuffer _INIT(false); // double buffering disabled on ESP8266 +#else +WLED_GLOBAL bool useGlobalLedBuffer _INIT(true); // double buffering enabled on ESP32 +#endif WLED_GLOBAL bool correctWB _INIT(false); // CCT color correction of RGB color WLED_GLOBAL bool cctFromRgb _INIT(false); // CCT is calculated from RGB instead of using seg.cct WLED_GLOBAL bool gammaCorrectCol _INIT(true); // use gamma correction on colors From f437fd6cd699302567d3fca93e98d8496d2b9cba Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Thu, 6 Jul 2023 21:16:29 +0200 Subject: [PATCH 13/34] Code readability. Fix for peek. Loop timing. --- wled00/FX_fcn.cpp | 5 +- wled00/bus_manager.cpp | 60 +++++------ wled00/bus_manager.h | 228 +++++++++++++++-------------------------- wled00/cfg.cpp | 4 +- wled00/json.cpp | 10 +- wled00/led.cpp | 4 +- wled00/wled.cpp | 7 +- wled00/wled.h | 2 +- wled00/ws.cpp | 14 ++- wled00/xml.cpp | 2 +- 10 files changed, 142 insertions(+), 194 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 3c009592..91ac9980 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1084,10 +1084,7 @@ void WS2812FX::service() { if(nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC)) { if (seg.grouping == 0) seg.grouping = 1; // sanity check -// if (!doShow) { -// busses.setBrightness(_brightness); // bus luminance must be set before FX using setPixelColor() - doShow = true; -// } + doShow = true; uint16_t delay = FRAMETIME; if (!seg.freeze) { //only run effect function if not frozen diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 24c2ea40..05197cd1 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -97,32 +97,33 @@ uint8_t *Bus::allocData(size_t size) { } -BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bus(bc.type, bc.start, bc.autoWhite), _colorOrderMap(com) { +BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) +: Bus(bc.type, bc.start, bc.autoWhite, bc.count, bc.reversed, (bc.refreshReq || bc.type == TYPE_TM1814)) +, _skip(bc.skipAmount) //sacrificial pixels +, _colorOrder(bc.colorOrder) +, _colorOrderMap(com) +{ if (!IS_DIGITAL(bc.type) || !bc.count) return; if (!pinManager.allocatePin(bc.pins[0], true, PinOwner::BusDigital)) return; _frequencykHz = 0U; _pins[0] = bc.pins[0]; if (IS_2PIN(bc.type)) { if (!pinManager.allocatePin(bc.pins[1], true, PinOwner::BusDigital)) { - cleanup(); return; + cleanup(); + return; } _pins[1] = bc.pins[1]; _frequencykHz = bc.frequency ? bc.frequency : 2000U; // 2MHz clock if undefined } - reversed = bc.reversed; - _needsRefresh = bc.refreshReq || bc.type == TYPE_TM1814; - _skip = bc.skipAmount; //sacrificial pixels - _len = bc.count; - _colorOrder = bc.colorOrder; _iType = PolyBus::getI(bc.type, _pins, nr); if (_iType == I_NONE) return; - if (bc.doubleBuffer && !allocData(_len * (Bus::hasWhite(_type) + 3*Bus::hasRGB(_type)))) return; //warning: hardcoded channel count + if (bc.doubleBuffer && !allocData(bc.count * (Bus::hasWhite(_type) + 3*Bus::hasRGB(_type)))) return; //warning: hardcoded channel count buffering = bc.doubleBuffer; - uint16_t lenToCreate = _len; - if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus + uint16_t lenToCreate = bc.count; + if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(bc.count); // only needs a third of "RGB" LEDs for NeoPixelBus _busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz); _valid = (_busPtr != nullptr); - DEBUG_PRINTF("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u)\n", _valid?"S":"Uns", nr, _len, bc.type, _pins[0],_pins[1],_iType); + DEBUG_PRINTF("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u)\n", _valid?"S":"Uns", nr, bc.count, bc.type, _pins[0], _pins[1], _iType); } void BusDigital::show() { @@ -149,8 +150,8 @@ void BusDigital::show() { c = RGBW32(_data[offset],_data[offset+1],_data[offset+2],(Bus::hasWhite(_type)?_data[offset+3]:0)); } uint16_t pix = i; - if (reversed) pix = _len - pix -1; - else pix += _skip; + if (_reversed) pix = _len - pix -1; + else pix += _skip; PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); } } else { @@ -206,8 +207,8 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { } if (Bus::hasWhite(_type)) _data[offset] = W(c); } else { - if (reversed) pix = _len - pix -1; - else pix += _skip; + if (_reversed) pix = _len - pix -1; + else pix += _skip; uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint16_t pOld = pix; @@ -236,8 +237,8 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { } return c; } else { - if (reversed) pix = _len - pix -1; - else pix += _skip; + if (_reversed) pix = _len - pix -1; + else pix += _skip; uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint16_t pOld = pix; @@ -283,8 +284,9 @@ void BusDigital::cleanup() { } -BusPwm::BusPwm(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { - _valid = false; +BusPwm::BusPwm(BusConfig &bc) +: Bus(bc.type, bc.start, bc.autoWhite, 1, bc.reversed) +{ if (!IS_PWM(bc.type)) return; uint8_t numPins = NUM_PWM_PINS(bc.type); _frequency = bc.frequency ? bc.frequency : WLED_PWM_FREQ; @@ -312,7 +314,6 @@ BusPwm::BusPwm(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { ledcAttachPin(_pins[i], _ledcStart + i); #endif } - reversed = bc.reversed; _data = _pwmdata; // avoid malloc() and use stack _valid = true; } @@ -381,7 +382,7 @@ void BusPwm::show() { uint8_t numPins = NUM_PWM_PINS(_type); for (uint8_t i = 0; i < numPins; i++) { uint8_t scaled = (_data[i] * _bri) / 255; - if (reversed) scaled = 255 - scaled; + if (_reversed) scaled = 255 - scaled; #ifdef ESP8266 analogWrite(_pins[i], scaled); #else @@ -416,8 +417,10 @@ void BusPwm::deallocatePins() { } -BusOnOff::BusOnOff(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { - _valid = false; +BusOnOff::BusOnOff(BusConfig &bc) +: Bus(bc.type, bc.start, bc.autoWhite, 1, bc.reversed) +, _onoffdata(0) +{ if (bc.type != TYPE_ONOFF) return; uint8_t currentPin = bc.pins[0]; @@ -426,7 +429,6 @@ BusOnOff::BusOnOff(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { } _pin = currentPin; //store only after allocatePin() succeeds pinMode(_pin, OUTPUT); - reversed = bc.reversed; _data = &_onoffdata; // avoid malloc() and use stack _valid = true; } @@ -448,7 +450,7 @@ uint32_t BusOnOff::getPixelColor(uint16_t pix) { void BusOnOff::show() { if (!_valid) return; - digitalWrite(_pin, reversed ? !(bool)_data[0] : (bool)_data[0]); + digitalWrite(_pin, _reversed ? !(bool)_data[0] : (bool)_data[0]); } uint8_t BusOnOff::getPins(uint8_t* pinArray) { @@ -458,8 +460,10 @@ uint8_t BusOnOff::getPins(uint8_t* pinArray) { } -BusNetwork::BusNetwork(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { - _valid = false; +BusNetwork::BusNetwork(BusConfig &bc) +: Bus(bc.type, bc.start, bc.autoWhite, bc.count) +, _broadcastLock(false) +{ switch (bc.type) { case TYPE_NET_ARTNET_RGB: _rgbw = false; @@ -475,9 +479,7 @@ BusNetwork::BusNetwork(BusConfig &bc) : Bus(bc.type, bc.start, bc.autoWhite) { break; } _UDPchannels = _rgbw ? 4 : 3; - _len = bc.count; _client = IPAddress(bc.pins[0],bc.pins[1],bc.pins[2],bc.pins[3]); - _broadcastLock = false; _valid = (allocData(_len * _UDPchannels) != nullptr); } diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 7f138cc0..8ca1bcc2 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -35,15 +35,24 @@ struct BusConfig { uint8_t pins[5] = {LEDPIN, 255, 255, 255, 255}; uint16_t frequency; bool doubleBuffer; - BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, bool dblBfr=false) { + + BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, bool dblBfr=false) + : count(len) + , start(pstart) + , colorOrder(pcolorOrder) + , reversed(rev) + , skipAmount(skip) + , autoWhite(aw) + , frequency(clock_kHz) + , doubleBuffer(dblBfr) + { refreshReq = (bool) GET_BIT(busType,7); type = busType & 0x7F; // bit 7 may be/is hacked to include refresh info (1=refresh in off state, 0=no refresh) - count = len; start = pstart; colorOrder = pcolorOrder; reversed = rev; skipAmount = skip; autoWhite = aw; frequency = clock_kHz; doubleBuffer = dblBfr; - uint8_t nPins = 1; + size_t nPins = 1; if (type >= TYPE_NET_DDP_RGB && type < 96) nPins = 4; //virtual network bus. 4 "pins" store IP address else if (type > 47) nPins = 2; else if (type > 40 && type < 46) nPins = NUM_PWM_PINS(type); - for (uint8_t i = 0; i < nPins; i++) pins[i] = ppins[i]; + for (size_t i = 0; i < nPins; i++) pins[i] = ppins[i]; } //validates start and length and extends total if needed @@ -70,9 +79,7 @@ struct ColorOrderMapEntry { struct ColorOrderMap { void add(uint16_t start, uint16_t len, uint8_t colorOrder); - uint8_t count() const { - return _count; - } + uint8_t count() const { return _count; } void reset() { _count = 0; @@ -97,38 +104,41 @@ struct ColorOrderMap { //parent class of BusDigital, BusPwm, and BusNetwork class Bus { public: - Bus(uint8_t type, uint16_t start, uint8_t aw) - : _bri(255) - , _len(1) - , _data(nullptr) // keep data access consistent across all types of buses + Bus(uint8_t type, uint16_t start, uint8_t aw, uint16_t len = 1, bool reversed = false, bool refresh = false) + : _type(type) + , _bri(255) + , _start(start) + , _len(len) + , _reversed(reversed) , _valid(false) - , _needsRefresh(false) + , _needsRefresh(refresh) + , _data(nullptr) // keep data access consistent across all types of buses { - _type = type; - _start = start; _autoWhiteMode = Bus::hasWhite(_type) ? aw : RGBW_MODE_MANUAL_ONLY; }; virtual ~Bus() {} //throw the bus under the bus virtual void show() = 0; - virtual bool canShow() { return true; } - virtual void setStatusPixel(uint32_t c) {} + virtual bool canShow() { return true; } + virtual void setStatusPixel(uint32_t c) {} virtual void setPixelColor(uint16_t pix, uint32_t c) = 0; virtual uint32_t getPixelColor(uint16_t pix) { return 0; } - virtual void setBrightness(uint8_t b) { _bri = b; }; + virtual void setBrightness(uint8_t b) { _bri = b; }; virtual void cleanup() = 0; - virtual uint8_t getPins(uint8_t* pinArray) { return 0; } - virtual uint16_t getLength() { return _len; } - virtual void setColorOrder() {} - virtual uint8_t getColorOrder() { return COL_ORDER_RGB; } - virtual uint8_t skippedLeds() { return 0; } - virtual uint16_t getFrequency() { return 0U; } - inline uint16_t getStart() { return _start; } - inline void setStart(uint16_t start) { _start = start; } - inline uint8_t getType() { return _type; } - inline bool isOk() { return _valid; } - inline bool isOffRefreshRequired() { return _needsRefresh; } + virtual uint8_t getPins(uint8_t* pinArray) { return 0; } + virtual uint16_t getLength() { return _len; } + virtual void setColorOrder() {} + virtual uint8_t getColorOrder() { return COL_ORDER_RGB; } + virtual uint8_t skippedLeds() { return 0; } + virtual uint16_t getFrequency() { return 0U; } + inline void setReversed(bool reversed) { _reversed = reversed; } + inline uint16_t getStart() { return _start; } + inline void setStart(uint16_t start) { _start = start; } + inline uint8_t getType() { return _type; } + inline bool isOk() { return _valid; } + inline bool isReversed() { return _reversed; } + inline bool isOffRefreshRequired() { return _needsRefresh; } bool containsPixel(uint16_t pix) { return pix >= _start && pix < _start+_len; } virtual bool hasRGB(void) { return Bus::hasRGB(_type); } @@ -165,17 +175,16 @@ class Bus { inline static void setGlobalAWMode(uint8_t m) { if (m < 5) _gAWM = m; else _gAWM = AW_GLOBAL_DISABLED; } inline static uint8_t getGlobalAWMode() { return _gAWM; } - bool reversed = false; - protected: uint8_t _type; uint8_t _bri; uint16_t _start; uint16_t _len; - uint8_t *_data; + bool _reversed; bool _valid; bool _needsRefresh; uint8_t _autoWhiteMode; + uint8_t *_data; static uint8_t _gAWM; static int16_t _cct; static uint8_t _cctBlend; @@ -189,54 +198,31 @@ class Bus { class BusDigital : public Bus { public: BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com); + ~BusDigital() { cleanup(); } - inline void show(); - + void show(); bool canShow(); - void setBrightness(uint8_t b); - void setStatusPixel(uint32_t c); - void setPixelColor(uint16_t pix, uint32_t c); - - uint32_t getPixelColor(uint16_t pix); - - uint8_t getColorOrder() { - return _colorOrder; - } - - uint16_t getLength() { - return _len - _skip; - } - - uint8_t getPins(uint8_t* pinArray); - void setColorOrder(uint8_t colorOrder); - - uint8_t skippedLeds() { - return _skip; - } - - uint16_t getFrequency() { return _frequencykHz; } - + uint32_t getPixelColor(uint16_t pix); + uint8_t getColorOrder() { return _colorOrder; } + uint8_t getPins(uint8_t* pinArray); + uint8_t skippedLeds() { return _skip; } + uint16_t getFrequency() { return _frequencykHz; } void reinit(); - void cleanup(); - ~BusDigital() { - cleanup(); - } - private: - uint8_t _colorOrder = COL_ORDER_GRB; - uint8_t _pins[2] = {255, 255}; - uint8_t _iType = 0; //I_NONE; - uint8_t _skip = 0; - uint16_t _frequencykHz = 0U; - void * _busPtr = nullptr; + uint8_t _skip; + uint8_t _colorOrder; + uint8_t _pins[2]; + uint8_t _iType; + uint16_t _frequencykHz; + void * _busPtr; const ColorOrderMap &_colorOrderMap; - bool buffering = false; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop + bool buffering; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop inline uint32_t restoreColorLossy(uint32_t c, uint_fast8_t _restaurationBri) { if (_bri == 255) return c; @@ -255,33 +241,22 @@ class BusDigital : public Bus { class BusPwm : public Bus { public: BusPwm(BusConfig &bc); + ~BusPwm() { cleanup(); } void setPixelColor(uint16_t pix, uint32_t c); - - //does no index check - uint32_t getPixelColor(uint16_t pix); - - void show(); - - uint8_t getPins(uint8_t* pinArray); - + uint32_t getPixelColor(uint16_t pix); //does no index check + uint8_t getPins(uint8_t* pinArray); uint16_t getFrequency() { return _frequency; } - - void cleanup() { - deallocatePins(); - } - - ~BusPwm() { - cleanup(); - } + void show(); + void cleanup() { deallocatePins(); } private: - uint8_t _pins[5] = {255, 255, 255, 255, 255}; - uint8_t _pwmdata[5] = {0}; + uint8_t _pins[5]; + uint8_t _pwmdata[5]; #ifdef ARDUINO_ARCH_ESP32 - uint8_t _ledcStart = 255; + uint8_t _ledcStart; #endif - uint16_t _frequency = 0U; + uint16_t _frequency; void deallocatePins(); }; @@ -290,59 +265,34 @@ class BusPwm : public Bus { class BusOnOff : public Bus { public: BusOnOff(BusConfig &bc); + ~BusOnOff() { cleanup(); } void setPixelColor(uint16_t pix, uint32_t c); - uint32_t getPixelColor(uint16_t pix); - + uint8_t getPins(uint8_t* pinArray); void show(); - - uint8_t getPins(uint8_t* pinArray); - - void cleanup() { - pinManager.deallocatePin(_pin, PinOwner::BusOnOff); - } - - ~BusOnOff() { - cleanup(); - } + void cleanup() { pinManager.deallocatePin(_pin, PinOwner::BusOnOff); } private: - uint8_t _pin = 255; - uint8_t _onoffdata = 0; + uint8_t _pin; + uint8_t _onoffdata; }; class BusNetwork : public Bus { public: BusNetwork(BusConfig &bc); + ~BusNetwork() { cleanup(); } - bool hasRGB() { return true; } + bool hasRGB() { return true; } bool hasWhite() { return _rgbw; } - + bool canShow() { return !_broadcastLock; } // this should be a return value from UDP routine if it is still sending data out void setPixelColor(uint16_t pix, uint32_t c); - uint32_t getPixelColor(uint16_t pix); - + uint8_t getPins(uint8_t* pinArray); void show(); - - bool canShow() { - // this should be a return value from UDP routine if it is still sending data out - return !_broadcastLock; - } - - uint8_t getPins(uint8_t* pinArray); - - uint16_t getLength() { - return _len; - } - void cleanup(); - ~BusNetwork() { - cleanup(); - } - private: IPAddress _client; uint8_t _UDPtype; @@ -354,7 +304,7 @@ class BusNetwork : public Bus { class BusManager { public: - BusManager() {}; + BusManager() : numBusses(0) {}; //utility to get the approx. memory usage of a given BusConfig static uint32_t memUsage(BusConfig &bc); @@ -365,38 +315,24 @@ class BusManager { void removeAll(); void show(); - - void setStatusPixel(uint32_t c); - - void setPixelColor(uint16_t pix, uint32_t c); - - void setBrightness(uint8_t b); - - void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); - - uint32_t getPixelColor(uint16_t pix); - bool canAllShow(); + void setStatusPixel(uint32_t c); + void setPixelColor(uint16_t pix, uint32_t c); + void setBrightness(uint8_t b); + void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); + uint32_t getPixelColor(uint16_t pix); Bus* getBus(uint8_t busNr); //semi-duplicate of strip.getLengthTotal() (though that just returns strip._length, calculated in finalizeInit()) uint16_t getTotalLength(); + inline uint8_t getNumBusses() const { return numBusses; } - inline void updateColorOrderMap(const ColorOrderMap &com) { - memcpy(&colorOrderMap, &com, sizeof(ColorOrderMap)); - } - - inline const ColorOrderMap& getColorOrderMap() const { - return colorOrderMap; - } - - inline uint8_t getNumBusses() { - return numBusses; - } + inline void updateColorOrderMap(const ColorOrderMap &com) { memcpy(&colorOrderMap, &com, sizeof(ColorOrderMap)); } + inline const ColorOrderMap& getColorOrderMap() const { return colorOrderMap; } private: - uint8_t numBusses = 0; + uint8_t numBusses; Bus* busses[WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES]; ColorOrderMap colorOrderMap; diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index 6730fe5f..2f2ebc02 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -178,7 +178,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { doInitBusses = busesChanged; // finalization done in beginStrip() } - if (hw_led["rev"]) busses.getBus(0)->reversed = true; //set 0.11 global reversed setting for first bus + if (hw_led["rev"]) busses.getBus(0)->setReversed(true); //set 0.11 global reversed setting for first bus // read color order map configuration JsonArray hw_com = hw[F("com")]; @@ -746,7 +746,7 @@ void serializeConfig() { uint8_t nPins = bus->getPins(pins); for (uint8_t i = 0; i < nPins; i++) ins_pin.add(pins[i]); ins[F("order")] = bus->getColorOrder(); - ins["rev"] = bus->reversed; + ins["rev"] = bus->isReversed(); ins[F("skip")] = bus->skippedLeds(); ins["type"] = bus->getType() & 0x7F; ins["ref"] = bus->isOffRefreshRequired(); diff --git a/wled00/json.cpp b/wled00/json.cpp index 06444cc3..a18fcbdb 100644 --- a/wled00/json.cpp +++ b/wled00/json.cpp @@ -1089,9 +1089,13 @@ bool serveLiveLeds(AsyncWebServerRequest* request, uint32_t wsClient) for (size_t i= 0; i < used; i += n) { uint32_t c = strip.getPixelColor(i); - uint8_t r = qadd8(W(c), R(c)); //add white channel to RGB channels as a simple RGBW -> RGB map - uint8_t g = qadd8(W(c), G(c)); - uint8_t b = qadd8(W(c), B(c)); + uint8_t r = useGlobalLedBuffer ? scale8(R(c), strip.getBrightness()) : R(c); + uint8_t g = useGlobalLedBuffer ? scale8(G(c), strip.getBrightness()) : G(c); + uint8_t b = useGlobalLedBuffer ? scale8(B(c), strip.getBrightness()) : B(c); + uint8_t w = useGlobalLedBuffer ? scale8(W(c), strip.getBrightness()) : W(c); + r = qadd8(w, r); //R, add white channel to RGB channels as a simple RGBW -> RGB map + g = qadd8(w, g); //G + b = qadd8(w, b); //B olen += sprintf(obuf + olen, "\"%06X\",", RGBW32(r,g,b,0)); } olen -= 1; diff --git a/wled00/led.cpp b/wled00/led.cpp index 4c5af70d..7901995f 100644 --- a/wled00/led.cpp +++ b/wled00/led.cpp @@ -194,7 +194,7 @@ void handleTransitions() applyFinalBri(); return; } - if (tper - tperLast < 0.004) return; + if (tper - tperLast < 0.004f) return; tperLast = tper; briT = briOld + ((bri - briOld) * tper); @@ -204,7 +204,7 @@ void handleTransitions() // legacy method, applies values from col, effectCurrent, ... to selected segments -void colorUpdated(byte callMode){ +void colorUpdated(byte callMode) { applyValuesToSelectedSegs(); stateUpdated(callMode); } diff --git a/wled00/wled.cpp b/wled00/wled.cpp index 83a79358..7da92937 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -35,6 +35,10 @@ void WLED::reset() void WLED::loop() { #ifdef WLED_DEBUG + static unsigned long lastRun = 0; + size_t loopDelay = (millis() - lastRun); + if (lastRun == 0) loopDelay=0; // startup - don't have valid data from last run. + if (loopDelay > 2) DEBUG_PRINTF("Loop delayed more than %dms.\n", loopDelay); static unsigned long maxUsermodMillis = 0; static size_t avgUsermodMillis = 0; static unsigned long maxStripMillis = 0; @@ -146,7 +150,7 @@ void WLED::loop() //LED settings have been saved, re-init busses //This code block causes severe FPS drop on ESP32 with the original "if (busConfigs[0] != nullptr)" conditional. Investigate! - if (busConfigs[0] != nullptr) { + if (doInitBusses) { doInitBusses = false; DEBUG_PRINTLN(F("Re-init busses.")); bool aligned = strip.checkSegmentAlignment(); //see if old segments match old bus(ses) @@ -217,6 +221,7 @@ void WLED::loop() debugTime = millis(); } loops++; + lastRun = millis(); #endif // WLED_DEBUG toki.resetTick(); diff --git a/wled00/wled.h b/wled00/wled.h index 28b11a06..1ef50ad9 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -8,7 +8,7 @@ */ // version code in format yymmddb (b = daily build) -#define VERSION 2307050 +#define VERSION 2307060 //uncomment this if you have a "my_config.h" file you'd like to use //#define WLED_USE_MY_CONFIG diff --git a/wled00/ws.cpp b/wled00/ws.cpp index 2a4d0b96..e295fe8e 100644 --- a/wled00/ws.cpp +++ b/wled00/ws.cpp @@ -178,11 +178,11 @@ bool sendLiveLedsWs(uint32_t wsClient) buffer[1] = 2; //version buffer[2] = Segment::maxWidth; buffer[3] = Segment::maxHeight; - if (Segment::maxWidth * Segment::maxHeight > MAX_LIVE_LEDS_WS*4) { + if (used > MAX_LIVE_LEDS_WS*4) { buffer[2] = Segment::maxWidth/4; buffer[3] = Segment::maxHeight/4; skipLines = 3; - } else if (Segment::maxWidth * Segment::maxHeight > MAX_LIVE_LEDS_WS) { + } else if (used > MAX_LIVE_LEDS_WS) { buffer[2] = Segment::maxWidth/2; buffer[3] = Segment::maxHeight/2; skipLines = 1; @@ -198,9 +198,13 @@ bool sendLiveLedsWs(uint32_t wsClient) } #endif uint32_t c = strip.getPixelColor(i); - buffer[pos++] = qadd8(W(c), R(c)); //R, add white channel to RGB channels as a simple RGBW -> RGB map - buffer[pos++] = qadd8(W(c), G(c)); //G - buffer[pos++] = qadd8(W(c), B(c)); //B + uint8_t r = useGlobalLedBuffer ? scale8(R(c), strip.getBrightness()) : R(c); + uint8_t g = useGlobalLedBuffer ? scale8(G(c), strip.getBrightness()) : G(c); + uint8_t b = useGlobalLedBuffer ? scale8(B(c), strip.getBrightness()) : B(c); + uint8_t w = useGlobalLedBuffer ? scale8(W(c), strip.getBrightness()) : W(c); + buffer[pos++] = qadd8(w, r); //R, add white channel to RGB channels as a simple RGBW -> RGB map + buffer[pos++] = qadd8(w, g); //G + buffer[pos++] = qadd8(w, b); //B } wsc->binary(wsBuf); diff --git a/wled00/xml.cpp b/wled00/xml.cpp index 12fc9717..fff58143 100644 --- a/wled00/xml.cpp +++ b/wled00/xml.cpp @@ -431,7 +431,7 @@ void getSettingsJS(byte subPage, char* dest) sappend('v',lt,bus->getType()); sappend('v',co,bus->getColorOrder() & 0x0F); sappend('v',ls,bus->getStart()); - sappend('c',cv,bus->reversed); + sappend('c',cv,bus->isReversed()); sappend('v',sl,bus->skippedLeds()); sappend('c',rf,bus->isOffRefreshRequired()); sappend('v',aw,bus->getAutoWhiteMode()); From 2ad3ab7f0da145bc076b2a4053cb0c3b6ef0563f Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Thu, 6 Jul 2023 22:48:13 +0200 Subject: [PATCH 14/34] Correct scaling for peek. --- wled00/json.cpp | 14 +++++++------- wled00/ws.cpp | 17 +++++++++-------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/wled00/json.cpp b/wled00/json.cpp index a18fcbdb..d48a54a2 100644 --- a/wled00/json.cpp +++ b/wled00/json.cpp @@ -1089,13 +1089,13 @@ bool serveLiveLeds(AsyncWebServerRequest* request, uint32_t wsClient) for (size_t i= 0; i < used; i += n) { uint32_t c = strip.getPixelColor(i); - uint8_t r = useGlobalLedBuffer ? scale8(R(c), strip.getBrightness()) : R(c); - uint8_t g = useGlobalLedBuffer ? scale8(G(c), strip.getBrightness()) : G(c); - uint8_t b = useGlobalLedBuffer ? scale8(B(c), strip.getBrightness()) : B(c); - uint8_t w = useGlobalLedBuffer ? scale8(W(c), strip.getBrightness()) : W(c); - r = qadd8(w, r); //R, add white channel to RGB channels as a simple RGBW -> RGB map - g = qadd8(w, g); //G - b = qadd8(w, b); //B + uint8_t r = R(c); + uint8_t g = G(c); + uint8_t b = B(c); + uint8_t w = W(c); + r = scale8(qadd8(w, r), strip.getBrightness()); //R, add white channel to RGB channels as a simple RGBW -> RGB map + g = scale8(qadd8(w, g), strip.getBrightness()); //G + b = scale8(qadd8(w, b), strip.getBrightness()); //B olen += sprintf(obuf + olen, "\"%06X\",", RGBW32(r,g,b,0)); } olen -= 1; diff --git a/wled00/ws.cpp b/wled00/ws.cpp index e295fe8e..49780d02 100644 --- a/wled00/ws.cpp +++ b/wled00/ws.cpp @@ -166,14 +166,15 @@ bool sendLiveLedsWs(uint32_t wsClient) size_t n = ((used -1)/MAX_LIVE_LEDS_WS) +1; //only serve every n'th LED if count over MAX_LIVE_LEDS_WS size_t pos = (strip.isMatrix ? 4 : 2); // start of data size_t bufSize = pos + (used/n)*3; - size_t skipLines = 0; AsyncWebSocketMessageBuffer * wsBuf = ws.makeBuffer(bufSize); if (!wsBuf) return false; //out of memory uint8_t* buffer = wsBuf->get(); buffer[0] = 'L'; buffer[1] = 1; //version + #ifndef WLED_DISABLE_2D + size_t skipLines = 0; if (strip.isMatrix) { buffer[1] = 2; //version buffer[2] = Segment::maxWidth; @@ -198,13 +199,13 @@ bool sendLiveLedsWs(uint32_t wsClient) } #endif uint32_t c = strip.getPixelColor(i); - uint8_t r = useGlobalLedBuffer ? scale8(R(c), strip.getBrightness()) : R(c); - uint8_t g = useGlobalLedBuffer ? scale8(G(c), strip.getBrightness()) : G(c); - uint8_t b = useGlobalLedBuffer ? scale8(B(c), strip.getBrightness()) : B(c); - uint8_t w = useGlobalLedBuffer ? scale8(W(c), strip.getBrightness()) : W(c); - buffer[pos++] = qadd8(w, r); //R, add white channel to RGB channels as a simple RGBW -> RGB map - buffer[pos++] = qadd8(w, g); //G - buffer[pos++] = qadd8(w, b); //B + uint8_t r = R(c); + uint8_t g = G(c); + uint8_t b = B(c); + uint8_t w = W(c); + buffer[pos++] = scale8(qadd8(w, r), strip.getBrightness()); //R, add white channel to RGB channels as a simple RGBW -> RGB map + buffer[pos++] = scale8(qadd8(w, g), strip.getBrightness()); //G + buffer[pos++] = scale8(qadd8(w, b), strip.getBrightness()); //B } wsc->binary(wsBuf); From 6267d11e513620cd165913ec3d96782bd85f849b Mon Sep 17 00:00:00 2001 From: cschwinne Date: Sun, 9 Jul 2023 12:32:28 +0200 Subject: [PATCH 15/34] Fix compilation and ABL scaling --- wled00/FX_fcn.cpp | 16 +++++++--------- wled00/bus_manager.cpp | 7 ++++--- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 6759d91c..b7684423 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1178,7 +1178,7 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { powerBudget = 0; } - uint32_t powerSum = 0; + uint32_t powerSum = 0; // could overflow if more than 22K LEDs (uint32_t MAX / 195075 PU per LED) for (uint_fast8_t bNum = 0; bNum < busses.getNumBusses(); bNum++) { Bus *bus = busses.getBus(bNum); @@ -1186,14 +1186,9 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { uint16_t len = bus->getLength(); uint32_t busPowerSum = 0; for (uint_fast16_t i = 0; i < len; i++) { //sum up the usage of each LED - uint32_t c = bus->getPixelColor(i); + uint32_t c = bus->getPixelColor(i); // always returns original or restored color without brightness scaling byte r = R(c), g = G(c), b = B(c), w = W(c); - if (useGlobalLedBuffer) { // TODO this should only apply for digital bus typpes - r = scale8(r, _brightness); - g = scale8(g, _brightness); - b = scale8(b, _brightness); - w = scale8(w, _brightness); - } + if(useWackyWS2815PowerModel) { //ignore white component on WS2815 power calculation busPowerSum += (MAX(MAX(r,g),b)) * 3; } else { @@ -1209,13 +1204,16 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { } uint8_t newBri = _brightness; + uint32_t powerSumUnscaled = powerSum; + powerSum *= _brightness; + if (powerSum > powerBudget) { //scale brightness down to stay in current limit float scale = (float)powerBudget / (float)powerSum; uint16_t scaleI = scale * 255; uint8_t scaleB = (scaleI > 255) ? 255 : scaleI; newBri = scale8(_brightness, scaleB); } - currentMilliamps = (powerSum * newBri) / puPerMilliamp; + currentMilliamps = (powerSumUnscaled * newBri) / puPerMilliamp; currentMilliamps += MA_FOR_ESP; //add power of ESP back to estimate currentMilliamps += pLen; //add standby power back to estimate return newBri; diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 5bd8fec6..ed1816ea 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -174,7 +174,7 @@ bool BusDigital::canShow() { return PolyBus::canShow(_busPtr, _iType); } -void BusDigital::setBrightness(uint8_t b, bool immediate) { +void BusDigital::setBrightness(uint8_t b) { //Fix for turning off onboard LED breaking bus #ifdef LED_BUILTIN if (_bri == 0 && b > 0) { @@ -224,6 +224,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { } } +// returns original color if global buffering is enabled, else returns lossly restored color from bus uint32_t BusDigital::getPixelColor(uint16_t pix) { if (!_valid) return 0; if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop @@ -587,9 +588,9 @@ void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c) { } } -void BusManager::setBrightness(uint8_t b, bool immediate) { +void BusManager::setBrightness(uint8_t b) { for (uint8_t i = 0; i < numBusses; i++) { - busses[i]->setBrightness(b, immediate); + busses[i]->setBrightness(b); } } From fa6070c6804d9988abb689b67dc9c8cdf74976db Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Wed, 12 Jul 2023 20:52:34 +0200 Subject: [PATCH 16/34] Multiple updates: - additional debug timings - removed local leds[] buffer - async segment bounds change (crashes seen otherwise) - added isActive() check to Segment drawing methods - ABL simplification - palette option for Black hole (FX) - (possible) crash mitigation is Segment handling (rapid preset changes) --- wled00/FX.cpp | 51 ++-------- wled00/FX.h | 36 +++---- wled00/FX_2Dfcn.cpp | 30 ++++-- wled00/FX_fcn.cpp | 217 ++++++++++++++++++++++------------------- wled00/bus_manager.cpp | 13 --- wled00/json.cpp | 11 ++- wled00/wled.cpp | 66 ++++++++----- wled00/wled.h | 4 +- 8 files changed, 210 insertions(+), 218 deletions(-) diff --git a/wled00/FX.cpp b/wled00/FX.cpp index c0b39c18..7bcd9395 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -606,7 +606,6 @@ static const char _data_FX_MODE_TWINKLE[] PROGMEM = "Twinkle@!,!;!,!;!;;m12=0"; uint16_t dissolve(uint32_t color) { //bool wa = (SEGCOLOR(1) != 0 && strip.getBrightness() < 255); //workaround, can't compare getPixel to color if not full brightness if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); //lossless getPixelColor() SEGMENT.fill(SEGCOLOR(1)); } @@ -1205,7 +1204,6 @@ uint16_t mode_fireworks() { const uint16_t height = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); //lossless getPixelColor() SEGMENT.fill(SEGCOLOR(1)); SEGENV.aux0 = UINT16_MAX; SEGENV.aux1 = UINT16_MAX; @@ -1904,7 +1902,6 @@ static const char _data_FX_MODE_PRIDE_2015[] PROGMEM = "Pride 2015@!;;"; uint16_t mode_juggle(void) { if (SEGLEN == 1) return mode_static(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); //lossless getPixelColor() SEGMENT.fill(BLACK); } @@ -4585,7 +4582,6 @@ uint16_t mode_2DBlackHole(void) { // By: Stepko https://editor.soulma // initialize on first call if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -4595,22 +4591,22 @@ uint16_t mode_2DBlackHole(void) { // By: Stepko https://editor.soulma for (size_t i = 0; i < 8; i++) { x = beatsin8(SEGMENT.custom1>>3, 0, cols - 1, 0, ((i % 2) ? 128 : 0) + t * i); y = beatsin8(SEGMENT.intensity>>3, 0, rows - 1, 0, ((i % 2) ? 192 : 64) + t * i); - SEGMENT.addPixelColorXY(x, y, CHSV(i*32, 255, 255)); + SEGMENT.addPixelColorXY(x, y, SEGMENT.color_from_palette(i*32, false, PALETTE_SOLID_WRAP, SEGMENT.check1?0:255)); } // inner stars for (size_t i = 0; i < 4; i++) { x = beatsin8(SEGMENT.custom2>>3, cols/4, cols - 1 - cols/4, 0, ((i % 2) ? 128 : 0) + t * i); y = beatsin8(SEGMENT.custom3 , rows/4, rows - 1 - rows/4, 0, ((i % 2) ? 192 : 64) + t * i); - SEGMENT.addPixelColorXY(x, y, CHSV(i*32, 255, 255)); + SEGMENT.addPixelColorXY(x, y, SEGMENT.color_from_palette(255-i*64, false, PALETTE_SOLID_WRAP, SEGMENT.check1?0:255)); } // central white dot - SEGMENT.setPixelColorXY(cols/2, rows/2, CHSV(0, 0, 255)); + SEGMENT.setPixelColorXY(cols/2, rows/2, WHITE); // blur everything a bit SEGMENT.blur(16); return FRAMETIME; } // mode_2DBlackHole() -static const char _data_FX_MODE_2DBLACKHOLE[] PROGMEM = "Black Hole@Fade rate,Outer Y freq.,Outer X freq.,Inner X freq.,Inner Y freq.;;;2"; +static const char _data_FX_MODE_2DBLACKHOLE[] PROGMEM = "Black Hole@Fade rate,Outer Y freq.,Outer X freq.,Inner X freq.,Inner Y freq.,Solid;!;!;2;pal=11"; //////////////////////////// @@ -4623,7 +4619,6 @@ uint16_t mode_2DColoredBursts() { // By: ldirko https://editor.so const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); SEGENV.aux0 = 0; // start with red hue } @@ -4677,7 +4672,6 @@ uint16_t mode_2Ddna(void) { // dna originally by by ldirko at https://pa const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -4704,7 +4698,6 @@ uint16_t mode_2DDNASpiral() { // By: ldirko https://editor.soulma const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -4750,7 +4743,6 @@ uint16_t mode_2DDrift() { // By: Stepko https://editor.soulmateli const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -4781,7 +4773,6 @@ uint16_t mode_2Dfirenoise(void) { // firenoise2d. By Andrew Tuline const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -4816,7 +4807,6 @@ uint16_t mode_2DFrizzles(void) { // By: Stepko https://editor.so const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -4855,8 +4845,6 @@ uint16_t mode_2Dgameoflife(void) { // Written by Ewoud Wijma, inspired by https: CRGB backgroundColor = SEGCOLOR(1); - if (SEGENV.call == 0) SEGMENT.setUpLeds(); - if (SEGENV.call == 0 || strip.now - SEGMENT.step > 3000) { SEGENV.step = strip.now; SEGENV.aux0 = 0; @@ -5122,7 +5110,6 @@ uint16_t mode_2Dmatrix(void) { // Matrix2D. By Jeremy Williams. const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5267,7 +5254,6 @@ uint16_t mode_2DPlasmaball(void) { // By: Stepko https://edito const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5315,7 +5301,6 @@ uint16_t mode_2DPolarLights(void) { // By: Kostyantyn Matviyevskyy https CRGBPalette16 auroraPalette = {0x000000, 0x003300, 0x006600, 0x009900, 0x00cc00, 0x00ff00, 0x33ff00, 0x66ff00, 0x99ff00, 0xccff00, 0xffff00, 0xffcc00, 0xff9900, 0xff6600, 0xff3300, 0xff0000}; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); SEGENV.step = 0; } @@ -5365,7 +5350,6 @@ uint16_t mode_2DPulser(void) { // By: ldirko https://edi const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5393,7 +5377,6 @@ uint16_t mode_2DSindots(void) { // By: ldirko http const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5425,7 +5408,6 @@ uint16_t mode_2Dsquaredswirl(void) { // By: Mark Kriegsman. https://g const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5468,7 +5450,6 @@ uint16_t mode_2DSunradiation(void) { // By: ldirko https://edi byte *bump = reinterpret_cast(SEGENV.data); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5516,7 +5497,6 @@ uint16_t mode_2Dtartan(void) { // By: Elliott Kember https://editor.so const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5556,7 +5536,6 @@ uint16_t mode_2Dspaceships(void) { //// Space ships by stepko (c)05.02.21 [ht const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -5625,7 +5604,6 @@ uint16_t mode_2Dcrazybees(void) { bee_t *bee = reinterpret_cast(SEGENV.data); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); for (size_t i = 0; i < n; i++) { bee[i].posX = random8(0, cols); @@ -5695,7 +5673,6 @@ uint16_t mode_2Dghostrider(void) { const size_t maxLighters = min(cols + rows, LIGHTERS_AM); - if (SEGENV.call == 0) SEGMENT.setUpLeds(); if (SEGENV.aux0 != cols || SEGENV.aux1 != rows) { SEGENV.aux0 = cols; SEGENV.aux1 = rows; @@ -5780,7 +5757,6 @@ uint16_t mode_2Dfloatingblobs(void) { if (!SEGENV.allocateData(sizeof(blob_t))) return mode_static(); //allocation failed blob_t *blob = reinterpret_cast(SEGENV.data); - if (SEGENV.call == 0) SEGMENT.setUpLeds(); if (SEGENV.aux0 != cols || SEGENV.aux1 != rows) { SEGENV.aux0 = cols; // re-initialise if virtual size changes SEGENV.aux1 = rows; @@ -5946,7 +5922,6 @@ uint16_t mode_2Ddriftrose(void) { const float L = min(cols, rows) / 2.f; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6101,7 +6076,6 @@ uint16_t mode_2DSwirl(void) { const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6148,7 +6122,6 @@ uint16_t mode_2DWaverly(void) { const uint16_t rows = SEGMENT.virtualHeight(); if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6377,7 +6350,6 @@ uint16_t mode_matripix(void) { // Matripix. By Andrew Tuline. int16_t volumeRaw = *(int16_t*)um_data->u_data[1]; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6505,7 +6477,6 @@ uint16_t mode_pixelwave(void) { // Pixelwave. By Andrew Tuline. // even with 1D effect we have to take logic for 2D segments for allocation as fill_solid() fills whole segment if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6731,7 +6702,6 @@ uint16_t mode_DJLight(void) { // Written by ??? Adapted by Wil uint8_t *fftResult = (uint8_t*)um_data->u_data[2]; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6800,7 +6770,6 @@ uint16_t mode_freqmatrix(void) { // Freqmatrix. By Andreas Plesch float volumeSmth = *(float*)um_data->u_data[0]; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -6902,7 +6871,6 @@ uint16_t mode_freqwave(void) { // Freqwave. By Andreas Pleschun float volumeSmth = *(float*)um_data->u_data[0]; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -7087,7 +7055,6 @@ uint16_t mode_waterfall(void) { // Waterfall. By: Andrew Tulin if (FFT_MajorPeak < 1) FFT_MajorPeak = 1; // log10(0) is "forbidden" (throws exception) if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); SEGENV.aux0 = 255; SEGMENT.custom1 = *binNum; @@ -7204,7 +7171,6 @@ uint16_t mode_2DFunkyPlank(void) { // Written by ??? Adapted by Wil uint8_t *fftResult = (uint8_t*)um_data->u_data[2]; if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); SEGMENT.fill(BLACK); } @@ -7417,7 +7383,6 @@ uint16_t mode_2Dsoap() { // init if (SEGENV.call == 0) { - SEGMENT.setUpLeds(); *noise32_x = random16(); *noise32_y = random16(); *noise32_z = random16(); @@ -7535,12 +7500,12 @@ uint16_t mode_2Doctopus() { SEGENV.aux1 = rows; *offsX = SEGMENT.custom1; *offsY = SEGMENT.custom2; - const uint8_t C_X = cols / 2 + (SEGMENT.custom1 - 128)*cols/255; - const uint8_t C_Y = rows / 2 + (SEGMENT.custom2 - 128)*rows/255; + const int C_X = (cols / 2) + ((SEGMENT.custom1 - 128)*cols)/255; + const int C_Y = (rows / 2) + ((SEGMENT.custom2 - 128)*rows)/255; for (int x = 0; x < cols; x++) { for (int y = 0; y < rows; y++) { - rMap[XY(x, y)].angle = 40.7436f * atan2f(y - C_Y, x - C_X); // avoid 128*atan2()/PI - rMap[XY(x, y)].radius = hypotf(x - C_X, y - C_Y) * mapp; //thanks Sutaburosu + rMap[XY(x, y)].angle = 40.7436f * atan2f((y - C_Y), (x - C_X)); // avoid 128*atan2()/PI + rMap[XY(x, y)].radius = hypotf((x - C_X), (y - C_Y)) * mapp; //thanks Sutaburosu } } } diff --git a/wled00/FX.h b/wled00/FX.h index 34b6f785..21f9d08c 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -329,7 +329,7 @@ typedef enum mapping1D2D { M12_pCorner = 3 } mapping1D2D_t; -// segment, 72 bytes +// segment, 80 bytes typedef struct Segment { public: uint16_t start; // start index / start X coordinate 2D (left) @@ -370,7 +370,7 @@ typedef struct Segment { }; uint8_t startY; // start Y coodrinate 2D (top); there should be no more than 255 rows uint8_t stopY; // stop Y coordinate 2D (bottom); there should be no more than 255 rows - char *name; + char *name; // runtime data unsigned long next_time; // millis() of next update @@ -378,8 +378,7 @@ typedef struct Segment { uint32_t call; // call counter uint16_t aux0; // custom var uint16_t aux1; // custom var - byte* data; // effect data pointer - uint32_t* leds; // local leds[] array (may be a pointer to global) + byte *data; // effect data pointer static uint16_t maxWidth, maxHeight; // these define matrix width & height (max. segment dimensions) private: @@ -393,10 +392,13 @@ typedef struct Segment { uint8_t _reserved : 4; }; }; - uint16_t _dataLen; + uint16_t _dataLen; static uint16_t _usedSegmentData; - // transition data, valid only if transitional==true, holds values during transition + uint16_t _qStart, _qStop, _qStartY, _qStopY; + bool _queuedChanges; + + // transition data, valid only if transitional==true, holds values during transition (72 bytes) struct Transition { uint32_t _colorT[NUM_COLORS]; uint8_t _briT; // temporary brightness @@ -407,7 +409,7 @@ typedef struct Segment { //uint16_t _aux0, _aux1; // previous mode/effect runtime data //uint32_t _step, _call; // previous mode/effect runtime data //byte *_data; // previous mode/effect runtime data - uint32_t _start; + unsigned long _start; // must accommodate millis() uint16_t _dur; Transition(uint16_t dur=750) : _briT(255) @@ -462,9 +464,9 @@ typedef struct Segment { aux0(0), aux1(0), data(nullptr), - leds(nullptr), _capabilities(0), _dataLen(0), + _queuedChanges(false), _t(nullptr) { //refreshLightCapabilities(); @@ -485,9 +487,8 @@ typedef struct Segment { //if (data) Serial.printf(" %d (%p)", (int)_dataLen, data); //Serial.println(); //#endif - if (name) delete[] name; - if (_t) delete _t; - if (leds) free(leds); + if (name) { delete[] name; name = nullptr; } + if (_t) { transitional = false; delete _t; _t = nullptr; } deallocateData(); } @@ -495,7 +496,7 @@ typedef struct Segment { Segment& operator= (Segment &&orig) noexcept; // move assignment #ifdef WLED_DEBUG - size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0) + (leds?sizeof(CRGB)*length():0); } + size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0); } #endif inline bool getOption(uint8_t n) const { return ((options >> n) & 0x01); } @@ -505,16 +506,16 @@ typedef struct Segment { inline bool hasRGB(void) const { return _isRGB; } inline bool hasWhite(void) const { return _hasW; } inline bool isCCT(void) const { return _isCCT; } - inline uint16_t width(void) const { return (stop > start) ? (stop - start) : 0; } // segment width in physical pixels (length if 1D) - inline uint16_t height(void) const { return (stopY > startY) ? (stopY - startY) : 0; } // segment height (if 2D) in physical pixels // softhack007: make sure its always > 0 - inline uint16_t length(void) const { return width() * height(); } // segment length (count) in physical pixels + inline uint16_t width(void) const { return isActive() ? (stop - start) : 0; } // segment width in physical pixels (length if 1D) + inline uint16_t height(void) const { return stopY - startY; } // segment height (if 2D) in physical pixels (it *is* always >=1) + inline uint16_t length(void) const { return width() * height(); } // segment length (count) in physical pixels inline uint16_t groupLength(void) const { return grouping + spacing; } inline uint8_t getLightCapabilities(void) const { return _capabilities; } static uint16_t getUsedSegmentData(void) { return _usedSegmentData; } static void addUsedSegmentData(int len) { _usedSegmentData += len; } - void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1); + void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1, bool immediate=false); bool setColor(uint8_t slot, uint32_t c); //returns true if changed void setCCT(uint16_t k); void setOpacity(uint8_t o); @@ -536,7 +537,6 @@ typedef struct Segment { * Safe to call from interrupts and network requests. */ inline void markForReset(void) { reset = true; } // setOption(SEG_OPTION_RESET, true) - void setUpLeds(void); // local double buffer/lossless getPixelColor() // transition functions void startTransition(uint16_t dur); // transition has to start before actual segment values change @@ -896,7 +896,7 @@ class WS2812FX { // 96 bytes uint16_t* customMappingTable; uint16_t customMappingSize; - uint32_t _lastShow; + unsigned long _lastShow; uint8_t _segment_index; uint8_t _mainSegment; diff --git a/wled00/FX_2Dfcn.cpp b/wled00/FX_2Dfcn.cpp index 45107fe5..417d0484 100644 --- a/wled00/FX_2Dfcn.cpp +++ b/wled00/FX_2Dfcn.cpp @@ -189,20 +189,16 @@ uint32_t WS2812FX::getPixelColorXY(uint16_t x, uint16_t y) { // XY(x,y) - gets pixel index within current segment (often used to reference leds[] array element) uint16_t /*IRAM_ATTR*/ Segment::XY(uint16_t x, uint16_t y) { - uint16_t width = virtualWidth(); // segment width in logical pixels - uint16_t height = virtualHeight(); // segment height in logical pixels - if (width == 0) return 0; // softhack007 avoid div/0 - if (height == 0) return (x%width); // softhack007 avoid div/0 - return (x%width) + (y%height) * width; + uint16_t width = virtualWidth(); // segment width in logical pixels (can be 0 if segment is inactive) + uint16_t height = virtualHeight(); // segment height in logical pixels (is always >= 1) + return isActive() ? (x%width) + (y%height) * width : 0; } void /*IRAM_ATTR*/ Segment::setPixelColorXY(int x, int y, uint32_t col) { - if (Segment::maxHeight==1) return; // not a matrix set-up + if (!isActive()) return; // not active if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return; // if pixel would fall out of virtual segment just exit - if (leds) leds[XY(x,y)] = col; - uint8_t _bri_t = currentBri(on ? opacity : 0); if (_bri_t < 255) { byte r = scale8(R(col), _bri_t); @@ -245,7 +241,7 @@ void /*IRAM_ATTR*/ Segment::setPixelColorXY(int x, int y, uint32_t col) // anti-aliased version of setPixelColorXY() void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa) { - if (Segment::maxHeight==1) return; // not a matrix set-up + if (!isActive()) return; // not active if (x<0.0f || x>1.0f || y<0.0f || y>1.0f) return; // not normalized const uint16_t cols = virtualWidth(); @@ -288,7 +284,8 @@ void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa) // returns RGBW values of pixel uint32_t Segment::getPixelColorXY(uint16_t x, uint16_t y) { - if (leds) return leds[XY(x,y)]; + if (!isActive()) return 0; // not active + if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return 0; // if pixel would fall out of virtual segment just exit if (reverse ) x = virtualWidth() - x - 1; if (reverse_y) y = virtualHeight() - y - 1; if (transpose) { uint16_t t = x; x = y; y = t; } // swap X & Y if segment transposed @@ -305,6 +302,7 @@ void Segment::blendPixelColorXY(uint16_t x, uint16_t y, uint32_t color, uint8_t // Adds the specified color with the existing pixel color perserving color balance. void Segment::addPixelColorXY(int x, int y, uint32_t color, bool fast) { + if (!isActive()) return; // not active if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return; // if pixel would fall out of virtual segment just exit uint32_t col = getPixelColorXY(x,y); uint8_t r = R(col); @@ -324,12 +322,14 @@ void Segment::addPixelColorXY(int x, int y, uint32_t color, bool fast) { } void Segment::fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) { + if (!isActive()) return; // not active CRGB pix = CRGB(getPixelColorXY(x,y)).nscale8_video(fade); setPixelColorXY(x, y, pix); } // blurRow: perform a blur on a row of a rectangular matrix void Segment::blurRow(uint16_t row, fract8 blur_amount) { + if (!isActive()) return; // not active const uint_fast16_t cols = virtualWidth(); const uint_fast16_t rows = virtualHeight(); @@ -357,6 +357,7 @@ void Segment::blurRow(uint16_t row, fract8 blur_amount) { // blurCol: perform a blur on a column of a rectangular matrix void Segment::blurCol(uint16_t col, fract8 blur_amount) { + if (!isActive()) return; // not active const uint_fast16_t cols = virtualWidth(); const uint_fast16_t rows = virtualHeight(); @@ -384,6 +385,7 @@ void Segment::blurCol(uint16_t col, fract8 blur_amount) { // 1D Box blur (with added weight - blur_amount: [0=no blur, 255=max blur]) void Segment::box_blur(uint16_t i, bool vertical, fract8 blur_amount) { + if (!isActive()) return; // not active const uint16_t cols = virtualWidth(); const uint16_t rows = virtualHeight(); const uint16_t dim1 = vertical ? rows : cols; @@ -436,6 +438,7 @@ void Segment::blur1d(fract8 blur_amount) { } void Segment::moveX(int8_t delta, bool wrap) { + if (!isActive()) return; // not active const uint16_t cols = virtualWidth(); const uint16_t rows = virtualHeight(); if (!delta || abs(delta) >= cols) return; @@ -453,6 +456,7 @@ void Segment::moveX(int8_t delta, bool wrap) { } void Segment::moveY(int8_t delta, bool wrap) { + if (!isActive()) return; // not active const uint16_t cols = virtualWidth(); const uint16_t rows = virtualHeight(); if (!delta || abs(delta) >= rows) return; @@ -488,6 +492,7 @@ void Segment::move(uint8_t dir, uint8_t delta, bool wrap) { } void Segment::draw_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { + if (!isActive()) return; // not active // Bresenham’s Algorithm int d = 3 - (2*radius); int y = radius, x = 0; @@ -512,6 +517,7 @@ void Segment::draw_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { // by stepko, taken from https://editor.soulmatelights.com/gallery/573-blobs void Segment::fill_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { + if (!isActive()) return; // not active const uint16_t cols = virtualWidth(); const uint16_t rows = virtualHeight(); for (int16_t y = -radius; y <= radius; y++) { @@ -525,6 +531,7 @@ void Segment::fill_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { } void Segment::nscale8(uint8_t scale) { + if (!isActive()) return; // not active const uint16_t cols = virtualWidth(); const uint16_t rows = virtualHeight(); for(uint16_t y = 0; y < rows; y++) for (uint16_t x = 0; x < cols; x++) { @@ -534,6 +541,7 @@ void Segment::nscale8(uint8_t scale) { //line function void Segment::drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint32_t c) { + if (!isActive()) return; // not active const uint16_t cols = virtualWidth(); const uint16_t rows = virtualHeight(); if (x0 >= cols || x1 >= cols || y0 >= rows || y1 >= rows) return; @@ -558,6 +566,7 @@ void Segment::drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint3 // draws a raster font character on canvas // only supports: 4x6=24, 5x8=40, 5x12=60, 6x8=48 and 7x9=63 fonts ATM void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t col2) { + if (!isActive()) return; // not active if (chr < 32 || chr > 126) return; // only ASCII 32-126 supported chr -= 32; // align with font table entries const uint16_t cols = virtualWidth(); @@ -593,6 +602,7 @@ void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, #define WU_WEIGHT(a,b) ((uint8_t) (((a)*(b)+(a)+(b))>>8)) void Segment::wu_pixel(uint32_t x, uint32_t y, CRGB c) { //awesome wu_pixel procedure by reddit u/sutaburosu + if (!isActive()) return; // not active // extract the fractional parts and derive their inverses uint8_t xx = x & 0xff, yy = y & 0xff, ix = 255 - xx, iy = 255 - yy; // calculate the intensities for each affected pixel diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index b7684423..bf26dbfc 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -81,22 +81,21 @@ uint16_t Segment::maxHeight = 1; Segment::Segment(const Segment &orig) { //DEBUG_PRINTLN(F("-- Copy segment constructor --")); memcpy((void*)this, (void*)&orig, sizeof(Segment)); + transitional = false; // copied segment cannot be in transition name = nullptr; data = nullptr; _dataLen = 0; _t = nullptr; - leds = nullptr; if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } - if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } - if (orig.leds) { leds = (uint32_t*)malloc(sizeof(uint32_t)*length()); if (leds) memcpy(leds, orig.leds, sizeof(uint32_t)*length()); } + //if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } } // move constructor Segment::Segment(Segment &&orig) noexcept { //DEBUG_PRINTLN(F("-- Move segment constructor --")); memcpy((void*)this, (void*)&orig, sizeof(Segment)); - orig.leds = nullptr; + orig.transitional = false; // old segment cannot be in transition any more orig.name = nullptr; orig.data = nullptr; orig._dataLen = 0; @@ -108,23 +107,22 @@ Segment& Segment::operator= (const Segment &orig) { //DEBUG_PRINTLN(F("-- Copying segment --")); if (this != &orig) { // clean destination + transitional = false; // copied segment cannot be in transition if (name) delete[] name; if (_t) delete _t; - if (leds) free(leds); deallocateData(); // copy source memcpy((void*)this, (void*)&orig, sizeof(Segment)); + transitional = false; // erase pointers to allocated data name = nullptr; data = nullptr; _dataLen = 0; _t = nullptr; - leds = nullptr; // copy source data if (orig.name) { name = new char[strlen(orig.name)+1]; if (name) strcpy(name, orig.name); } if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); } - if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } - if (orig.leds) { leds = (uint32_t*)malloc(sizeof(uint32_t)*length()); if (leds) memcpy(leds, orig.leds, sizeof(uint32_t)*length()); } + //if (orig._t) { _t = new Transition(orig._t->_dur, orig._t->_briT, orig._t->_cctT, orig._t->_colorT); } } return *this; } @@ -133,16 +131,16 @@ Segment& Segment::operator= (const Segment &orig) { Segment& Segment::operator= (Segment &&orig) noexcept { //DEBUG_PRINTLN(F("-- Moving segment --")); if (this != &orig) { - if (name) delete[] name; // free old name - if (leds) free(leds); + transitional = false; // just temporary + if (name) { delete[] name; name = nullptr; } // free old name deallocateData(); // free old runtime data - if (_t) delete _t; + if (_t) { delete _t; _t = nullptr; } memcpy((void*)this, (void*)&orig, sizeof(Segment)); + orig.transitional = false; // old segment cannot be in transition orig.name = nullptr; orig.data = nullptr; orig._dataLen = 0; orig._t = nullptr; - orig.leds = nullptr; } return *this; } @@ -152,12 +150,7 @@ bool Segment::allocateData(size_t len) { deallocateData(); if (Segment::getUsedSegmentData() + len > MAX_SEGMENT_DATA) return false; //not enough memory // do not use SPI RAM on ESP32 since it is slow - //#if defined(ARDUINO_ARCH_ESP32) && defined(BOARD_HAS_PSRAM) && defined(WLED_USE_PSRAM) - //if (psramFound()) - // data = (byte*) ps_malloc(len); - //else - //#endif - data = (byte*) malloc(len); + data = (byte*) malloc(len); if (!data) return false; //allocation failed Segment::addUsedSegmentData(len); _dataLen = len; @@ -182,28 +175,13 @@ void Segment::deallocateData() { */ void Segment::resetIfRequired() { if (reset) { - if (leds) { free(leds); leds = nullptr; } deallocateData(); next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; + if (_queuedChanges) setUp(_qStart, _qStop, grouping, spacing, offset, _qStartY, _qStopY, true); reset = false; // setOption(SEG_OPTION_RESET, false); } } -void Segment::setUpLeds() { - // deallocation happens in resetIfRequired() as it is called when segment changes or in destructor - if (useGlobalLedBuffer) return; // TODO optional seg buffer for FX without lossy restore due to opacity - - // no global buffer - if (leds == nullptr && length() > 0) { //softhack007 quickfix - avoid malloc(0) which is undefined behaviour (should not happen, but i've seen it) - //#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_PSRAM) - //if (psramFound()) - // leds = (CRGB*)ps_malloc(sizeof(CRGB)*length()); // softhack007 disabled; putting leds into psram leads to horrible slowdown on WROVER boards - //else - //#endif - leds = (uint32_t *)calloc(length(), sizeof(uint32_t)); - } -} - CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) { static unsigned long _lastPaletteChange = 0; // perhaps it should be per segment static CRGBPalette16 randomPalette = CRGBPalette16(DEFAULT_COLOR); @@ -326,7 +304,7 @@ void Segment::startTransition(uint16_t dur) { // transition progression between 0-65535 uint16_t Segment::progress() { if (!transitional || !_t) return 0xFFFFU; - uint32_t timeNow = millis(); + unsigned long timeNow = millis(); if (timeNow - _t->_start > _t->_dur || _t->_dur == 0) return 0xFFFFU; return (timeNow - _t->_start) * 0xFFFFU / _t->_dur; } @@ -355,7 +333,7 @@ CRGBPalette16 &Segment::currentPalette(CRGBPalette16 &targetPalette, uint8_t pal // blend palettes // there are about 255 blend passes of 48 "blends" to completely blend two palettes (in _dur time) // minimum blend time is 100ms maximum is 65535ms - uint32_t timeMS = millis() - _t->_start; + unsigned long timeMS = millis() - _t->_start; uint16_t noOfBlends = (255U * timeMS / _t->_dur) - _t->_prevPaletteBlends; for (int i=0; i_prevPaletteBlends++) nblendPaletteTowardPalette(_t->_palT, targetPalette, 48); targetPalette = _t->_palT; // copy transitioning/temporary palette @@ -376,8 +354,9 @@ void Segment::handleTransition() { } } -void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y) { - //return if neither bounds nor grouping have changed +void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y, bool immediate) { + _queuedChanges = false; // cancel anything queued + // return if neither bounds nor grouping have changed bool boundsUnchanged = (start == i1 && stop == i2); #ifndef WLED_DISABLE_2D if (Segment::maxHeight>1) boundsUnchanged &= (startY == i1Y && stopY == i2Y); // 2D @@ -386,29 +365,47 @@ void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t && (!grp || (grouping == grp && spacing == spc)) && (ofs == UINT16_MAX || ofs == offset)) return; - if (stop) fill(BLACK); //turn old segment range off - if (i2 <= i1) { //disable segment - stop = 0; - markForReset(); - return; - } - if (i1 < Segment::maxWidth || (i1 >= Segment::maxWidth*Segment::maxHeight && i1 < strip.getLengthTotal())) start = i1; // Segment::maxWidth equals strip.getLengthTotal() for 1D - stop = i2 > Segment::maxWidth*Segment::maxHeight ? MIN(i2,strip.getLengthTotal()) : (i2 > Segment::maxWidth ? Segment::maxWidth : MAX(1,i2)); - startY = 0; - stopY = 1; - #ifndef WLED_DISABLE_2D - if (Segment::maxHeight>1) { // 2D - if (i1Y < Segment::maxHeight) startY = i1Y; - stopY = i2Y > Segment::maxHeight ? Segment::maxHeight : MAX(1,i2Y); - } - #endif - if (grp) { + if (stop) fill(BLACK); // turn old segment range off (clears pixels if changing spacing) + if (grp) { // prevent assignment of 0 grouping = grp; spacing = spc; + } else { + grouping = 1; + spacing = 0; } if (ofs < UINT16_MAX) offset = ofs; + markForReset(); - if (!boundsUnchanged) refreshLightCapabilities(); + if (!boundsUnchanged) { + if (immediate) { + if (i2 <= i1) { //disable segment + stop = 0; + return; + } + if (i1 < Segment::maxWidth || (i1 >= Segment::maxWidth*Segment::maxHeight && i1 < strip.getLengthTotal())) start = i1; // Segment::maxWidth equals strip.getLengthTotal() for 1D + stop = i2 > Segment::maxWidth*Segment::maxHeight ? MIN(i2,strip.getLengthTotal()) : (i2 > Segment::maxWidth ? Segment::maxWidth : MAX(1,i2)); + startY = 0; + stopY = 1; + #ifndef WLED_DISABLE_2D + if (Segment::maxHeight>1) { // 2D + if (i1Y < Segment::maxHeight) startY = i1Y; + stopY = i2Y > Segment::maxHeight ? Segment::maxHeight : MAX(1,i2Y); + } + #endif + // safety check + if (start >= stop || startY >= stopY) { + stop = 0; + return; + } + if (!boundsUnchanged) refreshLightCapabilities(); + } else { + _qStart = i1; + _qStop = i2; + _qStartY = i1Y; + _qStopY = i2Y; + _queuedChanges = true; + } + } } @@ -455,8 +452,7 @@ void Segment::setMode(uint8_t fx, bool loadDefaults) { // if we have a valid mode & is not reserved if (fx < strip.getModeCount() && strncmp_P("RSVD", strip.getModeData(fx), 4)) { if (fx != mode) { - startTransition(strip.getTransition()); // set effect transitions - //markForReset(); // transition will handle this + if (fadeTransition) startTransition(strip.getTransition()); // set effect transitions mode = fx; // load default values from effect string @@ -541,8 +537,7 @@ uint16_t Segment::virtualLength() const { return vLen; } #endif - uint16_t groupLen = groupLength(); - if (groupLen < 1) groupLen = 1; // prevent division by zero - better safe than sorry ... + uint16_t groupLen = groupLength(); // is always >= 1 uint16_t vLength = (length() + groupLen - 1) / groupLen; if (mirror) vLength = (vLength + 1) /2; // divide by 2 if mirror, leave at least a single LED return vLength; @@ -550,6 +545,7 @@ uint16_t Segment::virtualLength() const { void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col) { + if (!isActive()) return; // not active #ifndef WLED_DISABLE_2D int vStrip = i>>16; // hack to allow running on virtual strips (2D segment columns/rows) #endif @@ -617,8 +613,6 @@ void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col) } #endif - if (leds) leds[i] = col; - uint16_t len = length(); uint8_t _bri_t = currentBri(on ? opacity : 0); if (_bri_t < 255) { @@ -660,6 +654,7 @@ void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col) // anti-aliased normalized version of setPixelColor() void Segment::setPixelColor(float i, uint32_t col, bool aa) { + if (!isActive()) return; // not active int vStrip = int(i/10.0f); // hack to allow running on virtual strips (2D segment columns/rows) i -= int(i); @@ -691,6 +686,7 @@ void Segment::setPixelColor(float i, uint32_t col, bool aa) uint32_t Segment::getPixelColor(int i) { + if (!isActive()) return 0; // not active #ifndef WLED_DISABLE_2D int vStrip = i>>16; #endif @@ -718,8 +714,6 @@ uint32_t Segment::getPixelColor(int i) } #endif - if (leds) return leds[i]; - if (reverse) i = virtualLength() - i - 1; i *= groupLength(); i += start; @@ -760,6 +754,11 @@ void Segment::refreshLightCapabilities() { uint16_t segStartIdx = 0xFFFFU; uint16_t segStopIdx = 0; + if (!isActive()) { + _capabilities = 0; + return; + } + if (start < Segment::maxWidth * Segment::maxHeight) { // we are withing 2D matrix (includes 1D segments) for (int y = startY; y < stopY; y++) for (int x = start; x < stop; x++) { @@ -804,6 +803,7 @@ void Segment::refreshLightCapabilities() { * Fills segment with color */ void Segment::fill(uint32_t c) { + if (!isActive()) return; // not active const uint16_t cols = is2D() ? virtualWidth() : virtualLength(); const uint16_t rows = virtualHeight(); // will be 1 for 1D for(uint16_t y = 0; y < rows; y++) for (uint16_t x = 0; x < cols; x++) { @@ -819,6 +819,7 @@ void Segment::blendPixelColor(int n, uint32_t color, uint8_t blend) { // Adds the specified color with the existing pixel color perserving color balance. void Segment::addPixelColor(int n, uint32_t color, bool fast) { + if (!isActive()) return; // not active uint32_t col = getPixelColor(n); uint8_t r = R(col); uint8_t g = G(col); @@ -837,6 +838,7 @@ void Segment::addPixelColor(int n, uint32_t color, bool fast) { } void Segment::fadePixelColor(uint16_t n, uint8_t fade) { + if (!isActive()) return; // not active CRGB pix = CRGB(getPixelColor(n)).nscale8_video(fade); setPixelColor(n, pix); } @@ -845,6 +847,7 @@ void Segment::fadePixelColor(uint16_t n, uint8_t fade) { * fade out function, higher rate = quicker fade */ void Segment::fade_out(uint8_t rate) { + if (!isActive()) return; // not active const uint16_t cols = is2D() ? virtualWidth() : virtualLength(); const uint16_t rows = virtualHeight(); // will be 1 for 1D @@ -882,7 +885,7 @@ void Segment::fade_out(uint8_t rate) { // fades all pixels to black using nscale8() void Segment::fadeToBlackBy(uint8_t fadeBy) { - if (fadeBy == 0) return; // optimization - no scaling to apply + if (!isActive() || fadeBy == 0) return; // optimization - no scaling to apply const uint16_t cols = is2D() ? virtualWidth() : virtualLength(); const uint16_t rows = virtualHeight(); // will be 1 for 1D @@ -897,7 +900,7 @@ void Segment::fadeToBlackBy(uint8_t fadeBy) { */ void Segment::blur(uint8_t blur_amount) { - if (blur_amount == 0) return; // optimization: 0 means "don't blur" + if (!isActive() || blur_amount == 0) return; // optimization: 0 means "don't blur" #ifndef WLED_DISABLE_2D if (is2D()) { // compatibility with 2D @@ -1071,7 +1074,7 @@ void WS2812FX::finalizeInit(void) } void WS2812FX::service() { - uint32_t nowUp = millis(); // Be aware, millis() rolls over every 49 days + unsigned long nowUp = millis(); // Be aware, millis() rolls over every 49 days now = nowUp + timebase; if (nowUp - _lastShow < MIN_SHOW_DELAY) return; bool doShow = false; @@ -1089,7 +1092,6 @@ void WS2812FX::service() { // last condition ensures all solid segments are updated at the same time if(nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC)) { - if (seg.grouping == 0) seg.grouping = 1; // sanity check doShow = true; uint16_t delay = FRAMETIME; @@ -1117,12 +1119,19 @@ void WS2812FX::service() { } _virtualSegmentLength = 0; busses.setSegmentCCT(-1); - if(doShow) { + _isServicing = false; + _triggered = false; + + #ifdef WLED_DEBUG + if (millis() - nowUp > _frametime) DEBUG_PRINTLN(F("Slow effects.")); + #endif + if (doShow) { yield(); show(); } - _triggered = false; - _isServicing = false; + #ifdef WLED_DEBUG + if (millis() - nowUp > _frametime) DEBUG_PRINTLN(F("Slow strip.")); + #endif } void IRAM_ATTR WS2812FX::setPixelColor(int i, uint32_t col) @@ -1159,31 +1168,25 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { bool useWackyWS2815PowerModel = false; byte actualMilliampsPerLed = milliampsPerLed; - if(milliampsPerLed == 255) { - useWackyWS2815PowerModel = true; - actualMilliampsPerLed = 12; // from testing an actual strip - } - if (ablMilliampsMax < 150 || actualMilliampsPerLed == 0) { //0 mA per LED and too low numbers turn off calculation currentMilliamps = 0; return _brightness; } - uint16_t pLen = getLengthPhysical(); - uint32_t puPerMilliamp = 195075 / actualMilliampsPerLed; - uint32_t powerBudget = (ablMilliampsMax - MA_FOR_ESP) * puPerMilliamp; //100mA for ESP power - if (powerBudget > puPerMilliamp * pLen) { //each LED uses about 1mA in standby, exclude that from power budget - powerBudget -= puPerMilliamp * pLen; - } else { - powerBudget = 0; + if (milliampsPerLed == 255) { + useWackyWS2815PowerModel = true; + actualMilliampsPerLed = 12; // from testing an actual strip } - uint32_t powerSum = 0; // could overflow if more than 22K LEDs (uint32_t MAX / 195075 PU per LED) + size_t powerBudget = (ablMilliampsMax - MA_FOR_ESP); //100mA for ESP power + size_t pLen = 0; //getLengthPhysical(); + size_t powerSum = 0; for (uint_fast8_t bNum = 0; bNum < busses.getNumBusses(); bNum++) { Bus *bus = busses.getBus(bNum); - if (bus->getType() >= TYPE_NET_DDP_RGB) continue; //exclude non-physical network busses + if (!IS_DIGITAL(bus->getType())) continue; //exclude non-digital network busses uint16_t len = bus->getLength(); + pLen += len; uint32_t busPowerSum = 0; for (uint_fast16_t i = 0; i < len; i++) { //sum up the usage of each LED uint32_t c = bus->getPixelColor(i); // always returns original or restored color without brightness scaling @@ -1198,38 +1201,44 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { if (bus->hasWhite()) { //RGBW led total output with white LEDs enabled is still 50mA, so each channel uses less busPowerSum *= 3; - busPowerSum = busPowerSum >> 2; //same as /= 4 + busPowerSum >>= 2; //same as /= 4 } powerSum += busPowerSum; } - uint8_t newBri = _brightness; - uint32_t powerSumUnscaled = powerSum; - powerSum *= _brightness; + if (powerBudget > pLen) { //each LED uses about 1mA in standby, exclude that from power budget + powerBudget -= pLen; + } else { + powerBudget = 0; + } - if (powerSum > powerBudget) { //scale brightness down to stay in current limit + // powerSum has all the values of channels summed (max would be pLen*765 as white is excluded) so convert to milliAmps + powerSum = (powerSum * actualMilliampsPerLed) / 765; + + uint8_t newBri = _brightness; + if (powerSum * _brightness / 255 > powerBudget) { //scale brightness down to stay in current limit float scale = (float)powerBudget / (float)powerSum; uint16_t scaleI = scale * 255; uint8_t scaleB = (scaleI > 255) ? 255 : scaleI; newBri = scale8(_brightness, scaleB); } - currentMilliamps = (powerSumUnscaled * newBri) / puPerMilliamp; + currentMilliamps = (powerSum * newBri) / 255; currentMilliamps += MA_FOR_ESP; //add power of ESP back to estimate - currentMilliamps += pLen; //add standby power back to estimate + currentMilliamps += pLen; //add standby power (1mA/LED) back to estimate return newBri; } void WS2812FX::show(void) { + // avoid race condition, caputre _callback value + show_callback callback = _callback; + if (callback) callback(); + #ifdef WLED_DEBUG static unsigned long sumMicros = 0, sumCurrent = 0; static size_t calls = 0; unsigned long microsStart = micros(); #endif - // avoid race condition, caputre _callback value - show_callback callback = _callback; - if (callback) callback(); - uint8_t busBrightness = estimateCurrentAndLimitBri(); busses.setBrightness(busBrightness); #ifdef WLED_DEBUG @@ -1240,21 +1249,22 @@ void WS2812FX::show(void) { // all of the data has been sent. // See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods busses.show(); - unsigned long now = millis(); - unsigned long diff = now - _lastShow; - uint16_t fpsCurr = 200; - if (diff > 0) fpsCurr = 1000 / diff; - _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; - _lastShow = now; #ifdef WLED_DEBUG sumMicros += micros() - microsStart; if (++calls == 100) { - DEBUG_PRINTF("show calls: %d micros: %lu avg: %lu (current: %lu avg: %lu)\n", calls, sumMicros, sumMicros/calls, sumCurrent, sumCurrent/calls); + DEBUG_PRINTF("%d show calls: %lu[us] avg: %lu[us] (current: %lu[us] avg: %lu[us])\n", calls, sumMicros, sumMicros/calls, sumCurrent, sumCurrent/calls); sumMicros = sumCurrent = 0; calls = 0; } #endif + + unsigned long now = millis(); + size_t diff = now - _lastShow; + size_t fpsCurr = 200; + if (diff > 0) fpsCurr = 1000 / diff; + _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; + _lastShow = now; } /** @@ -1431,6 +1441,7 @@ Segment& WS2812FX::getSegment(uint8_t id) { return _segments[id >= _segments.size() ? getMainSegmentId() : id]; // vectors } +// compatibility method (deprecated) void WS2812FX::setSegment(uint8_t n, uint16_t i1, uint16_t i2, uint8_t grouping, uint8_t spacing, uint16_t offset, uint16_t startY, uint16_t stopY) { if (n >= _segments.size()) return; _segments[n].setUp(i1, i2, grouping, spacing, offset, startY, stopY); diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index ed1816ea..c0d4e7e2 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -128,11 +128,6 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) void BusDigital::show() { if (!_valid) return; - #ifdef WLED_DEBUG - static unsigned long sumMicros = 0; - static size_t calls = 0; - unsigned long microsStart = micros(); - #endif PolyBus::setBrightness(_busPtr, _iType, _bri); if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); @@ -159,14 +154,6 @@ void BusDigital::show() { } PolyBus::show(_busPtr, _iType); PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) - #ifdef WLED_DEBUG - sumMicros += micros() - microsStart; - if (++calls == 100) { - DEBUG_PRINTF("Bus calls: %d micros: %lu avg: %lu\n", calls, sumMicros, sumMicros/calls); - sumMicros = 0; - calls = 0; - } - #endif } bool BusDigital::canShow() { diff --git a/wled00/json.cpp b/wled00/json.cpp index bff9f362..8858e9c9 100644 --- a/wled00/json.cpp +++ b/wled00/json.cpp @@ -22,7 +22,7 @@ bool deserializeSegment(JsonObject elem, byte it, byte presetId) int stop = elem["stop"] | -1; - // if using vectors use this code to append segment + // append segment if (id >= strip.getSegmentsNum()) { if (stop <= 0) return false; // ignore empty/inactive segments strip.appendSegment(Segment(0, strip.getLengthTotal())); @@ -110,7 +110,10 @@ bool deserializeSegment(JsonObject elem, byte it, byte presetId) of = offsetAbs; } if (stop > start && of > len -1) of = len -1; - seg.setUp(start, stop, grp, spc, of, startY, stopY); + + // update segment (delete if necessary) + // we must not change segment dimensions during drawing of effects as that may produce undesired behaviour (crash) + seg.setUp(start, stop, grp, spc, of, startY, stopY, !strip.isServicing()); if (seg.reset && seg.stop == 0) return true; // segment was deleted & is marked for reset, no need to change anything else @@ -468,12 +471,14 @@ void serializeSegment(JsonObject& root, Segment& seg, byte id, bool forPreset, b if (segmentBounds) { root["start"] = seg.start; root["stop"] = seg.stop; + #ifndef WLED_DISABLE_2D if (strip.isMatrix) { root[F("startY")] = seg.startY; root[F("stopY")] = seg.stopY; } + #endif } - if (!forPreset) root["len"] = (seg.stop >= seg.start) ? (seg.stop - seg.start) : 0; + if (!forPreset) root["len"] = seg.stop - seg.start; root["grp"] = seg.grouping; root[F("spc")] = seg.spacing; root[F("of")] = seg.offset; diff --git a/wled00/wled.cpp b/wled00/wled.cpp index a732bba3..e51fc37b 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -23,7 +23,7 @@ void WLED::reset() #ifdef WLED_ENABLE_WEBSOCKETS ws.closeAll(1012); #endif - long dly = millis(); + unsigned long dly = millis(); while (millis() - dly < 450) { yield(); // enough time to send response to client } @@ -36,13 +36,17 @@ void WLED::loop() { #ifdef WLED_DEBUG static unsigned long lastRun = 0; - size_t loopDelay = (millis() - lastRun); + unsigned long loopMillis = millis(); + size_t loopDelay = loopMillis - lastRun; if (lastRun == 0) loopDelay=0; // startup - don't have valid data from last run. - if (loopDelay > 2) DEBUG_PRINTF("Loop delayed more than %dms.\n", loopDelay); + if (loopDelay > 2) DEBUG_PRINTF("Loop delayed more than %ums.\n", loopDelay); + static unsigned long maxLoopMillis = 0; + static size_t avgLoopMillis = 0; static unsigned long maxUsermodMillis = 0; static size_t avgUsermodMillis = 0; static unsigned long maxStripMillis = 0; static size_t avgStripMillis = 0; + unsigned long stripMillis; #endif handleTime(); @@ -84,6 +88,9 @@ void WLED::loop() yield(); } + #ifdef WLED_DEBUG + stripMillis = millis(); + #endif if (!realtimeMode || realtimeOverride || (realtimeMode && useMainSegmentOnly)) // block stuff if WARLS/Adalight is enabled { if (apActive) dnsServer.processNextRequest(); @@ -102,22 +109,18 @@ void WLED::loop() handlePresets(); yield(); - #ifdef WLED_DEBUG - unsigned long stripMillis = millis(); - #endif if (!offMode || strip.isOffRefreshRequired()) strip.service(); #ifdef ESP8266 else if (!noWifiSleep) delay(1); //required to make sure ESP enters modem sleep (see #1184) #endif - #ifdef WLED_DEBUG - stripMillis = millis() - stripMillis; - if (stripMillis > 50) DEBUG_PRINTLN("Slow strip."); - avgStripMillis += stripMillis; - if (stripMillis > maxStripMillis) maxStripMillis = stripMillis; - #endif } + #ifdef WLED_DEBUG + stripMillis = millis() - stripMillis; + avgStripMillis += stripMillis; + if (stripMillis > maxStripMillis) maxStripMillis = stripMillis; + #endif yield(); #ifdef ESP8266 @@ -186,8 +189,31 @@ void WLED::loop() handleWs(); handleStatusLED(); + toki.resetTick(); + +#if WLED_WATCHDOG_TIMEOUT > 0 + // we finished our mainloop, reset the watchdog timer + if (!strip.isUpdating()) + #ifdef ARDUINO_ARCH_ESP32 + esp_task_wdt_reset(); + #else + ESP.wdtFeed(); + #endif +#endif + + if (doReboot && (!doInitBusses || !doSerializeConfig)) // if busses have to be inited & saved, wait until next iteration + reset(); + // DEBUG serial logging (every 30s) #ifdef WLED_DEBUG + loopMillis = millis() - loopMillis; + if (loopMillis > 30) { + DEBUG_PRINTF("Loop took %lums.\n", loopMillis); + DEBUG_PRINTF("Usermods took %lums.\n", usermodMillis); + DEBUG_PRINTF("Strip took %lums.\n", stripMillis); + } + avgLoopMillis += loopMillis; + if (loopMillis > maxLoopMillis) maxLoopMillis = loopMillis; if (millis() - debugTime > 29999) { DEBUG_PRINTLN(F("---DEBUG INFO---")); DEBUG_PRINT(F("Runtime: ")); DEBUG_PRINTLN(millis()); @@ -210,11 +236,13 @@ void WLED::loop() DEBUG_PRINT(F("Client IP: ")); DEBUG_PRINTLN(Network.localIP()); if (loops > 0) { // avoid division by zero DEBUG_PRINT(F("Loops/sec: ")); DEBUG_PRINTLN(loops / 30); + DEBUG_PRINT(F("Loop time[ms]: ")); DEBUG_PRINT(avgLoopMillis/loops); DEBUG_PRINT("/");DEBUG_PRINTLN(maxLoopMillis); DEBUG_PRINT(F("UM time[ms]: ")); DEBUG_PRINT(avgUsermodMillis/loops); DEBUG_PRINT("/");DEBUG_PRINTLN(maxUsermodMillis); DEBUG_PRINT(F("Strip time[ms]: ")); DEBUG_PRINT(avgStripMillis/loops); DEBUG_PRINT("/"); DEBUG_PRINTLN(maxStripMillis); } strip.printSize(); loops = 0; + maxLoopMillis = 0; maxUsermodMillis = 0; maxStripMillis = 0; avgUsermodMillis = 0; @@ -224,20 +252,6 @@ void WLED::loop() loops++; lastRun = millis(); #endif // WLED_DEBUG - toki.resetTick(); - -#if WLED_WATCHDOG_TIMEOUT > 0 - // we finished our mainloop, reset the watchdog timer - if (!strip.isUpdating()) - #ifdef ARDUINO_ARCH_ESP32 - esp_task_wdt_reset(); - #else - ESP.wdtFeed(); - #endif -#endif - - if (doReboot && (!doInitBusses || !doSerializeConfig)) // if busses have to be inited & saved, wait until next iteration - reset(); } void WLED::enableWatchdog() { diff --git a/wled00/wled.h b/wled00/wled.h index 71b48138..c9487789 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -8,7 +8,7 @@ */ // version code in format yymmddb (b = daily build) -#define VERSION 2307090 +#define VERSION 2307120 //uncomment this if you have a "my_config.h" file you'd like to use //#define WLED_USE_MY_CONFIG @@ -513,7 +513,7 @@ WLED_GLOBAL uint16_t userVar0 _INIT(0), userVar1 _INIT(0); //available for use i // wifi WLED_GLOBAL bool apActive _INIT(false); WLED_GLOBAL bool forceReconnect _INIT(false); -WLED_GLOBAL uint32_t lastReconnectAttempt _INIT(0); +WLED_GLOBAL unsigned long lastReconnectAttempt _INIT(0); WLED_GLOBAL bool interfacesInited _INIT(false); WLED_GLOBAL bool wasConnected _INIT(false); From 4766666913eb6e1eb4e4c34e3729bf5e5a951808 Mon Sep 17 00:00:00 2001 From: cschwinne Date: Thu, 13 Jul 2023 03:09:42 +0200 Subject: [PATCH 17/34] Static queued segment bounds (saves 180 bytes of RAM) Fixed segment index not increasing on inactive segments --- wled00/FX.h | 7 ++-- wled00/FX_fcn.cpp | 86 +++++++++++++++++++++++++++-------------------- wled00/json.cpp | 9 +++-- 3 files changed, 58 insertions(+), 44 deletions(-) diff --git a/wled00/FX.h b/wled00/FX.h index 21f9d08c..75a5a4c9 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -395,8 +395,8 @@ typedef struct Segment { uint16_t _dataLen; static uint16_t _usedSegmentData; - uint16_t _qStart, _qStop, _qStartY, _qStopY; - bool _queuedChanges; + static uint16_t _qStart, _qStop, _qStartY, _qStopY; + static uint8_t _queuedChangesSegId; // transition data, valid only if transitional==true, holds values during transition (72 bytes) struct Transition { @@ -466,7 +466,6 @@ typedef struct Segment { data(nullptr), _capabilities(0), _dataLen(0), - _queuedChanges(false), _t(nullptr) { //refreshLightCapabilities(); @@ -515,7 +514,7 @@ typedef struct Segment { static uint16_t getUsedSegmentData(void) { return _usedSegmentData; } static void addUsedSegmentData(int len) { _usedSegmentData += len; } - void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1, bool immediate=false); + void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1, uint8_t segId = 255); bool setColor(uint8_t slot, uint32_t c); //returns true if changed void setCCT(uint16_t k); void setOpacity(uint8_t o); diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index bf26dbfc..6160ef56 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -76,6 +76,9 @@ uint16_t Segment::_usedSegmentData = 0U; // amount of RAM all segments use for their data[] uint16_t Segment::maxWidth = DEFAULT_LED_COUNT; uint16_t Segment::maxHeight = 1; +uint8_t Segment::_queuedChangesSegId = 255U; +uint16_t Segment::_qStart = 0, Segment::_qStop = 0; +uint16_t Segment::_qStartY = 0, Segment::_qStopY = 0; // copy constructor Segment::Segment(const Segment &orig) { @@ -174,12 +177,15 @@ void Segment::deallocateData() { * may free that data buffer. */ void Segment::resetIfRequired() { - if (reset) { - deallocateData(); - next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; - if (_queuedChanges) setUp(_qStart, _qStop, grouping, spacing, offset, _qStartY, _qStopY, true); - reset = false; // setOption(SEG_OPTION_RESET, false); + if (!reset) return; + + deallocateData(); + next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; + if (_queuedChangesSegId == strip.getCurrSegmentId()) { // apply queued changes + setUp(_qStart, _qStop, grouping, spacing, offset, _qStartY, _qStopY); + _queuedChangesSegId = 255; } + reset = false; } CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) { @@ -354,8 +360,10 @@ void Segment::handleTransition() { } } -void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y, bool immediate) { - _queuedChanges = false; // cancel anything queued +// segId is given when called from network callback, changes are queued if that segment is currently in its effect function +void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y, uint8_t segId) { + if (_queuedChangesSegId == segId) _queuedChangesSegId = 255; // cancel queued change if already queued for this segment + // return if neither bounds nor grouping have changed bool boundsUnchanged = (start == i1 && stop == i2); #ifndef WLED_DISABLE_2D @@ -376,36 +384,39 @@ void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t if (ofs < UINT16_MAX) offset = ofs; markForReset(); - if (!boundsUnchanged) { - if (immediate) { - if (i2 <= i1) { //disable segment - stop = 0; - return; - } - if (i1 < Segment::maxWidth || (i1 >= Segment::maxWidth*Segment::maxHeight && i1 < strip.getLengthTotal())) start = i1; // Segment::maxWidth equals strip.getLengthTotal() for 1D - stop = i2 > Segment::maxWidth*Segment::maxHeight ? MIN(i2,strip.getLengthTotal()) : (i2 > Segment::maxWidth ? Segment::maxWidth : MAX(1,i2)); - startY = 0; - stopY = 1; - #ifndef WLED_DISABLE_2D - if (Segment::maxHeight>1) { // 2D - if (i1Y < Segment::maxHeight) startY = i1Y; - stopY = i2Y > Segment::maxHeight ? Segment::maxHeight : MAX(1,i2Y); - } - #endif - // safety check - if (start >= stop || startY >= stopY) { - stop = 0; - return; - } - if (!boundsUnchanged) refreshLightCapabilities(); - } else { - _qStart = i1; - _qStop = i2; - _qStartY = i1Y; - _qStopY = i2Y; - _queuedChanges = true; - } + if (boundsUnchanged) return; // TODO test if it is save to change grp/spc/ofs without queueing + // queuing a change for a second segment will lead to the loss of the first change if not yet applied + // however this is not a problem as the queued change is applied immediately after the effect function in that segment returns + if (segId < MAX_NUM_SEGMENTS && segId == strip.getCurrSegmentId() && strip.isServicing()) { // queue change to prevent concurrent access + _qStart = i1; + _qStop = i2; + _qStartY = i1Y; + _qStopY = i2Y; + _queuedChangesSegId = segId; + return; // queued changes are applied immediately after effect function returns } + + // apply change immediately + if (i2 <= i1) { //disable segment + stop = 0; + return; + } + if (i1 < Segment::maxWidth || (i1 >= Segment::maxWidth*Segment::maxHeight && i1 < strip.getLengthTotal())) start = i1; // Segment::maxWidth equals strip.getLengthTotal() for 1D + stop = i2 > Segment::maxWidth*Segment::maxHeight ? MIN(i2,strip.getLengthTotal()) : (i2 > Segment::maxWidth ? Segment::maxWidth : MAX(1,i2)); + startY = 0; + stopY = 1; + #ifndef WLED_DISABLE_2D + if (Segment::maxHeight>1) { // 2D + if (i1Y < Segment::maxHeight) startY = i1Y; + stopY = i2Y > Segment::maxHeight ? Segment::maxHeight : MAX(1,i2Y); + } + #endif + // safety check + if (start >= stop || startY >= stopY) { + stop = 0; + return; + } + refreshLightCapabilities(); } @@ -1087,7 +1098,7 @@ void WS2812FX::service() { // reset the segment runtime data if needed seg.resetIfRequired(); - if (!seg.isActive()) continue; + if (!seg.isActive()) { _segment_index++; continue; } // last condition ensures all solid segments are updated at the same time if(nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC)) @@ -1115,6 +1126,7 @@ void WS2812FX::service() { seg.next_time = nowUp + delay; } + seg.resetIfRequired(); // another reset chance, mainly to apply new segment bounds if queued _segment_index++; } _virtualSegmentLength = 0; diff --git a/wled00/json.cpp b/wled00/json.cpp index 8858e9c9..cbf1407c 100644 --- a/wled00/json.cpp +++ b/wled00/json.cpp @@ -112,8 +112,8 @@ bool deserializeSegment(JsonObject elem, byte it, byte presetId) if (stop > start && of > len -1) of = len -1; // update segment (delete if necessary) - // we must not change segment dimensions during drawing of effects as that may produce undesired behaviour (crash) - seg.setUp(start, stop, grp, spc, of, startY, stopY, !strip.isServicing()); + // we must not change segment dimensions during drawing of effects in that segment as concurrent access may cause a crash + seg.setUp(start, stop, grp, spc, of, startY, stopY, id); if (seg.reset && seg.stop == 0) return true; // segment was deleted & is marked for reset, no need to change anything else @@ -1065,7 +1065,10 @@ void serveJson(AsyncWebServerRequest* request) DEBUG_PRINTF("JSON buffer size: %u for request: %d\n", lDoc.memoryUsage(), subJson); - size_t len = response->setLength(); + #ifdef WLED_DEBUG + size_t len = + #endif + response->setLength(); DEBUG_PRINT(F("JSON content length: ")); DEBUG_PRINTLN(len); request->send(response); From 72a72dbc88ed73794e3148b1c519b98e71c12f5d Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Thu, 13 Jul 2023 12:49:19 +0200 Subject: [PATCH 18/34] proper rounding of FPS --- wled00/FX_fcn.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 6160ef56..c0949ae3 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1275,7 +1275,7 @@ void WS2812FX::show(void) { size_t diff = now - _lastShow; size_t fpsCurr = 200; if (diff > 0) fpsCurr = 1000 / diff; - _cumulativeFps = (3 * _cumulativeFps + fpsCurr) >> 2; + _cumulativeFps = (3 * _cumulativeFps + fpsCurr +2) >> 2; // "+2" for proper rounding (2/4 = 0.5) _lastShow = now; } From 5e20abd7f18f745f6f4ef1369513f9ace411b4f8 Mon Sep 17 00:00:00 2001 From: cschwinne Date: Thu, 13 Jul 2023 13:08:36 +0200 Subject: [PATCH 19/34] Move segment bounds queuing to WS2812FX --- wled00/FX.h | 22 +++++++++++++----- wled00/FX_fcn.cpp | 57 ++++++++++++++++++++++++----------------------- wled00/json.cpp | 5 +++-- wled00/set.cpp | 2 +- 4 files changed, 50 insertions(+), 36 deletions(-) diff --git a/wled00/FX.h b/wled00/FX.h index 75a5a4c9..d9426624 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -395,9 +395,6 @@ typedef struct Segment { uint16_t _dataLen; static uint16_t _usedSegmentData; - static uint16_t _qStart, _qStop, _qStartY, _qStopY; - static uint8_t _queuedChangesSegId; - // transition data, valid only if transitional==true, holds values during transition (72 bytes) struct Transition { uint32_t _colorT[NUM_COLORS]; @@ -689,7 +686,15 @@ class WS2812FX { // 96 bytes customMappingSize(0), _lastShow(0), _segment_index(0), - _mainSegment(0) + _mainSegment(0), + _queuedChangesSegId(255), + _qStart(0), + _qStop(0), + _qStartY(0), + _qStopY(0), + _qGrouping(0), + _qSpacing(0), + _qOffset(0) { WS2812FX::instance = this; _mode.reserve(_modeCount); // allocate memory to prevent initial fragmentation (does not increase size()) @@ -745,7 +750,7 @@ class WS2812FX { // 96 bytes inline void trigger(void) { _triggered = true; } // Forces the next frame to be computed on all active segments. inline void setShowCallback(show_callback cb) { _callback = cb; } inline void setTransition(uint16_t t) { _transitionDur = t; } - inline void appendSegment(const Segment &seg = Segment()) { _segments.push_back(seg); } + inline void appendSegment(const Segment &seg = Segment()) { if (_segments.size() < getMaxSegments()) _segments.push_back(seg); } bool checkSegmentAlignment(void), @@ -899,9 +904,16 @@ class WS2812FX { // 96 bytes uint8_t _segment_index; uint8_t _mainSegment; + uint8_t _queuedChangesSegId; + uint16_t _qStart, _qStop, _qStartY, _qStopY; + uint8_t _qGrouping, _qSpacing; + uint16_t _qOffset; uint8_t estimateCurrentAndLimitBri(void); + + void + setUpSegmentFromQueuedChanges(void); }; extern const char JSON_mode_names[]; diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index c0949ae3..3518e223 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -76,9 +76,6 @@ uint16_t Segment::_usedSegmentData = 0U; // amount of RAM all segments use for their data[] uint16_t Segment::maxWidth = DEFAULT_LED_COUNT; uint16_t Segment::maxHeight = 1; -uint8_t Segment::_queuedChangesSegId = 255U; -uint16_t Segment::_qStart = 0, Segment::_qStop = 0; -uint16_t Segment::_qStartY = 0, Segment::_qStopY = 0; // copy constructor Segment::Segment(const Segment &orig) { @@ -181,10 +178,6 @@ void Segment::resetIfRequired() { deallocateData(); next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; - if (_queuedChangesSegId == strip.getCurrSegmentId()) { // apply queued changes - setUp(_qStart, _qStop, grouping, spacing, offset, _qStartY, _qStopY); - _queuedChangesSegId = 255; - } reset = false; } @@ -362,8 +355,6 @@ void Segment::handleTransition() { // segId is given when called from network callback, changes are queued if that segment is currently in its effect function void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y, uint8_t segId) { - if (_queuedChangesSegId == segId) _queuedChangesSegId = 255; // cancel queued change if already queued for this segment - // return if neither bounds nor grouping have changed bool boundsUnchanged = (start == i1 && stop == i2); #ifndef WLED_DISABLE_2D @@ -384,17 +375,7 @@ void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t if (ofs < UINT16_MAX) offset = ofs; markForReset(); - if (boundsUnchanged) return; // TODO test if it is save to change grp/spc/ofs without queueing - // queuing a change for a second segment will lead to the loss of the first change if not yet applied - // however this is not a problem as the queued change is applied immediately after the effect function in that segment returns - if (segId < MAX_NUM_SEGMENTS && segId == strip.getCurrSegmentId() && strip.isServicing()) { // queue change to prevent concurrent access - _qStart = i1; - _qStop = i2; - _qStartY = i1Y; - _qStopY = i2Y; - _queuedChangesSegId = segId; - return; // queued changes are applied immediately after effect function returns - } + if (boundsUnchanged) return; // apply change immediately if (i2 <= i1) { //disable segment @@ -1098,10 +1079,8 @@ void WS2812FX::service() { // reset the segment runtime data if needed seg.resetIfRequired(); - if (!seg.isActive()) { _segment_index++; continue; } - // last condition ensures all solid segments are updated at the same time - if(nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC)) + if (seg.isActive() && (nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))) { doShow = true; uint16_t delay = FRAMETIME; @@ -1126,7 +1105,7 @@ void WS2812FX::service() { seg.next_time = nowUp + delay; } - seg.resetIfRequired(); // another reset chance, mainly to apply new segment bounds if queued + if (_segment_index == _queuedChangesSegId) setUpSegmentFromQueuedChanges(); _segment_index++; } _virtualSegmentLength = 0; @@ -1453,10 +1432,32 @@ Segment& WS2812FX::getSegment(uint8_t id) { return _segments[id >= _segments.size() ? getMainSegmentId() : id]; // vectors } -// compatibility method (deprecated) -void WS2812FX::setSegment(uint8_t n, uint16_t i1, uint16_t i2, uint8_t grouping, uint8_t spacing, uint16_t offset, uint16_t startY, uint16_t stopY) { - if (n >= _segments.size()) return; - _segments[n].setUp(i1, i2, grouping, spacing, offset, startY, stopY); +// sets new segment bounds, queues if that segment is currently running +void WS2812FX::setSegment(uint8_t segId, uint16_t i1, uint16_t i2, uint8_t grouping, uint8_t spacing, uint16_t offset, uint16_t startY, uint16_t stopY) { + if (segId >= getSegmentsNum()) { + if (i2 <= i1) return; // do not append empty/inactive segments + appendSegment(Segment(0, strip.getLengthTotal())); + segId = getSegmentsNum()-1; // segments are added at the end of list + } + + if (_queuedChangesSegId == segId) _queuedChangesSegId = 255; // cancel queued change if already queued for this segment + + if (segId < getMaxSegments() && segId == getCurrSegmentId() && isServicing()) { // queue change to prevent concurrent access + // queuing a change for a second segment will lead to the loss of the first change if not yet applied + // however this is not a problem as the queued change is applied immediately after the effect function in that segment returns + _qStart = i1; _qStop = i2; _qStartY = startY; _qStopY = stopY; + _qGrouping = grouping; _qSpacing = spacing; _qOffset = offset; + _queuedChangesSegId = segId; + return; // queued changes are applied immediately after effect function returns + } + + _segments[segId].setUp(i1, i2, grouping, spacing, offset, startY, stopY); +} + +void WS2812FX::setUpSegmentFromQueuedChanges() { + if (_queuedChangesSegId >= getSegmentsNum()) return; + getSegment(_queuedChangesSegId).setUp(_qStart, _qStop, _qGrouping, _qSpacing, _qOffset, _qStartY, _qStopY); + _queuedChangesSegId = 255; } void WS2812FX::restartRuntime() { diff --git a/wled00/json.cpp b/wled00/json.cpp index cbf1407c..c0c72989 100644 --- a/wled00/json.cpp +++ b/wled00/json.cpp @@ -112,8 +112,9 @@ bool deserializeSegment(JsonObject elem, byte it, byte presetId) if (stop > start && of > len -1) of = len -1; // update segment (delete if necessary) - // we must not change segment dimensions during drawing of effects in that segment as concurrent access may cause a crash - seg.setUp(start, stop, grp, spc, of, startY, stopY, id); + // do not call seg.setUp() here, as it may cause a crash due to concurrent access if the segment is currently drawing effects + // WS2812FX handles queueing of the change + strip.setSegment(id, start, stop, grp, spc, of, startY, stopY); if (seg.reset && seg.stop == 0) return true; // segment was deleted & is marked for reset, no need to change anything else diff --git a/wled00/set.cpp b/wled00/set.cpp index fb3e40c2..71db6c06 100644 --- a/wled00/set.cpp +++ b/wled00/set.cpp @@ -797,7 +797,7 @@ bool handleSet(AsyncWebServerRequest *request, const String& req, bool apply) if (pos > 0) { spcI = getNumVal(&req, pos); } - selseg.setUp(startI, stopI, grpI, spcI, UINT16_MAX, startY, stopY); + strip.setSegment(selectedSeg, startI, stopI, grpI, spcI, UINT16_MAX, startY, stopY); pos = req.indexOf(F("RV=")); //Segment reverse if (pos > 0) selseg.reverse = req.charAt(pos+3) != '0'; From f1e1bd41b92e2a902061e746306599982dd54657 Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Fri, 14 Jul 2023 15:58:03 +0200 Subject: [PATCH 20/34] Slight optimisation in BusDigial::getPixelColor() --- wled00/bus_manager.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index c0d4e7e2..e05483f5 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -228,18 +228,18 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { if (_reversed) pix = _len - pix -1; else pix += _skip; uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); + uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, (_type==TYPE_WS2812_1CH_X3) ? IC_INDEX_WS2812_1CH_3X(pix) : pix, co), _bri); if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs - uint16_t pOld = pix; - pix = IC_INDEX_WS2812_1CH_3X(pix); - uint32_t c = PolyBus::getPixelColor(_busPtr, _iType, pix, co); - switch (pOld % 3) { // get only the single channel - case 0: c = RGBW32(G(c), G(c), G(c), G(c)); break; - case 1: c = RGBW32(R(c), R(c), R(c), R(c)); break; - case 2: c = RGBW32(B(c), B(c), B(c), B(c)); break; + uint8_t r = R(c); + uint8_t g = _reversed ? B(c) : G(c); // should G and B be switched if _reversed? + uint8_t b = _reversed ? G(c) : B(c); + switch (pix % 3) { // get only the single channel + case 0: c = RGBW32(g, g, g, g); break; + case 1: c = RGBW32(r, r, r, r); break; + case 2: c = RGBW32(b, b, b, b); break; } - return c; } - return restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co), _bri); + return c; } } From 82e01f7b17d456bf5e7d7d16a6dd90166d78c981 Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Mon, 17 Jul 2023 16:15:17 +0200 Subject: [PATCH 21/34] Fixed ABL calculation. --- wled00/FX_fcn.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 3518e223..5f6fa79f 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1208,10 +1208,10 @@ uint8_t WS2812FX::estimateCurrentAndLimitBri() { uint8_t newBri = _brightness; if (powerSum * _brightness / 255 > powerBudget) { //scale brightness down to stay in current limit - float scale = (float)powerBudget / (float)powerSum; + float scale = (float)(powerBudget * 255) / (float)(powerSum * _brightness); uint16_t scaleI = scale * 255; uint8_t scaleB = (scaleI > 255) ? 255 : scaleI; - newBri = scale8(_brightness, scaleB); + newBri = scale8(_brightness, scaleB) + 1; } currentMilliamps = (powerSum * newBri) / 255; currentMilliamps += MA_FOR_ESP; //add power of ESP back to estimate From abfb8bbc3464440e08119198658494037734a95d Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Mon, 17 Jul 2023 17:06:04 +0200 Subject: [PATCH 22/34] Fix (almost good) for unbuffered ABL calculations. --- wled00/FX_fcn.cpp | 3 +-- wled00/bus_manager.cpp | 7 +++++-- wled00/bus_manager.h | 15 +++++++-------- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 5f6fa79f..43d2aa4e 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1230,8 +1230,7 @@ void WS2812FX::show(void) { unsigned long microsStart = micros(); #endif - uint8_t busBrightness = estimateCurrentAndLimitBri(); - busses.setBrightness(busBrightness); + busses.setBrightness(estimateCurrentAndLimitBri()); #ifdef WLED_DEBUG sumCurrent += micros() - microsStart; #endif diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index e05483f5..d798906b 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -153,7 +153,10 @@ void BusDigital::show() { PolyBus::applyPostAdjustments(_busPtr, _iType); } PolyBus::show(_busPtr, _iType); - PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) + // looks like the following causes periodic miscalculations in ABL when not using double buffering + // when we no longer restore full brightness at busl level we only get a single frame with incorrect brightness + // when turning WLED off otherwise ABL calculations are OK + //PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) } bool BusDigital::canShow() { @@ -228,7 +231,7 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { if (_reversed) pix = _len - pix -1; else pix += _skip; uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); - uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, (_type==TYPE_WS2812_1CH_X3) ? IC_INDEX_WS2812_1CH_3X(pix) : pix, co), _bri); + uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, (_type==TYPE_WS2812_1CH_X3) ? IC_INDEX_WS2812_1CH_3X(pix) : pix, co)); if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint8_t r = R(c); uint8_t g = _reversed ? B(c) : G(c); // should G and B be switched if _reversed? diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 8ca1bcc2..5b48e7c2 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -224,14 +224,13 @@ class BusDigital : public Bus { const ColorOrderMap &_colorOrderMap; bool buffering; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop - inline uint32_t restoreColorLossy(uint32_t c, uint_fast8_t _restaurationBri) { - if (_bri == 255) return c; - uint8_t* chan = (uint8_t*) &c; - - for (uint_fast8_t i=0; i<4; i++) - { - uint_fast16_t val = chan[i]; - chan[i] = ((val << 8) + _restaurationBri) / (_restaurationBri + 1); //adding _bri slighly improves recovery / stops degradation on re-scale + inline uint32_t restoreColorLossy(uint32_t c) { + if (_bri < 255) { + uint8_t* chan = (uint8_t*) &c; + for (uint_fast8_t i=0; i<4; i++) { + uint_fast16_t val = chan[i]; + chan[i] = ((val << 8) + _bri) / (_bri + 1); //adding _bri slighly improves recovery / stops degradation on re-scale + } } return c; } From ebb4628e663d71f00b73a6b496eaf3a43f4106a3 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:38:34 +0200 Subject: [PATCH 23/34] Minor correction (slider names) "Time delay" is actually "speed" - bigger values make the effect run faster. --- wled00/FX.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wled00/FX.cpp b/wled00/FX.cpp index 7bcd9395..be8998bc 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -6808,7 +6808,7 @@ uint16_t mode_freqmatrix(void) { // Freqmatrix. By Andreas Plesch return FRAMETIME; } // mode_freqmatrix() -static const char _data_FX_MODE_FREQMATRIX[] PROGMEM = "Freqmatrix@Time delay,Sound effect,Low bin,High bin,Sensivity;;;1f;m12=3,si=0"; // Corner, Beatsin +static const char _data_FX_MODE_FREQMATRIX[] PROGMEM = "Freqmatrix@Speed,Sound effect,Low bin,High bin,Sensivity;;;1f;m12=3,si=0"; // Corner, Beatsin ////////////////////// @@ -6911,7 +6911,7 @@ uint16_t mode_freqwave(void) { // Freqwave. By Andreas Pleschun return FRAMETIME; } // mode_freqwave() -static const char _data_FX_MODE_FREQWAVE[] PROGMEM = "Freqwave@Time delay,Sound effect,Low bin,High bin,Pre-amp;;;1f;m12=2,si=0"; // Circle, Beatsin +static const char _data_FX_MODE_FREQWAVE[] PROGMEM = "Freqwave@Speed,Sound effect,Low bin,High bin,Pre-amp;;;1f;m12=2,si=0"; // Circle, Beatsin /////////////////////// From 5ef7cd7bddaafd5ed5de3533574d9b3f7d070bb1 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Tue, 18 Jul 2023 11:29:08 +0200 Subject: [PATCH 24/34] blur bugfix turns out that fastLED 3.6.0 has an explicit uint32_t operator that returns RGBA, however 3.5.0 does not have this and the conversion returned only the "red" component". --- wled00/FX_2Dfcn.cpp | 8 ++++---- wled00/FX_fcn.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/wled00/FX_2Dfcn.cpp b/wled00/FX_2Dfcn.cpp index 417d0484..71000e90 100644 --- a/wled00/FX_2Dfcn.cpp +++ b/wled00/FX_2Dfcn.cpp @@ -340,7 +340,7 @@ void Segment::blurRow(uint16_t row, fract8 blur_amount) { CRGB carryover = CRGB::Black; for (uint_fast16_t x = 0; x < cols; x++) { CRGB cur = getPixelColorXY(x, row); - uint32_t before = uint32_t(cur); // remember color before blur + CRGB before = cur; // remember color before blur CRGB part = cur; part.nscale8(seep); cur.nscale8(keep); @@ -349,7 +349,7 @@ void Segment::blurRow(uint16_t row, fract8 blur_amount) { CRGB prev = CRGB(getPixelColorXY(x-1, row)) + part; setPixelColorXY(x-1, row, prev); } - if (before != uint32_t(cur)) // optimization: only set pixel if color has changed + if (before != cur) // optimization: only set pixel if color has changed setPixelColorXY(x, row, cur); carryover = part; } @@ -369,7 +369,7 @@ void Segment::blurCol(uint16_t col, fract8 blur_amount) { for (uint_fast16_t y = 0; y < rows; y++) { CRGB cur = getPixelColorXY(col, y); CRGB part = cur; - uint32_t before = uint32_t(cur); // remember color before blur + CRGB before = cur; // remember color before blur part.nscale8(seep); cur.nscale8(keep); cur += carryover; @@ -377,7 +377,7 @@ void Segment::blurCol(uint16_t col, fract8 blur_amount) { CRGB prev = CRGB(getPixelColorXY(col, y-1)) + part; setPixelColorXY(col, y-1, prev); } - if (before != uint32_t(cur)) // optimization: only set pixel if color has changed + if (before != cur) // optimization: only set pixel if color has changed setPixelColorXY(col, y, cur); carryover = part; } diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 43d2aa4e..e23051a4 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -911,7 +911,7 @@ void Segment::blur(uint8_t blur_amount) { CRGB cur = CRGB(getPixelColor(i)); CRGB part = cur; - uint32_t before = uint32_t(cur); // remember color before blur + CRGB before = cur; // remember color before blur part.nscale8(seep); cur.nscale8(keep); cur += carryover; @@ -922,7 +922,7 @@ void Segment::blur(uint8_t blur_amount) uint8_t b = B(c); setPixelColor((uint16_t)(i-1), qadd8(r, part.red), qadd8(g, part.green), qadd8(b, part.blue)); } - if (before != uint32_t(cur)) // optimization: only set pixel if color has changed + if (before != cur) // optimization: only set pixel if color has changed setPixelColor((uint16_t)i,cur.red, cur.green, cur.blue); carryover = part; } From 7dcbb409a92918735752a01192e67c300686288e Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Tue, 18 Jul 2023 23:33:28 +0200 Subject: [PATCH 25/34] Trying to solve ABL bug. (no more pulsing) --- wled00/FX_fcn.cpp | 18 ++++-- wled00/bus_manager.cpp | 34 ++++++----- wled00/bus_manager.h | 15 +++-- wled00/bus_wrapper.h | 130 ++++++++++++++++++++--------------------- wled00/wled.h | 2 +- 5 files changed, 107 insertions(+), 92 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index e23051a4..b139bb37 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1230,7 +1230,9 @@ void WS2812FX::show(void) { unsigned long microsStart = micros(); #endif - busses.setBrightness(estimateCurrentAndLimitBri()); + uint8_t newBri = estimateCurrentAndLimitBri(); + if (newBri < _brightness) busses.setBrightness(newBri, true); // "repaint" all pixels + #ifdef WLED_DEBUG sumCurrent += micros() - microsStart; #endif @@ -1240,6 +1242,9 @@ void WS2812FX::show(void) { // See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods busses.show(); + // return bus brightness to original value + if (newBri < _brightness) busses.setBrightness(_brightness); + #ifdef WLED_DEBUG sumMicros += micros() - microsStart; if (++calls == 100) { @@ -1320,11 +1325,16 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) { } } if (direct) { - // would be dangerous if applied immediately (could exceed ABL), but will not output until the next show() - busses.setBrightness(b); + // setting brightness with NeoPixelBusLg has no effect on already painted pixels, + // so we need to force an update to existing buffer + // that would be dangerous if applied immediately (could exceed ABL), but will not output until the next show() + busses.setBrightness(b, true); } else { + // setting brightness with NeoPixelBusLg has no effect on already painted pixels, + // so we need to redraw whole canvas for the change of brightness to take effect + busses.setBrightness(b); unsigned long t = millis(); - if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) show(); //apply brightness change immediately if no refresh soon + if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) trigger(); //apply brightness change immediately if no refresh soon } } diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index d798906b..92aa06fc 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -101,7 +101,9 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bus(bc.type, bc.start, bc.autoWhite, bc.count, bc.reversed, (bc.refreshReq || bc.type == TYPE_TM1814)) , _skip(bc.skipAmount) //sacrificial pixels , _colorOrder(bc.colorOrder) +, _prevBri(255) , _colorOrderMap(com) +, _dirty(false) { if (!IS_DIGITAL(bc.type) || !bc.count) return; if (!pinManager.allocatePin(bc.pins[0], true, PinOwner::BusDigital)) return; @@ -118,7 +120,7 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) _iType = PolyBus::getI(bc.type, _pins, nr); if (_iType == I_NONE) return; if (bc.doubleBuffer && !allocData(bc.count * (Bus::hasWhite(_type) + 3*Bus::hasRGB(_type)))) return; //warning: hardcoded channel count - buffering = bc.doubleBuffer; + _buffering = bc.doubleBuffer; uint16_t lenToCreate = bc.count; if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(bc.count); // only needs a third of "RGB" LEDs for NeoPixelBus _busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz); @@ -128,8 +130,7 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) void BusDigital::show() { if (!_valid) return; - PolyBus::setBrightness(_busPtr, _iType, _bri); - if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop + if (_buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); for (size_t i=0; i<_len; i++) { size_t offset = i*channels; @@ -149,14 +150,9 @@ void BusDigital::show() { else pix += _skip; PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); } - } else { - PolyBus::applyPostAdjustments(_busPtr, _iType); } - PolyBus::show(_busPtr, _iType); - // looks like the following causes periodic miscalculations in ABL when not using double buffering - // when we no longer restore full brightness at busl level we only get a single frame with incorrect brightness - // when turning WLED off otherwise ABL calculations are OK - //PolyBus::setBrightness(_busPtr, _iType, 255); // restore full brightness at bus level (setting unscaled pixel color) + PolyBus::show(_busPtr, _iType, !_buffering); // may be faster if buffer consistency is not important + _dirty = false; } bool BusDigital::canShow() { @@ -164,7 +160,7 @@ bool BusDigital::canShow() { return PolyBus::canShow(_busPtr, _iType); } -void BusDigital::setBrightness(uint8_t b) { +void BusDigital::setBrightness(uint8_t b, bool updateNPBBuffer) { //Fix for turning off onboard LED breaking bus #ifdef LED_BUILTIN if (_bri == 0 && b > 0) { @@ -172,6 +168,12 @@ void BusDigital::setBrightness(uint8_t b) { } #endif Bus::setBrightness(b); + PolyBus::setBrightness(_busPtr, _iType, b); + if (!_buffering && updateNPBBuffer) { + PolyBus::applyPostAdjustments(_busPtr, _iType); + _dirty = true; + _prevBri = b; + } } //If LEDs are skipped, it is possible to use the first as a status LED. @@ -187,7 +189,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { if (!_valid) return; if (Bus::hasWhite(_type)) c = autoWhiteCalc(c); if (_cct >= 1900) c = colorBalanceFromKelvin(_cct, c); //color correction from CCT - if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop + if (_buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); size_t offset = pix*channels; if (Bus::hasRGB(_type)) { @@ -203,7 +205,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint16_t pOld = pix; pix = IC_INDEX_WS2812_1CH_3X(pix); - uint32_t cOld = PolyBus::getPixelColor(_busPtr, _iType, pix, co); + uint32_t cOld = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co)); switch (pOld % 3) { // change only the single channel (TODO: this can cause loss because of get/set) case 0: c = RGBW32(R(cOld), W(c) , B(cOld), 0); break; case 1: c = RGBW32(W(c) , G(cOld), B(cOld), 0); break; @@ -217,7 +219,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { // returns original color if global buffering is enabled, else returns lossly restored color from bus uint32_t BusDigital::getPixelColor(uint16_t pix) { if (!_valid) return 0; - if (buffering) { // should be _data != nullptr, but that causes ~20% FPS drop + if (_buffering) { // should be _data != nullptr, but that causes ~20% FPS drop size_t channels = Bus::hasWhite(_type) + 3*Bus::hasRGB(_type); size_t offset = pix*channels; uint32_t c; @@ -578,9 +580,9 @@ void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c) { } } -void BusManager::setBrightness(uint8_t b) { +void BusManager::setBrightness(uint8_t b, bool updateBuffer) { for (uint8_t i = 0; i < numBusses; i++) { - busses[i]->setBrightness(b); + busses[i]->setBrightness(b, updateBuffer); } } diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 5b48e7c2..e92d4b6e 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -124,7 +124,7 @@ class Bus { virtual void setStatusPixel(uint32_t c) {} virtual void setPixelColor(uint16_t pix, uint32_t c) = 0; virtual uint32_t getPixelColor(uint16_t pix) { return 0; } - virtual void setBrightness(uint8_t b) { _bri = b; }; + virtual void setBrightness(uint8_t b, bool updateBuffer = false) { _bri = b; }; virtual void cleanup() = 0; virtual uint8_t getPins(uint8_t* pinArray) { return 0; } virtual uint16_t getLength() { return _len; } @@ -202,7 +202,7 @@ class BusDigital : public Bus { void show(); bool canShow(); - void setBrightness(uint8_t b); + void setBrightness(uint8_t b, bool updateBuffer = false); void setStatusPixel(uint32_t c); void setPixelColor(uint16_t pix, uint32_t c); void setColorOrder(uint8_t colorOrder); @@ -219,17 +219,20 @@ class BusDigital : public Bus { uint8_t _colorOrder; uint8_t _pins[2]; uint8_t _iType; + uint8_t _prevBri; uint16_t _frequencykHz; void * _busPtr; const ColorOrderMap &_colorOrderMap; - bool buffering; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop + bool _buffering; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop + bool _dirty; inline uint32_t restoreColorLossy(uint32_t c) { - if (_bri < 255) { + uint8_t restoreBri = _dirty ? _prevBri : _bri; + if (restoreBri < 255) { uint8_t* chan = (uint8_t*) &c; for (uint_fast8_t i=0; i<4; i++) { uint_fast16_t val = chan[i]; - chan[i] = ((val << 8) + _bri) / (_bri + 1); //adding _bri slighly improves recovery / stops degradation on re-scale + chan[i] = ((val << 8) + restoreBri) / (restoreBri + 1); //adding _bri slighly improves recovery / stops degradation on re-scale } } return c; @@ -317,7 +320,7 @@ class BusManager { bool canAllShow(); void setStatusPixel(uint32_t c); void setPixelColor(uint16_t pix, uint32_t c); - void setBrightness(uint8_t b); + void setBrightness(uint8_t b, bool updateBuffer = false); void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); uint32_t getPixelColor(uint16_t pix); diff --git a/wled00/bus_wrapper.h b/wled00/bus_wrapper.h index 9807c54b..8b6ee660 100644 --- a/wled00/bus_wrapper.h +++ b/wled00/bus_wrapper.h @@ -496,101 +496,101 @@ class PolyBus { return busPtr; } - static void show(void* busPtr, uint8_t busType) { + static void show(void* busPtr, uint8_t busType, bool consistent = true) { switch (busType) { case I_NONE: break; #ifdef ESP8266 - case I_8266_U0_NEO_3: (static_cast(busPtr))->Show(); break; - case I_8266_U1_NEO_3: (static_cast(busPtr))->Show(); break; - case I_8266_DM_NEO_3: (static_cast(busPtr))->Show(); break; - case I_8266_BB_NEO_3: (static_cast(busPtr))->Show(); break; - case I_8266_U0_NEO_4: (static_cast(busPtr))->Show(); break; - case I_8266_U1_NEO_4: (static_cast(busPtr))->Show(); break; - case I_8266_DM_NEO_4: (static_cast(busPtr))->Show(); break; - case I_8266_BB_NEO_4: (static_cast(busPtr))->Show(); break; - case I_8266_U0_400_3: (static_cast(busPtr))->Show(); break; - case I_8266_U1_400_3: (static_cast(busPtr))->Show(); break; - case I_8266_DM_400_3: (static_cast(busPtr))->Show(); break; - case I_8266_BB_400_3: (static_cast(busPtr))->Show(); break; - case I_8266_U0_TM1_4: (static_cast(busPtr))->Show(); break; - case I_8266_U1_TM1_4: (static_cast(busPtr))->Show(); break; - case I_8266_DM_TM1_4: (static_cast(busPtr))->Show(); break; - case I_8266_BB_TM1_4: (static_cast(busPtr))->Show(); break; - case I_8266_U0_TM2_3: (static_cast(busPtr))->Show(); break; - case I_8266_U1_TM2_3: (static_cast(busPtr))->Show(); break; - case I_8266_DM_TM2_3: (static_cast(busPtr))->Show(); break; - case I_8266_BB_TM2_3: (static_cast(busPtr))->Show(); break; - case I_8266_U0_UCS_3: (static_cast(busPtr))->Show(); break; - case I_8266_U1_UCS_3: (static_cast(busPtr))->Show(); break; - case I_8266_DM_UCS_3: (static_cast(busPtr))->Show(); break; - case I_8266_BB_UCS_3: (static_cast(busPtr))->Show(); break; - case I_8266_U0_UCS_4: (static_cast(busPtr))->Show(); break; - case I_8266_U1_UCS_4: (static_cast(busPtr))->Show(); break; - case I_8266_DM_UCS_4: (static_cast(busPtr))->Show(); break; - case I_8266_BB_UCS_4: (static_cast(busPtr))->Show(); break; + case I_8266_U0_NEO_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_NEO_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_NEO_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_NEO_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U0_NEO_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_NEO_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_NEO_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_NEO_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U0_400_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_400_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_400_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_400_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U0_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U0_TM2_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_TM2_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_TM2_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_TM2_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U0_UCS_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_UCS_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_UCS_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_UCS_3: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U0_UCS_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_U1_UCS_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_DM_UCS_4: (static_cast(busPtr))->Show(consistent); break; + case I_8266_BB_UCS_4: (static_cast(busPtr))->Show(consistent); break; #endif #ifdef ARDUINO_ARCH_ESP32 - case I_32_RN_NEO_3: (static_cast(busPtr))->Show(); break; + case I_32_RN_NEO_3: (static_cast(busPtr))->Show(consistent); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_NEO_3: (static_cast(busPtr))->Show(); break; + case I_32_I0_NEO_3: (static_cast(busPtr))->Show(consistent); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_NEO_3: (static_cast(busPtr))->Show(); break; + case I_32_I1_NEO_3: (static_cast(busPtr))->Show(consistent); break; #endif -// case I_32_BB_NEO_3: (static_cast(busPtr))->Show(); break; - case I_32_RN_NEO_4: (static_cast(busPtr))->Show(); break; +// case I_32_BB_NEO_3: (static_cast(busPtr))->Show(consistent); break; + case I_32_RN_NEO_4: (static_cast(busPtr))->Show(consistent); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_NEO_4: (static_cast(busPtr))->Show(); break; + case I_32_I0_NEO_4: (static_cast(busPtr))->Show(consistent); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_NEO_4: (static_cast(busPtr))->Show(); break; + case I_32_I1_NEO_4: (static_cast(busPtr))->Show(consistent); break; #endif -// case I_32_BB_NEO_4: (static_cast(busPtr))->Show(); break; - case I_32_RN_400_3: (static_cast(busPtr))->Show(); break; +// case I_32_BB_NEO_4: (static_cast(busPtr))->Show(consistent); break; + case I_32_RN_400_3: (static_cast(busPtr))->Show(consistent); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_400_3: (static_cast(busPtr))->Show(); break; + case I_32_I0_400_3: (static_cast(busPtr))->Show(consistent); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_400_3: (static_cast(busPtr))->Show(); break; + case I_32_I1_400_3: (static_cast(busPtr))->Show(consistent); break; #endif -// case I_32_BB_400_3: (static_cast(busPtr))->Show(); break; - case I_32_RN_TM1_4: (static_cast(busPtr))->Show(); break; - case I_32_RN_TM2_3: (static_cast(busPtr))->Show(); break; +// case I_32_BB_400_3: (static_cast(busPtr))->Show(consistent); break; + case I_32_RN_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_32_RN_TM2_3: (static_cast(busPtr))->Show(consistent); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_TM1_4: (static_cast(busPtr))->Show(); break; - case I_32_I0_TM2_3: (static_cast(busPtr))->Show(); break; + case I_32_I0_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_32_I0_TM2_3: (static_cast(busPtr))->Show(consistent); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_TM1_4: (static_cast(busPtr))->Show(); break; - case I_32_I1_TM2_3: (static_cast(busPtr))->Show(); break; + case I_32_I1_TM1_4: (static_cast(busPtr))->Show(consistent); break; + case I_32_I1_TM2_3: (static_cast(busPtr))->Show(consistent); break; #endif - case I_32_RN_UCS_3: (static_cast(busPtr))->Show(); break; + case I_32_RN_UCS_3: (static_cast(busPtr))->Show(consistent); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_UCS_3: (static_cast(busPtr))->Show(); break; + case I_32_I0_UCS_3: (static_cast(busPtr))->Show(consistent); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_UCS_3: (static_cast(busPtr))->Show(); break; + case I_32_I1_UCS_3: (static_cast(busPtr))->Show(consistent); break; #endif -// case I_32_BB_UCS_3: (static_cast(busPtr))->Show(); break; - case I_32_RN_UCS_4: (static_cast(busPtr))->Show(); break; +// case I_32_BB_UCS_3: (static_cast(busPtr))->Show(consistent); break; + case I_32_RN_UCS_4: (static_cast(busPtr))->Show(consistent); break; #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_UCS_4: (static_cast(busPtr))->Show(); break; + case I_32_I0_UCS_4: (static_cast(busPtr))->Show(consistent); break; #endif #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_UCS_4: (static_cast(busPtr))->Show(); break; + case I_32_I1_UCS_4: (static_cast(busPtr))->Show(consistent); break; #endif -// case I_32_BB_UCS_4: (static_cast(busPtr))->Show(); break; +// case I_32_BB_UCS_4: (static_cast(busPtr))->Show(consistent); break; #endif - case I_HS_DOT_3: (static_cast(busPtr))->Show(); break; - case I_SS_DOT_3: (static_cast(busPtr))->Show(); break; - case I_HS_LPD_3: (static_cast(busPtr))->Show(); break; - case I_SS_LPD_3: (static_cast(busPtr))->Show(); break; - case I_HS_LPO_3: (static_cast(busPtr))->Show(); break; - case I_SS_LPO_3: (static_cast(busPtr))->Show(); break; - case I_HS_WS1_3: (static_cast(busPtr))->Show(); break; - case I_SS_WS1_3: (static_cast(busPtr))->Show(); break; - case I_HS_P98_3: (static_cast(busPtr))->Show(); break; - case I_SS_P98_3: (static_cast(busPtr))->Show(); break; + case I_HS_DOT_3: (static_cast(busPtr))->Show(consistent); break; + case I_SS_DOT_3: (static_cast(busPtr))->Show(consistent); break; + case I_HS_LPD_3: (static_cast(busPtr))->Show(consistent); break; + case I_SS_LPD_3: (static_cast(busPtr))->Show(consistent); break; + case I_HS_LPO_3: (static_cast(busPtr))->Show(consistent); break; + case I_SS_LPO_3: (static_cast(busPtr))->Show(consistent); break; + case I_HS_WS1_3: (static_cast(busPtr))->Show(consistent); break; + case I_SS_WS1_3: (static_cast(busPtr))->Show(consistent); break; + case I_HS_P98_3: (static_cast(busPtr))->Show(consistent); break; + case I_SS_P98_3: (static_cast(busPtr))->Show(consistent); break; } } diff --git a/wled00/wled.h b/wled00/wled.h index 0415a0cc..e2cbf93d 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -8,7 +8,7 @@ */ // version code in format yymmddb (b = daily build) -#define VERSION 2307130 +#define VERSION 2307180 //uncomment this if you have a "my_config.h" file you'd like to use //#define WLED_USE_MY_CONFIG From 5b9630cf463738b7bce6abba2499e58ff3419aef Mon Sep 17 00:00:00 2001 From: cschwinne Date: Wed, 19 Jul 2023 13:50:09 +0200 Subject: [PATCH 26/34] Repaint NPB buffer on brightness updates --- wled00/FX_fcn.cpp | 10 ++++++++-- wled00/bus_manager.cpp | 23 +++++++++++++---------- wled00/bus_manager.h | 5 +---- 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index b139bb37..d7e47ae1 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1082,6 +1082,11 @@ void WS2812FX::service() { // last condition ensures all solid segments are updated at the same time if (seg.isActive() && (nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))) { + if (!doShow) { + // returning bus brightness to its original value is done here, as to not interfere with asyncronous show() + // TODO if it is safe, prefer to restore brightness in show() + busses.setBrightness(_brightness, true); // "repaint" all pixels if brightness has changed + } doShow = true; uint16_t delay = FRAMETIME; @@ -1242,8 +1247,9 @@ void WS2812FX::show(void) { // See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods busses.show(); - // return bus brightness to original value - if (newBri < _brightness) busses.setBrightness(_brightness); + // returning bus brightness to its original value is done in the next frame, as to not interfere with asyncronous show() + // TODO if it is safe, prefer to restore brightness here + //if (newBri < _brightness) busses.setBrightness(_brightness, true); #ifdef WLED_DEBUG sumMicros += micros() - microsStart; diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 92aa06fc..34efe7d8 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -101,9 +101,7 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) : Bus(bc.type, bc.start, bc.autoWhite, bc.count, bc.reversed, (bc.refreshReq || bc.type == TYPE_TM1814)) , _skip(bc.skipAmount) //sacrificial pixels , _colorOrder(bc.colorOrder) -, _prevBri(255) , _colorOrderMap(com) -, _dirty(false) { if (!IS_DIGITAL(bc.type) || !bc.count) return; if (!pinManager.allocatePin(bc.pins[0], true, PinOwner::BusDigital)) return; @@ -151,8 +149,7 @@ void BusDigital::show() { PolyBus::setPixelColor(_busPtr, _iType, pix, c, co); } } - PolyBus::show(_busPtr, _iType, !_buffering); // may be faster if buffer consistency is not important - _dirty = false; + PolyBus::show(_busPtr, _iType, !_buffering); // faster if buffer consistency is not important } bool BusDigital::canShow() { @@ -161,18 +158,24 @@ bool BusDigital::canShow() { } void BusDigital::setBrightness(uint8_t b, bool updateNPBBuffer) { + if (_bri == b) return; //Fix for turning off onboard LED breaking bus #ifdef LED_BUILTIN - if (_bri == 0 && b > 0) { + if (_bri == 0) { // && b > 0, covered by guard if above if (_pins[0] == LED_BUILTIN || _pins[1] == LED_BUILTIN) reinit(); } #endif + uint8_t prevBri = _bri; Bus::setBrightness(b); PolyBus::setBrightness(_busPtr, _iType, b); if (!_buffering && updateNPBBuffer) { - PolyBus::applyPostAdjustments(_busPtr, _iType); - _dirty = true; - _prevBri = b; + uint16_t hwLen = _len; + if (_type == TYPE_WS2812_1CH_X3) hwLen = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus + for (uint_fast16_t i = 0; i < hwLen; i++) { + // use 0 as color order, actual order does not matter here as we just update the channel values as-is + uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, i, 0),prevBri); + PolyBus::setPixelColor(_busPtr, _iType, i, c, 0); + } } } @@ -205,7 +208,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) { if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint16_t pOld = pix; pix = IC_INDEX_WS2812_1CH_3X(pix); - uint32_t cOld = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co)); + uint32_t cOld = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co),_bri); switch (pOld % 3) { // change only the single channel (TODO: this can cause loss because of get/set) case 0: c = RGBW32(R(cOld), W(c) , B(cOld), 0); break; case 1: c = RGBW32(W(c) , G(cOld), B(cOld), 0); break; @@ -233,7 +236,7 @@ uint32_t BusDigital::getPixelColor(uint16_t pix) { if (_reversed) pix = _len - pix -1; else pix += _skip; uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder); - uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, (_type==TYPE_WS2812_1CH_X3) ? IC_INDEX_WS2812_1CH_3X(pix) : pix, co)); + uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, (_type==TYPE_WS2812_1CH_X3) ? IC_INDEX_WS2812_1CH_3X(pix) : pix, co),_bri); if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs uint8_t r = R(c); uint8_t g = _reversed ? B(c) : G(c); // should G and B be switched if _reversed? diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index e92d4b6e..e46ac175 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -219,15 +219,12 @@ class BusDigital : public Bus { uint8_t _colorOrder; uint8_t _pins[2]; uint8_t _iType; - uint8_t _prevBri; uint16_t _frequencykHz; void * _busPtr; const ColorOrderMap &_colorOrderMap; bool _buffering; // temporary until we figure out why comparison "_data != nullptr" causes severe FPS drop - bool _dirty; - inline uint32_t restoreColorLossy(uint32_t c) { - uint8_t restoreBri = _dirty ? _prevBri : _bri; + inline uint32_t restoreColorLossy(uint32_t c, uint8_t restoreBri) { if (restoreBri < 255) { uint8_t* chan = (uint8_t*) &c; for (uint_fast8_t i=0; i<4; i++) { From 0cf50e8000ae3bc604b0117768f96772f2d46dff Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Wed, 19 Jul 2023 16:06:41 +0200 Subject: [PATCH 27/34] FX Fireworks optimisation --- wled00/FX.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/wled00/FX.cpp b/wled00/FX.cpp index be8998bc..b457e094 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -1212,19 +1212,21 @@ uint16_t mode_fireworks() { bool valid1 = (SEGENV.aux0 < width*height); bool valid2 = (SEGENV.aux1 < width*height); + uint8_t x = SEGENV.aux0%width, y = SEGENV.aux0/width; // 2D coordinates stored in upper and lower byte uint32_t sv1 = 0, sv2 = 0; - if (valid1) sv1 = SEGMENT.is2D() ? SEGMENT.getPixelColorXY(SEGENV.aux0%width, SEGENV.aux0/width) : SEGMENT.getPixelColor(SEGENV.aux0); // get spark color - if (valid2) sv2 = SEGMENT.is2D() ? SEGMENT.getPixelColorXY(SEGENV.aux1%width, SEGENV.aux1/width) : SEGMENT.getPixelColor(SEGENV.aux1); + if (valid1) sv1 = SEGMENT.is2D() ? SEGMENT.getPixelColorXY(x, y) : SEGMENT.getPixelColor(SEGENV.aux0); // get spark color + if (valid2) sv2 = SEGMENT.is2D() ? SEGMENT.getPixelColorXY(x, y) : SEGMENT.getPixelColor(SEGENV.aux1); if (!SEGENV.step) SEGMENT.blur(16); - if (valid1) { if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(SEGENV.aux0%width, SEGENV.aux0/width, sv1); else SEGMENT.setPixelColor(SEGENV.aux0, sv1); } // restore spark color after blur - if (valid2) { if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(SEGENV.aux1%width, SEGENV.aux1/width, sv2); else SEGMENT.setPixelColor(SEGENV.aux1, sv2); } // restore old spark color after blur + if (valid1) { if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(x, y, sv1); else SEGMENT.setPixelColor(SEGENV.aux0, sv1); } // restore spark color after blur + if (valid2) { if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(x, y, sv2); else SEGMENT.setPixelColor(SEGENV.aux1, sv2); } // restore old spark color after blur for (int i=0; i> 1)) == 0) { uint16_t index = random16(width*height); - uint16_t j = index % width, k = index / width; + x = index % width; + y = index / width; uint32_t col = SEGMENT.color_from_palette(random8(), false, false, 0); - if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(j, k, col); + if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(x, y, col); else SEGMENT.setPixelColor(index, col); SEGENV.aux1 = SEGENV.aux0; // old spark SEGENV.aux0 = index; // remember where spark occured From 2fce15db94d389740e58b2224b40365819fe3544 Mon Sep 17 00:00:00 2001 From: cschwinne Date: Wed, 19 Jul 2023 16:22:34 +0200 Subject: [PATCH 28/34] Restore brightness immediately after show() --- wled00/FX_fcn.cpp | 14 +++---- wled00/bus_wrapper.h | 98 -------------------------------------------- 2 files changed, 6 insertions(+), 106 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index d7e47ae1..ce845ce3 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1082,11 +1082,6 @@ void WS2812FX::service() { // last condition ensures all solid segments are updated at the same time if (seg.isActive() && (nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))) { - if (!doShow) { - // returning bus brightness to its original value is done here, as to not interfere with asyncronous show() - // TODO if it is safe, prefer to restore brightness in show() - busses.setBrightness(_brightness, true); // "repaint" all pixels if brightness has changed - } doShow = true; uint16_t delay = FRAMETIME; @@ -1247,9 +1242,10 @@ void WS2812FX::show(void) { // See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods busses.show(); - // returning bus brightness to its original value is done in the next frame, as to not interfere with asyncronous show() - // TODO if it is safe, prefer to restore brightness here - //if (newBri < _brightness) busses.setBrightness(_brightness, true); + // restore bus brightness to its original value + // this is done right after show, so this is only OK if LED updates are completed before show() returns + // or async show has a separate buffer (ESP32 RMT and I2S are ok) + if (newBri < _brightness) busses.setBrightness(_brightness, true); #ifdef WLED_DEBUG sumMicros += micros() - microsStart; @@ -1321,6 +1317,8 @@ void WS2812FX::setCCT(uint16_t k) { } } +// direct=true either expects the caller to call show() themselves (realtime modes) or be ok waiting for the next frame for the change to apply +// direct=false immediately triggers an effect redraw void WS2812FX::setBrightness(uint8_t b, bool direct) { if (gammaCorrectBri) b = gamma8(b); if (_brightness == b) return; diff --git a/wled00/bus_wrapper.h b/wled00/bus_wrapper.h index 8b6ee660..72b4435e 100644 --- a/wled00/bus_wrapper.h +++ b/wled00/bus_wrapper.h @@ -911,104 +911,6 @@ class PolyBus { } } - static void applyPostAdjustments(void* busPtr, uint8_t busType) { - switch (busType) { - case I_NONE: break; - #ifdef ESP8266 - case I_8266_U0_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U0_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_U1_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_DM_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_8266_BB_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifdef ARDUINO_ARCH_ESP32 - case I_32_RN_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_NEO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif -// case I_32_BB_NEO_3: (static_cast(busPtr))->SetLuminance(b); (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif -// case I_32_BB_NEO_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif -// case I_32_BB_400_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_I0_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_TM1_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_I1_TM2_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - case I_32_RN_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif -// case I_32_BB_UCS_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_32_RN_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #ifndef WLED_NO_I2S0_PIXELBUS - case I_32_I0_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - #ifndef WLED_NO_I2S1_PIXELBUS - case I_32_I1_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif -// case I_32_BB_UCS_4: (static_cast(busPtr))->ApplyPostAdjustments(); break; - #endif - case I_HS_DOT_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_DOT_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_LPD_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_LPD_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_LPO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_LPO_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_WS1_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_WS1_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_HS_P98_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - case I_SS_P98_3: (static_cast(busPtr))->ApplyPostAdjustments(); break; - } - } - static uint32_t getPixelColor(void* busPtr, uint8_t busType, uint16_t pix, uint8_t co) { RgbwColor col(0,0,0,0); switch (busType) { From 8ccf349458d3b044dac74f215a63ec2db5f83ef8 Mon Sep 17 00:00:00 2001 From: cschwinne Date: Wed, 19 Jul 2023 17:25:25 +0200 Subject: [PATCH 29/34] Always repaint NPB buffer on brightness change Fix bus re-init causing full brightness (every show() now attempts to set the brightness, bus will ignore this if it stays the same) --- wled00/FX_fcn.cpp | 17 ++++++----------- wled00/bus_manager.cpp | 26 +++++++++++++++----------- wled00/bus_manager.h | 6 +++--- 3 files changed, 24 insertions(+), 25 deletions(-) diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index ce845ce3..74d61cb4 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -1231,7 +1231,7 @@ void WS2812FX::show(void) { #endif uint8_t newBri = estimateCurrentAndLimitBri(); - if (newBri < _brightness) busses.setBrightness(newBri, true); // "repaint" all pixels + busses.setBrightness(newBri); // "repaints" all pixels if brightness changed #ifdef WLED_DEBUG sumCurrent += micros() - microsStart; @@ -1245,7 +1245,7 @@ void WS2812FX::show(void) { // restore bus brightness to its original value // this is done right after show, so this is only OK if LED updates are completed before show() returns // or async show has a separate buffer (ESP32 RMT and I2S are ok) - if (newBri < _brightness) busses.setBrightness(_brightness, true); + if (newBri < _brightness) busses.setBrightness(_brightness); #ifdef WLED_DEBUG sumMicros += micros() - microsStart; @@ -1328,15 +1328,10 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) { seg.freeze = false; } } - if (direct) { - // setting brightness with NeoPixelBusLg has no effect on already painted pixels, - // so we need to force an update to existing buffer - // that would be dangerous if applied immediately (could exceed ABL), but will not output until the next show() - busses.setBrightness(b, true); - } else { - // setting brightness with NeoPixelBusLg has no effect on already painted pixels, - // so we need to redraw whole canvas for the change of brightness to take effect - busses.setBrightness(b); + // setting brightness with NeoPixelBusLg has no effect on already painted pixels, + // so we need to force an update to existing buffer + busses.setBrightness(b); + if (!direct) { unsigned long t = millis(); if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) trigger(); //apply brightness change immediately if no refresh soon } diff --git a/wled00/bus_manager.cpp b/wled00/bus_manager.cpp index 34efe7d8..7ea44b15 100644 --- a/wled00/bus_manager.cpp +++ b/wled00/bus_manager.cpp @@ -157,7 +157,7 @@ bool BusDigital::canShow() { return PolyBus::canShow(_busPtr, _iType); } -void BusDigital::setBrightness(uint8_t b, bool updateNPBBuffer) { +void BusDigital::setBrightness(uint8_t b) { if (_bri == b) return; //Fix for turning off onboard LED breaking bus #ifdef LED_BUILTIN @@ -168,14 +168,18 @@ void BusDigital::setBrightness(uint8_t b, bool updateNPBBuffer) { uint8_t prevBri = _bri; Bus::setBrightness(b); PolyBus::setBrightness(_busPtr, _iType, b); - if (!_buffering && updateNPBBuffer) { - uint16_t hwLen = _len; - if (_type == TYPE_WS2812_1CH_X3) hwLen = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus - for (uint_fast16_t i = 0; i < hwLen; i++) { - // use 0 as color order, actual order does not matter here as we just update the channel values as-is - uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, i, 0),prevBri); - PolyBus::setPixelColor(_busPtr, _iType, i, c, 0); - } + + if (_buffering) return; + + // must update/repaint every LED in the NeoPixelBus buffer to the new brightness + // the only case where repainting is unnecessary is when all pixels are set after the brightness change but before the next show + // (which we can't rely on) + uint16_t hwLen = _len; + if (_type == TYPE_WS2812_1CH_X3) hwLen = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus + for (uint_fast16_t i = 0; i < hwLen; i++) { + // use 0 as color order, actual order does not matter here as we just update the channel values as-is + uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, i, 0),prevBri); + PolyBus::setPixelColor(_busPtr, _iType, i, c, 0); } } @@ -583,9 +587,9 @@ void IRAM_ATTR BusManager::setPixelColor(uint16_t pix, uint32_t c) { } } -void BusManager::setBrightness(uint8_t b, bool updateBuffer) { +void BusManager::setBrightness(uint8_t b) { for (uint8_t i = 0; i < numBusses; i++) { - busses[i]->setBrightness(b, updateBuffer); + busses[i]->setBrightness(b); } } diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index e46ac175..4249c880 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -124,7 +124,7 @@ class Bus { virtual void setStatusPixel(uint32_t c) {} virtual void setPixelColor(uint16_t pix, uint32_t c) = 0; virtual uint32_t getPixelColor(uint16_t pix) { return 0; } - virtual void setBrightness(uint8_t b, bool updateBuffer = false) { _bri = b; }; + virtual void setBrightness(uint8_t b) { _bri = b; }; virtual void cleanup() = 0; virtual uint8_t getPins(uint8_t* pinArray) { return 0; } virtual uint16_t getLength() { return _len; } @@ -202,7 +202,7 @@ class BusDigital : public Bus { void show(); bool canShow(); - void setBrightness(uint8_t b, bool updateBuffer = false); + void setBrightness(uint8_t b); void setStatusPixel(uint32_t c); void setPixelColor(uint16_t pix, uint32_t c); void setColorOrder(uint8_t colorOrder); @@ -317,7 +317,7 @@ class BusManager { bool canAllShow(); void setStatusPixel(uint32_t c); void setPixelColor(uint16_t pix, uint32_t c); - void setBrightness(uint8_t b, bool updateBuffer = false); + void setBrightness(uint8_t b); void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); uint32_t getPixelColor(uint16_t pix); From aa54d65f636cdde3c878b4f1d6f2fe443a1e9861 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Thu, 20 Jul 2023 21:39:25 +0200 Subject: [PATCH 30/34] upgrade -S3/-S2/-C3 to platform 5.3.0 platform 5.3.0 = arduino-esp32 v2.0.6 + esp-idf v4.4.3 --> you will need new bootloader files for arduino-esp32 v2.0.6 --> coredumps are supported now, if you leave 64Kb of flash at the end of your partitions file (see example in wled_esp32_8MB.csv) --- platformio.ini | 12 ++++-------- tools/WLED_ESP32_16MB_9MB_FS.csv | 8 ++++++++ tools/WLED_ESP32_8MB.csv | 3 ++- 3 files changed, 14 insertions(+), 9 deletions(-) create mode 100644 tools/WLED_ESP32_16MB_9MB_FS.csv diff --git a/platformio.ini b/platformio.ini index d3b71d3c..430263b7 100644 --- a/platformio.ini +++ b/platformio.ini @@ -249,9 +249,8 @@ lib_deps = ;; ;; please note that you can NOT update existing ESP32 installs with a "V4" build. Also updating by OTA will not work properly. ;; You need to completely erase your device (esptool erase_flash) first, then install the "V4" build from VSCode+platformio. -platform = espressif32@5.2.0 +platform = espressif32@5.3.0 platform_packages = - toolchain-riscv32-esp @ 8.4.0+2021r2-patch5 ; required for platform version < 5.3.0, remove this line when upgrading to platform >=5.3.0 build_flags = -g -Wshadow=compatible-local ;; emit warning in case a local variable "shadows" another local one -DARDUINO_ARCH_ESP32 -DESP32 @@ -265,9 +264,8 @@ lib_deps = [esp32s2] ;; generic definitions for all ESP32-S2 boards -platform = espressif32@5.2.0 +platform = espressif32@5.3.0 platform_packages = - toolchain-riscv32-esp @ 8.4.0+2021r2-patch5 ; required for platform version < 5.3.0, remove this line when upgrading to platform >=5.3.0 build_flags = -g -DARDUINO_ARCH_ESP32 -DARDUINO_ARCH_ESP32S2 @@ -285,9 +283,8 @@ lib_deps = [esp32c3] ;; generic definitions for all ESP32-C3 boards -platform = espressif32@5.2.0 +platform = espressif32@5.3.0 platform_packages = - toolchain-riscv32-esp @ 8.4.0+2021r2-patch5 ; required for platform version < 5.3.0, remove this line when upgrading to platform >=5.3.0 build_flags = -g -DARDUINO_ARCH_ESP32 -DARDUINO_ARCH_ESP32C3 @@ -304,9 +301,8 @@ lib_deps = [esp32s3] ;; generic definitions for all ESP32-S3 boards -platform = espressif32@5.2.0 +platform = espressif32@5.3.0 platform_packages = - toolchain-riscv32-esp @ 8.4.0+2021r2-patch5 ; required for platform version < 5.3.0, remove this line when upgrading to platform >=5.3.0 build_flags = -g -DESP32 -DARDUINO_ARCH_ESP32 diff --git a/tools/WLED_ESP32_16MB_9MB_FS.csv b/tools/WLED_ESP32_16MB_9MB_FS.csv new file mode 100644 index 00000000..f2f3f778 --- /dev/null +++ b/tools/WLED_ESP32_16MB_9MB_FS.csv @@ -0,0 +1,8 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x300000, +app1, app, ota_1, 0x310000,0x300000, +spiffs, data, spiffs, 0x610000,0x9E0000, +coredump, data, coredump,,64K +# to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage \ No newline at end of file diff --git a/tools/WLED_ESP32_8MB.csv b/tools/WLED_ESP32_8MB.csv index 5e930b89..3cf3afc3 100644 --- a/tools/WLED_ESP32_8MB.csv +++ b/tools/WLED_ESP32_8MB.csv @@ -3,4 +3,5 @@ nvs, data, nvs, 0x9000, 0x5000, otadata, data, ota, 0xe000, 0x2000, app0, app, ota_0, 0x10000, 0x200000, app1, app, ota_1, 0x210000,0x200000, -spiffs, data, spiffs, 0x410000,0x3F0000, \ No newline at end of file +spiffs, data, spiffs, 0x410000,0x3E0000, +coredump, data, coredump,,64K From 2db966ba476a5eb73b2587a0ceba675674d68bc0 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Thu, 20 Jul 2023 22:09:14 +0200 Subject: [PATCH 31/34] Improvements for -S3 with PSRAM qio_opi: PSRAM 8MB or 16MB qio_qspi: PSRAM 2MB or 4MB fun fact: _opi and _qspi modes both require a special bootloader. --- platformio.ini | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/platformio.ini b/platformio.ini index 430263b7..c939a73b 100644 --- a/platformio.ini +++ b/platformio.ini @@ -446,6 +446,7 @@ board_build.flash_mode = qio upload_speed = 460800 build_unflags = ${common.build_unflags} build_flags = ${common.build_flags} ${esp32s2.build_flags} #-D WLED_RELEASE_NAME=S2_saola + ;-DLOLIN_WIFI_FIX ;; try this in case Wifi does not work -DARDUINO_USB_CDC_ON_BOOT=1 lib_deps = ${esp32s2.lib_deps} @@ -458,6 +459,7 @@ board = esp32-c3-devkitm-1 board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv build_flags = ${common.build_flags} ${esp32c3.build_flags} #-D WLED_RELEASE_NAME=ESP32-C3 -D WLED_WATCHDOG_TIMEOUT=0 + -DLOLIN_WIFI_FIX ; seems to work much better with this -DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB ;-DARDUINO_USB_CDC_ON_BOOT=0 ;; for serial-to-USB chip upload_speed = 460800 @@ -474,7 +476,7 @@ build_unflags = ${common.build_unflags} build_flags = ${common.build_flags} ${esp32s3.build_flags} -D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0 -D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip - ;-D ARDUINO_USB_CDC_ON_BOOT=1 ;; -D ARDUINO_USB_MODE=0 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") + ;-D ARDUINO_USB_CDC_ON_BOOT=1 ;; -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") ;-D WLED_DEBUG lib_deps = ${esp32s3.lib_deps} board_build.partitions = tools/WLED_ESP32_8MB.csv @@ -483,19 +485,18 @@ board_build.flash_mode = qio ; board_build.flash_mode = dio ;; try this if you have problems at startup monitor_filters = esp32_exception_decoder -[env:esp32s3dev_8MB_PSRAM] -;; ESP32-TinyS3 development board, with 8MB FLASH and 8MB PSRAM (memory_type: qio_opi, qio_qspi, or opi_opi) -;board = um_tinys3 ; -> needs workaround from https://github.com/Aircoookie/WLED/pull/2905#issuecomment-1328049860 -;board = esp32s3box ; -> error: 'esp32_adc2gpio' was not declared in this scope -board = esp32-s3-devkitc-1 ; -> compiles, but does not support PSRAM +[env:esp32s3dev_8MB_PSRAM_opi] +;; ESP32-S3 development board, with 8MB FLASH and >= 8MB PSRAM (memory_type: qio_opi) +board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support +board_build.arduino.memory_type = qio_opi ;; use with PSRAM: 8MB or 16MB platform = ${esp32s3.platform} platform_packages = ${esp32s3.platform_packages} upload_speed = 921600 build_unflags = ${common.build_unflags} build_flags = ${common.build_flags} ${esp32s3.build_flags} -D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0 - ;-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip - -D ARDUINO_USB_CDC_ON_BOOT=1 ;; -D ARDUINO_USB_MODE=0 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") + ;-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip + -D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") ; -D WLED_RELEASE_NAME=ESP32-S3_PSRAM -D WLED_USE_PSRAM -DBOARD_HAS_PSRAM ; tells WLED that PSRAM shall be used lib_deps = ${esp32s3.lib_deps} @@ -504,6 +505,13 @@ board_build.f_flash = 80000000L board_build.flash_mode = qio monitor_filters = esp32_exception_decoder +[env:esp32s3dev_8MB_PSRAM_qspi] +;; ESP32-TinyS3 development board, with 8MB FLASH and PSRAM (memory_type: qio_qspi) +extends = env:esp32s3dev_8MB_PSRAM_opi +;board = um_tinys3 ; -> needs workaround from https://github.com/Aircoookie/WLED/pull/2905#issuecomment-1328049860 +board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support +board_build.arduino.memory_type = qio_qspi ;; use with PSRAM: 2MB or 4MB + [env:esp8285_4CH_MagicHome] board = esp8285 platform = ${common.platform_wled_default} From 050489dd80e6a713048d7fbb89ccaf4a13de6705 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Thu, 20 Jul 2023 22:09:48 +0200 Subject: [PATCH 32/34] allow Lolin Wifi Fix on -S3 --- wled00/wled.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wled00/wled.cpp b/wled00/wled.cpp index e51fc37b..3a0cf467 100644 --- a/wled00/wled.cpp +++ b/wled00/wled.cpp @@ -536,7 +536,7 @@ void WLED::initAP(bool resetAP) DEBUG_PRINTLN(apSSID); WiFi.softAPConfig(IPAddress(4, 3, 2, 1), IPAddress(4, 3, 2, 1), IPAddress(255, 255, 255, 0)); WiFi.softAP(apSSID, apPass, apChannel, apHide); - #if defined(LOLIN_WIFI_FIX) && (defined(ARDUINO_ARCH_ESP32C3) || defined(ARDUINO_ARCH_ESP32S2)) + #if defined(LOLIN_WIFI_FIX) && (defined(ARDUINO_ARCH_ESP32C3) || defined(ARDUINO_ARCH_ESP32S2) || defined(ARDUINO_ARCH_ESP32S3)) WiFi.setTxPower(WIFI_POWER_8_5dBm); #endif @@ -714,7 +714,7 @@ void WLED::initConnection() WiFi.begin(clientSSID, clientPass); #ifdef ARDUINO_ARCH_ESP32 - #if defined(LOLIN_WIFI_FIX) && (defined(ARDUINO_ARCH_ESP32C3) || defined(ARDUINO_ARCH_ESP32S2)) + #if defined(LOLIN_WIFI_FIX) && (defined(ARDUINO_ARCH_ESP32C3) || defined(ARDUINO_ARCH_ESP32S2) || defined(ARDUINO_ARCH_ESP32S3)) WiFi.setTxPower(WIFI_POWER_8_5dBm); #endif WiFi.setSleep(!noWifiSleep); From f8e766ffc0565f575bae819bd31057f3ae5a50bc Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Thu, 20 Jul 2023 22:21:02 +0200 Subject: [PATCH 33/34] add -S3 PSRAM (qio_opi) to nightly builds --- platformio.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platformio.ini b/platformio.ini index c939a73b..abba37bd 100644 --- a/platformio.ini +++ b/platformio.ini @@ -11,7 +11,7 @@ # CI binaries ; default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth # ESP32 variant builds are temporarily excluded from CI due to toolchain issues on the GitHub Actions Linux environment -default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB +default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB, esp32s3dev_8MB_PSRAM_opi # Release binaries ; default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB From c8fdf3731a1c9b4b8557cb77174b0c66851e4200 Mon Sep 17 00:00:00 2001 From: Frank <91616163+softhack007@users.noreply.github.com> Date: Thu, 20 Jul 2023 22:36:47 +0200 Subject: [PATCH 34/34] upgrade to FastLED 3.6.0 changes from 3.50 to 3.6.0: * bugfixes * removed "register" keyword * some speedups * explicit bool() and uint32_t() operators, see https://github.com/FastLED/FastLED/issues/819 FX.cpp: bugfix for "wled00/FX.cpp:4906:36: error: cannot convert 'CRGB' to 'uint32_t' {aka 'unsigned int'} in initialization" --- platformio.ini | 4 ++-- wled00/FX.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/platformio.ini b/platformio.ini index abba37bd..73da6250 100644 --- a/platformio.ini +++ b/platformio.ini @@ -175,7 +175,7 @@ upload_speed = 115200 # ------------------------------------------------------------------------------ lib_compat_mode = strict lib_deps = - fastled/FastLED @ 3.5.0 + fastled/FastLED @ 3.6.0 IRremoteESP8266 @ 2.8.2 makuna/NeoPixelBus @ 2.7.5 https://github.com/Aircoookie/ESPAsyncWebServer.git @ ~2.0.7 @@ -201,7 +201,7 @@ build_flags = -DESP8266 -DFP_IN_IROM ;-Wno-deprecated-declarations - -Wno-register ;; leaves some warnings when compiling C files: command-line option '-Wno-register' is valid for C++/ObjC++ but not for C + ;-Wno-register ;; leaves some warnings when compiling C files: command-line option '-Wno-register' is valid for C++/ObjC++ but not for C ;-Dregister= # remove warnings in C++17 due to use of deprecated register keyword by the FastLED library ;; warning: this can be dangerous -Wno-misleading-indentation ; NONOSDK22x_190703 = 2.2.2-dev(38a443e) diff --git a/wled00/FX.cpp b/wled00/FX.cpp index b457e094..9ed56710 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -4903,7 +4903,7 @@ uint16_t mode_2Dgameoflife(void) { // Written by Ewoud Wijma, inspired by https: } // i,j // Rules of Life - uint32_t col = prevLeds[XY(x,y)]; + uint32_t col = uint32_t(prevLeds[XY(x,y)]) & 0x00FFFFFF; // uint32_t operator returns RGBA, we want RGBW -> cut off "alpha" byte uint32_t bgc = RGBW32(backgroundColor.r, backgroundColor.g, backgroundColor.b, 0); if ((col != bgc) && (neighbors < 2)) SEGMENT.setPixelColorXY(x,y, bgc); // Loneliness else if ((col != bgc) && (neighbors > 3)) SEGMENT.setPixelColorXY(x,y, bgc); // Overpopulation