Просмотр исходного кода

Merge pull request #4207 from SybexX/main

fix memory-management
SybexXx 2 дней назад
Родитель
Сommit
10c513af57
38 измененных файлов с 3397 добавлено и 2915 удалено
  1. 0 9
      code/components/jomjol_controlGPIO/Color.cpp
  2. 1 1
      code/components/jomjol_controlGPIO/Color.h
  3. 53 0
      code/components/jomjol_controlcamera/CameraSettings.h
  4. 498 345
      code/components/jomjol_controlcamera/ClassControllCamera.cpp
  5. 23 56
      code/components/jomjol_controlcamera/ClassControllCamera.h
  6. 30 39
      code/components/jomjol_controlcamera/server_camera.cpp
  7. 0 8
      code/components/jomjol_fileserver_ota/md5.cpp
  8. 0 2
      code/components/jomjol_fileserver_ota/md5.h
  9. 1 0
      code/components/jomjol_flowcontroll/ClassFlow.h
  10. 425 379
      code/components/jomjol_flowcontroll/ClassFlowAlignment.cpp
  11. 53 51
      code/components/jomjol_flowcontroll/ClassFlowAlignment.h
  12. 144 29
      code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp
  13. 1 0
      code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.h
  14. 58 36
      code/components/jomjol_flowcontroll/ClassFlowControll.cpp
  15. 3 1
      code/components/jomjol_flowcontroll/ClassFlowControll.h
  16. 77 60
      code/components/jomjol_flowcontroll/ClassFlowTakeImage.cpp
  17. 2 4
      code/components/jomjol_flowcontroll/ClassFlowTakeImage.h
  18. 126 257
      code/components/jomjol_flowcontroll/MainFlowControl.cpp
  19. 4 54
      code/components/jomjol_flowcontroll/MainFlowControl.h
  20. 1 145
      code/components/jomjol_helper/Helper.cpp
  21. 3 14
      code/components/jomjol_helper/Helper.h
  22. 146 179
      code/components/jomjol_helper/esp_sys.cpp
  23. 46 54
      code/components/jomjol_helper/esp_sys.h
  24. 248 133
      code/components/jomjol_helper/psram.cpp
  25. 4 16
      code/components/jomjol_helper/psram.h
  26. 163 92
      code/components/jomjol_image_proc/CAlignAndCutImage.cpp
  27. 1 2
      code/components/jomjol_image_proc/CAlignAndCutImage.h
  28. 87 111
      code/components/jomjol_image_proc/CFindTemplate.cpp
  29. 492 349
      code/components/jomjol_image_proc/CImageBasis.cpp
  30. 18 5
      code/components/jomjol_image_proc/CImageBasis.h
  31. 451 326
      code/components/jomjol_image_proc/CRotateImage.cpp
  32. 59 36
      code/components/jomjol_mqtt/mqtt_outbox.c
  33. 159 107
      code/components/jomjol_tfliteclass/CTfLiteClass.cpp
  34. 4 1
      code/components/jomjol_tfliteclass/CTfLiteClass.h
  35. 0 10
      code/components/jomjol_time_sntp/time_sntp.cpp
  36. 0 2
      code/components/jomjol_time_sntp/time_sntp.h
  37. 4 0
      code/components/jomjol_webhook/interface_webhook.cpp
  38. 12 2
      code/main/server_main.cpp

+ 0 - 9
code/components/jomjol_controlGPIO/Color.cpp

@@ -143,15 +143,6 @@ Rgb& Rgb::operator-=(const Rgb& in) {
     return *this;
 }
 
-Rgb& Rgb::blend(const Rgb& in) {
-    unsigned int inAlpha = in.a * (255 - a);
-    unsigned int alpha = a + inAlpha;
-    r = iRgbSqrt(((r * r * a) + (in.r * in.r * inAlpha)) / alpha);
-    g = iRgbSqrt(((g * g * a) + (in.g * in.g * inAlpha)) / alpha);
-    b = iRgbSqrt(((b * b * a) + (in.b * in.b * inAlpha)) / alpha);
-    a = alpha;
-    return *this;
-}
 
 Hsv::Hsv(const Rgb& r) {
     int min = std::min(r.r, std::min(r.g, r.b));

+ 1 - 1
code/components/jomjol_controlGPIO/Color.h

@@ -53,7 +53,7 @@ union Rgb {
     Rgb operator-(const Rgb& in) const;
     Rgb& operator-=(const Rgb& in);
     bool operator==(const Rgb& in) const { return in.value == value; }
-    Rgb& blend(const Rgb& in);
+
     void swap(const Rgb& o) { value = o.value; }
     void linearize() {
         r = channelGamma(r);

+ 53 - 0
code/components/jomjol_controlcamera/CameraSettings.h

@@ -0,0 +1,53 @@
+#pragma once
+
+#ifndef JOMJOL_CAMERA_SETTINGS_H
+#define JOMJOL_CAMERA_SETTINGS_H
+
+#include "esp_camera.h"
+
+// Shared sensor/image parameters. Runtime state and temporary-flow flags live
+// in their respective status structures, not in this common settings object.
+struct CameraSettings
+{
+    framesize_t ImageFrameSize = FRAMESIZE_VGA;
+    int ImageWidth = 640;
+    int ImageHeight = 480;
+    int CamXclkFreqMhz = 20;
+    gainceiling_t ImageGainceiling;
+
+    int ImageQuality;
+    int ImageBrightness;
+    int ImageContrast;
+    int ImageSaturation;
+    int ImageSharpness;
+    bool ImageAutoSharpness;
+    int ImageSpecialEffect;
+    int ImageWbMode;
+    int ImageAwb;
+    int ImageAwbGain;
+    int ImageAec;
+    int ImageAec2;
+    int ImageAeLevel;
+    int ImageAecValue;
+    int ImageAgc;
+    int ImageAgcGain;
+    int ImageBpc;
+    int ImageWpc;
+    int ImageRawGma;
+    int ImageLenc;
+    int ImageHmirror;
+    int ImageVflip;
+    int ImageDcw;
+    int ImageDenoiseLevel;
+
+    int ImageLedIntensity;
+
+    bool ImageZoomEnabled;
+    int ImageZoomOffsetX;
+    int ImageZoomOffsetY;
+    int ImageZoomSize;
+
+    int WaitBeforePicture;
+};
+
+#endif // JOMJOL_CAMERA_SETTINGS_H

Разница между файлами не показана из-за своего большого размера
+ 498 - 345
code/components/jomjol_controlcamera/ClassControllCamera.cpp


+ 23 - 56
code/components/jomjol_controlcamera/ClassControllCamera.h

@@ -4,80 +4,45 @@
 #define CLASSCONTROLLCAMERA_H
 
 #include <string>
+#include <vector>
 #include "freertos/FreeRTOS.h"
-#include "freertos/task.h"
-#include "freertos/queue.h"
-#include "freertos/event_groups.h"
+#include "freertos/semphr.h"
 
 #include "esp_camera.h"
-#include <string>
 #include <esp_http_server.h>
+#include "CameraSettings.h"
 #include "CImageBasis.h"
 #include "../../include/defines.h"
 
-typedef struct
+struct camera_controll_config_temp_t : public CameraSettings
 {
+    // Hardware identity/dimensions and runtime flags are not camera settings.
     uint16_t CamSensor_id;
 
-    framesize_t ImageFrameSize = FRAMESIZE_VGA; // 0 - 10
-    gainceiling_t ImageGainceiling;             // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
-
-    int ImageQuality;    // 0 - 63
-    int ImageBrightness; // (-2 to 2) - set brightness
-    int ImageContrast;   //-2 - 2
-    int ImageSaturation; //-2 - 2
-    int ImageSharpness;  //-2 - 2
-    bool ImageAutoSharpness;
-    int ImageSpecialEffect; // 0 - 6
-    int ImageWbMode;        // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
-    int ImageAwb;           // white balance enable (0 or 1)
-    int ImageAwbGain;       // Auto White Balance enable (0 or 1)
-    int ImageAec;           // auto exposure off (1 or 0)
-    int ImageAec2;          // automatic exposure sensor  (0 or 1)
-    int ImageAeLevel;       // auto exposure levels (-2 to 2)
-    int ImageAecValue;      // set exposure manually  (0-1200)
-    int ImageAgc;           // auto gain off (1 or 0)
-    int ImageAgcGain;       // set gain manually (0 - 30)
-    int ImageBpc;           // black pixel correction
-    int ImageWpc;           // white pixel correction
-    int ImageRawGma;        // (1 or 0)
-    int ImageLenc;          // lens correction (1 or 0)
-    int ImageHmirror;       // (0 or 1) flip horizontally
-    int ImageVflip;         // Invert image (0 or 1)
-    int ImageDcw;           // downsize enable (1 or 0)
-
-    int ImageDenoiseLevel; // The OV2640 does not support it, OV3660 and OV5640 (0 to 8)
-
-    int ImageWidth;
-    int ImageHeight;
-
-    int ImageLedIntensity;
-
-    bool ImageZoomEnabled;
-    int ImageZoomOffsetX;
-    int ImageZoomOffsetY;
-    int ImageZoomSize;
-
-    int WaitBeforePicture;
-    bool isImageSize;
-
     bool CameraInitSuccessful;
-    bool changedCameraSettings;
     bool DemoMode;
     bool SaveAllFiles;
-} camera_controll_config_temp_t;
+};
 
 extern camera_controll_config_temp_t CCstatus;
 
 class CCamera
 {
 protected:
+    SemaphoreHandle_t m_cameraMutex;
+    bool m_driverInitialized;
+    bool m_temporarySettingsActive;
+    bool m_previewCapturePending;
+    int m_previewCaptureDelayMs;
+    std::vector<std::string> m_demoFiles;
+
     void ledc_init(void);
-    bool loadNextDemoImage(camera_fb_t *fb);
+    bool loadNextDemoImage(uint8_t **data, size_t *length);
     long GetFileSize(std::string filename);
     void SetCamWindow(sensor_t *s, int frameSizeX, int frameSizeY, int xOffset, int yOffset, int xTotal, int yTotal, int xOutput, int yOutput, int imageVflip);
-    void SetImageWidthHeightFromResolution(framesize_t resol);
-    void SanitizeZoomParams(int imageSize, int frameSizeX, int frameSizeY, int &imageWidth, int &imageHeight, int &zoomOffsetX, int &zoomOffsetY);
+    void SetImageWidthHeightFromResolution(CameraSettings &settings);
+    void SanitizeZoomParams(const CameraSettings &settings, int imageSize, int frameSizeX, int frameSizeY,
+                            int &imageWidth, int &imageHeight, int &zoomOffsetX, int &zoomOffsetY);
 
 public:
     int LedIntensity = 4096;
@@ -89,6 +54,9 @@ public:
     void LEDOnOff(bool status);
 
     esp_err_t setSensorDatenFromCCstatus(void);
+    esp_err_t ApplySettings(CameraSettings &settings);
+    esp_err_t ApplyPreviewSettings(const CameraSettings &settings);
+    esp_err_t RestoreCommittedSettingsIfNeeded(void);
     esp_err_t getSensorDatenToCCstatus(void);
 
     int SetCamGainceiling(sensor_t *s, gainceiling_t gainceilingLevel);
@@ -96,18 +64,17 @@ public:
     void SetCamSpecialEffect(sensor_t *s, int specialEffect);
     void SetCamContrastBrightness(sensor_t *s, int _contrast, int _brightness);
 
-    esp_err_t CaptureToHTTP(httpd_req_t *req, int delay = 0);
+    esp_err_t CaptureToHTTP(httpd_req_t *req, int delay = 0, bool previewCapture = false);
     esp_err_t CaptureToStream(httpd_req_t *req, bool FlashlightOn);
 
-    void SetQualityZoomSize(int qual, framesize_t resol, bool zoomEnabled, int zoomOffsetX, int zoomOffsetY, int imageSize, int imageVflip);
-    void SetZoomSize(bool zoomEnabled, int zoomOffsetX, int zoomOffsetY, int imageSize, int imageVflip);
+    esp_err_t SetQualityZoomSize(CameraSettings &settings);
+    esp_err_t SetZoomSize(const CameraSettings &settings);
 
     int SetLEDIntensity(int _intrel);
     bool testCamera(void);
     bool getCameraInitSuccessful(void);
     void useDemoMode(void);
 
-    framesize_t TextToFramesize(const char *text);
 
     esp_err_t CaptureToFile(std::string nm, int delay = 0);
     esp_err_t CaptureToBasisImage(CImageBasis *_Image, int delay = 0);

+ 30 - 39
code/components/jomjol_controlcamera/server_camera.cpp

@@ -106,14 +106,7 @@ esp_err_t handler_capture(httpd_req_t *req)
 
     if (Camera.getCameraInitSuccessful())
     {
-        // If the camera settings were changed by creating a new reference image, they must be reset
-        if (CFstatus.changedCameraSettings)
-        {
-            Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
-            Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
-            Camera.LedIntensity = CCstatus.ImageLedIntensity;
-            CFstatus.changedCameraSettings = false;
-        }
+
 
 #ifdef DEBUG_DETAIL_ON
         ESP_LOGD(TAG, "Size: %d, Quality: %d", CCstatus.ImageFrameSize, CCstatus.ImageQuality);
@@ -165,27 +158,13 @@ esp_err_t handler_capture_with_light(httpd_req_t *req)
             }
         }
 
-        // If the camera settings were changed by creating a new reference image, they must be reset
-        if (CFstatus.changedCameraSettings)
-        {
-            Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
-            Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
-            Camera.LedIntensity = CCstatus.ImageLedIntensity;
-            CFstatus.changedCameraSettings = false;
-        }
+
 
 #ifdef DEBUG_DETAIL_ON
         ESP_LOGD(TAG, "Size: %d, Quality: %d", CCstatus.ImageFrameSize, CCstatus.ImageQuality);
 #endif        
 
-        Camera.LightOnOff(true);
-        const TickType_t xDelay = delay / portTICK_PERIOD_MS;
-        vTaskDelay(xDelay);
-
-        esp_err_t result;
-        result = Camera.CaptureToHTTP(req);
-
-        Camera.LightOnOff(false);
+        const esp_err_t result = Camera.CaptureToHTTP(req, delay);
 
 #ifdef DEBUG_DETAIL_ON
         LogFile.WriteHeapInfo("handler_capture_with_light - Done");
@@ -211,15 +190,22 @@ esp_err_t handler_capture_save_to_file(httpd_req_t *req)
         char _query[100];
         char _delay[10];
         int delay = 0;
-        char filename[100];
+        char filename[100] = {0};
         std::string fn = "/sdcard/";
 
         if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
         {
             ESP_LOGD(TAG, "Query: %s", _query);
 
-            if (httpd_query_key_value(_query, "filename", filename, 100) == ESP_OK)
+            if (httpd_query_key_value(_query, "filename", filename, sizeof(filename)) == ESP_OK)
             {
+                if (filename[0] == '\0' || strchr(filename, '/') != NULL ||
+                    strchr(filename, '\\') != NULL || strcmp(filename, ".") == 0 ||
+                    strcmp(filename, "..") == 0)
+                {
+                    httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid filename");
+                    return ESP_ERR_INVALID_ARG;
+                }
                 fn.append(filename);
 #ifdef DEBUG_DETAIL_ON
                 ESP_LOGD(TAG, "Filename: %s", fn.c_str());
@@ -248,30 +234,35 @@ esp_err_t handler_capture_save_to_file(httpd_req_t *req)
             fn.append("noname.jpg");
         }
 
-        // If the camera settings were changed by creating a new reference image, they must be reset
-        if (CFstatus.changedCameraSettings)
-        {
-            Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
-            Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
-            Camera.LedIntensity = CCstatus.ImageLedIntensity;
-            CFstatus.changedCameraSettings = false;
-        }
+
 
 #ifdef DEBUG_DETAIL_ON
         ESP_LOGD(TAG, "Size: %d, Quality: %d", CCstatus.ImageFrameSize, CCstatus.ImageQuality);
 #endif        
 
-        esp_err_t result;
-        result = Camera.CaptureToFile(fn, delay);
+        const esp_err_t result = Camera.CaptureToFile(fn, delay);
+        if (result != ESP_OK)
+        {
+            if (result == ESP_ERR_TIMEOUT)
+            {
+                httpd_resp_set_status(req, "503 Service Unavailable");
+                httpd_resp_send(req, "Camera is busy", HTTPD_RESP_USE_STRLEN);
+            }
+            else
+            {
+                httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR,
+                                    "Image capture or file save failed");
+            }
+            return result;
+        }
 
-        const char *resp_str = (const char *)fn.c_str();
-        httpd_resp_send(req, resp_str, strlen(resp_str));
+        const esp_err_t responseResult = httpd_resp_send(req, fn.c_str(), fn.length());
 
 #ifdef DEBUG_DETAIL_ON
         LogFile.WriteHeapInfo("handler_capture_save_to_file - Done");
 #endif
 
-        return result;
+        return responseResult;
     }
     else
     {

+ 0 - 8
code/components/jomjol_fileserver_ota/md5.cpp

@@ -197,14 +197,6 @@ void md5Step(uint32_t *buffer, uint32_t *input){
  * Functions that run the algorithm on the provided input and put the digest into result.
  * result should be able to store 16 bytes.
  */
-void md5String(char *input, uint8_t *result){
-    MD5Context ctx;
-    md5Init(&ctx);
-    md5Update(&ctx, (uint8_t *)input, strlen(input));
-    md5Finalize(&ctx);
-
-    memcpy(result, ctx.digest, 16);
-}
 
 
 void md5File(FILE *file, uint8_t *result){

+ 0 - 2
code/components/jomjol_fileserver_ota/md5.h

@@ -21,8 +21,6 @@ void md5Init(MD5Context *ctx);
 void md5Update(MD5Context *ctx, uint8_t *input, size_t input_len);
 void md5Finalize(MD5Context *ctx);
 void md5Step(uint32_t *buffer, uint32_t *input);
-
-void md5String(char *input, uint8_t *result);
 void md5File(FILE *file, uint8_t *result);
 
 #endif // MD5_H

+ 1 - 0
code/components/jomjol_flowcontroll/ClassFlow.h

@@ -40,6 +40,7 @@ protected:
 
 public:
 	ClassFlow(void);
+	virtual ~ClassFlow() = default;
 	ClassFlow(std::vector<ClassFlow*> * lfc);
 	ClassFlow(std::vector<ClassFlow*> * lfc, ClassFlow *_prev);	
 	

+ 425 - 379
code/components/jomjol_flowcontroll/ClassFlowAlignment.cpp

@@ -1,379 +1,425 @@
-#include "ClassFlowAlignment.h"
-#include "ClassFlowTakeImage.h"
-#include "ClassFlow.h"
-#include "MainFlowControl.h"
-
-#include "CRotateImage.h"
-#include "esp_log.h"
-
-#include "ClassLogFile.h"
-#include "psram.h"
-#include "../../include/defines.h"
-
-static const char *TAG = "ALIGN";
-
-// #define DEBUG_DETAIL_ON
-
-void ClassFlowAlignment::SetInitialParameter(void)
-{
-    initialrotate = 0;
-    anz_ref = 0;
-    use_antialiasing = false;
-    initialflip = false;
-    SaveAllFiles = false;
-    namerawimage = "/sdcard/img_tmp/raw.jpg";
-    FileStoreRefAlignment = "/sdcard/config/align.txt";
-    ListFlowControll = NULL;
-    AlignAndCutImage = NULL;
-    ImageBasis = NULL;
-    ImageTMP = NULL;
-#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
-    AlgROI = (ImageData *)malloc_psram_heap(std::string(TAG) + "->AlgROI", sizeof(ImageData), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
-#endif
-    previousElement = NULL;
-    disabled = false;
-    SAD_criteria = 0.05;
-}
-
-ClassFlowAlignment::ClassFlowAlignment(std::vector<ClassFlow *> *lfc)
-{
-    SetInitialParameter();
-    ListFlowControll = lfc;
-
-    for (int i = 0; i < ListFlowControll->size(); ++i) {
-        if (((*ListFlowControll)[i])->name().compare("ClassFlowTakeImage") == 0) {
-            ImageBasis = ((ClassFlowTakeImage *)(*ListFlowControll)[i])->rawImage;
-        }
-    }
-
-    // the function take pictures does not exist --> must be created first ONLY FOR TEST PURPOSES
-    if (!ImageBasis)  {
-        ESP_LOGD(TAG, "CImageBasis had to be created");
-        ImageBasis = new CImageBasis("ImageBasis", namerawimage);
-    }
-}
-
-bool ClassFlowAlignment::ReadParameter(FILE *pfile, string &aktparamgraph)
-{
-    std::vector<string> splitted;
-    int suchex = 40;
-    int suchey = 40;
-    int alg_algo = 0; // default=0; 1 =HIGHACCURACY; 2= FAST; 3= OFF //add disable aligment algo |01.2023
-
-    aktparamgraph = trim(aktparamgraph);
-
-    if (aktparamgraph.size() == 0)
-    {
-        if (!this->GetNextParagraph(pfile, aktparamgraph)) {
-            return false;
-        }
-    }
-
-    if (aktparamgraph.compare("[Alignment]") != 0)
-    {
-        // Paragraph does not fit Alignment
-        return false;
-    }
-
-    while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
-    {
-        splitted = ZerlegeZeile(aktparamgraph);
-
-        if ((toUpper(splitted[0]) == "FLIPIMAGESIZE") && (splitted.size() > 1)) {
-            initialflip = alphanumericToBoolean(splitted[1]);
-        }
-        else if (((toUpper(splitted[0]) == "initialrotate") || (toUpper(splitted[0]) == "INITIALROTATE")) && (splitted.size() > 1)) {
-            if (isStringNumeric(splitted[1])) {
-                this->initialrotate = std::stod(splitted[1]);
-            }
-        }
-        else if ((toUpper(splitted[0]) == "SEARCHFIELDX") && (splitted.size() > 1)) {
-            if (isStringNumeric(splitted[1])) {
-                suchex = std::stod(splitted[1]);
-            }
-        }
-        else if ((toUpper(splitted[0]) == "SEARCHFIELDY") && (splitted.size() > 1)) {
-            if (isStringNumeric(splitted[1])) {
-                suchey = std::stod(splitted[1]);
-            }
-        }
-        else if ((toUpper(splitted[0]) == "ANTIALIASING") && (splitted.size() > 1)) {
-            use_antialiasing = alphanumericToBoolean(splitted[1]);
-        }
-        else if ((splitted.size() == 3) && (anz_ref < 2)) {
-            if ((isStringNumeric(splitted[1])) && (isStringNumeric(splitted[2])))
-            {
-                References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
-                References[anz_ref].target_x = std::stod(splitted[1]);
-                References[anz_ref].target_y = std::stod(splitted[2]);
-                anz_ref++;
-            }
-            else
-            {
-                References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
-                References[anz_ref].target_x = 10;
-                References[anz_ref].target_y = 10;
-                anz_ref++;
-            }
-        }
-
-        else if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1)) {
-            SaveAllFiles = alphanumericToBoolean(splitted[1]);
-        }
-        else if ((toUpper(splitted[0]) == "ALIGNMENTALGO") && (splitted.size() > 1)) {
-#ifdef DEBUG_DETAIL_ON
-            std::string zw2 = "Alignment mode selected: " + splitted[1];
-            LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
-#endif
-            if (toUpper(splitted[1]) == "HIGHACCURACY") {
-                alg_algo = 1;
-            }
-            if (toUpper(splitted[1]) == "FAST") {
-                alg_algo = 2;
-            }
-            if (toUpper(splitted[1]) == "OFF") {
-                // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
-                alg_algo = 3;
-            }
-        }
-    }
-
-    for (int i = 0; i < anz_ref; ++i) {
-        References[i].search_x = suchex;
-        References[i].search_y = suchey;
-        References[i].fastalg_SAD_criteria = SAD_criteria;
-        References[i].alignment_algo = alg_algo;
-#ifdef DEBUG_DETAIL_ON
-        std::string zw2 = "Alignment mode written: " + std::to_string(alg_algo);
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
-#endif
-    }
-
-    // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
-    if (References[0].alignment_algo != 3) {
-        return LoadReferenceAlignmentValues();
-    }
-
-    return true;
-}
-
-string ClassFlowAlignment::getHTMLSingleStep(string host)
-{
-    string result;
-
-    result = "<p>Rotated Image: </p> <p><img src=\"" + host + "/img_tmp/rot.jpg\"></p>\n";
-    result = result + "<p>Found Alignment: </p> <p><img src=\"" + host + "/img_tmp/rot_roi.jpg\"></p>\n";
-    result = result + "<p>Aligned Image: </p> <p><img src=\"" + host + "/img_tmp/alg.jpg\"></p>\n";
-    return result;
-}
-
-bool ClassFlowAlignment::doFlow(string time)
-{
-#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
-    // AlgROI needs to be allocated before ImageTMP to avoid heap fragmentation
-    if (!AlgROI)  {
-        AlgROI = (ImageData *)heap_caps_realloc(AlgROI, sizeof(ImageData), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
-
-        if (!AlgROI) {
-            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlgROI");
-            LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
-        }
-    }
-
-    if (AlgROI) {
-        ImageBasis->writeToMemoryAsJPG((ImageData *)AlgROI, 90);
-    }
-#endif
-
-    if (!ImageTMP) {
-        ImageTMP = new CImageBasis("tmpImage", ImageBasis); // Make sure the name does not get change, it is relevant for the PSRAM allocation!
-
-        if (!ImageTMP) {
-            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tmpImage -> Exec this round aborted!");
-            LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
-            return false;
-        }
-    }
-
-    delete AlignAndCutImage;
-    AlignAndCutImage = new CAlignAndCutImage("AlignAndCutImage", ImageBasis, ImageTMP);
-
-    if (!AlignAndCutImage) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlignAndCutImage -> Exec this round aborted!");
-        LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
-        return false;
-    }
-
-    CRotateImage rt("rawImage", AlignAndCutImage, ImageTMP, initialflip);
-
-    if (initialflip) {
-        int _zw = ImageBasis->height;
-        ImageBasis->height = ImageBasis->width;
-        ImageBasis->width = _zw;
-
-        _zw = ImageTMP->width;
-        ImageTMP->width = ImageTMP->height;
-        ImageTMP->height = _zw;
-    }
-
-    if ((initialrotate != 0) || initialflip) {
-        if (use_antialiasing) {
-            rt.RotateAntiAliasing(initialrotate);
-        }
-        else {
-            rt.Rotate(initialrotate);
-        }
-
-        if (SaveAllFiles) {
-            AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/rot.jpg"));
-        }
-    }
-
-    // no align algo if set to 3 = off //add disable aligment algo |01.2023
-    if (References[0].alignment_algo != 3) {
-        if (!AlignAndCutImage->Align(&References[0], &References[1])) {
-            SaveReferenceAlignmentValues();
-        }
-    } // no align
-
-#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
-    if (AlgROI) {
-        // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
-        if (References[0].alignment_algo != 3) {
-            DrawRef(ImageTMP);
-        }
-
-        flowctrl.DigitDrawROI(ImageTMP);
-        flowctrl.AnalogDrawROI(ImageTMP);
-        ImageTMP->writeToMemoryAsJPG((ImageData *)AlgROI, 90);
-    }
-#endif
-
-    if (SaveAllFiles) {
-        AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/alg.jpg"));
-        ImageTMP->SaveToFile(FormatFileName("/sdcard/img_tmp/alg_roi.jpg"));
-    }
-
-    // must be deleted to have memory space for loading tflite
-    delete ImageTMP;
-    ImageTMP = NULL;
-
-    // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
-    if (References[0].alignment_algo != 3) {
-        return LoadReferenceAlignmentValues();
-    }
-
-    return true;
-}
-
-void ClassFlowAlignment::SaveReferenceAlignmentValues()
-{
-    FILE *pFile;
-    std::string zwtime, zwvalue;
-
-    pFile = fopen(FileStoreRefAlignment.c_str(), "w");
-
-    if (pFile == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SaveReferenceAlignmentValues: Failed to open " + FileStoreRefAlignment);
-        return;
-    }
-
-    if (strlen(zwtime.c_str()) == 0) {
-        time_t rawtime;
-        struct tm *timeinfo;
-        char buffer[80];
-
-        time(&rawtime);
-        timeinfo = localtime(&rawtime);
-
-        strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S", timeinfo);
-        zwtime = std::string(buffer);
-    }
-
-    fputs(zwtime.c_str(), pFile);
-    fputs("\n", pFile);
-
-    zwvalue = std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_y);
-    zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
-    zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
-    fputs(zwvalue.c_str(), pFile);
-    fputs("\n", pFile);
-
-    zwvalue = std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_y);
-    zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
-    zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
-    fputs(zwvalue.c_str(), pFile);
-    fputs("\n", pFile);
-
-    fclose(pFile);
-}
-
-bool ClassFlowAlignment::LoadReferenceAlignmentValues(void)
-{
-    FILE *pFile;
-    char zw[1024];
-    string zwvalue;
-    std::vector<string> splitted;
-
-    pFile = fopen(FileStoreRefAlignment.c_str(), "r");
-
-    if (pFile == NULL) {
-        return false;
-    }
-
-    fgets(zw, 1024, pFile);
-    ESP_LOGD(TAG, "%s", zw);
-
-    fgets(zw, 1024, pFile);
-    splitted = ZerlegeZeile(std::string(zw), " \t");
-
-    if (splitted.size() < 6) {
-        fclose(pFile);
-        return false;
-    }
-
-    References[0].fastalg_x = stoi(splitted[0]);
-    References[0].fastalg_y = stoi(splitted[1]);
-    References[0].fastalg_SAD = stof(splitted[2]);
-    References[0].fastalg_min = stoi(splitted[3]);
-    References[0].fastalg_max = stoi(splitted[4]);
-    References[0].fastalg_avg = stof(splitted[5]);
-
-    fgets(zw, 1024, pFile);
-    splitted = ZerlegeZeile(std::string(zw));
-
-    if (splitted.size() < 6) {
-        fclose(pFile);
-        return false;
-    }
-
-    References[1].fastalg_x = stoi(splitted[0]);
-    References[1].fastalg_y = stoi(splitted[1]);
-    References[1].fastalg_SAD = stof(splitted[2]);
-    References[1].fastalg_min = stoi(splitted[3]);
-    References[1].fastalg_max = stoi(splitted[4]);
-    References[1].fastalg_avg = stof(splitted[5]);
-
-    fclose(pFile);
-
-    /*#ifdef DEBUG_DETAIL_ON
-        std::string _zw = "\tLoadReferences[0]\tx,y:\t" + std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_x);
-        _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
-        _zw = _zw + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
-        LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
-        _zw = "\tLoadReferences[1]\tx,y:\t" + std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_x);
-        _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
-        _zw = _zw + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
-        LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
-    #endif*/
-
-    return true;
-}
-
-void ClassFlowAlignment::DrawRef(CImageBasis *_zw)
-{
-    if (_zw->ImageOkay()) {
-        _zw->drawRect(References[0].target_x, References[0].target_y, References[0].width, References[0].height, 255, 0, 0, 2);
-        _zw->drawRect(References[1].target_x, References[1].target_y, References[1].width, References[1].height, 255, 0, 0, 2);
-    }
-}
+#include "ClassFlowAlignment.h"
+#include "ClassFlowTakeImage.h"
+#include "ClassFlow.h"
+#include "MainFlowControl.h"
+
+#include "CRotateImage.h"
+#include "esp_log.h"
+
+#include "ClassLogFile.h"
+#include "psram.h"
+#include "../../include/defines.h"
+#include <new>
+
+static const char *TAG = "ALIGN";
+
+// #define DEBUG_DETAIL_ON
+
+void ClassFlowAlignment::SetInitialParameter(void)
+{
+    initialrotate = 0;
+    anz_ref = 0;
+    use_antialiasing = false;
+    initialflip = false;
+    SaveAllFiles = false;
+    namerawimage = "/sdcard/img_tmp/raw.jpg";
+    FileStoreRefAlignment = "/sdcard/config/align.txt";
+    ListFlowControll = NULL;
+    AlignAndCutImage = NULL;
+    ImageBasis = NULL;
+    ownsImageBasis = false;
+    ImageTMP = NULL;
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    AlgROI = new (std::nothrow) ImageData;
+#endif
+    previousElement = NULL;
+    disabled = false;
+    SAD_criteria = 0.05;
+}
+
+ClassFlowAlignment::ClassFlowAlignment(std::vector<ClassFlow *> *lfc)
+{
+    SetInitialParameter();
+    ListFlowControll = lfc;
+
+    for (int i = 0; i < ListFlowControll->size(); ++i) {
+        if (((*ListFlowControll)[i])->name().compare("ClassFlowTakeImage") == 0) {
+            ImageBasis = ((ClassFlowTakeImage *)(*ListFlowControll)[i])->rawImage;
+        }
+    }
+
+    // the function take pictures does not exist --> must be created first ONLY FOR TEST PURPOSES
+    if (!ImageBasis)  {
+        ESP_LOGD(TAG, "CImageBasis had to be created");
+        ImageBasis = new (std::nothrow) CImageBasis("ImageBasis", namerawimage);
+        ownsImageBasis = (ImageBasis != NULL);
+        if (ImageBasis != NULL && !ImageBasis->ImageOkay()) { delete ImageBasis; ImageBasis = NULL; ownsImageBasis = false; }
+    }
+}
+
+ClassFlowAlignment::~ClassFlowAlignment()
+{
+    delete AlignAndCutImage;
+    AlignAndCutImage = NULL;
+    delete ImageTMP;
+    ImageTMP = NULL;
+    if (ownsImageBasis) {
+        delete ImageBasis;
+        ImageBasis = NULL;
+        ownsImageBasis = false;
+    }
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    delete AlgROI;
+    AlgROI = NULL;
+#endif
+}
+
+bool ClassFlowAlignment::ReadParameter(FILE *pfile, string &aktparamgraph)
+{
+    std::vector<string> splitted;
+    int suchex = 40;
+    int suchey = 40;
+    int alg_algo = 0; // default=0; 1 =HIGHACCURACY; 2= FAST; 3= OFF //add disable aligment algo |01.2023
+
+    aktparamgraph = trim(aktparamgraph);
+
+    if (aktparamgraph.size() == 0)
+    {
+        if (!this->GetNextParagraph(pfile, aktparamgraph)) {
+            return false;
+        }
+    }
+
+    if (aktparamgraph.compare("[Alignment]") != 0)
+    {
+        // Paragraph does not fit Alignment
+        return false;
+    }
+
+    while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
+    {
+        splitted = ZerlegeZeile(aktparamgraph);
+
+        if ((toUpper(splitted[0]) == "FLIPIMAGESIZE") && (splitted.size() > 1)) {
+            initialflip = alphanumericToBoolean(splitted[1]);
+        }
+        else if (((toUpper(splitted[0]) == "initialrotate") || (toUpper(splitted[0]) == "INITIALROTATE")) && (splitted.size() > 1)) {
+            if (isStringNumeric(splitted[1])) {
+                this->initialrotate = std::stod(splitted[1]);
+            }
+        }
+        else if ((toUpper(splitted[0]) == "SEARCHFIELDX") && (splitted.size() > 1)) {
+            if (isStringNumeric(splitted[1])) {
+                suchex = std::stod(splitted[1]);
+            }
+        }
+        else if ((toUpper(splitted[0]) == "SEARCHFIELDY") && (splitted.size() > 1)) {
+            if (isStringNumeric(splitted[1])) {
+                suchey = std::stod(splitted[1]);
+            }
+        }
+        else if ((toUpper(splitted[0]) == "ANTIALIASING") && (splitted.size() > 1)) {
+            use_antialiasing = alphanumericToBoolean(splitted[1]);
+        }
+        else if ((splitted.size() == 3) && (anz_ref < 2)) {
+            if ((isStringNumeric(splitted[1])) && (isStringNumeric(splitted[2])))
+            {
+                References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
+                References[anz_ref].target_x = std::stod(splitted[1]);
+                References[anz_ref].target_y = std::stod(splitted[2]);
+                anz_ref++;
+            }
+            else
+            {
+                References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
+                References[anz_ref].target_x = 10;
+                References[anz_ref].target_y = 10;
+                anz_ref++;
+            }
+        }
+
+        else if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1)) {
+            SaveAllFiles = alphanumericToBoolean(splitted[1]);
+        }
+        else if ((toUpper(splitted[0]) == "ALIGNMENTALGO") && (splitted.size() > 1)) {
+#ifdef DEBUG_DETAIL_ON
+            std::string zw2 = "Alignment mode selected: " + splitted[1];
+            LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
+#endif
+            if (toUpper(splitted[1]) == "HIGHACCURACY") {
+                alg_algo = 1;
+            }
+            if (toUpper(splitted[1]) == "FAST") {
+                alg_algo = 2;
+            }
+            if (toUpper(splitted[1]) == "OFF") {
+                // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
+                alg_algo = 3;
+            }
+        }
+    }
+
+    for (int i = 0; i < anz_ref; ++i) {
+        References[i].search_x = suchex;
+        References[i].search_y = suchey;
+        References[i].fastalg_SAD_criteria = SAD_criteria;
+        References[i].alignment_algo = alg_algo;
+#ifdef DEBUG_DETAIL_ON
+        std::string zw2 = "Alignment mode written: " + std::to_string(alg_algo);
+        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
+#endif
+    }
+
+    // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
+    if (References[0].alignment_algo != 3) {
+        return LoadReferenceAlignmentValues();
+    }
+
+    return true;
+}
+
+string ClassFlowAlignment::getHTMLSingleStep(string host)
+{
+    string result;
+
+    result = "<p>Rotated Image: </p> <p><img src=\"" + host + "/img_tmp/rot.jpg\"></p>\n";
+    result = result + "<p>Found Alignment: </p> <p><img src=\"" + host + "/img_tmp/rot_roi.jpg\"></p>\n";
+    result = result + "<p>Aligned Image: </p> <p><img src=\"" + host + "/img_tmp/alg.jpg\"></p>\n";
+    return result;
+}
+
+bool ClassFlowAlignment::doFlow(string time)
+{
+    if (ImageBasis == NULL || !ImageBasis->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Alignment has no valid source image");
+        return false;
+    }
+
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    // Reserve the optional JPEG output before tmpImage to reduce PSRAM fragmentation.
+    if (AlgROI == NULL) AlgROI = new (std::nothrow) ImageData;
+    if (AlgROI != NULL) {
+        ImageBasis->writeToMemoryAsJPG(AlgROI, 90);
+    } else {
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "AlgROI PSRAM allocation failed; continuing without in-memory ROI JPEG");
+        LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
+    }
+#endif
+
+    if (ImageTMP == NULL) {
+        ImageTMP = new (std::nothrow) CImageBasis("tmpImage", ImageBasis);
+        if (ImageTMP == NULL || !ImageTMP->ImageOkay()) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tmpImage -> Exec this round aborted!");
+            LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
+            delete ImageTMP;
+            ImageTMP = NULL;
+            return false;
+        }
+    }
+
+    delete AlignAndCutImage;
+    AlignAndCutImage = new (std::nothrow) CAlignAndCutImage("AlignAndCutImage", ImageBasis, ImageTMP);
+    if (AlignAndCutImage == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlignAndCutImage -> Exec this round aborted!");
+        LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
+        delete ImageTMP;
+        ImageTMP = NULL;
+        return false;
+    }
+
+    CRotateImage rt("rawImage", AlignAndCutImage, ImageTMP, initialflip);
+
+    if (initialflip) {
+        uint8_t* sourceImage = ImageBasis->RGBImageLock();
+        if (sourceImage == NULL) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to lock source image for initial flip");
+            delete AlignAndCutImage;
+            AlignAndCutImage = NULL;
+            delete ImageTMP;
+            ImageTMP = NULL;
+            return false;
+        }
+        uint8_t* temporaryImage = ImageTMP->RGBImageLock();
+        if (temporaryImage == NULL) {
+            ImageBasis->RGBImageRelease();
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to lock temporary image for initial flip");
+            delete AlignAndCutImage;
+            AlignAndCutImage = NULL;
+            delete ImageTMP;
+            ImageTMP = NULL;
+            return false;
+        }
+
+        int _zw = ImageBasis->height;
+        ImageBasis->height = ImageBasis->width;
+        ImageBasis->width = _zw;
+
+        _zw = ImageTMP->width;
+        ImageTMP->width = ImageTMP->height;
+        ImageTMP->height = _zw;
+
+        ImageTMP->RGBImageRelease();
+        ImageBasis->RGBImageRelease();
+    }
+
+    if ((initialrotate != 0) || initialflip) {
+        if (use_antialiasing) {
+            rt.RotateAntiAliasing(initialrotate);
+        }
+        else {
+            rt.Rotate(initialrotate);
+        }
+
+        if (SaveAllFiles) {
+            AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/rot.jpg"));
+        }
+    }
+
+    // no align algo if set to 3 = off //add disable aligment algo |01.2023
+    if (References[0].alignment_algo != 3) {
+        if (!AlignAndCutImage->Align(&References[0], &References[1])) {
+            SaveReferenceAlignmentValues();
+        }
+    } // no align
+
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    if (AlgROI) {
+        // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
+        if (References[0].alignment_algo != 3) {
+            DrawRef(ImageTMP);
+        }
+
+        flowctrl.DigitDrawROI(ImageTMP);
+        flowctrl.AnalogDrawROI(ImageTMP);
+        ImageTMP->writeToMemoryAsJPG((ImageData *)AlgROI, 90);
+    }
+#endif
+
+    if (SaveAllFiles) {
+        AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/alg.jpg"));
+        ImageTMP->SaveToFile(FormatFileName("/sdcard/img_tmp/alg_roi.jpg"));
+    }
+
+    // must be deleted to have memory space for loading tflite
+    delete ImageTMP;
+    ImageTMP = NULL;
+
+    // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
+    if (References[0].alignment_algo != 3) {
+        return LoadReferenceAlignmentValues();
+    }
+
+    return true;
+}
+
+void ClassFlowAlignment::SaveReferenceAlignmentValues()
+{
+    FILE *pFile;
+    std::string zwtime, zwvalue;
+
+    pFile = fopen(FileStoreRefAlignment.c_str(), "w");
+
+    if (pFile == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SaveReferenceAlignmentValues: Failed to open " + FileStoreRefAlignment);
+        return;
+    }
+
+    if (strlen(zwtime.c_str()) == 0) {
+        time_t rawtime;
+        struct tm *timeinfo;
+        char buffer[80];
+
+        time(&rawtime);
+        timeinfo = localtime(&rawtime);
+
+        strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S", timeinfo);
+        zwtime = std::string(buffer);
+    }
+
+    fputs(zwtime.c_str(), pFile);
+    fputs("\n", pFile);
+
+    zwvalue = std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_y);
+    zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
+    zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
+    fputs(zwvalue.c_str(), pFile);
+    fputs("\n", pFile);
+
+    zwvalue = std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_y);
+    zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
+    zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
+    fputs(zwvalue.c_str(), pFile);
+    fputs("\n", pFile);
+
+    fclose(pFile);
+}
+
+bool ClassFlowAlignment::LoadReferenceAlignmentValues(void)
+{
+    FILE *pFile;
+    char zw[1024];
+    string zwvalue;
+    std::vector<string> splitted;
+
+    pFile = fopen(FileStoreRefAlignment.c_str(), "r");
+
+    if (pFile == NULL) {
+        return false;
+    }
+
+    fgets(zw, 1024, pFile);
+    ESP_LOGD(TAG, "%s", zw);
+
+    fgets(zw, 1024, pFile);
+    splitted = ZerlegeZeile(std::string(zw), " \t");
+
+    if (splitted.size() < 6) {
+        fclose(pFile);
+        return false;
+    }
+
+    References[0].fastalg_x = stoi(splitted[0]);
+    References[0].fastalg_y = stoi(splitted[1]);
+    References[0].fastalg_SAD = stof(splitted[2]);
+    References[0].fastalg_min = stoi(splitted[3]);
+    References[0].fastalg_max = stoi(splitted[4]);
+    References[0].fastalg_avg = stof(splitted[5]);
+
+    fgets(zw, 1024, pFile);
+    splitted = ZerlegeZeile(std::string(zw));
+
+    if (splitted.size() < 6) {
+        fclose(pFile);
+        return false;
+    }
+
+    References[1].fastalg_x = stoi(splitted[0]);
+    References[1].fastalg_y = stoi(splitted[1]);
+    References[1].fastalg_SAD = stof(splitted[2]);
+    References[1].fastalg_min = stoi(splitted[3]);
+    References[1].fastalg_max = stoi(splitted[4]);
+    References[1].fastalg_avg = stof(splitted[5]);
+
+    fclose(pFile);
+
+    /*#ifdef DEBUG_DETAIL_ON
+        std::string _zw = "\tLoadReferences[0]\tx,y:\t" + std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_x);
+        _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
+        _zw = _zw + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
+        LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
+        _zw = "\tLoadReferences[1]\tx,y:\t" + std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_x);
+        _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
+        _zw = _zw + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
+        LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
+    #endif*/
+
+    return true;
+}
+
+void ClassFlowAlignment::DrawRef(CImageBasis *_zw)
+{
+    if (_zw->ImageOkay()) {
+        _zw->drawRect(References[0].target_x, References[0].target_y, References[0].width, References[0].height, 255, 0, 0, 2);
+        _zw->drawRect(References[1].target_x, References[1].target_y, References[1].width, References[1].height, 255, 0, 0, 2);
+    }
+}

+ 53 - 51
code/components/jomjol_flowcontroll/ClassFlowAlignment.h

@@ -1,51 +1,53 @@
-#pragma once
-
-#ifndef CLASSFLOWALIGNMENT_H
-#define CLASSFLOWALIGNMENT_H
-
-#include "ClassFlow.h"
-#include "Helper.h"
-#include "CAlignAndCutImage.h"
-#include "CFindTemplate.h"
-
-#include <string>
-
-using namespace std;
-
-class ClassFlowAlignment : public ClassFlow
-{
-protected:
-    float initialrotate;
-    bool initialflip;
-    bool use_antialiasing;
-    RefInfo References[2];
-    int anz_ref;
-    string namerawimage;
-    bool SaveAllFiles;
-    CAlignAndCutImage *AlignAndCutImage;
-    std::string FileStoreRefAlignment;
-    float SAD_criteria;
-
-    void SetInitialParameter(void);
-    bool LoadReferenceAlignmentValues(void);
-    void SaveReferenceAlignmentValues();
-
-public:
-    CImageBasis *ImageBasis, *ImageTMP;
-#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
-    ImageData *AlgROI;
-#endif
-
-    ClassFlowAlignment(std::vector<ClassFlow *> *lfc);
-
-    CAlignAndCutImage *GetAlignAndCutImage() { return AlignAndCutImage; };
-
-    void DrawRef(CImageBasis *_zw);
-
-    bool ReadParameter(FILE *pfile, string &aktparamgraph);
-    bool doFlow(string time);
-    string getHTMLSingleStep(string host);
-    string name() { return "ClassFlowAlignment"; };
-};
-
-#endif // CLASSFLOWALIGNMENT_H
+#pragma once
+
+#ifndef CLASSFLOWALIGNMENT_H
+#define CLASSFLOWALIGNMENT_H
+
+#include "ClassFlow.h"
+#include "Helper.h"
+#include "CAlignAndCutImage.h"
+#include "CFindTemplate.h"
+
+#include <string>
+
+using namespace std;
+
+class ClassFlowAlignment : public ClassFlow
+{
+protected:
+    float initialrotate;
+    bool initialflip;
+    bool use_antialiasing;
+    RefInfo References[2];
+    int anz_ref;
+    string namerawimage;
+    bool SaveAllFiles;
+    CAlignAndCutImage *AlignAndCutImage;
+    std::string FileStoreRefAlignment;
+    float SAD_criteria;
+    bool ownsImageBasis;
+
+    void SetInitialParameter(void);
+    bool LoadReferenceAlignmentValues(void);
+    void SaveReferenceAlignmentValues();
+
+public:
+    CImageBasis *ImageBasis, *ImageTMP;
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    ImageData *AlgROI;
+#endif
+
+    ClassFlowAlignment(std::vector<ClassFlow *> *lfc);
+    ~ClassFlowAlignment() override;
+
+    CAlignAndCutImage *GetAlignAndCutImage() { return AlignAndCutImage; };
+
+    void DrawRef(CImageBasis *_zw);
+
+    bool ReadParameter(FILE *pfile, string &aktparamgraph);
+    bool doFlow(string time);
+    string getHTMLSingleStep(string host);
+    string name() { return "ClassFlowAlignment"; };
+};
+
+#endif // CLASSFLOWALIGNMENT_H

+ 144 - 29
code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

@@ -1,7 +1,8 @@
 #include "ClassFlowCNNGeneral.h"
 
 #include <math.h>
-#include <iomanip> 
+#include <iomanip>
+#include <new> 
 #include <sys/types.h>
 #include <sstream>      // std::stringstream
 
@@ -37,6 +38,24 @@ ClassFlowCNNGeneral::ClassFlowCNNGeneral(ClassFlowAlignment *_flowalign, t_CNNTy
     imagesRetention = 5;
 }
 
+ClassFlowCNNGeneral::~ClassFlowCNNGeneral()
+{
+    for (general* sequence : GENERAL) {
+        if (sequence == NULL) continue;
+        for (roi* region : sequence->ROI) {
+            if (region == NULL) continue;
+            delete region->image;
+            region->image = NULL;
+            delete region->image_org;
+            region->image_org = NULL;
+            delete region;
+        }
+        sequence->ROI.clear();
+        delete sequence;
+    }
+    GENERAL.clear();
+}
+
 string ClassFlowCNNGeneral::getReadout(int _analog = 0, bool _extendedResolution, int prev, float _before_narrow_Analog, float AnalogToDigitTransitionStart, bool ContinuousLastDigit) {
     string result = "";    
 
@@ -386,6 +405,11 @@ bool ClassFlowCNNGeneral::ReadParameter(FILE* pfile, string& aktparamgraph) {
         
         if (splitted.size() >= 5) {
             general* _analog = GetGENERAL(splitted[0], true);
+            if (_analog == NULL || _analog->ROI.empty()) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to create ROI " + splitted[0]);
+                disabled = true;
+                return false;
+            }
             roi* neuroi = _analog->ROI[_analog->ROI.size()-1];
             neuroi->posx = std::stoi(splitted[1]);
             neuroi->posy = std::stoi(splitted[2]);
@@ -415,10 +439,20 @@ bool ClassFlowCNNGeneral::ReadParameter(FILE* pfile, string& aktparamgraph) {
 
     for (int _ana = 0; _ana < GENERAL.size(); ++_ana) {
         for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) {
-            GENERAL[_ana]->ROI[i]->image = new CImageBasis("ROI " + GENERAL[_ana]->ROI[i]->name, 
+            GENERAL[_ana]->ROI[i]->image = new (std::nothrow) CImageBasis("ROI " + GENERAL[_ana]->ROI[i]->name,
                     modelxsize, modelysize, modelchannel);
-            GENERAL[_ana]->ROI[i]->image_org = new CImageBasis("ROI " + GENERAL[_ana]->ROI[i]->name + " original",
+            GENERAL[_ana]->ROI[i]->image_org = new (std::nothrow) CImageBasis("ROI " + GENERAL[_ana]->ROI[i]->name + " original",
                     GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, 3);
+            if (GENERAL[_ana]->ROI[i]->image == NULL || GENERAL[_ana]->ROI[i]->image_org == NULL ||
+                !GENERAL[_ana]->ROI[i]->image->ImageOkay() || !GENERAL[_ana]->ROI[i]->image_org->ImageOkay()) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate ROI image buffers for " + GENERAL[_ana]->ROI[i]->name);
+                delete GENERAL[_ana]->ROI[i]->image;
+                GENERAL[_ana]->ROI[i]->image = NULL;
+                delete GENERAL[_ana]->ROI[i]->image_org;
+                GENERAL[_ana]->ROI[i]->image_org = NULL;
+                disabled = true;
+                return false;
+            }
         }
     }
 
@@ -462,14 +496,27 @@ general* ClassFlowCNNGeneral::GetGENERAL(string _name, bool _create = true) {
     }
 
     if (_ret == NULL) {
-        _ret = new general;
+        _ret = new (std::nothrow) general;
+        if (_ret == NULL) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GENERAL sequence");
+            return NULL;
+        }
         _ret->name = _analog;
         GENERAL.push_back(_ret);
     }
 
-    roi* neuroi = new roi;
+    roi* neuroi = new (std::nothrow) roi;
+    if (neuroi == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate ROI descriptor");
+        return NULL;
+    }
+    neuroi->image = NULL;
+    neuroi->image_org = NULL;
+    neuroi->result_float = -1;
+    neuroi->result_klasse = -1;
+    neuroi->isReject = true;
+    neuroi->CCW = false;
     neuroi->name = _roi;
-
     _ret->ROI.push_back(neuroi);
 
     ESP_LOGD(TAG, "GetGENERAL - GENERAL %s - roi %s - CCW: %d", _analog.c_str(), _roi.c_str(), neuroi->CCW);
@@ -535,39 +582,56 @@ bool ClassFlowCNNGeneral::doAlignAndCut(string time) {
         return true;
     }
 
-    CAlignAndCutImage *caic = flowpostalignment->GetAlignAndCutImage();    
+    if (flowpostalignment == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Alignment flow is unavailable");
+        return false;
+    }
+    CAlignAndCutImage *caic = flowpostalignment->GetAlignAndCutImage();
+    if (caic == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Aligned source image is unavailable");
+        return false;
+    }
 
     for (int _ana = 0; _ana < GENERAL.size(); ++_ana) {
         for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i) {
+            roi *region = GENERAL[_ana]->ROI[i];
+            if (region == NULL || region->image_org == NULL || region->image == NULL) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ROI image buffers are unavailable");
+                return false;
+            }
             ESP_LOGD(TAG, "General %d - Align&Cut", i);
-            
-            caic->CutAndSave(GENERAL[_ana]->ROI[i]->posx, GENERAL[_ana]->ROI[i]->posy, GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, GENERAL[_ana]->ROI[i]->image_org);
+
+            if (!caic->CutAndSave(region->posx, region->posy, region->deltax, region->deltay, region->image_org)) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ROI crop failed");
+                return false;
+            }
             if (SaveAllFiles) {
                 if (GENERAL[_ana]->name == "default") {
-                    GENERAL[_ana]->ROI[i]->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
+                    region->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + region->name + ".jpg"));
+                } else {
+                    region->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + region->name + ".jpg"));
                 }
-                else {
-                    GENERAL[_ana]->ROI[i]->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
-                }
-            } 
+            }
 
-            GENERAL[_ana]->ROI[i]->image_org->Resize(modelxsize, modelysize, GENERAL[_ana]->ROI[i]->image);
+            if (!region->image_org->Resize(modelxsize, modelysize, region->image)) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ROI resize failed");
+                return false;
+            }
             if (SaveAllFiles) {
                 if (GENERAL[_ana]->name == "default") {
-                    GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
+                    region->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + region->name + ".jpg"));
+                } else {
+                    region->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + region->name + ".jpg"));
                 }
-                else {
-                    GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
-                }
-            } 
+            }
         }
     }
-
     return true;
 } 
 
 void ClassFlowCNNGeneral::DrawROI(CImageBasis *_zw) {
-    if (_zw->ImageOkay()) { 
+    if (_zw == NULL || !_zw->ImageOkay()) return;
+    { 
         if (CNNType == Analogue || CNNType == Analogue100) {
             int r = 0;
             int g = 255;
@@ -597,7 +661,12 @@ bool ClassFlowCNNGeneral::getNetworkParameter() {
         return true;
     }
 
-    CTfLiteClass *tflite = new CTfLiteClass;  
+    CTfLiteClass *tflite = new (std::nothrow) CTfLiteClass;
+    if (tflite == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate CTfLiteClass object");
+        LogFile.WriteHeapInfo("CTfLiteClass object allocation");
+        return false;
+    }  
     string zwcnn = "/sdcard" + cnnmodelfile;
     zwcnn = FormatFileName(zwcnn);
     ESP_LOGD(TAG, "%s", zwcnn.c_str());
@@ -671,7 +740,12 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
 
     string logPath = CreateLogFolder(time);
 
-    CTfLiteClass *tflite = new CTfLiteClass;  
+    CTfLiteClass *tflite = new (std::nothrow) CTfLiteClass;
+    if (tflite == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate CTfLiteClass object");
+        LogFile.WriteHeapInfo("CTfLiteClass object allocation");
+        return false;
+    }  
     string zwcnn = "/sdcard" + cnnmodelfile;
     zwcnn = FormatFileName(zwcnn);
     ESP_LOGD(TAG, "%s", zwcnn.c_str());
@@ -704,8 +778,19 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                     {
                         float f1 = 0, f2 = 0;
 
-                        tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);        
+                        if (!tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image)) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CNN input image could not be copied into Tensor Arena");
+                            continue;
+                        }
                         tflite->Invoke();
+                        if (!tflite->LastInvokeSucceeded()) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite inference failed");
+                            continue;
+                        }
                         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "After Invoke");
 
                         f1 = tflite->GetOutputValue(0);
@@ -728,8 +813,12 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                 case Digit:
                     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CNN Type: Digit");
                     {
-                        GENERAL[n]->ROI[roi]->result_klasse = 0;
                         GENERAL[n]->ROI[roi]->result_klasse = tflite->GetClassFromImageBasis(GENERAL[n]->ROI[roi]->image);
+                        if (GENERAL[n]->ROI[roi]->result_klasse < 0) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Digit inference failed for ROI " + GENERAL[n]->ROI[roi]->name);
+                            continue;
+                        }
                         ESP_LOGD(TAG, "General result (Digit)%i: %d", roi, GENERAL[n]->ROI[roi]->result_klasse);
 
                         if (isLogImage) {
@@ -753,8 +842,19 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                         float _fit;
                         float _result_save_file;
 
-                        tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);        
+                        if (!tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image)) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CNN input image could not be copied into Tensor Arena");
+                            continue;
+                        }
                         tflite->Invoke();
+                        if (!tflite->LastInvokeSucceeded()) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite inference failed");
+                            continue;
+                        }
                         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "After Invoke");
 
                         _num = tflite->GetOutClassification(0, 9);
@@ -824,8 +924,19 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                         int _num;
                         float _result_save_file;
                         
-                        tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);        
+                        if (!tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image)) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CNN input image could not be copied into Tensor Arena");
+                            continue;
+                        }
                         tflite->Invoke();
+                        if (!tflite->LastInvokeSucceeded()) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite inference failed");
+                            continue;
+                        }
     
                         _num = tflite->GetOutClassification();
                         
@@ -890,7 +1001,11 @@ std::vector<HTMLInfo*> ClassFlowCNNGeneral::GetHTMLInfo() {
                 }
             }
 
-            HTMLInfo *zw = new HTMLInfo;
+            HTMLInfo *zw = new (std::nothrow) HTMLInfo;
+            if (zw == NULL) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate ROI HTML metadata");
+                continue;
+            }
             if (GENERAL[_ana]->name == "default") {
                 zw->filename = GENERAL[_ana]->ROI[i]->name + ".jpg";
                 zw->filename_org = GENERAL[_ana]->ROI[i]->name + ".jpg";

+ 1 - 0
code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.h

@@ -47,6 +47,7 @@ protected:
 
 public:
     ClassFlowCNNGeneral(ClassFlowAlignment *_flowalign, t_CNNType _cnntype = AutoDetect);
+    ~ClassFlowCNNGeneral() override;
 
     bool ReadParameter(FILE* pfile, string& aktparamgraph);
     bool doFlow(string time);

+ 58 - 36
code/components/jomjol_flowcontroll/ClassFlowControll.cpp

@@ -6,6 +6,7 @@
 #include "freertos/task.h"
 
 #include <sys/stat.h>
+#include <new>
 
 #ifdef __cplusplus
 extern "C" {
@@ -204,14 +205,36 @@ bool ClassFlowControll::StartMQTTService()
 }
 #endif //ENABLE_MQTT
 
+ClassFlowControll::ClassFlowControll()
+{
+    SetInitialParameter();
+}
+
+ClassFlowControll::~ClassFlowControll()
+{
+    // Destroy dependants before the flows they reference (PostProcessing, CNN,
+    // Alignment, then TakeImage), so borrowed image pointers remain valid.
+    for (auto it = FlowControll.rbegin(); it != FlowControll.rend(); ++it) {
+        delete *it;
+    }
+    FlowControll.clear();
+    flowpostprocessing = NULL;
+    flowdigit = NULL;
+    flowanalog = NULL;
+    flowalignment = NULL;
+    flowtakeimage = NULL;
+}
+
 void ClassFlowControll::SetInitialParameter(void)
 {
     AutoStart = true;
     SetupModeActive = false;
-    AutoInterval = 10; // Minutes
+    AutoInterval = 10;
     flowdigit = NULL;
     flowanalog = NULL;
     flowpostprocessing = NULL;
+    flowalignment = NULL;
+    flowtakeimage = NULL;
     disabled = false;
     aktRunNr = 0;
     setStatus("Flow task not yet created", "Flow task not yet created");
@@ -235,55 +258,57 @@ ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
     _type = trim(_type);
 
     if (toUpper(_type).compare("[TAKEIMAGE]") == 0) {
-        cfc = new ClassFlowTakeImage(&FlowControll);
+        cfc = new (std::nothrow) ClassFlowTakeImage(&FlowControll);
         flowtakeimage = (ClassFlowTakeImage*) cfc;
     }
 	
     if (toUpper(_type).compare("[ALIGNMENT]") == 0) {
-        cfc = new ClassFlowAlignment(&FlowControll);
+        cfc = new (std::nothrow) ClassFlowAlignment(&FlowControll);
         flowalignment = (ClassFlowAlignment*) cfc;
     }
 	
     if (toUpper(_type).compare("[ANALOG]") == 0) {
-        cfc = new ClassFlowCNNGeneral(flowalignment);
+        cfc = new (std::nothrow) ClassFlowCNNGeneral(flowalignment);
         flowanalog = (ClassFlowCNNGeneral*) cfc;
     }
 	
     if (toUpper(_type).compare(0, 7, "[DIGITS") == 0) {
-        cfc = new ClassFlowCNNGeneral(flowalignment);
+        cfc = new (std::nothrow) ClassFlowCNNGeneral(flowalignment);
         flowdigit = (ClassFlowCNNGeneral*) cfc;
     }
 	
     #ifdef ENABLE_MQTT
         if (toUpper(_type).compare("[MQTT]") == 0) {
-            cfc = new ClassFlowMQTT(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowMQTT(&FlowControll);
         }
     #endif //ENABLE_MQTT
 	
     #ifdef ENABLE_INFLUXDB
         if (toUpper(_type).compare("[INFLUXDB]") == 0) {
-            cfc = new ClassFlowInfluxDB(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowInfluxDB(&FlowControll);
         }
 
         if (toUpper(_type).compare("[INFLUXDBV2]") == 0) {
-            cfc = new ClassFlowInfluxDBv2(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowInfluxDBv2(&FlowControll);
         }
     #endif //ENABLE_INFLUXDB
 	
     #ifdef ENABLE_WEBHOOK
         if (toUpper(_type).compare("[WEBHOOK]") == 0) {
-            cfc = new ClassFlowWebhook(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowWebhook(&FlowControll);
         }
     #endif //ENABLE_WEBHOOK
 
     if (toUpper(_type).compare("[POSTPROCESSING]") == 0) {
-        cfc = new ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit); 
+        cfc = new (std::nothrow) ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit); 
         flowpostprocessing = (ClassFlowPostProcessing*) cfc;
     }
 
-    if (cfc) {                           
-        // Attached only if it is not [AutoTimer], because this is for FlowControll
+    if (cfc) {
         FlowControll.push_back(cfc);
+    } else if (_type != "[AUTOTIMER]" && _type != "[DATALOGGING]" &&
+               _type != "[DEBUG]" && _type != "[SYSTEM]") {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate flow component " + _type);
     }
 
     if (toUpper(_type).compare("[AUTOTIMER]") == 0) {
@@ -684,9 +709,9 @@ int ClassFlowControll::CleanTempFolder() {
     return 0;
 }
 
-esp_err_t ClassFlowControll::SendRawJPG(httpd_req_t *req)
+esp_err_t ClassFlowControll::SendRawJPG(httpd_req_t *req, bool previewCapture)
 {
-    return flowtakeimage != NULL ? flowtakeimage->SendRawJPG(req) : ESP_FAIL;
+    return flowtakeimage != NULL ? flowtakeimage->SendRawJPG(req, previewCapture) : ESP_FAIL;
 }
 
 esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
@@ -702,7 +727,7 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
     bool _sendDelete = false;
 
     if (_fn == "alg.jpg") {
-        if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
+        if (flowalignment && flowalignment->ImageBasis && flowalignment->ImageBasis->ImageOkay()) {
             _send = flowalignment->ImageBasis;
         }
         else {
@@ -807,7 +832,7 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 }
                 else {
                     LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg_roi.jpg cannot be served -> alg.jpg is going to be served!");
-                    if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
+                    if (flowalignment && flowalignment->ImageBasis && flowalignment->ImageBasis->ImageOkay()) {
                         _send = flowalignment->ImageBasis;
                     }
                     else {
@@ -817,13 +842,14 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 }
             }
             else {
-                if (flowalignment && flowalignment->AlgROI) {
+                if (flowalignment && flowalignment->AlgROI &&
+                    flowalignment->AlgROI->size > 0 && flowalignment->AlgROI->size <= MAX_JPG_SIZE) {
                     httpd_resp_set_type(req, "image/jpeg");
                     result = httpd_resp_send(req, (const char *)flowalignment->AlgROI->data, flowalignment->AlgROI->size);
                 }
                 else {
-                    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg_roi.jpg cannot be served -> alg.jpg is going to be served!");
-                    if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
+                    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg_roi.jpg is unavailable -> alg.jpg is going to be served!");
+                    if (flowalignment && flowalignment->ImageBasis && flowalignment->ImageBasis->ImageOkay()) {
                         _send = flowalignment->ImageBasis;
                     }
                     else {
@@ -839,26 +865,22 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 return ESP_FAIL;
             }
 
-            _send = new CImageBasis("alg_roi", flowalignment->ImageBasis);
-			
-            if (_send->ImageOkay()) {
-                if (flowalignment) { flowalignment->DrawRef(_send); }
-                if (flowdigit) { flowdigit->DrawROI(_send); }
-                if (flowanalog) { flowanalog->DrawROI(_send); }
-                _sendDelete = true; // delete temporary _send element after sending
+            if (flowalignment->ImageBasis == NULL || !flowalignment->ImageBasis->ImageOkay()) {
+                httpd_resp_send(req, NULL, 0);
+                return ESP_FAIL;
             }
-            else {
+            _send = new (std::nothrow) CImageBasis("alg_roi", flowalignment->ImageBasis);
+
+            if (_send != NULL && _send->ImageOkay()) {
+                flowalignment->DrawRef(_send);
+                if (flowdigit) flowdigit->DrawROI(_send);
+                if (flowanalog) flowanalog->DrawROI(_send);
+                _sendDelete = true;
+            } else {
                 LogFile.WriteToFile(ESP_LOG_WARN, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create alg_roi.jpg -> alg.jpg is going to be served!");
                 delete _send;
-                _send = NULL;
-
-                if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
-                    _send = flowalignment->ImageBasis;
-                }
-                else {
-                    httpd_resp_send(req, NULL, 0);
-                    return ESP_OK;
-                }
+                _send = flowalignment->ImageBasis;
+                _sendDelete = false;
             }
         #endif
     }

+ 3 - 1
code/components/jomjol_flowcontroll/ClassFlowControll.h

@@ -46,6 +46,8 @@ protected:
 	int aktRunNr;
 
 public:
+	ClassFlowControll();
+	~ClassFlowControll() override;
 	bool SetupModeActive;
 
 	void InitFlow(std::string config);
@@ -69,7 +71,7 @@ public:
 	#endif
 
 	esp_err_t GetJPGStream(std::string _fn, httpd_req_t *req);
-	esp_err_t SendRawJPG(httpd_req_t *req);
+	esp_err_t SendRawJPG(httpd_req_t *req, bool previewCapture);
 
 	std::string doSingleStep(std::string _stepname, std::string _host);
 

+ 77 - 60
code/components/jomjol_flowcontroll/ClassFlowTakeImage.cpp

@@ -1,9 +1,12 @@
 #include <iostream>
 #include <string>
+#include <limits.h>
+#include <algorithm>
 #include <vector>
 #include <regex>
 
 #include "ClassFlowTakeImage.h"
+#include <new>
 #include "Helper.h"
 #include "ClassLogFile.h"
 
@@ -23,33 +26,31 @@
 
 static const char *TAG = "TAKEIMAGE";
 
-esp_err_t ClassFlowTakeImage::camera_capture(void)
-{
-    string nm = namerawimage;
-    Camera.CaptureToFile(nm);
-    time(&TimeImageTaken);
-    localtime(&TimeImageTaken);
 
-    return ESP_OK;
-}
-
-void ClassFlowTakeImage::takePictureWithFlash(int flash_duration)
+bool ClassFlowTakeImage::takePictureWithFlash(int flash_duration)
 {
-    // in case the image is flipped, it must be reset here //
-    rawImage->width = CCstatus.ImageWidth;
-    rawImage->height = CCstatus.ImageHeight;
+    if (rawImage == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "takePictureWithFlash: raw image object is unavailable");
+        return false;
+    }
+    const CameraSettings &activeSettings = static_cast<const CameraSettings &>(CCstatus);
+    if (rawImage->width != activeSettings.ImageWidth || rawImage->height != activeSettings.ImageHeight ||
+        rawImage->channels != 3) {
+        rawImage->CreateEmptyImage(activeSettings.ImageWidth, activeSettings.ImageHeight, 3);
+    }
+    if (!rawImage->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "takePictureWithFlash: raw image PSRAM buffer is unavailable");
+        return false;
+    }
 
     ESP_LOGD(TAG, "flash_duration: %d", flash_duration);
-
-    Camera.CaptureToBasisImage(rawImage, flash_duration);
+    if (Camera.CaptureToBasisImage(rawImage, flash_duration) != ESP_OK) return false;
 
     time(&TimeImageTaken);
     localtime(&TimeImageTaken);
 
-    if (CCstatus.SaveAllFiles)
-    {
-        rawImage->SaveToFile(namerawimage);
-    }
+    if (CCstatus.SaveAllFiles) rawImage->SaveToFile(namerawimage);
+    return true;
 }
 
 void ClassFlowTakeImage::SetInitialParameter(void)
@@ -112,14 +113,15 @@ bool ClassFlowTakeImage::ReadParameter(FILE *pfile, string &aktparamgraph)
             if (isStringNumeric(splitted[1]))
             {
                 int _WaitBeforePicture = std::stoi(splitted[1]);
-                if (_WaitBeforePicture != 0)
-                {
-                    CCstatus.WaitBeforePicture = _WaitBeforePicture;
-                }
-                else
-                {
-                    CCstatus.WaitBeforePicture = 2;
-                }
+                CCstatus.WaitBeforePicture = (_WaitBeforePicture != 0) ? max(0, _WaitBeforePicture) : 2;
+            }
+        }
+
+        else if ((toUpper(splitted[0]) == "CAMXCLKFREQMHZ") && (splitted.size() > 1))
+        {
+            if (isStringNumeric(splitted[1]))
+            {
+                CCstatus.CamXclkFreqMhz = clipInt(std::stoi(splitted[1]), 20, 1);
             }
         }
 
@@ -514,11 +516,25 @@ bool ClassFlowTakeImage::ReadParameter(FILE *pfile, string &aktparamgraph)
         }
     }
 
-    Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
-    Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
+    if (Camera.ApplySettings(CCstatus) != ESP_OK)
+    {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to apply configured camera settings");
+        return false;
+    }
 
-    rawImage = new CImageBasis("rawImage");
+    delete rawImage;
+    rawImage = new (std::nothrow) CImageBasis("rawImage");
+    if (rawImage == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate raw image object");
+        return false;
+    }
     rawImage->CreateEmptyImage(CCstatus.ImageWidth, CCstatus.ImageHeight, 3);
+    if (!rawImage->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate raw image PSRAM buffer");
+        delete rawImage;
+        rawImage = NULL;
+        return false;
+    }
 
     return true;
 }
@@ -540,30 +556,32 @@ string ClassFlowTakeImage::getHTMLSingleStep(string host)
 // wird bei jeder Auswertrunde aufgerufen
 bool ClassFlowTakeImage::doFlow(string zwtime)
 {
-    psram_init_shared_memory_for_take_image_step();
+    const bool sharedMemoryLeaseAcquired = psram_init_shared_memory_for_take_image_step();
+    if (!sharedMemoryLeaseAcquired) {
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared PSRAM image lease unavailable; STBI will use independent PSRAM allocations");
+    }
 
     string logPath = CreateLogFolder(zwtime);
 
-    int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
+    const CameraSettings &activeSettings = static_cast<const CameraSettings &>(CCstatus);
+    int flash_duration = static_cast<int>(activeSettings.WaitBeforePicture * 1000);
 
 #ifdef DEBUG_DETAIL_ON
     LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - Before takePictureWithFlash");
 #endif
 
-#ifdef WIFITURNOFF
-    esp_wifi_stop(); // to save power usage and
-#endif
-
-    // wenn die Kameraeinstellungen durch Erstellen eines neuen Referenzbildes verändert wurden, müssen sie neu gesetzt werden
-    if (CFstatus.changedCameraSettings)
+    if (Camera.RestoreCommittedSettingsIfNeeded() != ESP_OK)
     {
-        Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
-        Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
-        Camera.LedIntensity = CCstatus.ImageLedIntensity;
-        CFstatus.changedCameraSettings = false;
+        if (sharedMemoryLeaseAcquired) psram_deinit_shared_memory_for_take_image_step();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to restore committed camera settings");
+        return false;
     }
 
-    takePictureWithFlash(flash_duration);
+#ifdef WIFITURNOFF
+    esp_wifi_stop(); // save power during image capture
+#endif
+
+    const bool captured = takePictureWithFlash(flash_duration);
 
 #ifdef WIFITURNOFF
     esp_wifi_start();
@@ -573,6 +591,12 @@ bool ClassFlowTakeImage::doFlow(string zwtime)
     LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After takePictureWithFlash");
 #endif
 
+    if (!captured) {
+        if (sharedMemoryLeaseAcquired) psram_deinit_shared_memory_for_take_image_step();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image capture failed; aborting this flow round");
+        return false;
+    }
+
     LogImage(logPath, "raw", NULL, NULL, zwtime, rawImage);
 
     RemoveOldLogs();
@@ -581,34 +605,27 @@ bool ClassFlowTakeImage::doFlow(string zwtime)
     LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After RemoveOldLogs");
 #endif
 
-    psram_deinit_shared_memory_for_take_image_step();
+    if (sharedMemoryLeaseAcquired) psram_deinit_shared_memory_for_take_image_step();
 
     return true;
 }
 
-esp_err_t ClassFlowTakeImage::SendRawJPG(httpd_req_t *req)
+esp_err_t ClassFlowTakeImage::SendRawJPG(httpd_req_t *req, bool previewCapture)
 {
-    int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
     time(&TimeImageTaken);
     localtime(&TimeImageTaken);
 
-    return Camera.CaptureToHTTP(req, flash_duration);
-}
-
-ImageData *ClassFlowTakeImage::SendRawImage(void)
-{
-    CImageBasis *zw = new CImageBasis("SendRawImage", rawImage);
-    ImageData *id;
-    int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
-    Camera.CaptureToBasisImage(zw, flash_duration);
-    time(&TimeImageTaken);
-    localtime(&TimeImageTaken);
+    if (previewCapture)
+    {
+        return Camera.CaptureToHTTP(req, 0, true);
+    }
 
-    id = zw->writeToMemoryAsJPG();
-    delete zw;
-    return id;
+    const int waitSeconds = std::max(0, CCstatus.WaitBeforePicture);
+    const int flashDuration = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
+    return Camera.CaptureToHTTP(req, flashDuration);
 }
 
+
 time_t ClassFlowTakeImage::getTimeImageTaken(void)
 {
     return TimeImageTaken;

+ 2 - 4
code/components/jomjol_flowcontroll/ClassFlowTakeImage.h

@@ -15,8 +15,7 @@ protected:
     time_t TimeImageTaken;
     string namerawimage;
 
-    esp_err_t camera_capture(void);
-    void takePictureWithFlash(int flash_duration);
+    bool takePictureWithFlash(int flash_duration);
 
     void SetInitialParameter(void);
 
@@ -31,8 +30,7 @@ public:
     time_t getTimeImageTaken(void);
     string name() { return "ClassFlowTakeImage"; };
 
-    ImageData *SendRawImage(void);
-    esp_err_t SendRawJPG(httpd_req_t *req);
+    esp_err_t SendRawJPG(httpd_req_t *req, bool previewCapture);
 
     ~ClassFlowTakeImage(void);
 };

+ 126 - 257
code/components/jomjol_flowcontroll/MainFlowControl.cpp

@@ -1,4 +1,5 @@
 #include "MainFlowControl.h"
+#include <new>
 
 #include <string>
 #include <vector>
@@ -89,9 +90,9 @@ esp_err_t GetJPG(std::string _filename, httpd_req_t *req)
     return flowctrl.GetJPGStream(_filename, req);
 }
 
-esp_err_t GetRawJPG(httpd_req_t *req)
+esp_err_t GetRawJPG(httpd_req_t *req, bool previewCapture)
 {
-    return flowctrl.SendRawJPG(req);
+    return flowctrl.SendRawJPG(req, previewCapture);
 }
 
 bool isSetupModusActive(void)
@@ -151,166 +152,6 @@ bool doflow(void)
     return true;
 }
 
-esp_err_t setCCstatusToCFstatus(void)
-{
-    CFstatus.CamSensor_id = CCstatus.CamSensor_id;
-
-    CFstatus.ImageFrameSize = CCstatus.ImageFrameSize;
-
-    CFstatus.ImageContrast = CCstatus.ImageContrast;
-    CFstatus.ImageBrightness = CCstatus.ImageBrightness;
-    CFstatus.ImageSaturation = CCstatus.ImageSaturation;
-
-    CFstatus.ImageQuality = CCstatus.ImageQuality;
-
-    CFstatus.ImageGainceiling = CCstatus.ImageGainceiling;
-
-    CFstatus.ImageAgc = CCstatus.ImageAgc;
-    CFstatus.ImageAec = CCstatus.ImageAec;
-    CFstatus.ImageHmirror = CCstatus.ImageHmirror;
-    CFstatus.ImageVflip = CCstatus.ImageVflip;
-
-    CFstatus.ImageAwb = CCstatus.ImageAwb;
-    CFstatus.ImageAec2 = CCstatus.ImageAec2;
-    CFstatus.ImageAecValue = CCstatus.ImageAecValue;
-    CFstatus.ImageSpecialEffect = CCstatus.ImageSpecialEffect;
-    CFstatus.ImageWbMode = CCstatus.ImageWbMode;
-    CFstatus.ImageAeLevel = CCstatus.ImageAeLevel;
-
-    CFstatus.ImageDcw = CCstatus.ImageDcw;
-    CFstatus.ImageBpc = CCstatus.ImageBpc;
-    CFstatus.ImageWpc = CCstatus.ImageWpc;
-    CFstatus.ImageAwbGain = CCstatus.ImageAwbGain;
-    CFstatus.ImageAgcGain = CCstatus.ImageAgcGain;
-
-    CFstatus.ImageRawGma = CCstatus.ImageRawGma;
-    CFstatus.ImageLenc = CCstatus.ImageLenc;
-
-    CFstatus.ImageSharpness = CCstatus.ImageSharpness;
-    CFstatus.ImageAutoSharpness = CCstatus.ImageAutoSharpness;
-
-    CFstatus.ImageDenoiseLevel = CCstatus.ImageDenoiseLevel;
-
-    CFstatus.ImageLedIntensity = CCstatus.ImageLedIntensity;
-
-    CFstatus.ImageZoomEnabled = CCstatus.ImageZoomEnabled;
-    CFstatus.ImageZoomOffsetX = CCstatus.ImageZoomOffsetX;
-    CFstatus.ImageZoomOffsetY = CCstatus.ImageZoomOffsetY;
-    CFstatus.ImageZoomSize = CCstatus.ImageZoomSize;
-
-    CFstatus.WaitBeforePicture = CCstatus.WaitBeforePicture;
-
-    return ESP_OK;
-}
-
-esp_err_t setCFstatusToCCstatus(void)
-{
-    // CCstatus.CamSensor_id = CFstatus.CamSensor_id;
-
-    CCstatus.ImageFrameSize = CFstatus.ImageFrameSize;
-
-    CCstatus.ImageContrast = CFstatus.ImageContrast;
-    CCstatus.ImageBrightness = CFstatus.ImageBrightness;
-    CCstatus.ImageSaturation = CFstatus.ImageSaturation;
-
-    CCstatus.ImageQuality = CFstatus.ImageQuality;
-
-    CCstatus.ImageGainceiling = CFstatus.ImageGainceiling;
-
-    CCstatus.ImageAgc = CFstatus.ImageAgc;
-    CCstatus.ImageAec = CFstatus.ImageAec;
-    CCstatus.ImageHmirror = CFstatus.ImageHmirror;
-    CCstatus.ImageVflip = CFstatus.ImageVflip;
-
-    CCstatus.ImageAwb = CFstatus.ImageAwb;
-    CCstatus.ImageAec2 = CFstatus.ImageAec2;
-    CCstatus.ImageAecValue = CFstatus.ImageAecValue;
-    CCstatus.ImageSpecialEffect = CFstatus.ImageSpecialEffect;
-    CCstatus.ImageWbMode = CFstatus.ImageWbMode;
-    CCstatus.ImageAeLevel = CFstatus.ImageAeLevel;
-
-    CCstatus.ImageDcw = CFstatus.ImageDcw;
-    CCstatus.ImageBpc = CFstatus.ImageBpc;
-    CCstatus.ImageWpc = CFstatus.ImageWpc;
-    CCstatus.ImageAwbGain = CFstatus.ImageAwbGain;
-    CCstatus.ImageAgcGain = CFstatus.ImageAgcGain;
-
-    CCstatus.ImageRawGma = CFstatus.ImageRawGma;
-    CCstatus.ImageLenc = CFstatus.ImageLenc;
-
-    CCstatus.ImageSharpness = CFstatus.ImageSharpness;
-    CCstatus.ImageAutoSharpness = CFstatus.ImageAutoSharpness;
-
-    CCstatus.ImageDenoiseLevel = CFstatus.ImageDenoiseLevel;
-
-    CCstatus.ImageLedIntensity = CFstatus.ImageLedIntensity;
-
-    CCstatus.ImageZoomEnabled = CFstatus.ImageZoomEnabled;
-    CCstatus.ImageZoomOffsetX = CFstatus.ImageZoomOffsetX;
-    CCstatus.ImageZoomOffsetY = CFstatus.ImageZoomOffsetY;
-    CCstatus.ImageZoomSize = CFstatus.ImageZoomSize;
-
-    CCstatus.WaitBeforePicture = CFstatus.WaitBeforePicture;
-
-    return ESP_OK;
-}
-
-esp_err_t setCFstatusToCam(void)
-{
-    sensor_t *s = esp_camera_sensor_get();
-
-    if (s != NULL)
-    {
-        s->set_framesize(s, CFstatus.ImageFrameSize);
-
-        // s->set_contrast(s, CFstatus.ImageContrast);     // -2 to 2
-        // s->set_brightness(s, CFstatus.ImageBrightness); // -2 to 2
-        Camera.SetCamContrastBrightness(s, CFstatus.ImageContrast, CFstatus.ImageBrightness);
-		
-        s->set_saturation(s, CFstatus.ImageSaturation); // -2 to 2
-
-        s->set_quality(s, CFstatus.ImageQuality); // 0 - 63
-
-        // s->set_gainceiling(s, CFstatus.ImageGainceiling); // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
-        Camera.SetCamGainceiling(s, CFstatus.ImageGainceiling);
-
-        s->set_gain_ctrl(s, CFstatus.ImageAgc);     // 0 = disable , 1 = enable
-        s->set_exposure_ctrl(s, CFstatus.ImageAec); // 0 = disable , 1 = enable
-        s->set_hmirror(s, CFstatus.ImageHmirror);   // 0 = disable , 1 = enable
-        s->set_vflip(s, CFstatus.ImageVflip);       // 0 = disable , 1 = enable
-
-        s->set_whitebal(s, CFstatus.ImageAwb);       // 0 = disable , 1 = enable
-        s->set_aec2(s, CFstatus.ImageAec2);          // 0 = disable , 1 = enable
-        s->set_aec_value(s, CFstatus.ImageAecValue); // 0 to 1200
-        // s->set_special_effect(s, CFstatus.ImageSpecialEffect); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)
-        Camera.SetCamSpecialEffect(s, CFstatus.ImageSpecialEffect);
-        s->set_wb_mode(s, CFstatus.ImageWbMode);   // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
-        s->set_ae_level(s, CFstatus.ImageAeLevel); // -2 to 2
-
-        s->set_dcw(s, CFstatus.ImageDcw);          // 0 = disable , 1 = enable
-        s->set_bpc(s, CFstatus.ImageBpc);          // 0 = disable , 1 = enable
-        s->set_wpc(s, CFstatus.ImageWpc);          // 0 = disable , 1 = enable
-        s->set_awb_gain(s, CFstatus.ImageAwbGain); // 0 = disable , 1 = enable
-        s->set_agc_gain(s, CFstatus.ImageAgcGain); // 0 to 30
-
-        s->set_raw_gma(s, CFstatus.ImageRawGma); // 0 = disable , 1 = enable
-        s->set_lenc(s, CFstatus.ImageLenc);      // 0 = disable , 1 = enable
-
-        // s->set_sharpness(s, CFstatus.ImageSharpness);   // auto-sharpness is not officially supported, default to 0
-        Camera.SetCamSharpness(CFstatus.ImageAutoSharpness, CFstatus.ImageSharpness);
-        s->set_denoise(s, CFstatus.ImageDenoiseLevel); // The OV2640 does not support it, OV3660 and OV5640 (0 to 8)
-
-        TickType_t xDelay2 = 100 / portTICK_PERIOD_MS;
-        vTaskDelay(xDelay2);
-
-        return ESP_OK;
-    }
-    else
-    {
-        return ESP_FAIL;
-    }
-}
-
 esp_err_t handler_get_heap(httpd_req_t *req)
 {
 #ifdef DEBUG_DETAIL_ON
@@ -939,22 +780,28 @@ esp_err_t handler_editflow(httpd_req_t *req)
         {
             LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Taking image for Alignment Mark Update...");
 
-            CAlignAndCutImage *caic = new CAlignAndCutImage("cutref", in);
-            caic->CutAndSave(out2, x, y, dx, dy);
-            delete caic;
-
-            CImageBasis *cim = new CImageBasis("cutref", out2);
-
-            if (enhance)
-            {
-                cim->Contrast(90);
+            bool operationOk = false;
+            CAlignAndCutImage *caic = new (std::nothrow) CAlignAndCutImage("cutref", in);
+            if (caic != NULL) {
+                caic->CutAndSave(out2, x, y, dx, dy);
+                delete caic;
+
+                CImageBasis *cim = new (std::nothrow) CImageBasis("cutref", out2);
+                if (cim != NULL && cim->ImageOkay()) {
+                    if (enhance) cim->Contrast(90);
+                    cim->SaveToFile(out);
+                    operationOk = true;
+                }
+                delete cim;
+            }
+            if (operationOk) zw = "CutImage Done";
+            else {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Alignment mark update failed due to an allocation or image I/O error");
+                zw = "CutImage Failed";
             }
 
-            cim->SaveToFile(out);
-            delete cim;
-
+            // Release only after every STBI-backed temporary image has been destroyed.
             psram_deinit_shared_memory_for_take_image_step();
-            zw = "CutImage Done";
         }
         else
         {
@@ -975,20 +822,37 @@ esp_err_t handler_editflow(httpd_req_t *req)
         {
             std::string _host = "";
 
-            // laden der aktuellen Kameraeinstellungen(CCstatus) in den Zwischenspeicher(CFstatus)
-            setCCstatusToCFstatus(); // CCstatus >>> CFstatus
+            // CFstatus is only used as the temporary settings copy for test_take.
+            const bool isTestTake = (_task.compare("test_take") == 0);
+            CameraSettings *settingsTarget = &static_cast<CameraSettings &>(CCstatus);
+            if (isTestTake)
+            {
+                static_cast<CameraSettings &>(CFstatus) =
+                    static_cast<const CameraSettings &>(CCstatus);
+                settingsTarget = &static_cast<CameraSettings &>(CFstatus);
+            }
+            CameraSettings &settings = *settingsTarget;
 
             if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK)
             {
                 _host = std::string(_valuechar);
             }
 
+            if (httpd_query_key_value(_query, "xclk", _valuechar, 30) == ESP_OK)
+            {
+                std::string _xclk = std::string(_valuechar);
+                if (isStringNumeric(_xclk))
+                {
+                    settings.CamXclkFreqMhz = clipInt(std::stoi(_xclk), 20, 1);
+                }
+            }
+
             if (httpd_query_key_value(_query, "waitb", _valuechar, 30) == ESP_OK)
             {
                 std::string _waitb = std::string(_valuechar);
                 if (isStringNumeric(_waitb))
                 {
-                    CFstatus.WaitBeforePicture = std::stoi(_valuechar);
+                    settings.WaitBeforePicture = std::max(0, std::stoi(_valuechar));
                 }
             }
 
@@ -1001,49 +865,49 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     switch (_aecgc_)
                     {
                         case 1:
-                            CFstatus.ImageGainceiling = GAINCEILING_4X; 
+                            settings.ImageGainceiling = GAINCEILING_4X; 
                             break;
                         case 2:
-                            CFstatus.ImageGainceiling = GAINCEILING_8X; 
+                            settings.ImageGainceiling = GAINCEILING_8X; 
                             break;
                         case 3:
-                            CFstatus.ImageGainceiling = GAINCEILING_16X; 
+                            settings.ImageGainceiling = GAINCEILING_16X; 
                             break;
                         case 4:
-                            CFstatus.ImageGainceiling = GAINCEILING_32X; 
+                            settings.ImageGainceiling = GAINCEILING_32X; 
                             break;
                         case 5:
-                            CFstatus.ImageGainceiling = GAINCEILING_64X; 
+                            settings.ImageGainceiling = GAINCEILING_64X; 
                             break;
                         case 6:
-                            CFstatus.ImageGainceiling = GAINCEILING_128X; 
+                            settings.ImageGainceiling = GAINCEILING_128X; 
                             break;
                         default:
-                            CFstatus.ImageGainceiling = GAINCEILING_2X;
+                            settings.ImageGainceiling = GAINCEILING_2X;
                     }
                 }
                 else
                 {
                     if (_aecgc == "X4") {
-                        CFstatus.ImageGainceiling = GAINCEILING_4X;
+                        settings.ImageGainceiling = GAINCEILING_4X;
                     }
                     else if (_aecgc == "X8") {
-                        CFstatus.ImageGainceiling = GAINCEILING_8X;
+                        settings.ImageGainceiling = GAINCEILING_8X;
                     }
                     else if (_aecgc == "X16") {
-                        CFstatus.ImageGainceiling = GAINCEILING_16X;
+                        settings.ImageGainceiling = GAINCEILING_16X;
                     }
                     else if (_aecgc == "X32") {
-                        CFstatus.ImageGainceiling = GAINCEILING_32X;
+                        settings.ImageGainceiling = GAINCEILING_32X;
                     }
                     else if (_aecgc == "X64") {
-                        CFstatus.ImageGainceiling = GAINCEILING_64X;
+                        settings.ImageGainceiling = GAINCEILING_64X;
                     }
                     else if (_aecgc == "X128") {
-                        CFstatus.ImageGainceiling = GAINCEILING_128X;
+                        settings.ImageGainceiling = GAINCEILING_128X;
                     }
                     else {
-                        CFstatus.ImageGainceiling = GAINCEILING_2X;
+                        settings.ImageGainceiling = GAINCEILING_2X;
                     }
                 }
             }
@@ -1054,7 +918,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_qual))
                 {
                     int _qual_ = std::stoi(_valuechar);
-                    CFstatus.ImageQuality = clipInt(_qual_, 63, 6);
+                    settings.ImageQuality = clipInt(_qual_, 63, 6);
                 }
             }
 
@@ -1064,7 +928,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_bri))
                 {
                     int _bri_ = std::stoi(_valuechar);
-                    CFstatus.ImageBrightness = clipInt(_bri_, 2, -2);
+                    settings.ImageBrightness = clipInt(_bri_, 2, -2);
                 }
             }
 
@@ -1074,7 +938,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_con))
                 {
                     int _con_ = std::stoi(_valuechar);
-                    CFstatus.ImageContrast = clipInt(_con_, 2, -2);
+                    settings.ImageContrast = clipInt(_con_, 2, -2);
                 }
             }
 
@@ -1084,7 +948,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_sat))
                 {
                     int _sat_ = std::stoi(_valuechar);
-                    CFstatus.ImageSaturation = clipInt(_sat_, 2, -2);
+                    settings.ImageSaturation = clipInt(_sat_, 2, -2);
                 }
             }
 
@@ -1096,11 +960,11 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     int _shp_ = std::stoi(_valuechar);
                     if (CCstatus.CamSensor_id == OV2640_PID)
                     {
-                        CFstatus.ImageSharpness = clipInt(_shp_, 2, -2);
+                        settings.ImageSharpness = clipInt(_shp_, 2, -2);
                     }
                     else
                     {
-                        CFstatus.ImageSharpness = clipInt(_shp_, 3, -3);
+                        settings.ImageSharpness = clipInt(_shp_, 3, -3);
                     }
                 }
             }
@@ -1108,7 +972,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
             if (httpd_query_key_value(_query, "ashp", _valuechar, 30) == ESP_OK)
             {
                 std::string _ashp = std::string(_valuechar);
-                CFstatus.ImageAutoSharpness = alphanumericToBoolean(_ashp);
+                settings.ImageAutoSharpness = alphanumericToBoolean(_ashp);
             }
 
             if (httpd_query_key_value(_query, "spe", _valuechar, 30) == ESP_OK)
@@ -1117,30 +981,30 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_spe))
                 {
                     int _spe_ = std::stoi(_valuechar);
-                    CFstatus.ImageSpecialEffect = clipInt(_spe_, 6, 0);
+                    settings.ImageSpecialEffect = clipInt(_spe_, 6, 0);
                 }
                 else
                 {
                     if (_spe == "negative") {
-                        CFstatus.ImageSpecialEffect = 1;
+                        settings.ImageSpecialEffect = 1;
                     }
                     else if (_spe == "grayscale") {
-                        CFstatus.ImageSpecialEffect = 2;
+                        settings.ImageSpecialEffect = 2;
                     }
                     else if (_spe == "red") {
-                        CFstatus.ImageSpecialEffect = 3;
+                        settings.ImageSpecialEffect = 3;
                     }
                     else if (_spe == "green") {
-                        CFstatus.ImageSpecialEffect = 4;
+                        settings.ImageSpecialEffect = 4;
                     }
                     else if (_spe == "blue") {
-                        CFstatus.ImageSpecialEffect = 5;
+                        settings.ImageSpecialEffect = 5;
                     }
                     else if (_spe == "retro") {
-                        CFstatus.ImageSpecialEffect = 6;
+                        settings.ImageSpecialEffect = 6;
                     }
                     else {
-                        CFstatus.ImageSpecialEffect = 0;
+                        settings.ImageSpecialEffect = 0;
                     }
                 }
             }
@@ -1151,24 +1015,24 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_wbm))
                 {
                     int _wbm_ = std::stoi(_valuechar);
-                    CFstatus.ImageWbMode = clipInt(_wbm_, 4, 0);
+                    settings.ImageWbMode = clipInt(_wbm_, 4, 0);
                 }
                 else
                 {
                     if (_wbm == "sunny") {
-                        CFstatus.ImageWbMode = 1;
+                        settings.ImageWbMode = 1;
                     }
                     else if (_wbm == "cloudy") {
-                        CFstatus.ImageWbMode = 2;
+                        settings.ImageWbMode = 2;
                     }
                     else if (_wbm == "office") {
-                        CFstatus.ImageWbMode = 3;
+                        settings.ImageWbMode = 3;
                     }
                     else if (_wbm == "home") {
-                        CFstatus.ImageWbMode = 4;
+                        settings.ImageWbMode = 4;
                     }
                     else {
-                        CFstatus.ImageWbMode = 0;
+                        settings.ImageWbMode = 0;
                     }
                 }
             }
@@ -1176,25 +1040,25 @@ esp_err_t handler_editflow(httpd_req_t *req)
             if (httpd_query_key_value(_query, "awb", _valuechar, 30) == ESP_OK)
             {
                 std::string _awb = std::string(_valuechar);
-                CFstatus.ImageAwb = alphanumericToBoolean(_awb);
+                settings.ImageAwb = alphanumericToBoolean(_awb);
             }
 
             if (httpd_query_key_value(_query, "awbg", _valuechar, 30) == ESP_OK)
             {
                 std::string _awbg = std::string(_valuechar);
-                CFstatus.ImageAwbGain = alphanumericToBoolean(_awbg);
+                settings.ImageAwbGain = alphanumericToBoolean(_awbg);
             }
 
             if (httpd_query_key_value(_query, "aec", _valuechar, 30) == ESP_OK)
             {
                 std::string _aec = std::string(_valuechar);
-                CFstatus.ImageAec = alphanumericToBoolean(_aec);
+                settings.ImageAec = alphanumericToBoolean(_aec);
             }
 
             if (httpd_query_key_value(_query, "aec2", _valuechar, 30) == ESP_OK)
             {
                 std::string _aec2 = std::string(_valuechar);
-                CFstatus.ImageAec2 = alphanumericToBoolean(_aec2);
+                settings.ImageAec2 = alphanumericToBoolean(_aec2);
             }
 
             if (httpd_query_key_value(_query, "ael", _valuechar, 30) == ESP_OK)
@@ -1205,11 +1069,11 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     int _ael_ = std::stoi(_valuechar);
                     if (CCstatus.CamSensor_id == OV2640_PID)
                     {
-                        CFstatus.ImageAeLevel = clipInt(_ael_, 2, -2);
+                        settings.ImageAeLevel = clipInt(_ael_, 2, -2);
                     }
                     else
                     {
-                        CFstatus.ImageAeLevel = clipInt(_ael_, 5, -5);
+                        settings.ImageAeLevel = clipInt(_ael_, 5, -5);
                     }
                 }
             }
@@ -1220,14 +1084,14 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_aecv))
                 {
                     int _aecv_ = std::stoi(_valuechar);
-                    CFstatus.ImageAecValue = clipInt(_aecv_, 1200, 0);
+                    settings.ImageAecValue = clipInt(_aecv_, 1200, 0);
                 }
             }
 
             if (httpd_query_key_value(_query, "agc", _valuechar, 30) == ESP_OK)
             {
                 std::string _agc = std::string(_valuechar);
-                CFstatus.ImageAgc = alphanumericToBoolean(_agc);
+                settings.ImageAgc = alphanumericToBoolean(_agc);
             }
 
             if (httpd_query_key_value(_query, "agcg", _valuechar, 30) == ESP_OK)
@@ -1236,50 +1100,50 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_agcg))
                 {
                     int _agcg_ = std::stoi(_valuechar);
-                    CFstatus.ImageAgcGain = clipInt(_agcg_, 30, 0);
+                    settings.ImageAgcGain = clipInt(_agcg_, 30, 0);
                 }
             }
 
             if (httpd_query_key_value(_query, "bpc", _valuechar, 30) == ESP_OK)
             {
                 std::string _bpc = std::string(_valuechar);
-                CFstatus.ImageBpc = alphanumericToBoolean(_bpc);
+                settings.ImageBpc = alphanumericToBoolean(_bpc);
             }
 
             if (httpd_query_key_value(_query, "wpc", _valuechar, 30) == ESP_OK)
             {
                 std::string _wpc = std::string(_valuechar);
-                CFstatus.ImageWpc = alphanumericToBoolean(_wpc);
+                settings.ImageWpc = alphanumericToBoolean(_wpc);
             }
 
             if (httpd_query_key_value(_query, "rgma", _valuechar, 30) == ESP_OK)
             {
                 std::string _rgma = std::string(_valuechar);
-                CFstatus.ImageRawGma = alphanumericToBoolean(_rgma);
+                settings.ImageRawGma = alphanumericToBoolean(_rgma);
             }
 
             if (httpd_query_key_value(_query, "lenc", _valuechar, 30) == ESP_OK)
             {
                 std::string _lenc = std::string(_valuechar);
-                CFstatus.ImageLenc = alphanumericToBoolean(_lenc);
+                settings.ImageLenc = alphanumericToBoolean(_lenc);
             }
 
             if (httpd_query_key_value(_query, "mirror", _valuechar, 30) == ESP_OK)
             {
                 std::string _mirror = std::string(_valuechar);
-                CFstatus.ImageHmirror = alphanumericToBoolean(_mirror);
+                settings.ImageHmirror = alphanumericToBoolean(_mirror);
             }
 
             if (httpd_query_key_value(_query, "flip", _valuechar, 30) == ESP_OK)
             {
                 std::string _flip = std::string(_valuechar);
-                CFstatus.ImageVflip = alphanumericToBoolean(_flip);
+                settings.ImageVflip = alphanumericToBoolean(_flip);
             }
 
             if (httpd_query_key_value(_query, "dcw", _valuechar, 30) == ESP_OK)
             {
                 std::string _dcw = std::string(_valuechar);
-                CFstatus.ImageDcw = alphanumericToBoolean(_dcw);
+                settings.ImageDcw = alphanumericToBoolean(_dcw);
             }
 
             if (httpd_query_key_value(_query, "den", _valuechar, 30) == ESP_OK)
@@ -1290,11 +1154,11 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     int _ImageDenoiseLevel = std::stoi(_valuechar);
                     if (CCstatus.CamSensor_id == OV2640_PID)
                     {
-                        CFstatus.ImageDenoiseLevel = 0;
+                        settings.ImageDenoiseLevel = 0;
                     }
                     else
                     {
-                        CFstatus.ImageDenoiseLevel = clipInt(_ImageDenoiseLevel, 8, 0);
+                        settings.ImageDenoiseLevel = clipInt(_ImageDenoiseLevel, 8, 0);
                     }
                 }
             }
@@ -1302,7 +1166,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
             if (httpd_query_key_value(_query, "zoom", _valuechar, 30) == ESP_OK)
             {
                 std::string _zoom = std::string(_valuechar);
-                CFstatus.ImageZoomEnabled = alphanumericToBoolean(_zoom);
+                settings.ImageZoomEnabled = alphanumericToBoolean(_zoom);
             }
 
             if (httpd_query_key_value(_query, "zoomx", _valuechar, 30) == ESP_OK)
@@ -1313,15 +1177,15 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     int _ImageZoomOffsetX = std::stoi(_valuechar);
                     if (CCstatus.CamSensor_id == OV2640_PID)
                     {
-                        CFstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 480, -480);
+                        settings.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 480, -480);
                     }
                     else if (CCstatus.CamSensor_id == OV3660_PID)
                     {
-                        CFstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 704, -704);
+                        settings.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 704, -704);
                     }
                     else if (CCstatus.CamSensor_id == OV5640_PID)
                     {
-                        CFstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 960, -960);
+                        settings.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 960, -960);
                     }
                 }
             }
@@ -1334,15 +1198,15 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     int _ImageZoomOffsetY = std::stoi(_valuechar);
                     if (CCstatus.CamSensor_id == OV2640_PID)
                     {
-                        CFstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 360, -360);
+                        settings.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 360, -360);
                     }
                     else if (CCstatus.CamSensor_id == OV3660_PID)
                     {
-                        CFstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 528, -528);
+                        settings.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 528, -528);
                     }
                     else if (CCstatus.CamSensor_id == OV5640_PID)
                     {
-                        CFstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 720, -720);
+                        settings.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 720, -720);
                     }
                 }
             }
@@ -1355,15 +1219,15 @@ esp_err_t handler_editflow(httpd_req_t *req)
                     int _ImageZoomSize = std::stoi(_valuechar);
                     if (CCstatus.CamSensor_id == OV2640_PID)
                     {
-                        CFstatus.ImageZoomSize = clipInt(_ImageZoomSize, 29, 0);
+                        settings.ImageZoomSize = clipInt(_ImageZoomSize, 29, 0);
                     }
                     else if (CCstatus.CamSensor_id == OV3660_PID)
                     {
-                        CFstatus.ImageZoomSize = clipInt(_ImageZoomSize, 43, 0);
+                        settings.ImageZoomSize = clipInt(_ImageZoomSize, 43, 0);
                     }
                     else if (CCstatus.CamSensor_id == OV5640_PID)
                     {
-                        CFstatus.ImageZoomSize = clipInt(_ImageZoomSize, 59, 0);
+                        settings.ImageZoomSize = clipInt(_ImageZoomSize, 59, 0);
                     }
                 }
             }
@@ -1374,17 +1238,18 @@ esp_err_t handler_editflow(httpd_req_t *req)
                 if (isStringNumeric(_ledi))
                 {
                     int _ImageLedIntensity = std::stoi(_valuechar);
-                    CFstatus.ImageLedIntensity = Camera.SetLEDIntensity(_ImageLedIntensity);
+                    settings.ImageLedIntensity = Camera.SetLEDIntensity(_ImageLedIntensity);
                 }
             }
 
-            if (_task.compare("cam_settings") == 0)
+            if (!isTestTake)
             {
-                // wird aufgerufen, wenn das Referenzbild + Kameraeinstellungen gespeichert wurden
-                setCFstatusToCCstatus(); // CFstatus >>> CCstatus
-
-                // Kameraeinstellungen wurden verädert
-                CFstatus.changedCameraSettings = true;
+                // Saved camera settings are committed in CCstatus.
+                if (Camera.setSensorDatenFromCCstatus() != ESP_OK)
+                {
+                    httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Could not apply committed camera settings");
+                    return ESP_FAIL;
+                }
 
                 ESP_LOGD(TAG, "Cam Settings set");
                 std::string _zw = "CamSettingsSet";
@@ -1393,18 +1258,22 @@ esp_err_t handler_editflow(httpd_req_t *req)
             }
             else
             {
-                // wird aufgerufen, wenn ein neues Referenzbild erstellt oder aktualisiert wurde
-                // CFstatus >>> Kamera
-                setCFstatusToCam();
-
-                Camera.SetQualityZoomSize(CFstatus.ImageQuality, CFstatus.ImageFrameSize, CFstatus.ImageZoomEnabled, CFstatus.ImageZoomOffsetX, CFstatus.ImageZoomOffsetY, CFstatus.ImageZoomSize, CFstatus.ImageVflip);
-                // Camera.SetZoomSize(CFstatus.ImageZoomEnabled, CFstatus.ImageZoomOffsetX, CFstatus.ImageZoomOffsetY, CFstatus.ImageZoomSize, CFstatus.ImageVflip);
-
-                // Kameraeinstellungen wurden verädert
-                CFstatus.changedCameraSettings = true;
+                // Only test_take applies temporary camera settings.
+                if (Camera.ApplyPreviewSettings(settings) != ESP_OK)
+                {
+                    httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Could not apply temporary camera settings");
+                    return ESP_FAIL;
+                }
 
                 ESP_LOGD(TAG, "test_take - vor TakeImage");
                 std::string image_temp = flowctrl.doSingleStep("[TakeImage]", _host);
+                const std::string rawImagePath = "/img_tmp/raw.jpg";
+                const std::size_t rawImagePosition = image_temp.find(rawImagePath);
+                if (rawImagePosition != std::string::npos)
+                {
+                    image_temp.replace(rawImagePosition, rawImagePath.length(),
+                                       rawImagePath + "?preview=1");
+                }
                 httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
                 httpd_resp_send(req, image_temp.c_str(), image_temp.length());
             }

+ 4 - 54
code/components/jomjol_flowcontroll/MainFlowControl.h

@@ -9,66 +9,16 @@
 #include <esp_http_server.h>
 #include "CImageBasis.h"
 #include "ClassFlowControll.h"
+#include "CameraSettings.h"
 #include "openmetrics.h"
 
-typedef struct
+struct camera_flow_config_temp_t : public CameraSettings
 {
-    uint16_t CamSensor_id;
-
-    framesize_t ImageFrameSize = FRAMESIZE_VGA; // 0 - 10
-    gainceiling_t ImageGainceiling;             // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
-
-    int ImageQuality;    // 0 - 63
-    int ImageBrightness; // (-2 to 2) - set brightness
-    int ImageContrast;   //-2 - 2
-    int ImageSaturation; //-2 - 2
-    int ImageSharpness;  //-2 - 2
-    bool ImageAutoSharpness;
-    int ImageSpecialEffect; // 0 - 6
-    int ImageWbMode;        // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
-    int ImageAwb;           // white balance enable (0 or 1)
-    int ImageAwbGain;       // Auto White Balance enable (0 or 1)
-    int ImageAec;           // auto exposure off (1 or 0)
-    int ImageAec2;          // automatic exposure sensor  (0 or 1)
-    int ImageAeLevel;       // auto exposure levels (-2 to 2)
-    int ImageAecValue;      // set exposure manually  (0-1200)
-    int ImageAgc;           // auto gain off (1 or 0)
-    int ImageAgcGain;       // set gain manually (0 - 30)
-    int ImageBpc;           // black pixel correction
-    int ImageWpc;           // white pixel correction
-    int ImageRawGma;        // (1 or 0)
-    int ImageLenc;          // lens correction (1 or 0)
-    int ImageHmirror;       // (0 or 1) flip horizontally
-    int ImageVflip;         // Invert image (0 or 1)
-    int ImageDcw;           // downsize enable (1 or 0)
-
-    int ImageDenoiseLevel; // The OV2640 does not support it, OV3660 and OV5640 (0 to 8)
-
-    int ImageWidth;
-    int ImageHeight;
-
-    int ImageLedIntensity;
-
-    bool ImageZoomEnabled;
-    int ImageZoomOffsetX;
-    int ImageZoomOffsetY;
-    int ImageZoomSize;
-
-    int WaitBeforePicture;
-    bool isImageSize;
-
-    bool CameraInitSuccessful;
-    bool changedCameraSettings;
-    bool DemoMode;
-    bool SaveAllFiles;
-} camera_flow_config_temp_t;
+};
 
 extern camera_flow_config_temp_t CFstatus;
 extern ClassFlowControll flowctrl;
 
-esp_err_t setCCstatusToCFstatus(void); // CCstatus >>> CFstatus
-esp_err_t setCFstatusToCCstatus(void); // CFstatus >>> CCstatus
-esp_err_t setCFstatusToCam(void);      // CFstatus >>> Kamera
 
 void register_server_main_flow_task_uri(httpd_handle_t server);
 
@@ -85,7 +35,7 @@ int getCountFlowRounds(void);
 esp_err_t MQTTCtrlFlowStart(std::string _topic);
 #endif // ENABLE_MQTT
 
-esp_err_t GetRawJPG(httpd_req_t *req);
+esp_err_t GetRawJPG(httpd_req_t *req, bool previewCapture = false);
 esp_err_t GetJPG(std::string _filename, httpd_req_t *req);
 
 #endif // MAINFLOWCONTROL_H

+ 1 - 145
code/components/jomjol_helper/Helper.cpp

@@ -92,10 +92,6 @@ size_t getESPHeapSize()
 	return heap_caps_get_free_size(MALLOC_CAP_8BIT);
 }
 
-size_t getInternalESPHeapSize()
-{
-	return heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
-}
 
 string getSDCardPartitionSize()
 {
@@ -180,139 +176,12 @@ string getSDCardSectorSize()
 
 ///////////////////////////////////////////////////////////////////////////////////////////////
 
-bool copy_string(char *dst, size_t dst_size, const char *src)
-{
-	if (dst == nullptr || src == nullptr || dst_size == 0)
-	{
-		return false;
-	}
-
-	size_t len = strlen(src);
-
-	if (len >= dst_size)
-	{
-		dst[0] = '\0';
-		return false; // Target too small
-	}
-
-	memcpy(dst, src, len + 1);
-	return true;
-}
-
-void mem_copy(uint8_t *_target, uint8_t *_source, int _size)
-{
-	if ((_target != nullptr) && (_source != nullptr) && (_size > 0))
-	{
-		uint8_t *dst = _target;
-		uint8_t *src = _source;
-
-		for (int i = 0; i < _size; ++i)
-		{
-			*dst++ = *src++;
-		}
-	}
-}
-
-void mem_copy32(void *_target, const void *_source, size_t _size)
-{
-	if ((_target != nullptr) && (_source != nullptr) && (_size > 0))
-	{
-		uint32_t *d32 = (uint32_t *)_target;
-		const uint32_t *s32 = (const uint32_t *)_source;
-
-		size_t words = _size / 4;
-
-		for (size_t i = 0; i < words; i++)
-		{
-			d32[i] = s32[i];
-		}
-
-		// Copy remaining bytes
-		uint8_t *d8 = (uint8_t *)(d32 + words);
-		const uint8_t *s8 = (const uint8_t *)(s32 + words);
-
-		for (size_t i = 0; i < (_size % 4); i++)
-		{
-			d8[i] = s8[i];
-		}
-	}
-}
-
-float fast_atan2(float y, float x)
-{
-	float abs_y = fabs(y) + 1e-10;
-	float r = (x - abs_y) / (x + abs_y);
-	float angle = 0.78539816339 - 0.78539816339 * r;
-	return (y < 0) ? -angle : angle;
-}
 
-double pow10_double(int pot)
-{
-	static const double pow10_table[] = {
-		1.0,
-		10.0,
-		100.0,
-		1000.0,
-		10000.0,
-		100000.0,
-		1000000.0,
-		10000000.0,
-		100000000.0,
-		1000000000.0};
-
-	if (pot >= 0 && pot < (int)(sizeof(pow10_table) / sizeof(pow10_table[0])))
-	{
-		return pow10_table[pot];
-	}
 
-	// Fallback if pot is larger
-	double result = 1.0;
-	for (int i = 0; i < pot; ++i)
-	{
-		result *= 10.0;
-	}
 
-	return result;
-}
 
-uint32_t pow10_int(int pot)
-{
-	// Lookup table for small exponents 0-9
-	static const uint32_t table[] = {
-		1,		   // 10^0
-		10,		   // 10^1
-		100,	   // 10^2
-		1000,	   // 10^3
-		10000,	   // 10^4
-		100000,	   // 10^5
-		1000000,   // 10^6
-		10000000,  // 10^7
-		100000000, // 10^8
-		1000000000 // 10^9
-	};
-
-	if (pot >= 0 && pot < (int)(sizeof(table) / sizeof(table[0])))
-	{
-		return table[pot];
-	}
 
-	// Fallback for larger pot
-	uint32_t result = 1;
-	for (int i = 0; i < pot; ++i)
-	{
-		result *= 10;
-	}
 
-	return result;
-}
-
-void memCopyGen(uint8_t *_source, uint8_t *_target, int _size)
-{
-	for (int i = 0; i < _size; ++i)
-	{
-		*(_target + i) = *(_source + i);
-	}
-}
 
 std::string FormatFileName(std::string input)
 {
@@ -545,20 +414,6 @@ bool FileExists(string filename)
 	return true;
 }
 
-bool FolderExists(string foldername)
-{
-	DIR *fpSourceFolder = opendir(foldername.c_str());
-
-	// Sourcefolder does not exist
-	if (!fpSourceFolder)
-	{
-		return false;
-	}
-
-	closedir(fpSourceFolder);
-
-	return true;
-}
 
 bool DeleteFile(string filename)
 {
@@ -1194,6 +1049,7 @@ string RundeOutput(double _in, int _anzNachkomma)
 	return stream.str();
 }
 
+
 string getMac(void)
 {
 	uint8_t macInt[6];

+ 3 - 14
code/components/jomjol_helper/Helper.h

@@ -21,7 +21,6 @@ bool RenameFile(string from, string to);
 bool RenameFolder(string from, string to);
 bool MakeDir(std::string _what);
 bool FileExists(string filename);
-bool FolderExists(string foldername);
 
 string RundeOutput(double _in, int _anzNachkomma);
 
@@ -45,21 +44,11 @@ float temperatureRead();
 std::string intToHexString(int _valueInt);
 time_t addDays(time_t startTime, int days);
 
-bool copy_string(char *dst, size_t dst_size, const char *src);
-void mem_copy(uint8_t *_target, uint8_t *_source, int _size);
-void mem_copy32(void *_target, const void *_source, size_t size);
-float fast_atan2(float y, float x);
-
-double pow10_double(int pot); // faster than pow(10, pot)
-uint32_t pow10_int(int pot);  // faster than pow(10, pot)
-
-void memCopyGen(uint8_t* _source, uint8_t* _target, int _size);
-
 std::vector<string> HelperZerlegeZeile(std::string input, std::string _delimiter);
 std::vector<std::string> ZerlegeZeile(std::string input, std::string delimiter = " =, \t");
 
 ///////////////////////////
-size_t getInternalESPHeapSize();
+
 size_t getESPHeapSize();
 string getESPHeapInfo();
 
@@ -75,8 +64,6 @@ string getSDCardName();
 string getSDCardCapacity();
 string getSDCardSectorSize();
 
-string getMac(void);
-
 /* Error bit fields
    One bit per error
    Make sure it matches https://jomjol.github.io/AI-on-the-edge-device-docs/Error-Codes */
@@ -120,4 +107,6 @@ int clipInt(int input, int high, int low);
 bool numericStrToBool(std::string input);
 bool stringToBoolean(std::string input);
 
+string getMac(void);
+
 #endif //HELPER_H

+ 146 - 179
code/components/jomjol_helper/esp_sys.cpp

@@ -1,179 +1,146 @@
-#include "../../include/defines.h"
-
-#ifdef DEBUG_ENABLE_SYSINFO
-
-#include "esp_sys.h"
-#include "esp_chip_info.h"
-
-#include <string>
-
-
-#include "esp_chip_info.h"
-
-
-void Restart() {
-    esp_restart();
-}
-
-//source : https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/misc_system_api.html#_CPPv416esp_chip_model_t
-
-//https://github.com/espressif/esp-idf/blob/8464186e67e34b417621df6b6f1f289a6c60b859/components/esp_hw_support/include/esp_chip_info.h
-/*
-typedef enum {
-    CHIP_ESP32  = 1, //!< ESP32
-    CHIP_ESP32S2 = 2, //!< ESP32-S2
-    CHIP_ESP32S3 = 9, //!< ESP32-S3
-    CHIP_ESP32C3 = 5, //!< ESP32-C3
-    CHIP_ESP32H4 = 6, //!< ESP32-H4
-    CHIP_ESP32C2 = 12, //!< ESP32-C2
-    CHIP_ESP32C6 = 13, //!< ESP32-C6
-    CHIP_ESP32H2 = 16, //!< ESP32-H2
-    CHIP_POSIX_LINUX = 999, //!< The code is running on POSIX/Linux simulator
-} esp_chip_model_t;
-*/
-
-char* GetChipModel(){
-    esp_chip_info_t chipInfo;
-    esp_chip_info(&chipInfo);
-    switch((int)chipInfo.model) {
-        case 0 : return (char*)"ESP8266";
-        case (int)esp_chip_model_t::CHIP_ESP32 : return (char*)"ESP32";
-#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)        
-        case (int)esp_chip_model_t::CHIP_ESP32S2 : return (char*)"ESP32-S2";
-        case (int)esp_chip_model_t::CHIP_ESP32S3 : return (char*)"ESP32-S3";
-        case (int)esp_chip_model_t::CHIP_ESP32C3 : return (char*)"ESP32-C3";
-        case 6 : return (char*)"ESP32-H4";
-        case 12 : return (char*)"ESP32-C2";
-        case 13 : return (char*)"ESP32-C6";
-        //case (int)esp_chip_model_t::CHIP_ESP32H4 : return (char*)"ESP32-H4";
-        //case (int)esp_chip_model_t::CHIP_ESP32C2 : return (char*)"ESP32-C2";
-        //case (int)esp_chip_model_t::CHIP_ESP32C6 : return (char*)"ESP32-C6";
-        //case (int)esp_chip_model_t::CHIP_ESP32H2 : return (char*)"ESP32-H2";
-        case 16 : return (char*)"ESP32-H2";
-        //case (int)esp_chip_model_t::CHIP_POSIX_LINUX : return (char*)"CHIP_POSIX_LINUX";
-
-#endif
-    }
-    return (char*)"Chip Unknown";
-}
-
-uint8_t GetChipCoreCount() {
-    esp_chip_info_t chipInfo;
-    esp_chip_info(&chipInfo);
-    return chipInfo.cores;
-}
-
-uint16_t GetChipRevision() {
-    esp_chip_info_t chipInfo;
-    esp_chip_info(&chipInfo);
-    return chipInfo.revision;
-}
-
-uint32_t  GetChipfeatures() {
-    esp_chip_info_t chipInfo;
-    esp_chip_info(&chipInfo);
-    return chipInfo.features;
-}
-
-
-uint32_t GetFreeHeap() {
-    return esp_get_free_heap_size();
-}
-
-uint32_t GetLeastHeapFreeSinceBoot() {
-    return esp_get_minimum_free_heap_size();
-}
-
-
-std::string get_device_info()
-{
-    esp_chip_info_t chip_info;
-    esp_chip_info(&chip_info);
-    
-    std::string espInfoResultStr = "";
-    char aMsgBuf[40];
-
-    espInfoResultStr += "Device Info:";
-    espInfoResultStr += "---------------\n";
-    espInfoResultStr += "Chip Model: " + std::string(GetChipModel()) +"\n";
-    sprintf(aMsgBuf,"Chip Revision: %d\n", chip_info.revision);
-    espInfoResultStr += std::string(aMsgBuf);
-    sprintf(aMsgBuf,"CPU Cores: %d\n", chip_info.cores);
-    espInfoResultStr += std::string(aMsgBuf);
-    sprintf(aMsgBuf,"Flash Memory: %dMB\n", spi_flash_get_chip_size()/(1024*1024));
-    espInfoResultStr += std::string(aMsgBuf);
-    if(chip_info.features & CHIP_FEATURE_WIFI_BGN)
-        //espInfoResultStr += "Base MAC: " + std::string(getMac()) +"\n";
-        espInfoResultStr += "ESP-IDF version: " + std::string(esp_get_idf_version()) +"\n";
-    if((chip_info.features & CHIP_FEATURE_WIFI_BGN) || (chip_info.features & CHIP_FEATURE_BT) ||
-       (chip_info.features & CHIP_FEATURE_BLE) || (chip_info.features & CHIP_FEATURE_EMB_FLASH))
-    {
-        espInfoResultStr += "Characteristics:\n";
-        if(chip_info.features & CHIP_FEATURE_WIFI_BGN)
-            espInfoResultStr += "    WiFi 2.4GHz\n";
-        if(chip_info.features & CHIP_FEATURE_BT)
-            espInfoResultStr += "    Bluetooth Classic\n";
-        if(chip_info.features & CHIP_FEATURE_BLE)
-            espInfoResultStr += "    Bluetooth Low Energy\n";
-        if(chip_info.features & CHIP_FEATURE_EMB_FLASH)
-            espInfoResultStr += "    Embedded Flash memory\n";
-        else
-           espInfoResultStr += "    External Flash memory\n";
-    }
-
-    #ifdef USE_HIMEM_IF_AVAILABLE
-        sprintf(aMsgBuf,"spiram size %u\n", esp_psram_get_size());
-        espInfoResultStr += std::string(aMsgBuf);
-        sprintf(aMsgBuf,"himem free %u\n", esp_himem_get_free_size());
-        espInfoResultStr += std::string(aMsgBuf);
-        sprintf(aMsgBuf,"himem phys %u\n", esp_himem_get_phys_size());
-        espInfoResultStr += std::string(aMsgBuf);
-        sprintf(aMsgBuf,"himem reserved %u\n", esp_himem_reserved_area_size());
-        espInfoResultStr += std::string(aMsgBuf);
-    #endif
-    
-    return espInfoResultStr; 
-}
-
-
-size_t getFreeMemoryInternal(){ //Current Free Memory
-    return heap_caps_get_free_size(MALLOC_CAP_8BIT) - heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
-}
-
-size_t getFreeMemorySPIRAM(){ //Current Free Memory
-    return heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
-}
-
-
-size_t getLargestFreeBlockInternal(){ //Largest Free Block
-    return heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
-}
-
-size_t getLargestFreeBlockSPIRAM(){ //Largest Free Block
-    return heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM);
-}
-
-
-size_t getMinEverFreeMemInternal(){ //Min. Ever Free Size
-    return heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
-}
-
-size_t getMinEverFreeMemSPIRAM(){ //Min. Ever Free Size
-    return heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM);
-}
-
-#ifdef USE_HIMEM_IF_AVAILABLE
-    size_t getHimemTotSpace(){ 
-        return esp_himem_get_phys_size();
-    }
-
-    size_t getHimemFreeSpace(){ 
-        return esp_himem_get_free_size();
-    }
-
-    size_t getHimemReservedArea(){ 
-        return esp_himem_reserved_area_size();
-    }
-#endif
-
-#endif //DEBUG_ENABLE_SYSINFO
+#include "../../include/defines.h"
+
+#ifdef DEBUG_ENABLE_SYSINFO
+
+#include "esp_sys.h"
+#include "esp_chip_info.h"
+
+#include <string>
+
+
+#include "esp_chip_info.h"
+
+
+void Restart() {
+    esp_restart();
+}
+
+//source : https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/misc_system_api.html#_CPPv416esp_chip_model_t
+
+//https://github.com/espressif/esp-idf/blob/8464186e67e34b417621df6b6f1f289a6c60b859/components/esp_hw_support/include/esp_chip_info.h
+/*
+typedef enum {
+    CHIP_ESP32  = 1, //!< ESP32
+    CHIP_ESP32S2 = 2, //!< ESP32-S2
+    CHIP_ESP32S3 = 9, //!< ESP32-S3
+    CHIP_ESP32C3 = 5, //!< ESP32-C3
+    CHIP_ESP32H4 = 6, //!< ESP32-H4
+    CHIP_ESP32C2 = 12, //!< ESP32-C2
+    CHIP_ESP32C6 = 13, //!< ESP32-C6
+    CHIP_ESP32H2 = 16, //!< ESP32-H2
+    CHIP_POSIX_LINUX = 999, //!< The code is running on POSIX/Linux simulator
+} esp_chip_model_t;
+*/
+
+char* GetChipModel(){
+    esp_chip_info_t chipInfo;
+    esp_chip_info(&chipInfo);
+    switch((int)chipInfo.model) {
+        case 0 : return (char*)"ESP8266";
+        case (int)esp_chip_model_t::CHIP_ESP32 : return (char*)"ESP32";
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)        
+        case (int)esp_chip_model_t::CHIP_ESP32S2 : return (char*)"ESP32-S2";
+        case (int)esp_chip_model_t::CHIP_ESP32S3 : return (char*)"ESP32-S3";
+        case (int)esp_chip_model_t::CHIP_ESP32C3 : return (char*)"ESP32-C3";
+        case 6 : return (char*)"ESP32-H4";
+        case 12 : return (char*)"ESP32-C2";
+        case 13 : return (char*)"ESP32-C6";
+        //case (int)esp_chip_model_t::CHIP_ESP32H4 : return (char*)"ESP32-H4";
+        //case (int)esp_chip_model_t::CHIP_ESP32C2 : return (char*)"ESP32-C2";
+        //case (int)esp_chip_model_t::CHIP_ESP32C6 : return (char*)"ESP32-C6";
+        //case (int)esp_chip_model_t::CHIP_ESP32H2 : return (char*)"ESP32-H2";
+        case 16 : return (char*)"ESP32-H2";
+        //case (int)esp_chip_model_t::CHIP_POSIX_LINUX : return (char*)"CHIP_POSIX_LINUX";
+
+#endif
+    }
+    return (char*)"Chip Unknown";
+}
+
+
+
+
+
+uint32_t GetFreeHeap() {
+    return esp_get_free_heap_size();
+}
+
+uint32_t GetLeastHeapFreeSinceBoot() {
+    return esp_get_minimum_free_heap_size();
+}
+
+
+std::string get_device_info()
+{
+    esp_chip_info_t chip_info;
+    esp_chip_info(&chip_info);
+    
+    std::string espInfoResultStr = "";
+    char aMsgBuf[40];
+
+    espInfoResultStr += "Device Info:";
+    espInfoResultStr += "---------------\n";
+    espInfoResultStr += "Chip Model: " + std::string(GetChipModel()) +"\n";
+    sprintf(aMsgBuf,"Chip Revision: %d\n", chip_info.revision);
+    espInfoResultStr += std::string(aMsgBuf);
+    sprintf(aMsgBuf,"CPU Cores: %d\n", chip_info.cores);
+    espInfoResultStr += std::string(aMsgBuf);
+    sprintf(aMsgBuf,"Flash Memory: %dMB\n", spi_flash_get_chip_size()/(1024*1024));
+    espInfoResultStr += std::string(aMsgBuf);
+    if(chip_info.features & CHIP_FEATURE_WIFI_BGN)
+        //espInfoResultStr += "Base MAC: " + std::string(getMac()) +"\n";
+        espInfoResultStr += "ESP-IDF version: " + std::string(esp_get_idf_version()) +"\n";
+    if((chip_info.features & CHIP_FEATURE_WIFI_BGN) || (chip_info.features & CHIP_FEATURE_BT) ||
+       (chip_info.features & CHIP_FEATURE_BLE) || (chip_info.features & CHIP_FEATURE_EMB_FLASH))
+    {
+        espInfoResultStr += "Characteristics:\n";
+        if(chip_info.features & CHIP_FEATURE_WIFI_BGN)
+            espInfoResultStr += "    WiFi 2.4GHz\n";
+        if(chip_info.features & CHIP_FEATURE_BT)
+            espInfoResultStr += "    Bluetooth Classic\n";
+        if(chip_info.features & CHIP_FEATURE_BLE)
+            espInfoResultStr += "    Bluetooth Low Energy\n";
+        if(chip_info.features & CHIP_FEATURE_EMB_FLASH)
+            espInfoResultStr += "    Embedded Flash memory\n";
+        else
+           espInfoResultStr += "    External Flash memory\n";
+    }
+
+    #ifdef USE_HIMEM_IF_AVAILABLE
+        sprintf(aMsgBuf,"spiram size %u\n", esp_psram_get_size());
+        espInfoResultStr += std::string(aMsgBuf);
+        sprintf(aMsgBuf,"himem free %u\n", esp_himem_get_free_size());
+        espInfoResultStr += std::string(aMsgBuf);
+        sprintf(aMsgBuf,"himem phys %u\n", esp_himem_get_phys_size());
+        espInfoResultStr += std::string(aMsgBuf);
+        sprintf(aMsgBuf,"himem reserved %u\n", esp_himem_reserved_area_size());
+        espInfoResultStr += std::string(aMsgBuf);
+    #endif
+    
+    return espInfoResultStr; 
+}
+
+
+
+
+
+
+
+
+
+
+#ifdef USE_HIMEM_IF_AVAILABLE
+    size_t getHimemTotSpace(){ 
+        return esp_himem_get_phys_size();
+    }
+
+    size_t getHimemFreeSpace(){ 
+        return esp_himem_get_free_size();
+    }
+
+    size_t getHimemReservedArea(){ 
+        return esp_himem_reserved_area_size();
+    }
+#endif
+
+#endif //DEBUG_ENABLE_SYSINFO

+ 46 - 54
code/components/jomjol_helper/esp_sys.h

@@ -1,54 +1,46 @@
-#pragma once
-
-#include "../../include/defines.h"
-
-#ifdef DEBUG_ENABLE_SYSINFO
-
-#ifndef ESP_SYS_H
-#define ESP_SYS_H
-
-
-#include <string>
-
-
-// Device libraries (ESP-IDF)
-#include <esp_system.h>
-#include <esp_spi_flash.h>
-#include <esp_heap_caps.h>
-
-// for esp_psram_get_size
-extern "C" {
-    #include "esp_psram.h"
-    #ifdef USE_HIMEM_IF_AVAILABLE
-        #include <esp32/himem.h>
-    #endif
-}
-
-
-
-    void Restart();
-    char *GetChipModel();
-    uint8_t GetChipCoreCount();
-    uint16_t GetChipRevision();
-    uint32_t  GetChipfeatures();
-    uint32_t GetFreeHeap();
-    uint32_t GetLeastHeapFreeSinceBoot();
-
-    std::string get_device_info();
-
-    size_t getFreeMemoryInternal();
-    size_t getFreeMemorySPIRAM();
-    size_t getLargestFreeBlockInternal();
-    size_t getLargestFreeBlockSPIRAM();
-    size_t getMinEverFreeMemInternal();
-    size_t getMinEverFreeMemSPIRAM();
-    #ifdef USE_HIMEM_IF_AVAILABLE
-        size_t getHimemTotSpace();
-        size_t getHimemFreeSpace();
-        size_t getHimemReservedArea();
-    #endif
-
-
-#endif //ESP_SYS_H
-
-#endif // DEBUG_ENABLE_SYSINFO
+#pragma once
+
+#include "../../include/defines.h"
+
+#ifdef DEBUG_ENABLE_SYSINFO
+
+#ifndef ESP_SYS_H
+#define ESP_SYS_H
+
+
+#include <string>
+
+
+// Device libraries (ESP-IDF)
+#include <esp_system.h>
+#include <esp_spi_flash.h>
+#include <esp_heap_caps.h>
+
+// for esp_psram_get_size
+extern "C" {
+    #include "esp_psram.h"
+    #ifdef USE_HIMEM_IF_AVAILABLE
+        #include <esp32/himem.h>
+    #endif
+}
+
+
+
+    void Restart();
+    char *GetChipModel();
+
+    uint32_t GetFreeHeap();
+    uint32_t GetLeastHeapFreeSinceBoot();
+
+    std::string get_device_info();
+
+    #ifdef USE_HIMEM_IF_AVAILABLE
+        size_t getHimemTotSpace();
+        size_t getHimemFreeSpace();
+        size_t getHimemReservedArea();
+    #endif
+
+
+#endif //ESP_SYS_H
+
+#endif // DEBUG_ENABLE_SYSINFO

+ 248 - 133
code/components/jomjol_helper/psram.cpp

@@ -2,210 +2,325 @@
 #include "../../include/defines.h"
 #include "psram.h"
 
-static const char* TAG = "PSRAM";
-
-using namespace std;
+#include <cstring>
+#include <stdint.h>
+#include <stdio.h>
+#include <limits.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/portmacro.h"
 
+static const char* TAG = "PSRAM";
 
-void *shared_region = NULL;
-uint32_t allocatedBytesForSTBI = 0;
-std::string sharedMemoryInUseFor = "";
-
+namespace {
+enum class SharedMemoryUser : uint8_t { None, TakeImage, Aligning, Digitization };
+static const uint32_t STBI_SHARED_BLOCK_MAGIC = 0x53544249;
+static const size_t STBI_ALIGNMENT = 16;
+struct alignas(16) StbiSharedBlockHeader {
+    size_t size;
+    uint32_t magic;
+    uint8_t reserved[STBI_ALIGNMENT - sizeof(size_t) - sizeof(uint32_t)];
+};
+static_assert(sizeof(StbiSharedBlockHeader) == STBI_ALIGNMENT, "STBI shared allocation header must preserve alignment");
+static portMUX_TYPE sharedMemoryMux = portMUX_INITIALIZER_UNLOCKED;
+static uint8_t* sharedRegion = nullptr;
+static size_t allocatedBytesForSTBI = 0;
+static SharedMemoryUser sharedMemoryUser = SharedMemoryUser::None;
+static bool tensorArenaClaimed = false;
+static bool modelMemoryClaimed = false;
+
+static bool getSharedRegionSize(size_t* size) {
+    if (size == nullptr) return false;
+    const size_t arenaSize = static_cast<size_t>(TENSOR_ARENA_SIZE);
+    const size_t modelSize = static_cast<size_t>(MAX_MODEL_SIZE);
+    if (arenaSize == 0 || modelSize == 0 || arenaSize > SIZE_MAX - modelSize) return false;
+    *size = arenaSize + modelSize;
+    return true;
+}
+static const char* sharedMemoryUserName(SharedMemoryUser user) {
+    switch (user) {
+        case SharedMemoryUser::TakeImage: return "TakeImage";
+        case SharedMemoryUser::Aligning: return "Aligning";
+        case SharedMemoryUser::Digitization: return "Digitization";
+        default: return "";
+    }
+}
+static bool isInsideSharedRegionLocked(const void* ptr, size_t regionSize) {
+    if (ptr == nullptr || sharedRegion == nullptr) return false;
+    const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
+    const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
+    return address >= begin && (address - begin) < regionSize;
+}
+static bool alignStbiOffset(size_t value, size_t* aligned) {
+    if (aligned == nullptr || value > SIZE_MAX - (STBI_ALIGNMENT - 1)) return false;
+    *aligned = (value + STBI_ALIGNMENT - 1) & ~(STBI_ALIGNMENT - 1);
+    return true;
+}
+} // namespace
 
-/** Reserve a large block in the PSRAM which will be shared between the different steps.
- * Each step uses it differently but only wiuthin itself. */
 bool reserve_psram_shared_region(void) {
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + 
-            std::to_string(TENSOR_ARENA_SIZE + MAX_MODEL_SIZE) + " bytes)...");
-    shared_region = malloc_psram_heap("Shared PSRAM region", TENSOR_ARENA_SIZE + MAX_MODEL_SIZE, 
-            MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
-
-    if (shared_region == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocating shared PSRAM region!");
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid shared PSRAM region size");
         return false;
     }
-    else {
-        return true;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    const bool alreadyReserved = (sharedRegion != nullptr);
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (alreadyReserved) return true;
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + std::to_string(regionSize) + " bytes)...");
+    uint8_t* candidate = static_cast<uint8_t*>(malloc_psram_heap("Shared PSRAM region", regionSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (candidate == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate shared PSRAM region!");
+        return false;
     }
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedRegion == nullptr) { sharedRegion = candidate; candidate = nullptr; }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (candidate != nullptr) free_psram_heap("Unused duplicate shared PSRAM region", candidate);
+    return true;
 }
 
-
-
 /*******************************************************************
  * Memory used in Take Image (STBI)
  *******************************************************************/
 bool psram_init_shared_memory_for_take_image_step(void) {
-    if (sharedMemoryInUseFor != "") {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
+    SharedMemoryUser currentUser;
+    bool success = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
+        allocatedBytesForSTBI = 0;
+        sharedMemoryUser = SharedMemoryUser::TakeImage;
+        success = true;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (!success) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, sharedRegion == nullptr ?
+            "Shared PSRAM region is not initialized" :
+            "Shared memory in PSRAM already in use for " + std::string(sharedMemoryUserName(currentUser)) + "!");
         return false;
     }
-
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init shared memory for step 'Take Image' (STBI buffers)");
-    allocatedBytesForSTBI = 0;
-    sharedMemoryInUseFor = "TakeImage";
-
     return true;
 }
 
-
 void psram_deinit_shared_memory_for_take_image_step(void) {
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Deinit shared memory for step 'Take Image' (STBI buffers)");
-    allocatedBytesForSTBI = 0;
-    sharedMemoryInUseFor = "";
+    bool released = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedMemoryUser == SharedMemoryUser::TakeImage) {
+        allocatedBytesForSTBI = 0;
+        sharedMemoryUser = SharedMemoryUser::None;
+        released = true;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Deinit shared memory for step 'Take Image' (STBI buffers)");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched STBI shared-memory release");
 }
 
-
 void *psram_reserve_shared_stbi_memory(size_t size) {
-    /* Only large buffers should be placed in the shared PSRAM 
-     * If we also place all smaller STBI buffers here, we get artefacts for some reasons. */
-    if (size >= 100000) {
-        if ((allocatedBytesForSTBI + size) > TENSOR_ARENA_SIZE + MAX_MODEL_SIZE) { // Check if it still fits in the shared region
-            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM too small (STBI) to fit additional " + 
-                    std::to_string(size) + " bytes! Available: " + std::to_string(TENSOR_ARENA_SIZE + MAX_MODEL_SIZE - allocatedBytesForSTBI) + " bytes!");
-
-            return NULL;
-        }
-        
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating memory (" + std::to_string(size) + " bytes) for STBI (use shared memory in PSRAM)...");
-        allocatedBytesForSTBI += size;
-        return (uint8_t *)shared_region + allocatedBytesForSTBI - size;
+    if (size == 0) return nullptr;
+    if (size < 100000) return malloc_psram_heap("STBI", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) {
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared PSRAM region is unavailable; allocating STBI buffer from PSRAM heap");
+        return malloc_psram_heap("STBI fallback", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
     }
-    else { // Normal PSRAM
-        return malloc_psram_heap("STBI", size, MALLOC_CAP_SPIRAM);
+    size_t userOffset = 0, endOffset = 0, available = 0;
+    void* result = nullptr;
+    SharedMemoryUser currentUser = SharedMemoryUser::None;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::TakeImage &&
+        allocatedBytesForSTBI <= SIZE_MAX - sizeof(StbiSharedBlockHeader) &&
+        alignStbiOffset(allocatedBytesForSTBI + sizeof(StbiSharedBlockHeader), &userOffset) &&
+        userOffset <= regionSize && size <= regionSize - userOffset) {
+        endOffset = userOffset + size;
+        StbiSharedBlockHeader* header = reinterpret_cast<StbiSharedBlockHeader*>(sharedRegion + userOffset - sizeof(StbiSharedBlockHeader));
+        header->size = size;
+        header->magic = STBI_SHARED_BLOCK_MAGIC;
+        std::memset(header->reserved, 0, sizeof(header->reserved));
+        result = sharedRegion + userOffset;
+        allocatedBytesForSTBI = endOffset;
+    } else if (allocatedBytesForSTBI <= regionSize) available = regionSize - allocatedBytesForSTBI;
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result != nullptr) {
+        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in shared PSRAM for STBI");
+        return result;
     }
+    LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared STBI PSRAM unavailable for " + std::to_string(size) +
+        " bytes (owner: " + sharedMemoryUserName(currentUser) + ", available: " + std::to_string(available) +
+        " bytes); falling back to PSRAM heap");
+    return malloc_psram_heap("STBI fallback", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
 }
 
-
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize) {
-    char buf[20];
-    sprintf(buf, "%p", ptr);
-    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "STBI requested realloc for " + std::string(buf) + " but this is currently unsupported!");
-    return NULL;
-}
-
-
-void psram_free_shared_stbi_memory(void *p) {
-    if ((p >= shared_region) && (p <= ((uint8_t *)shared_region + allocatedBytesForSTBI))) { // was allocated inside the shared memory
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Part of shared memory used for STBI (PSRAM, part of shared memory) is free again");
+    if (ptr == nullptr) return psram_reserve_shared_stbi_memory(newsize);
+    if (newsize == 0) { psram_free_shared_stbi_memory(ptr); return nullptr; }
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize))
+        return realloc_psram_heap("STBI", ptr, newsize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    size_t oldSize = 0;
+    bool sharedPointer = false, validSharedHeader = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    sharedPointer = isInsideSharedRegionLocked(ptr, regionSize);
+    if (sharedPointer) {
+        const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
+        const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
+        if ((address - begin) >= sizeof(StbiSharedBlockHeader)) {
+            const StbiSharedBlockHeader* header = reinterpret_cast<const StbiSharedBlockHeader*>(static_cast<const uint8_t*>(ptr) - sizeof(StbiSharedBlockHeader));
+            if (header->magic == STBI_SHARED_BLOCK_MAGIC) { oldSize = header->size; validSharedHeader = true; }
+        }
     }
-    else { // Normal PSRAM
-        free_psram_heap("STBI", p);
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (!sharedPointer) return realloc_psram_heap("STBI", ptr, newsize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (!validSharedHeader) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "STBI realloc received an unknown shared-region pointer");
+        return nullptr;
     }
+    void* replacement = psram_reserve_shared_stbi_memory(newsize);
+    if (replacement == nullptr) return nullptr;
+    std::memcpy(replacement, ptr, oldSize < newsize ? oldSize : newsize);
+    return replacement;
 }
 
-
+void psram_free_shared_stbi_memory(void *ptr) {
+    if (ptr == nullptr) return;
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) { free_psram_heap("STBI", ptr); return; }
+    portENTER_CRITICAL(&sharedMemoryMux);
+    const bool isShared = isInsideSharedRegionLocked(ptr, regionSize);
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (!isShared) free_psram_heap("STBI", ptr);
+}
 
 /*******************************************************************
- * Memory used in Aligning Step 
- * During this step we only use the shared part of the PSRAM
- * for the tmpImage. 
+ * Memory used in Aligning Step
  *******************************************************************/
 void *psram_reserve_shared_tmp_image_memory(void) {
-    if (sharedMemoryInUseFor != "") {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
-        return NULL;
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize) || static_cast<size_t>(IMAGE_SIZE) > regionSize) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tmpImage does not fit in the reserved shared PSRAM region");
+        return nullptr;
+    }
+    SharedMemoryUser currentUser;
+    void* result = nullptr;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
+        sharedMemoryUser = SharedMemoryUser::Aligning;
+        result = sharedRegion;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM unavailable for tmpImage (owner: " +
+            std::string(sharedMemoryUserName(currentUser)) + ")");
+        return nullptr;
     }
-
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(IMAGE_SIZE) + " bytes, use shared memory in PSRAM)...");
-    sharedMemoryInUseFor = "Aligning";
-    return shared_region; // Use 1th part of the shared memory for the tmpImage (only user)
+    return result;
 }
 
-
 void psram_free_shared_temp_image_memory(void) {
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for tmpImage (PSRAM, part of shared memory) is free again");
-    sharedMemoryInUseFor = "";
+    bool released = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedMemoryUser == SharedMemoryUser::Aligning) { sharedMemoryUser = SharedMemoryUser::None; released = true; }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for tmpImage is free again");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched tmpImage shared-memory release");
 }
 
-
-
 /*******************************************************************
  * Memory used in Digitization Steps
- * During this step we only use the shared part of the PSRAM for the
- * Tensor Arena and one of the Models.
- * The shared memory is large enough for the largest model and the
- * Tensor Arena. Therefore we do not need to monitor the usage.
  *******************************************************************/
 void *psram_get_shared_tensor_arena_memory(void) {
-    if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Model")) {
-        sharedMemoryInUseFor = "Digitization_Tensor";
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes, use shared memory in PSRAM)...");
-        return shared_region; // Use 1th part of the shared memory for Tensor
-    }
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
-        return NULL;
+    bool unavailable = false, duplicateClaim = false;
+    void* result = nullptr;
+    SharedMemoryUser currentUser;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
+    else if (tensorArenaClaimed) duplicateClaim = true;
+    else { sharedMemoryUser = SharedMemoryUser::Digitization; tensorArenaClaimed = true; result = sharedRegion; }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Tensor Arena shared memory was claimed more than once" :
+            (unavailable ? "Shared PSRAM is unavailable for Tensor Arena (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Tensor Arena allocation failed"));
+        return nullptr;
     }
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes in shared PSRAM)...");
+    return result;
 }
 
-
 void *psram_get_shared_model_memory(void) {
-    if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Tensor")) {
-        sharedMemoryInUseFor = "Digitization_Model";
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes, use shared memory in PSRAM)...");
-        return (uint8_t *)shared_region + TENSOR_ARENA_SIZE; // Use 2nd part of the shared memory (after Tensor Arena) for the model
-    }
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
-        return NULL;
+    bool unavailable = false, duplicateClaim = false;
+    void* result = nullptr;
+    SharedMemoryUser currentUser;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
+    else if (modelMemoryClaimed) duplicateClaim = true;
+    else { sharedMemoryUser = SharedMemoryUser::Digitization; modelMemoryClaimed = true; result = sharedRegion + static_cast<size_t>(TENSOR_ARENA_SIZE); }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Model shared memory was claimed more than once" :
+            (unavailable ? "Shared PSRAM is unavailable for Model (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Model allocation failed"));
+        return nullptr;
     }
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes in shared PSRAM)...");
+    return result;
 }
 
-
 void psram_free_shared_tensor_arena_and_model_memory(void) {
-    sharedMemoryInUseFor = "";
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for Tensor Arena and model (PSRAM, part of shared memory) is free again");
+    bool released = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedMemoryUser == SharedMemoryUser::Digitization) {
+        tensorArenaClaimed = false; modelMemoryClaimed = false;
+        sharedMemoryUser = SharedMemoryUser::None; released = true;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for Tensor Arena and model is free again");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched Tensor Arena/Model shared-memory release");
 }
 
-
-
 /*******************************************************************
- * General
+ * General PSRAM heap wrappers
  *******************************************************************/
 void *malloc_psram_heap(std::string name, size_t size, uint32_t caps) {
-	void *ptr;
-
-	ptr = heap_caps_malloc(size, caps);
-    if (ptr != NULL) {
-	    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + to_string(size) + " bytes in PSRAM for '" + name + "'");
-	}
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    if (size == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM allocation for '" + name + "'");
+        return nullptr;
     }
-
-	return ptr;
+    void* ptr = heap_caps_malloc(size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    return ptr;
 }
 
-
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
-	ptr = heap_caps_realloc(ptr, size, caps);
-    if (ptr != NULL) {
-	    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + to_string(size) + " bytes in PSRAM for '" + name + "'");
-	}
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + to_string(size) + " bytes in PSRAM for '" + name + "'!");
-    }
-
-	return ptr;
+    void* resized = heap_caps_realloc(ptr, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
+    else if (size != 0) LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    return resized;
 }
 
-
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps) {
-	void *ptr;
-
-	ptr = heap_caps_calloc(n, size, caps);
-    if (ptr != NULL) {
-	    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Allocated " + to_string(size) + " bytes in PSRAM for '" + name + "'");
-	}
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    if (size != 0 && n > SIZE_MAX / size) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM calloc size overflow for '" + name + "'");
+        return nullptr;
     }
-
-	return ptr;
+    const size_t totalSize = n * size;
+    if (totalSize == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM calloc for '" + name + "'");
+        return nullptr;
+    }
+    void* ptr = heap_caps_calloc(n, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'!");
+    return ptr;
 }
 
-
 void free_psram_heap(std::string name, void *ptr) {
+    if (ptr == nullptr) return;
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing memory in PSRAM used for '" + name + "'...");
     heap_caps_free(ptr);
 }

+ 4 - 16
code/components/jomjol_helper/psram.h

@@ -1,35 +1,23 @@
 #pragma once
 #ifndef PSRAM_h
 #define PSRAM_h
-
+#include <stddef.h>
+#include <stdint.h>
+#include <string>
 #include "esp_heap_caps.h"
-
-
 bool reserve_psram_shared_region(void);
-
-
-/* Memory used in Take Image Step */
 bool psram_init_shared_memory_for_take_image_step(void);
 void psram_deinit_shared_memory_for_take_image_step(void);
 void *psram_reserve_shared_stbi_memory(size_t size);
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize);
-void psram_free_shared_stbi_memory(void *p);
-
-
-/* Memory used in Aligning Step */
+void psram_free_shared_stbi_memory(void *ptr);
 void *psram_reserve_shared_tmp_image_memory(void);
 void psram_free_shared_temp_image_memory(void);
-
-/* Memory used in Digitization Steps */
 void *psram_get_shared_tensor_arena_memory(void);
 void *psram_get_shared_model_memory(void);
 void psram_free_shared_tensor_arena_and_model_memory(void);
-
-/* General */
 void *malloc_psram_heap(std::string name, size_t size, uint32_t caps);
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps);
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps);
-
 void free_psram_heap(std::string name, void *ptr);
-
 #endif // PSRAM_h

+ 163 - 92
code/components/jomjol_image_proc/CAlignAndCutImage.cpp

@@ -4,6 +4,10 @@
 
 #include <math.h>
 #include <algorithm>
+#include <cstring>
+#include <stdint.h>
+#include <limits.h>
+#include <new>
 #include <esp_log.h>
 #include "psram.h"
 
@@ -12,6 +16,50 @@
 
 static const char* TAG = "c_align_and_cut_image";
 
+class ScopedImageAccess
+{
+    CImageBasis* image;
+    bool locked;
+public:
+    explicit ScopedImageAccess(CImageBasis* value) : image(value), locked(false)
+    {
+        if (image != NULL) locked = image->RGBImageLock() != NULL;
+    }
+    ~ScopedImageAccess()
+    {
+        if (locked) image->RGBImageRelease();
+    }
+    bool isLocked() const { return locked; }
+};
+
+static bool getCutRectangle(int imageWidth, int imageHeight,
+                             int x, int y, int requestedWidth, int requestedHeight,
+                             int* right, int* bottom)
+{
+    if (right == NULL || bottom == NULL || imageWidth <= 0 || imageHeight <= 0 ||
+        x < 0 || y < 0 || requestedWidth <= 0 || requestedHeight <= 0 ||
+        x >= imageWidth || y >= imageHeight) return false;
+
+    const int64_t requestedRight = static_cast<int64_t>(x) + requestedWidth;
+    const int64_t requestedBottom = static_cast<int64_t>(y) + requestedHeight;
+    *right = static_cast<int>(std::min<int64_t>(requestedRight, imageWidth));
+    *bottom = static_cast<int>(std::min<int64_t>(requestedBottom, imageHeight));
+    return *right > x && *bottom > y;
+}
+
+static bool getCutBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
 CAlignAndCutImage::CAlignAndCutImage(std::string _name, CImageBasis *_org, CImageBasis *_temp) : CImageBasis(_name)
 {
     name = _name;
@@ -27,13 +75,6 @@ CAlignAndCutImage::CAlignAndCutImage(std::string _name, CImageBasis *_org, CImag
     ImageTMP = _temp;
 }
 
-void CAlignAndCutImage::GetRefSize(int *ref_dx, int *ref_dy)
-{
-    ref_dx[0] = t0_dx;
-    ref_dy[0] = t0_dy;
-    ref_dx[1] = t1_dx;
-    ref_dy[1] = t1_dy;
-}
 
 bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
 {
@@ -41,7 +82,20 @@ bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
     int r0_x, r0_y, r1_x, r1_y;
     bool isSimilar1, isSimilar2;
 
-    CFindTemplate* ft = new CFindTemplate("align", rgb_image, channels, width, height, bpp);
+    if (_temp1 == NULL || _temp2 == NULL || rgb_image == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: source image or reference is unavailable");
+        return false;
+    }
+    ScopedImageAccess sourceAccess(this);
+    if (!sourceAccess.isLocked()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: unable to lock source image");
+        return false;
+    }
+    CFindTemplate* ft = new (std::nothrow) CFindTemplate("align", rgb_image, channels, width, height, bpp);
+    if (ft == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: unable to allocate template matcher");
+        return false;
+    }
 
     r0_x = _temp1->target_x;
     r0_y = _temp1->target_y;
@@ -94,112 +148,129 @@ bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
 
 void CAlignAndCutImage::CutAndSave(std::string _template1, int x1, int y1, int dx, int dy)
 {
-    int x2, y2;
-
-    x2 = x1 + dx;
-    y2 = y1 + dy;
-    x2 = std::min(x2, width - 1);
-    y2 = std::min(y2, height - 1);
-
-    dx = x2 - x1;
-    dy = y2 - y1;
-
-    int memsize = dx * dy * channels;
-    uint8_t* odata = (unsigned char*) malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
+    if (rgb_image == NULL || channels <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: source image is not available");
+        return;
+    }
 
-    stbi_uc* p_target;
-    stbi_uc* p_source;
+    int x2 = 0, y2 = 0;
+    if (!getCutRectangle(width, height, x1, y1, dx, dy, &x2, &y2)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: invalid crop rectangle");
+        return;
+    }
+    const int cropWidth = x2 - x1;
+    const int cropHeight = y2 - y1;
+    size_t bufferSize = 0;
+    if (!getCutBufferSize(cropWidth, cropHeight, channels, &bufferSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: crop size overflow");
+        return;
+    }
 
-    RGBImageLock();
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: source image is locked");
+        return;
+    }
+    uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (output == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: PSRAM allocation failed");
+        return;
+    }
 
-    for (int x = x1; x < x2; ++x)
-        for (int y = y1; y < y2; ++y)
-        {
-            p_target = odata + (channels * ((y - y1) * dx + (x - x1)));
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_target[_channels] = p_source[_channels];
-        }
+    const size_t rowBytes = static_cast<size_t>(cropWidth) * static_cast<size_t>(channels);
+    for (int row = 0; row < cropHeight; ++row) {
+        const size_t sourceOffset = (static_cast<size_t>(y1 + row) * static_cast<size_t>(width) +
+                                     static_cast<size_t>(x1)) * static_cast<size_t>(channels);
+        std::memcpy(output + static_cast<size_t>(row) * rowBytes, source + sourceOffset, rowBytes);
+    }
 
 #ifdef STBI_ONLY_JPEG
-    stbi_write_jpg(_template1.c_str(), dx, dy, channels, odata, 100);
+    stbi_write_jpg(_template1.c_str(), cropWidth, cropHeight, channels, output, 100);
 #else
-    stbi_write_bmp(_template1.c_str(), dx, dy, channels, odata);
+    stbi_write_bmp(_template1.c_str(), cropWidth, cropHeight, channels, output);
 #endif
-    
-    RGBImageRelease();
 
-    free_psram_heap(std::string(TAG) + "->odata", odata);
+    RGBImageRelease();
+    free_psram_heap(std::string(TAG) + "->odata", output);
 }
 
-void CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *_target)
+bool CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *_target)
 {
-    int x2, y2;
-
-    x2 = x1 + dx;
-    y2 = y1 + dy;
-    x2 = std::min(x2, width - 1);
-    y2 = std::min(y2, height - 1);
-
-    dx = x2 - x1;
-    dy = y2 - y1;
-
-    if ((_target->height != dy) || (_target->width != dx) || (_target->channels != channels))
-    {
+    if (_target == NULL || rgb_image == NULL || channels <= 0) return false;
+
+    int x2 = 0, y2 = 0;
+    if (!getCutRectangle(width, height, x1, y1, dx, dy, &x2, &y2)) return false;
+    const int cropWidth = x2 - x1;
+    const int cropHeight = y2 - y1;
+    size_t cropBufferSize = 0;
+    if (!getCutBufferSize(cropWidth, cropHeight, channels, &cropBufferSize)) return false;
+    if (_target->height != cropHeight || _target->width != cropWidth ||
+        _target->channels != channels || !_target->ImageOkay()) {
         ESP_LOGD(TAG, "CAlignAndCutImage::CutAndSave - Image size does not match!");
-        return;
+        return false;
     }
 
-    uint8_t* odata = _target->RGBImageLock();
-    RGBImageLock();
-
-    stbi_uc* p_target;
-    stbi_uc* p_source;
+    uint8_t* output = _target->RGBImageLock();
+    if (output == NULL) return false;
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        _target->RGBImageRelease();
+        return false;
+    }
 
-    for (int x = x1; x < x2; ++x)
-        for (int y = y1; y < y2; ++y)
-        {
-            p_target = odata + (channels * ((y - y1) * dx + (x - x1)));
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_target[_channels] = p_source[_channels];
-        }
+    const size_t rowBytes = static_cast<size_t>(cropWidth) * static_cast<size_t>(channels);
+    for (int row = 0; row < cropHeight; ++row) {
+        const size_t sourceOffset = (static_cast<size_t>(y1 + row) * static_cast<size_t>(width) +
+                                     static_cast<size_t>(x1)) * static_cast<size_t>(channels);
+        std::memcpy(output + static_cast<size_t>(row) * rowBytes, source + sourceOffset, rowBytes);
+    }
 
     RGBImageRelease();
     _target->RGBImageRelease();
+    return true;
 }
 
 CImageBasis* CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy)
 {
-    int x2, y2;
-
-    x2 = x1 + dx;
-    y2 = y1 + dy;
-    x2 = std::min(x2, width - 1);
-    y2 = std::min(y2, height - 1);
-
-    dx = x2 - x1;
-    dy = y2 - y1;
-
-    int memsize = dx * dy * channels;
-    uint8_t* odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-
-    stbi_uc* p_target;
-    stbi_uc* p_source;
-
-    RGBImageLock();
-
-    for (int x = x1; x < x2; ++x)
-        for (int y = y1; y < y2; ++y)
-        {
-            p_target = odata + (channels * ((y - y1) * dx + (x - x1)));
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_target[_channels] = p_source[_channels];
-        }
+    if (rgb_image == NULL || channels <= 0) return NULL;
+    int x2 = 0, y2 = 0;
+    if (!getCutRectangle(width, height, x1, y1, dx, dy, &x2, &y2)) return NULL;
+    const int cropWidth = x2 - x1;
+    const int cropHeight = y2 - y1;
+    size_t bufferSize = 0;
+    if (!getCutBufferSize(cropWidth, cropHeight, channels, &bufferSize)) return NULL;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) return NULL;
+    uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (output == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: PSRAM allocation failed");
+        return NULL;
+    }
 
-    CImageBasis* rs = new CImageBasis("CutAndSave", odata, channels, dx, dy, bpp);
+    const size_t rowBytes = static_cast<size_t>(cropWidth) * static_cast<size_t>(channels);
+    for (int row = 0; row < cropHeight; ++row) {
+        const size_t sourceOffset = (static_cast<size_t>(y1 + row) * static_cast<size_t>(width) +
+                                     static_cast<size_t>(x1)) * static_cast<size_t>(channels);
+        std::memcpy(output + static_cast<size_t>(row) * rowBytes, source + sourceOffset, rowBytes);
+    }
     RGBImageRelease();
-    rs->SetIndepended();
-    return rs;
+
+    CImageBasis* result = new (std::nothrow) CImageBasis("CutAndSave", output, channels, cropWidth, cropHeight, bpp);
+    if (result == NULL) {
+        free_psram_heap(std::string(TAG) + "->odata (unowned)", output);
+        return NULL;
+    }
+    if (!result->SetIndepended()) {
+        delete result;
+        free_psram_heap(std::string(TAG) + "->odata (invalid result)", output);
+        return NULL;
+    }
+    // SetIndepended copied the externally-owned crop into its own managed PSRAM block.
+    free_psram_heap(std::string(TAG) + "->odata (transferred)", output);
+    return result;
 }

+ 1 - 2
code/components/jomjol_image_proc/CAlignAndCutImage.h

@@ -20,8 +20,7 @@ class CAlignAndCutImage : public CImageBasis
 //        void Align(std::string _template1, int x1, int y1, std::string _template2, int x2, int y2, int deltax = 40, int deltay = 40, std::string imageROI = "");
         void CutAndSave(std::string _template1, int x1, int y1, int dx, int dy);
         CImageBasis* CutAndSave(int x1, int y1, int dx, int dy);
-        void CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *_target);
-        void GetRefSize(int *ref_dx, int *ref_dy);
+        bool CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *_target);
 };
 
 #endif //CALIGNANDCUTIMAGE_H

+ 87 - 111
code/components/jomjol_image_proc/CFindTemplate.cpp

@@ -9,159 +9,144 @@
 #include "freertos/FreeRTOS.h"
 #include "freertos/task.h"
 #include <cstdint>
+#include <limits.h>
 
 static const char* TAG = "C FIND TEMPL";
 
+static bool getTemplateBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
 // #define DEBUG_DETAIL_ON  
 
 
 bool CFindTemplate::FindTemplate(RefInfo *_ref)
 {
-    uint8_t* rgb_template;
-
+    if (_ref == NULL || rgb_image == NULL || width <= 0 || height <= 0 || channels <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image or reference is unavailable");
+        return false;
+    }
     if (file_size(_ref->image_file.c_str()) == 0) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _ref->image_file + " is empty!");
         return false;
     }
-   
-    rgb_template = stbi_load(_ref->image_file.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
 
+    uint8_t* rgb_template = stbi_load(_ref->image_file.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
     if (rgb_template == NULL) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to load " + _ref->image_file + "! Is it corrupted?");
         return false;
     }
 
-//    ESP_LOGD(TAG, "FindTemplate 01");
+    size_t templateBytes = 0;
+    if (!getTemplateBufferSize(tpl_width, tpl_height, channels, &templateBytes) ||
+        tpl_width > width || tpl_height > height) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: template dimensions are invalid or exceed source image");
+        stbi_image_free(rgb_template);
+        return false;
+    }
 
-    int ow, ow_start, ow_stop;
-    int oh, oh_start, oh_stop;
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image is locked");
+        stbi_image_free(rgb_template);
+        return false;
+    }
 
-    if (_ref->search_x == 0)
-    {
+    if (_ref->search_x == 0) {
         _ref->search_x = width;
         _ref->found_x = 0;
     }
-
-    if (_ref->search_y == 0)
-    {
+    if (_ref->search_y == 0) {
         _ref->search_y = height;
         _ref->found_y = 0;
     }
 
-
-    ow_start = _ref->target_x - _ref->search_x;
-    ow_start = std::max(ow_start, 0);
-    ow_stop = _ref->target_x + _ref->search_x;
-    if ((ow_stop + tpl_width) > width)
-        ow_stop = width - tpl_width;
-    ow = ow_stop - ow_start + 1;
-
-    oh_start = _ref->target_y - _ref->search_y;
-    oh_start = std::max(oh_start, 0);
-    oh_stop = _ref->target_y + _ref->search_y;
-    if ((oh_stop + tpl_height) > height)
-        oh_stop = height - tpl_height;
-    oh = oh_stop - oh_start + 1;
+    const int64_t leftCandidate = static_cast<int64_t>(_ref->target_x) - _ref->search_x;
+    const int64_t rightCandidate = static_cast<int64_t>(_ref->target_x) + _ref->search_x;
+    const int64_t topCandidate = static_cast<int64_t>(_ref->target_y) - _ref->search_y;
+    const int64_t bottomCandidate = static_cast<int64_t>(_ref->target_y) + _ref->search_y;
+    const int ow_start = static_cast<int>(std::max<int64_t>(0, leftCandidate));
+    const int ow_stop = static_cast<int>(std::min<int64_t>(rightCandidate, width - tpl_width));
+    const int oh_start = static_cast<int>(std::max<int64_t>(0, topCandidate));
+    const int oh_stop = static_cast<int>(std::min<int64_t>(bottomCandidate, height - tpl_height));
+
+    if (ow_stop < ow_start || oh_stop < oh_start) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: search window does not intersect source image");
+        RGBImageRelease();
+        stbi_image_free(rgb_template);
+        return false;
+    }
 
     float avg = 0, SAD = 0;
     int min = 0, max = 0;
     bool isSimilar = false;
-
-//    ESP_LOGD(TAG, "FindTemplate 02");
-
-    if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1))     // für Testzwecke immer Berechnen
-    {
-        isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y, min, avg, max, SAD, _ref->fastalg_SAD, _ref->fastalg_SAD_criteria);
-/*#ifdef DEBUG_DETAIL_ON
-        std::string zw = "\t" + _ref->image_file + "\tt1_x_y:\t" + std::to_string(_ref->fastalg_x) + "\t" + std::to_string(_ref->fastalg_y);
-        zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(min) + "\t" + std::to_string(avg) + "\t" + std::to_string(max) + "\t"+ std::to_string(SAD);
-        LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
-#endif*/
+    if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1)) {
+        isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y,
+                                          min, avg, max, SAD, _ref->fastalg_SAD,
+                                          _ref->fastalg_SAD_criteria);
     }
-
-//    ESP_LOGD(TAG, "FindTemplate 03");
-
-
-    if (isSimilar)
-    {
-#ifdef DEBUG_DETAIL_ON  
-        LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment sucessfull");
+    if (isSimilar) {
+#ifdef DEBUG_DETAIL_ON
+        LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment successful");
 #endif
         _ref->found_x = _ref->fastalg_x;
         _ref->found_y = _ref->fastalg_y;
-
+        RGBImageRelease();
         stbi_image_free(rgb_template);
-        
         return true;
     }
 
-//    ESP_LOGD(TAG, "FindTemplate 04");
-
-
-    // Sum of squared differences in integer arithmetic: the ESP32 FPU is single precision only,
-    // so the former double/pow() version ran in software emulation and took several seconds per reference.
-    // The result is identical: the sum is exact either way and the search order / tie-breaking is unchanged.
     uint64_t aktSAD;
     uint64_t minSAD = UINT64_MAX;
-
-    RGBImageLock();
-
-//    ESP_LOGD(TAG, "FindTemplate 05");
-    int xouter, youter, tpl_x, tpl_y, _ch;
-    int _anzchannels = channels;
-    if (_ref->alignment_algo == 0)  // 0 = "Default" (nur R-Kanal)
-        _anzchannels = 1;
-
-    // PSRAM-Zugriffe auf Core 0 verdrängen den WiFi-Stack. Spätestens alle 50 ms
-    // den Core abgeben, damit Beacons weiter verarbeitet werden (Tick = 10 ms).
+    const int anzChannels = (_ref->alignment_algo == 0) ? 1 : channels;
+    const size_t templateRowLength = static_cast<size_t>(tpl_width) * static_cast<size_t>(channels);
     int64_t nextYieldUs = esp_timer_get_time() + 50000;
-    const int tpl_row_len = tpl_width * channels;
 
-    for (xouter = ow_start; xouter <= ow_stop; xouter++)
-        for (youter = oh_start; youter <= oh_stop; ++youter)
-        {
+    for (int xouter = ow_start; xouter <= ow_stop; ++xouter) {
+        for (int youter = oh_start; youter <= oh_stop; ++youter) {
             aktSAD = 0;
-            // Walk the template row by row so that image accesses stay sequential in (PSRAM) memory
-            for (tpl_y = 0; tpl_y < tpl_height; tpl_y++)
-            {
-                const stbi_uc* p_org = rgb_image + (channels * ((youter + tpl_y) * width + xouter));
-                const stbi_uc* p_tpl = rgb_template + (tpl_y * tpl_row_len);
-                uint32_t rowSAD = 0;
-                for (tpl_x = 0; tpl_x < tpl_row_len; tpl_x += channels)
-                {
-                    for (_ch = 0; _ch < _anzchannels; ++_ch)
-                    {
-                        int dif = p_tpl[tpl_x + _ch] - p_org[tpl_x + _ch];
-                        rowSAD += dif * dif;
+            for (int tpl_y = 0; tpl_y < tpl_height; ++tpl_y) {
+                const stbi_uc* p_org = source +
+                    (static_cast<size_t>(youter + tpl_y) * static_cast<size_t>(width) +
+                     static_cast<size_t>(xouter)) * static_cast<size_t>(channels);
+                const stbi_uc* p_tpl = rgb_template + static_cast<size_t>(tpl_y) * templateRowLength;
+                uint64_t rowSAD = 0;
+                for (size_t tpl_x = 0; tpl_x < templateRowLength; tpl_x += static_cast<size_t>(channels)) {
+                    for (int ch = 0; ch < anzChannels; ++ch) {
+                        const int diff = static_cast<int>(p_tpl[tpl_x + static_cast<size_t>(ch)]) -
+                                         static_cast<int>(p_org[tpl_x + static_cast<size_t>(ch)]);
+                        rowSAD += static_cast<uint64_t>(diff * diff);
                     }
                 }
                 aktSAD += rowSAD;
-                if (aktSAD >= minSAD)   // can no longer become the new minimum
-                    break;
+                if (aktSAD >= minSAD) break;
             }
-            if (aktSAD < minSAD)
-            {
+            if (aktSAD < minSAD) {
                 minSAD = aktSAD;
                 _ref->found_x = xouter;
                 _ref->found_y = youter;
             }
-
-            if (esp_timer_get_time() >= nextYieldUs)
-            {
+            if (esp_timer_get_time() >= nextYieldUs) {
                 vTaskDelay(1);
                 nextYieldUs = esp_timer_get_time() + 50000;
             }
         }
+    }
 
-//    ESP_LOGD(TAG, "FindTemplate 06");
-
-
-    if (_ref->alignment_algo == 2)
-        CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y, min, avg, max, SAD, _ref->fastalg_SAD, _ref->fastalg_SAD_criteria);
-
-
-//    ESP_LOGD(TAG, "FindTemplate 07");
-
+    if (_ref->alignment_algo == 2) {
+        CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y,
+                              min, avg, max, SAD, _ref->fastalg_SAD,
+                              _ref->fastalg_SAD_criteria);
+    }
     _ref->fastalg_x = _ref->found_x;
     _ref->fastalg_y = _ref->found_y;
     _ref->fastalg_min = min;
@@ -169,23 +154,12 @@ bool CFindTemplate::FindTemplate(RefInfo *_ref)
     _ref->fastalg_max = max;
     _ref->fastalg_SAD = SAD;
 
-    
-/*#ifdef DEBUG_DETAIL_ON
-    std::string zw = "\t" + _ref->image_file + "\tt1_x_y:\t" + std::to_string(_ref->fastalg_x) + "\t" + std::to_string(_ref->fastalg_y);
-    zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(min) + "\t" + std::to_string(avg) + "\t" + std::to_string(max) + "\t"+ std::to_string(SAD);
-    LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
-#endif*/
-
     RGBImageRelease();
     stbi_image_free(rgb_template);
-    
-//    ESP_LOGD(TAG, "FindTemplate 08");
-
     return false;
 }
 
 
-
 // Compares the template with the image at (_startx, _starty) and reports whether the match is still as
 // good as the stored one. Used by the "Fast" alignment to skip the full search.
 bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _starty, int &min, float &avg, int &max, float &SAD, float _SADold, float _SADcrit)
@@ -199,10 +173,11 @@ bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _
 
     int xouter, youter, _ch;
 
-    // The template has to lie completely inside the image at this position. The stored position comes
-    // from /config/align.txt and may belong to an older reference image.
-    if ((_startx < 0) || (_starty < 0) || ((_startx + tpl_width) > width) || ((_starty + tpl_height) > height))
-        return false;
+    // The template has to lie completely inside the image at this position.
+    if (_rgb_tmpl == NULL || rgb_image == NULL || width <= 0 || height <= 0 ||
+        channels <= 0 || tpl_width <= 0 || tpl_height <= 0 ||
+        _startx < 0 || _starty < 0 || tpl_width > width || tpl_height > height ||
+        _startx > width - tpl_width || _starty > height - tpl_height) return false;
 
     // Walk the template, not the search area: the former loop ran over the search area size (plus one)
     // and so read past the end of the template buffer and compared pixels that are not part of the marker.
@@ -222,6 +197,7 @@ bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _
             }
         }
 
+    if (anz == 0) return false;
     avg = avgDifSum / anz;
     min = minDif;
     max = maxDif;

+ 492 - 349
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -5,11 +5,15 @@
 #include "server_ota.h"
 
 #include <esp_log.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/semphr.h"
+#include "freertos/portmacro.h"
 #include "../../include/defines.h"
 
 #include "esp_system.h"
 
 #include <cstring>
+#include <limits.h>
 
 #include <math.h>
 #include <algorithm>
@@ -19,80 +23,159 @@ using namespace std;
 
 static const char *TAG = "C IMG BASIS";
 
-bool jpgFileTooLarge = false;   // JPG creation verfication
+static SemaphoreHandle_t s_imageAccessMutex = nullptr;
+static portMUX_TYPE s_imageMutexInitMux = portMUX_INITIALIZER_UNLOCKED;
 
+static SemaphoreHandle_t getImageAccessMutex()
+{
+    portENTER_CRITICAL(&s_imageMutexInitMux);
+    SemaphoreHandle_t mutex = s_imageAccessMutex;
+    portEXIT_CRITICAL(&s_imageMutexInitMux);
+    if (mutex != nullptr) return mutex;
 
-//#define DEBUG_DETAIL_ON
+    SemaphoreHandle_t candidate = xSemaphoreCreateRecursiveMutex();
+    if (candidate == nullptr) return nullptr;
 
+    portENTER_CRITICAL(&s_imageMutexInitMux);
+    if (s_imageAccessMutex == nullptr) {
+        s_imageAccessMutex = candidate;
+        candidate = nullptr;
+    }
+    mutex = s_imageAccessMutex;
+    portEXIT_CRITICAL(&s_imageMutexInitMux);
+    if (candidate != nullptr) vSemaphoreDelete(candidate);
+    return mutex;
+}
 
-uint8_t * CImageBasis::RGBImageLock(int _waitmaxsec)
+static bool lockImageAccess(int waitSeconds = 60)
 {
-    if (islocked)
-    {
-        #ifdef DEBUG_DETAIL_ON   
-                ESP_LOGD(TAG, "Image is locked: sleep for: %ds", _waitmaxsec);
-        #endif
-        TickType_t xDelay;
-        xDelay = 1000 / portTICK_PERIOD_MS;
-        for (int i = 0; i <= _waitmaxsec; ++i)
-        {
-            vTaskDelay( xDelay ); 
-            if (!islocked)
-                break;
-        }
+    SemaphoreHandle_t mutex = getImageAccessMutex();
+    if (mutex == nullptr) return false;
+    TickType_t waitTicks = portMAX_DELAY;
+    if (waitSeconds >= 0) {
+        const uint64_t waitMs = static_cast<uint64_t>(waitSeconds) * 1000ULL;
+        waitTicks = pdMS_TO_TICKS(waitMs > UINT32_MAX ? UINT32_MAX : static_cast<uint32_t>(waitMs));
     }
+    return xSemaphoreTakeRecursive(mutex, waitTicks) == pdTRUE;
+}
 
-    if (islocked)
-        return NULL;
-
-    return rgb_image;
+static void unlockImageAccess()
+{
+    SemaphoreHandle_t mutex = getImageAccessMutex();
+    if (mutex != nullptr) (void)xSemaphoreGiveRecursive(mutex);
 }
 
+static bool getImageBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == nullptr || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
 
-void CImageBasis::RGBImageRelease()
+static void releaseOwnedImageBuffer(const std::string& tag, const std::string& name,
+                                    uint8_t* image, int size, bool sharedLease)
 {
-    islocked = false;
+    if (image == nullptr) return;
+    if (sharedLease) psram_free_shared_temp_image_memory();
+    else if (size == 0) stbi_image_free(image);
+    else free_psram_heap(tag + " (" + name + ", " + std::to_string(size) + ")", image);
 }
 
 
-uint8_t * CImageBasis::RGBImageGet()
+
+//#define DEBUG_DETAIL_ON
+
+
+uint8_t * CImageBasis::RGBImageLock(int _waitmaxsec)
 {
+    if (!lockImageAccess(_waitmaxsec)) {
+        ESP_LOGW(TAG, "Timed out waiting for image access lock");
+        return NULL;
+    }
+    if (rgb_image == NULL) {
+        unlockImageAccess();
+        return NULL;
+    }
     return rgb_image;
 }
 
 
-void writejpghelp(void *context, void *data, int size)
+void CImageBasis::RGBImageRelease()
 {
-//    ESP_LOGD(TAG, "Size all: %d, size %d", ((ImageData*)context)->size, size);
-    ImageData* _zw = (ImageData*) context;
-    uint8_t *voidstart = _zw->data;
-    uint8_t *datastart = (uint8_t*) data;
-    
-    if ((_zw->size < MAX_JPG_SIZE)) {   // Abort copy to prevent buffer overflow
-        voidstart += _zw->size;
+    unlockImageAccess();
+}
+
+
 
-        for (int i = 0; i < size; ++i)
-            *(voidstart + i) = *(datastart + i);
+bool CImageBasis::SetIndepended()
+{
+    size_t size = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return false;
+
+    uint8_t* independent = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->SetIndepended (" + name + ")", size,
+        MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (independent == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetIndepended: PSRAM allocation failed");
+        return false;
+    }
 
-        _zw->size += size;
+    uint8_t* source = RGBImageLock();
+    if (source == nullptr) {
+        free_psram_heap(std::string(TAG) + "->SetIndepended failed (" + name + ")", independent);
+        return false;
     }
-    else {
-        jpgFileTooLarge = true;
+    memCopy(source, independent, static_cast<int>(size));
+
+    uint8_t* previous = rgb_image;
+    const bool previousExternal = externalImage;
+    const int previousSize = memsize;
+    const bool previousSharedLease = ownsSharedTempImageLease;
+
+    rgb_image = independent;
+    memsize = static_cast<int>(size);
+    externalImage = false;
+    ownsSharedTempImageLease = false;
+
+    if (!previousExternal) {
+        releaseOwnedImageBuffer(std::string(TAG) + "->SetIndepended old", name,
+                                previous, previousSize, previousSharedLease);
     }
+    RGBImageRelease();
+    return true;
 }
 
 
-ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
+void writejpghelp(void *context, void *data, int size)
 {
-    ImageData* ii = new ImageData;
+    ImageData* output = static_cast<ImageData*>(context);
+    if (output == nullptr || data == nullptr || size <= 0 || output->size > MAX_JPG_SIZE) return;
+    if (static_cast<size_t>(size) > (MAX_JPG_SIZE - output->size)) {
+        output->size = MAX_JPG_SIZE + 1U;
+        return;
+    }
+    std::memcpy(output->data + output->size, data, static_cast<size_t>(size));
+    output->size += static_cast<size_t>(size);
+}
 
-    RGBImageLock();
-    stbi_write_jpg_to_func(writejpghelp, ii, width, height, channels, rgb_image, quality);
-    RGBImageRelease();
 
-    if (jpgFileTooLarge) {
-        jpgFileTooLarge = false;
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: Creation aborted! JPG size > preallocated buffer: " + std::to_string(MAX_JPG_SIZE));
+ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
+{
+    ImageData* ii = new (std::nothrow) ImageData;
+    if (ii == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: PSRAM allocation failed");
+        return nullptr;
+    }
+    writeToMemoryAsJPG(ii, quality);
+    if (ii->size == 0) {
+        delete ii;
+        return nullptr;
     }
     return ii;
 }
@@ -100,18 +183,22 @@ ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
 
 void CImageBasis::writeToMemoryAsJPG(ImageData* i, const int quality)
 {
-    ImageData* ii = new ImageData;
-    
-    RGBImageLock();
-    stbi_write_jpg_to_func(writejpghelp, ii, width, height, channels, rgb_image, quality);
+    if (i == nullptr || !ImageOkay()) return;
+    i->size = 0;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: image is unavailable or locked");
+        return;
+    }
+    const int success = stbi_write_jpg_to_func(writejpghelp, i, width, height, channels, image, quality);
     RGBImageRelease();
-
-    if (jpgFileTooLarge) {
-        jpgFileTooLarge = false;
+    if (i->size > MAX_JPG_SIZE) {
+        i->size = 0;
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: Creation aborted! JPG size > preallocated buffer: " + std::to_string(MAX_JPG_SIZE));
+    } else if (!success) {
+        i->size = 0;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: JPEG encoder failed");
     }
-    memCopy((uint8_t*) ii, (uint8_t*) i, sizeof(ImageData));
-    delete ii;
 }
 
 
@@ -119,76 +206,76 @@ struct SendJPGHTTP
 {
     httpd_req_t *req;
     esp_err_t res;
-    char buf[HTTP_BUFFER_SENT];
-    int size = 0;
+    char *buf;
+    size_t size = 0;
 };
-
-
+static void flushJPGHTTPBuffer(SendJPGHTTP* send)
+{
+    if (send == nullptr || send->res != ESP_OK || send->size == 0) return;
+    if (httpd_resp_send_chunk(send->req, send->buf, send->size) != ESP_OK) {
+        ESP_LOGE(TAG, "File sending failed!");
+        send->res = ESP_FAIL;
+    }
+    send->size = 0;
+}
 inline void writejpgtohttphelp(void *context, void *data, int size)
 {
-    SendJPGHTTP* _send = (SendJPGHTTP*) context;
-    if ((_send->size + size) >= HTTP_BUFFER_SENT)     // data no longer fits in buffer
-    {
-        if (httpd_resp_send_chunk(_send->req, _send->buf, _send->size) != ESP_OK) 
-        {
-                    ESP_LOGE(TAG, "File sending failed!");
-                    _send->res = ESP_FAIL;  
+    SendJPGHTTP* send = static_cast<SendJPGHTTP*>(context);
+    if (send == nullptr || data == nullptr || size <= 0 || send->res != ESP_OK) return;
+    const uint8_t* source = static_cast<const uint8_t*>(data);
+    size_t remaining = static_cast<size_t>(size);
+    while (remaining > 0 && send->res == ESP_OK) {
+        if (send->size >= HTTP_BUFFER_SENT) {
+            flushJPGHTTPBuffer(send);
+            if (send->res != ESP_OK) return;
         }
-        _send->size = 0;      
+        const size_t available = HTTP_BUFFER_SENT - send->size;
+        const size_t copySize = std::min(available, remaining);
+        std::memcpy(send->buf + send->size, source, copySize);
+        send->size += copySize;
+        source += copySize;
+        remaining -= copySize;
     }
-    std::memcpy((void*) (&(_send->buf[0]) + _send->size), data, size);
-    _send->size+= size;
-} 
-
-
+}
 esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
 {
-    SendJPGHTTP ii;
-    ii.req = _req;
-    ii.res = ESP_OK;
-    ii.size = 0;
-
-    RGBImageLock();
-    stbi_write_jpg_to_func(writejpgtohttphelp, &ii, width, height, channels, rgb_image, quality);
-
-    if (ii.size > 0)
-    {
-        if (httpd_resp_send_chunk(_req, (char*) ii.buf, ii.size) != ESP_OK)             //still send the rest
-        {
-            ESP_LOGE(TAG, "File sending failed!");
-            ii.res = ESP_FAIL;  
-        }
+    if (_req == nullptr || !ImageOkay()) return ESP_FAIL;
+    SendJPGHTTP send;
+    send.req = _req; send.res = ESP_OK; send.size = 0;
+    send.buf = static_cast<char*>(malloc_psram_heap("JPEG HTTP stream buffer", HTTP_BUFFER_SENT, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (send.buf == nullptr) return ESP_ERR_NO_MEM;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) {
+        free_psram_heap("JPEG HTTP stream buffer", send.buf);
+        return ESP_FAIL;
     }
-
+    const int encoded = stbi_write_jpg_to_func(writejpgtohttphelp, &send, width, height, channels, image, quality);
+    if (!encoded && send.res == ESP_OK) send.res = ESP_FAIL;
+    flushJPGHTTPBuffer(&send);
     RGBImageRelease();
-
-    return ii.res;
-}  
+    free_psram_heap("JPEG HTTP stream buffer", send.buf);
+    return send.res;
+}
 
 
 bool CImageBasis::CopyFromMemory(uint8_t* _source, int _size)
 {
-    int gr = height * width * channels;
-    if (gr != _size)            // Size does not fit
-    {
-        ESP_LOGE(TAG, "Cannot copy image from memory - sizes do not match: should be %d, but is %d", _size, gr);
+    size_t expected = 0;
+    if (_source == nullptr || rgb_image == nullptr || _size < 0 ||
+        !getImageBufferSize(width, height, channels, &expected) ||
+        expected != static_cast<size_t>(_size)) {
+        ESP_LOGE(TAG, "Cannot copy image from memory - sizes do not match: should be %u, but is %d",
+                 static_cast<unsigned int>(expected), _size);
         return false;
     }
-
-    RGBImageLock();
-    memCopy(_source, rgb_image, _size);
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return false;
+    memCopy(_source, image, _size);
     RGBImageRelease();
-
     return true;
 }
 
 
-uint8_t CImageBasis::GetPixelColor(int x, int y, int ch)
-{
-    stbi_uc* p_source;
-    p_source = rgb_image + (channels * (y * width + x));
-    return p_source[ch];
-}
 
 
 void CImageBasis::memCopy(uint8_t* _source, uint8_t* _target, int _size)
@@ -216,16 +303,17 @@ bool CImageBasis::isInImage(int x, int y)
 
 void CImageBasis::setPixelColor(int x, int y, int r, int g, int b)
 {
-    stbi_uc* p_source;
-
-    RGBImageLock();
-    p_source = rgb_image + (channels * (y * width + x));
-    p_source[0] = r;
-    if ( channels > 2)
-    {
-        p_source[1] = g;
-        p_source[2] = b;
-    }
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !isInImage(x, y) ||
+        !getImageBufferSize(width, height, channels, &imageSize)) return;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    const size_t offset = static_cast<size_t>(channels) *
+        (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
+    if (offset >= imageSize) { RGBImageRelease(); return; }
+    uint8_t* pixel = image + offset;
+    pixel[0] = static_cast<uint8_t>(r);
+    if (channels > 2) { pixel[1] = static_cast<uint8_t>(g); pixel[2] = static_cast<uint8_t>(b); }
     RGBImageRelease();
 }
 
@@ -240,7 +328,7 @@ void CImageBasis::drawRect(int x, int y, int dx, int dy, int r, int g, int b, in
     zwy1 = y;
     zwy2 = y;
 
-    RGBImageLock();
+    if (RGBImageLock() == nullptr) return;
 
     for (_thick = 0; _thick < thickness; _thick++)
         for (_x = zwx1; _x <= zwx2; ++_x)
@@ -288,7 +376,7 @@ void CImageBasis::drawLine(int x1, int y1, int x2, int y2, int r, int g, int b,
     int _zwy1, _zwy2;
     thickness = (thickness-1) / 2;
 
-    RGBImageLock();
+    if (RGBImageLock() == nullptr) return;
 
     for (_thick = 0; _thick <= thickness; ++_thick)
         for (_x = x1 - _thick; _x <= x2 + _thick; ++_x)
@@ -324,7 +412,7 @@ void CImageBasis::drawEllipse(int x1, int y1, int radx, int rady, int r, int g,
 
     deltarad = 1 / (4 * M_PI * (rad + thickness - 1));
 
-    RGBImageLock();
+    if (RGBImageLock() == nullptr) return;
 
     for (aktrad = 0; aktrad <= (2 * M_PI); aktrad += deltarad)
         for (_thick = 0; _thick < thickness; ++_thick)
@@ -346,7 +434,7 @@ void CImageBasis::drawCircle(int x1, int y1, int rad, int r, int g, int b, int t
 
     deltarad = 1 / (4 * M_PI * (rad + thickness - 1));
 
-    RGBImageLock();
+    if (RGBImageLock() == nullptr) return;
 
     for (aktrad = 0; aktrad <= (2 * M_PI); aktrad += deltarad)
         for (_thick = 0; _thick < thickness; ++_thick)
@@ -375,154 +463,186 @@ CImageBasis::CImageBasis(string _name)
 
 void CImageBasis::CreateEmptyImage(int _width, int _height, int _channels)
 {
-    bpp = _channels;
-    width = _width;
-    height = _height;
-    channels = _channels;
-
-    RGBImageLock();
-
-    #ifdef DEBUG_DETAIL_ON 
+    if (_width <= 0 || _height <= 0 || _channels <= 0 || name == "tmpImage") return;
+    size_t newSize = 0;
+    if (!getImageBufferSize(_width, _height, _channels, &newSize)) return;
+    uint8_t* newImage = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->CImageBasis (" + name + ")", newSize,
+        MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (newImage == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CreateEmptyImage: allocation failed");
         LogFile.WriteHeapInfo("CreateEmptyImage");
-    #endif
-
-    memsize = width * height * channels;
-
-    rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
-
-    if (rgb_image == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CreateEmptyImage: Can't allocate enough memory: " + std::to_string(memsize));
-        LogFile.WriteHeapInfo("CreateEmptyImage");
-        RGBImageRelease();
         return;
     }
-
-    // One contiguous memset instead of a per-pixel, column-by-column loop through PSRAM
-    memset(rgb_image, 0, width * height * channels);
-
-    RGBImageRelease();
+    std::memset(newImage, 0, newSize);
+    if (!lockImageAccess()) {
+        free_psram_heap(std::string(TAG) + "->CImageBasis (lock failed)", newImage);
+        return;
+    }
+    if (rgb_image != nullptr && !externalImage) {
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis old", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
+    }
+    rgb_image = newImage;
+    width = _width;
+    height = _height;
+    channels = _channels;
+    bpp = _channels;
+    memsize = static_cast<int>(newSize);
+    externalImage = false;
+    ownsSharedTempImageLease = false;
+    unlockImageAccess();
 }
 
 
 void CImageBasis::EmptyImage()
 {
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("EmptyImage");
-    #endif
-
-    RGBImageLock();
-
-    // One contiguous memset instead of a per-pixel, column-by-column loop through PSRAM
-    memset(rgb_image, 0, width * height * channels);
-
+    size_t size = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    std::memset(image, 0, size);
     RGBImageRelease();
 }
 
 
-void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
+bool CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 {
-    RGBImageLock();
-
-    if (rgb_image != NULL) {
-        stbi_image_free(rgb_image);
-        //free_psram_heap(std::string(TAG) + "->rgb_image (LoadFromMemory)", rgb_image);
+    if (_buffer == NULL || len <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: invalid input buffer");
+        return false;
     }
 
-    rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, STBI_rgb);
-    bpp = channels;
-    ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
-    
-    if ((width * height * channels) == 0)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image with size 0 loaded --> reboot to be done! "
-                "Check that your camera module is working and connected properly.");
+    int newWidth = 0, newHeight = 0, sourceChannels = 0;
+    uint8_t* decoded = stbi_load_from_memory(_buffer, len, &newWidth, &newHeight,
+                                              &sourceChannels, STBI_rgb);
+    size_t decodedSize = 0;
+    if (decoded == NULL || !getImageBufferSize(newWidth, newHeight, STBI_rgb, &decodedSize)) {
+        if (decoded != NULL) stbi_image_free(decoded);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: image decode failed or returned invalid dimensions");
         LogFile.WriteHeapInfo("LoadFromMemory");
+        return false;
+    }
 
-        doReboot();
+    if (!lockImageAccess()) {
+        stbi_image_free(decoded);
+        return false;
     }
-    RGBImageRelease();
+    if (rgb_image != NULL && !externalImage) {
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
+    }
+    rgb_image = decoded;
+    width = newWidth;
+    height = newHeight;
+    channels = STBI_rgb;
+    bpp = sourceChannels;
+    memsize = 0;
+    externalImage = false;
+    ownsSharedTempImageLease = false;
+    unlockImageAccess();
+    ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
+    return true;
 }
 
 
 void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom)
 {
-    unsigned int maxTopIndex = cropTop * width * channels;
-    unsigned int minBottomIndex = ((width*height) - (cropBottom * width)) * channels;
-    unsigned short maxX = width - cropRight; // In pixels
-    unsigned short newWidth = width - cropLeft - cropRight;
-    unsigned short newHeight = height - cropTop - cropBottom;
-
-    unsigned int writeIndex = 0;
-    // Loop over all bytes
-    for (int i = 0; i < width * height * channels; i += channels) {
-        // Calculate current X, Y pixel position
-        int x = (i/channels) % width;
-
-        // Crop from the top
-        if (i < maxTopIndex) { continue; }
-
-        // Crop from the bottom
-        if (i > minBottomIndex) { continue; }
-
-        // Crop from the left
-        if (x <= cropLeft) { continue; }
-
-        // Crop from the right
-        if (x > maxX) { continue; }
-
-        // If we get here, keep the pixels
-        for (int c = 0; c < channels; c++) {
-            rgb_image[writeIndex++] = rgb_image[i+c];
+    size_t inputSize = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &inputSize) ||
+        static_cast<unsigned int>(cropLeft) + cropRight >= static_cast<unsigned int>(width) ||
+        static_cast<unsigned int>(cropTop) + cropBottom >= static_cast<unsigned int>(height)) return;
+
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    const int oldWidth = width;
+    const int oldHeight = height;
+    const size_t rowBytes = static_cast<size_t>(oldWidth) * static_cast<size_t>(channels);
+    const size_t firstRow = static_cast<size_t>(cropTop) * rowBytes;
+    const size_t endRow = static_cast<size_t>(oldHeight - cropBottom) * rowBytes;
+    const unsigned int maxX = static_cast<unsigned int>(oldWidth) - cropRight;
+    const unsigned int newWidth = static_cast<unsigned int>(oldWidth) - cropLeft - cropRight;
+    const unsigned int newHeight = static_cast<unsigned int>(oldHeight) - cropTop - cropBottom;
+    size_t writeIndex = 0;
+
+    for (size_t i = 0; i < inputSize; i += static_cast<size_t>(channels)) {
+        const unsigned int x = static_cast<unsigned int>((i / static_cast<size_t>(channels)) % static_cast<size_t>(oldWidth));
+        if (i < firstRow || i >= endRow || x < cropLeft || x >= maxX) continue;
+        const size_t pixelBytes = static_cast<size_t>(channels);
+        if (i > inputSize || pixelBytes > inputSize - i || writeIndex > inputSize ||
+            pixelBytes > inputSize - writeIndex) {
+            RGBImageRelease();
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "crop_image: computed crop bounds exceeded image buffer");
+            return;
         }
+        std::memmove(image + writeIndex, image + i, pixelBytes);
+        writeIndex += pixelBytes;
     }
-
-    // Set the new dimensions of the framebuffer for further use.
-    width = newWidth;
-    height = newHeight;
+    width = static_cast<int>(newWidth);
+    height = static_cast<int>(newHeight);
+    RGBImageRelease();
 }
 
 
-CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom) 
+CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
 {
     name = _name;
     islocked = false;
     externalImage = false;
-    channels = _copyfrom->channels;
+    rgb_image = NULL;
+    width = height = channels = bpp = 0;
+    memsize = 0;
+    ownsSharedTempImageLease = false;
+
+    if (_copyfrom == NULL || !_copyfrom->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: source image is not available");
+        return;
+    }
+
+    size_t imageSize = 0;
+    if (!getImageBufferSize(_copyfrom->width, _copyfrom->height, _copyfrom->channels, &imageSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: invalid source dimensions");
+        return;
+    }
     width = _copyfrom->width;
     height = _copyfrom->height;
+    channels = _copyfrom->channels;
     bpp = _copyfrom->bpp;
 
-    RGBImageLock();
-
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_copyfrom - Start");
-    #endif
-
-    memsize = width * height * channels;
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_copyfrom - Start");
+#endif
 
+    uint8_t* source = _copyfrom->RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: source image is locked");
+        return;
+    }
 
     if (name == "tmpImage") {
-        rgb_image = (unsigned char*)psram_reserve_shared_tmp_image_memory();
-    }
-    else {
-        rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
+        rgb_image = static_cast<uint8_t*>(psram_reserve_shared_tmp_image_memory());
+        ownsSharedTempImageLease = (rgb_image != NULL);
+        memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
+    } else {
+        rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
+            std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
+            MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+        memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
     }
 
-    if (rgb_image == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: Can't allocate enough memory: " + std::to_string(memsize));
+    if (rgb_image == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
         LogFile.WriteHeapInfo("CImageBasis-Copyfrom");
-        RGBImageRelease();
+        _copyfrom->RGBImageRelease();
         return;
     }
 
-    memCopy(_copyfrom->rgb_image, rgb_image, memsize);
-    RGBImageRelease();
+    memCopy(source, rgb_image, static_cast<int>(imageSize));
+    _copyfrom->RGBImageRelease();
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_copyfrom - done");
-    #endif
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_copyfrom - done");
+#endif
 }
 
 
@@ -531,34 +651,39 @@ CImageBasis::CImageBasis(string _name, int _width, int _height, int _channels)
     name = _name;
     islocked = false;
     externalImage = false;
-    channels = _channels;
-    width = _width;
-    height = _height;
-    bpp = _channels;
-
-    RGBImageLock();
-
-     #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_width,height,ch - Start");
-    #endif
+    ownsSharedTempImageLease = false;
+    rgb_image = NULL;
+    width = height = channels = bpp = 0;
+    memsize = 0;
 
-    memsize = width * height * channels;
+    size_t imageSize = 0;
+    if (!getImageBufferSize(_width, _height, _channels, &imageSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: invalid image dimensions");
+        return;
+    }
 
-    rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_width,height,ch - Start");
+#endif
 
-    if (rgb_image == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: Can't allocate enough memory: " + std::to_string(memsize));
+    rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
+        MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (rgb_image == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
         LogFile.WriteHeapInfo("CImageBasis-width,height,ch");
-        RGBImageRelease();
         return;
     }
 
-    RGBImageRelease();
+    width = _width;
+    height = _height;
+    channels = _channels;
+    bpp = _channels;
+    memsize = static_cast<int>(imageSize);
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_width,height,ch - done");
-    #endif
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_width,height,ch - done");
+#endif
 }
 
 
@@ -566,8 +691,12 @@ CImageBasis::CImageBasis(string _name, std::string _image)
 {
     name = _name;
     islocked = false;
-    channels = 3;
+    channels = STBI_rgb;
+    width = height = bpp = 0;
+    memsize = 0;
     externalImage = false;
+    ownsSharedTempImageLease = false;
+    rgb_image = NULL;
     filename = _image;
 
     if (file_size(_image.c_str()) == 0) {
@@ -575,37 +704,45 @@ CImageBasis::CImageBasis(string _name, std::string _image)
         return;
     }
 
-    RGBImageLock();
-
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_image - Start");
-    #endif
-
-    rgb_image = stbi_load(_image.c_str(), &width, &height, &bpp, channels);
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_image - Start");
+#endif
 
-    if (rgb_image == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-image: Failed to load " + _image + "! Is it corrupted?");
+    int loadedWidth = 0, loadedHeight = 0, sourceChannels = 0;
+    uint8_t* loaded = stbi_load(_image.c_str(), &loadedWidth, &loadedHeight,
+                                &sourceChannels, STBI_rgb);
+    size_t imageSize = 0;
+    if (loaded == NULL || !getImageBufferSize(loadedWidth, loadedHeight, STBI_rgb, &imageSize)) {
+        if (loaded != NULL) stbi_image_free(loaded);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-image: Failed to load valid image " + _image);
         LogFile.WriteHeapInfo("CImageBasis-image");
-        RGBImageRelease();
         return;
     }
-    
-    RGBImageRelease();
-
-    #ifdef DEBUG_DETAIL_ON 
-        std::string zw = "CImageBasis after load " + _image;
-        ESP_LOGD(TAG, "%s", zw.c_str());
-        ESP_LOGD(TAG, "w %d, h %d, b %d, c %d", width, height, bpp, channels);
-    #endif
-
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_image - done");
-    #endif
+    if (!lockImageAccess()) {
+        stbi_image_free(loaded);
+        return;
+    }
+    rgb_image = loaded;
+    width = loadedWidth;
+    height = loadedHeight;
+    bpp = sourceChannels;
+    unlockImageAccess();
+
+#ifdef DEBUG_DETAIL_ON
+    std::string zw = "CImageBasis after load " + _image;
+    ESP_LOGD(TAG, "%s", zw.c_str());
+    ESP_LOGD(TAG, "w %d, h %d, b %d, c %d", width, height, bpp, channels);
+    LogFile.WriteHeapInfo("CImageBasis_image - done");
+#endif
 }
 
 
 bool CImageBasis::ImageOkay(){
-    return rgb_image != NULL;
+    if (!lockImageAccess()) return false;
+    size_t imageSize = 0;
+    const bool okay = rgb_image != NULL && getImageBufferSize(width, height, channels, &imageSize);
+    unlockImageAccess();
+    return okay;
 }
 
 
@@ -624,80 +761,64 @@ CImageBasis::CImageBasis(string _name, uint8_t* _rgb_image, int _channels, int _
 
 void CImageBasis::Negative(void)
 {
-    RGBImageLock();
-
-    for (int i = 0; i < width * height * channels; i += channels) {
-        for (int c = 0; c < channels; c++) {
-            rgb_image[i+c] = 255 - rgb_image[i+c];
-        }
-    }
-
+    size_t size = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    for (size_t i = 0; i < size; i += static_cast<size_t>(channels))
+        for (int c = 0; c < channels; ++c) image[i + static_cast<size_t>(c)] = 255 - image[i + static_cast<size_t>(c)];
     RGBImageRelease();
 }
 
 
-void CImageBasis::Contrast(float _contrast)  //input range [-100..100]
-{
-    stbi_uc* p_source;
-    
-    float contrast = (_contrast/100) + 1;  //convert to decimal & shift range: [0..2]
-    float intercept = 128 * (1 - contrast);
-
-    RGBImageLock();
-
-
-    for (int x = 0; x < width; ++x)
-        for (int y = 0; y < height; ++y)
-        {
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_source[_channels] = (uint8_t) std::min(255, std::max(0, (int) (p_source[_channels] * contrast + intercept)));
+void CImageBasis::Contrast(float _contrast)
+{
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    const float contrast = (_contrast / 100) + 1;
+    const float intercept = 128 * (1 - contrast);
+    for (int y = 0; y < height; ++y) {
+        for (int x = 0; x < width; ++x) {
+            const size_t offset = static_cast<size_t>(channels) *
+                (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
+            uint8_t* pixel = image + offset;
+            for (int channel = 0; channel < channels; ++channel)
+                pixel[channel] = static_cast<uint8_t>(std::min(255, std::max(0,
+                    static_cast<int>(pixel[channel] * contrast + intercept))));
         }
-
+    }
     RGBImageRelease();
 }
 
 
 CImageBasis::~CImageBasis()
 {
-    RGBImageLock();
-
-
-    if (!externalImage) {
-        if (name == "tmpImage") { // This image should be placed in the shared part of PSRAM
-            psram_free_shared_temp_image_memory();
-        }
-        else { // All other images are much smaller and can go into the normal PSRAM region
-            //stbi_image_free(rgb_image);
-            if (memsize == 0) {
-                LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Not freeing (" + name + " as there was never PSRAM allocated for it)");
-            }
-            else {
-                free_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ", " + to_string(memsize) + ")", rgb_image);
-            }
-        }
+    if (!lockImageAccess(-1)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Destructor could not acquire image lock");
+        return;
     }
-
-    RGBImageRelease();
+    if (!externalImage && rgb_image != NULL) {
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
+    }
+    rgb_image = NULL;
+    ownsSharedTempImageLease = false;
+    unlockImageAccess();
 }
 
 
 void CImageBasis::SaveToFile(std::string _imageout)
 {
-    string typ = getFileType(_imageout);
-
-    RGBImageLock();
-
-    if ((typ == "jpg") || (typ == "JPG"))       // CAUTION PROBLEMATIC IN ESP32
-    {
-        stbi_write_jpg(_imageout.c_str(), width, height, channels, rgb_image, 0);
-    }
- 
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
+    const string typ = getFileType(_imageout);
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    if ((typ == "jpg") || (typ == "JPG")) stbi_write_jpg(_imageout.c_str(), width, height, channels, image, 0);
 #ifndef STBI_ONLY_JPEG
-    if ((typ == "bmp") || (typ == "BMP"))
-    {
-        stbi_write_bmp(_imageout.c_str(), width, height, channels, rgb_image);
-    }
+    if ((typ == "bmp") || (typ == "BMP")) stbi_write_bmp(_imageout.c_str(), width, height, channels, image);
 #endif
     RGBImageRelease();
 }
@@ -705,57 +826,79 @@ void CImageBasis::SaveToFile(std::string _imageout)
 
 void CImageBasis::Resize(int _new_dx, int _new_dy)
 {
-    // tmpImage lives in the shared PSRAM region and its destructor relies on that; never resize it in place
-    if ((rgb_image == NULL) || (name == "tmpImage")) {
+    if (rgb_image == NULL || name == "tmpImage") {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: not possible for image " + name);
         return;
     }
-
-    int new_memsize = _new_dx * _new_dy * channels;
-    uint8_t* odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis Resize (" + name + ")", new_memsize, MALLOC_CAP_SPIRAM);
-
-    if (odata == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: Can't allocate enough memory: " + std::to_string(new_memsize));
+    size_t newSize = 0;
+    if (!getImageBufferSize(_new_dx, _new_dy, channels, &newSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: invalid target dimensions");
         return;
     }
 
-    RGBImageLock();
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) return;
+    uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->CImageBasis Resize (" + name + ")", newSize,
+        MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (output == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: PSRAM allocation failed: " + std::to_string(newSize));
+        return;
+    }
 
-    stbir_resize_uint8(rgb_image, width, height, 0, odata, _new_dx, _new_dy, 0, channels);
+    const int resized = stbir_resize_uint8(source, width, height, 0,
+                                            output, _new_dx, _new_dy, 0, channels);
+    if (resized == 0) {
+        RGBImageRelease();
+        free_psram_heap(std::string(TAG) + "->CImageBasis Resize (failed)", output);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: stb resize failed");
+        return;
+    }
 
-    // Release the old buffer with the allocator it came from (same rule as the destructor)
     if (!externalImage) {
-        if (memsize == 0) { // Loaded via STBI (STBI_MALLOC)
-            stbi_image_free(rgb_image);
-        }
-        else {
-            free_psram_heap(std::string(TAG) + "->CImageBasis Resize old (" + name + ")", rgb_image);
-        }
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis Resize old", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
     }
-
-    rgb_image = odata;
-    memsize = new_memsize;
-    externalImage = false; // The image now owns a normal PSRAM buffer
+    rgb_image = output;
+    memsize = static_cast<int>(newSize);
+    externalImage = false;
+    ownsSharedTempImageLease = false;
     width = _new_dx;
     height = _new_dy;
-
     RGBImageRelease();
 }
 
 
-void CImageBasis::Resize(int _new_dx, int _new_dy, CImageBasis *_target)
+bool CImageBasis::Resize(int _new_dx, int _new_dy, CImageBasis *_target)
 {
-    if ((_target->height != _new_dy) || (_target->width != _new_dx) || (_target->channels != channels))
-    {
-        ESP_LOGE(TAG, "Resize - Target image size does not fit!");
-        return;
+    if (_target == this || _target == NULL || rgb_image == NULL || !_target->ImageOkay() ||
+        _target->height != _new_dy || _target->width != _new_dx ||
+        _target->channels != channels) {
+        ESP_LOGE(TAG, "Resize - Target image size does not fit or is unavailable!");
+        return false;
     }
 
-    RGBImageLock();
+    size_t sourceSize = 0, targetSize = 0;
+    if (!getImageBufferSize(width, height, channels, &sourceSize) ||
+        !getImageBufferSize(_new_dx, _new_dy, channels, &targetSize)) {
+        ESP_LOGE(TAG, "Resize - Invalid source or target dimensions");
+        return false;
+    }
 
-    uint8_t* odata = _target->rgb_image;
-    stbir_resize_uint8(rgb_image, width, height, 0, odata, _new_dx, _new_dy, 0, channels);
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) return false;
+    uint8_t* target = _target->RGBImageLock();
+    if (target == NULL) {
+        RGBImageRelease();
+        return false;
+    }
 
+    const int resized = stbir_resize_uint8(source, width, height, 0,
+                                            target, _new_dx, _new_dy, 0, channels);
+    _target->RGBImageRelease();
     RGBImageRelease();
+    if (resized == 0) ESP_LOGE(TAG, "Resize - stb resize failed");
+    return resized != 0;
 }
 

+ 18 - 5
code/components/jomjol_image_proc/CImageBasis.h

@@ -4,6 +4,9 @@
 #define CIMAGEBASIS_H
 
 #include <stdint.h>
+#include <stddef.h>
+#include <new>
+#include <stdlib.h>
 #include <string>
 #include <esp_http_server.h>
 
@@ -21,6 +24,17 @@ struct ImageData
 {
     uint8_t data[MAX_JPG_SIZE];
     size_t size = 0;
+
+    static void* operator new(size_t size) {
+        void* ptr = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+        if (ptr == nullptr) abort();
+        return ptr;
+    }
+    static void* operator new(size_t size, const std::nothrow_t&) noexcept {
+        return heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    }
+    static void operator delete(void* ptr) noexcept { heap_caps_free(ptr); }
+    static void operator delete(void* ptr, const std::nothrow_t&) noexcept { heap_caps_free(ptr); }
 };
 
 
@@ -29,6 +43,7 @@ class CImageBasis
 {
     protected:
         bool externalImage;
+        bool ownsSharedTempImageLease = false;
         std::string filename;
         std::string name; // Just used for diagnostics
         int memsize = 0;
@@ -45,7 +60,6 @@ class CImageBasis
 
         uint8_t * RGBImageLock(int _waitmaxsec = 60);
         void RGBImageRelease();
-        uint8_t * RGBImageGet();
 
         int getWidth(){return this->width;};   
         int getHeight(){return this->height;};   
@@ -61,7 +75,7 @@ class CImageBasis
         bool ImageOkay();
         bool CopyFromMemory(uint8_t* _source, int _size);
 
-        void SetIndepended(){externalImage = false; memsize = width * height * channels;};
+        bool SetIndepended();
 
         void CreateEmptyImage(int _width, int _height, int _channels);
         void EmptyImage();
@@ -74,17 +88,16 @@ class CImageBasis
         CImageBasis(std::string name, CImageBasis *_copyfrom);
 
         void Resize(int _new_dx, int _new_dy);        
-        void Resize(int _new_dx, int _new_dy, CImageBasis *_target);        
+        bool Resize(int _new_dx, int _new_dy, CImageBasis *_target);        
         void crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom);
 
-        void LoadFromMemory(stbi_uc *_buffer, int len);
+        bool LoadFromMemory(stbi_uc *_buffer, int len);
 
         ImageData* writeToMemoryAsJPG(const int quality = 90);
         void writeToMemoryAsJPG(ImageData* ii, const int quality = 90);
 
         esp_err_t SendJPGtoHTTP(httpd_req_t *req, const int quality = 90);   
 
-        uint8_t GetPixelColor(int x, int y, int ch);
 
         ~CImageBasis();
 

+ 451 - 326
code/components/jomjol_image_proc/CRotateImage.cpp

@@ -1,326 +1,451 @@
-#include <string>
-#include "CRotateImage.h"
-#include "psram.h"
-
-static const char *TAG = "C ROTATE IMG";
-
-// Value written to target pixels whose source lies outside the image (the gaps left by a rotation or
-// translation). It has to be black: the reference image is rotated in the browser (edit_reference.html),
-// which exports the uncovered canvas area as black. The alignment markers are cut from that reference,
-// so a marker that reaches into the gap would otherwise be matched against the wrong colour (#4169).
-static const stbi_uc FILL_VALUE = 0;
-
-CRotateImage::CRotateImage(std::string _name, CImageBasis *_org, CImageBasis *_temp, bool _flip) : CImageBasis(_name)
-{
-    rgb_image = _org->rgb_image;
-    channels = _org->channels;
-    width = _org->width;
-    height = _org->height;
-    bpp = _org->bpp;
-    externalImage = true;   
-    ImageTMP = _temp;   
-    ImageOrg = _org; 
-    islocked = false;
-    doflip = _flip;
-}
-
-void CRotateImage::Rotate(float _angle, int _centerx, int _centery)
-{
-    if ((_angle == 0) && !doflip) {  // identity transform, the copy would leave the image unchanged
-        return;
-    }
-
-    int org_width, org_height;
-    float m[2][3];
-
-    float x_center = _centerx;
-    float y_center = _centery;
-    _angle = _angle / 180 * M_PI;
-
-    if (doflip)
-    {
-        org_width = width;
-        org_height = height;
-        height = org_width;
-        width = org_height;
-        x_center =  x_center - (org_width/2) + (org_height/2);
-        y_center =  y_center + (org_width/2) - (org_height/2);
-        if (ImageOrg)
-        {
-            ImageOrg->height = height;
-            ImageOrg->width = width;
-        }
-    }
-    else
-    {
-        org_width = width;
-        org_height = height;
-    }
-
-    m[0][0] = cos(_angle);
-    m[0][1] = sin(_angle);
-    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
-
-    m[1][0] = -m[0][1];
-    m[1][1] = m[0][0];
-    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
-
-    if (doflip)
-    {
-        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
-        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
-    }
-
-    int memsize = width * height * channels;
-    uint8_t* odata;
-    if (ImageTMP)
-    {
-        odata = ImageTMP->RGBImageLock();
-    }
-    else
-    {
-        odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-    }
-    
-
-    int x_source, y_source;
-    stbi_uc* p_target;
-    stbi_uc* p_source;
-
-    RGBImageLock();
-
-    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
-    for (int y = 0; y < height; ++y)
-        for (int x = 0; x < width; ++x)
-        {
-            p_target = odata + (channels * (y * width + x));
-
-            x_source = int(m[0][0] * x + m[0][1] * y);
-            y_source = int(m[1][0] * x + m[1][1] * y);
-
-            x_source += int(m[0][2]);
-            y_source += int(m[1][2]);
-
-            if ((x_source >= 0) && (x_source < org_width) && (y_source >= 0) && (y_source < org_height))
-            {
-                p_source = rgb_image + (channels * (y_source * org_width + x_source));
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = p_source[_channels];
-            }
-            else
-            {
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = FILL_VALUE;
-            }
-        }
-
-    //    memcpy(rgb_image, odata, memsize);
-    memCopy(odata, rgb_image, memsize);
-
-    if (!ImageTMP)
-    {
-        free_psram_heap(std::string(TAG) + "->odata", odata);
-    }
-    if (ImageTMP)
-        ImageTMP->RGBImageRelease();
-
-    RGBImageRelease();
-}
-
-
-
-void CRotateImage::RotateAntiAliasing(float _angle, int _centerx, int _centery)
-{
-    int org_width, org_height;
-    float m[2][3];
-
-    float x_center = _centerx;
-    float y_center = _centery;
-    _angle = _angle / 180 * M_PI;
-
-    if (doflip)
-    {
-        org_width = width;
-        org_height = height;
-        height = org_width;
-        width = org_height;
-        x_center =  x_center - (org_width/2) + (org_height/2);
-        y_center =  y_center + (org_width/2) - (org_height/2);
-        if (ImageOrg)
-        {
-            ImageOrg->height = height;
-            ImageOrg->width = width;
-        }
-    }
-    else
-    {
-        org_width = width;
-        org_height = height;
-    }
-
-    m[0][0] = cos(_angle);
-    m[0][1] = sin(_angle);
-    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
-
-    m[1][0] = -m[0][1];
-    m[1][1] = m[0][0];
-    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
-
-    if (doflip)
-    {
-        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
-        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
-    }
-
-    int memsize = width * height * channels;
-    uint8_t* odata;
-    if (ImageTMP)
-    {
-        odata = ImageTMP->RGBImageLock();
-    }
-    else
-    {
-        odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-    }
-    
-
-    int x_source_1, y_source_1, x_source_2, y_source_2;
-    float x_source, y_source;
-    float quad_ul, quad_ur, quad_ol, quad_or;
-    stbi_uc* p_target;
-    stbi_uc *p_source_ul, *p_source_ur, *p_source_ol, *p_source_or;
-
-    RGBImageLock();
-
-    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
-    for (int y = 0; y < height; ++y)
-        for (int x = 0; x < width; ++x)
-        {
-            p_target = odata + (channels * (y * width + x));
-
-            x_source = (m[0][0] * x + m[0][1] * y);
-            y_source = (m[1][0] * x + m[1][1] * y);
-
-            x_source += (m[0][2]);
-            y_source += (m[1][2]);
-
-            x_source_1 = (int)x_source;
-            x_source_2 = x_source_1 + 1;
-            y_source_1 = (int)y_source;
-            y_source_2 = y_source_1 + 1;
-
-            quad_ul = (x_source_2 - x_source) * (y_source_2 - y_source);
-            quad_ur = (1- (x_source_2 - x_source)) * (y_source_2 - y_source);
-            quad_or = (x_source_2 - x_source) * (1-(y_source_2 - y_source));
-            quad_ol = (1- (x_source_2 - x_source)) * (1-(y_source_2 - y_source));
-
-
-            if ((x_source_1 >= 0) && (x_source_2 < org_width) && (y_source_1 >= 0) && (y_source_2 < org_height))
-            {
-                p_source_ul = rgb_image + (channels * (y_source_1 * org_width + x_source_1));
-                p_source_ur = rgb_image + (channels * (y_source_1 * org_width + x_source_2));
-                p_source_or = rgb_image + (channels * (y_source_2 * org_width + x_source_1));
-                p_source_ol = rgb_image + (channels * (y_source_2 * org_width + x_source_2));
-                for (int _channels = 0; _channels < channels; ++_channels)
-                {
-                    p_target[_channels] = (int)((float)p_source_ul[_channels] * quad_ul
-                                                + (float)p_source_ur[_channels] * quad_ur
-                                                + (float)p_source_or[_channels] * quad_or
-                                                + (float)p_source_ol[_channels] * quad_ol);
-                }
-            }
-            else
-            {
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = FILL_VALUE;
-            }
-        }
-
-    //    memcpy(rgb_image, odata, memsize);
-    memCopy(odata, rgb_image, memsize);
-
-    if (!ImageTMP)
-    {
-        free_psram_heap(std::string(TAG) + "->odata", odata);
-    }
-    if (ImageTMP)
-        ImageTMP->RGBImageRelease();
-
-    RGBImageRelease();
-}
-
-
-void CRotateImage::Rotate(float _angle)
-{
-//    ESP_LOGD(TAG, "width %d, height %d", width, height);
-    Rotate(_angle, width / 2, height / 2);
-}
-
-void CRotateImage::RotateAntiAliasing(float _angle)
-{
-//    ESP_LOGD(TAG, "width %d, height %d", width, height);
-    RotateAntiAliasing(_angle, width / 2, height / 2);
-}
-
-void CRotateImage::Translate(int _dx, int _dy)
-{
-    if ((_dx == 0) && (_dy == 0)) {  // identity transform, the copy would leave the image unchanged
-        return;
-    }
-
-    int memsize = width * height * channels;
-    uint8_t* odata;
-    if (ImageTMP)
-    {
-        odata = ImageTMP->RGBImageLock();
-    }
-    else
-    {
-        odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-    }
-
-
-
-    int x_source, y_source;
-    stbi_uc* p_target;
-    stbi_uc* p_source;
-
-    RGBImageLock();
-
-    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
-    for (int y = 0; y < height; ++y)
-        for (int x = 0; x < width; ++x)
-        {
-            p_target = odata + (channels * (y * width + x));
-
-            x_source = x - _dx;
-            y_source = y - _dy;
-
-            if ((x_source >= 0) && (x_source < width) && (y_source >= 0) && (y_source < height))
-            {
-                p_source = rgb_image + (channels * (y_source * width + x_source));
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = p_source[_channels];
-            }
-            else
-            {
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = FILL_VALUE;
-            }
-        }
-
-    //    memcpy(rgb_image, odata, memsize);
-    memCopy(odata, rgb_image, memsize);
-    if (!ImageTMP)
-    {
-        free_psram_heap(std::string(TAG) + "->odata", odata);
-    }
-
-    if (ImageTMP)
-    {
-        ImageTMP->RGBImageRelease();
-    }
-    RGBImageRelease();
-
-}
-
+#include <string>
+#include <limits.h>
+#include "CRotateImage.h"
+#include "ClassLogFile.h"
+#include "psram.h"
+
+static const char *TAG = "C ROTATE IMG";
+
+class ScopedImageAccess
+{
+    CImageBasis* image;
+    bool locked;
+public:
+    explicit ScopedImageAccess(CImageBasis* value) : image(value), locked(false)
+    {
+        if (image != NULL) locked = image->RGBImageLock() != NULL;
+    }
+    ~ScopedImageAccess()
+    {
+        if (locked) image->RGBImageRelease();
+    }
+    bool isLocked() const { return locked; }
+};
+
+static bool getRotateBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
+// Value written to target pixels whose source lies outside the image (the gaps left by a rotation or
+// translation). It has to be black: the reference image is rotated in the browser (edit_reference.html),
+// which exports the uncovered canvas area as black. The alignment markers are cut from that reference,
+// so a marker that reaches into the gap would otherwise be matched against the wrong colour (#4169).
+static const stbi_uc FILL_VALUE = 0;
+
+CRotateImage::CRotateImage(std::string _name, CImageBasis *_org, CImageBasis *_temp, bool _flip) : CImageBasis(_name)
+{
+    rgb_image = _org->rgb_image;
+    channels = _org->channels;
+    width = _org->width;
+    height = _org->height;
+    bpp = _org->bpp;
+    externalImage = true;   
+    ImageTMP = _temp;   
+    ImageOrg = _org; 
+    islocked = false;
+    doflip = _flip;
+}
+
+void CRotateImage::Rotate(float _angle, int _centerx, int _centery)
+{
+    ScopedImageAccess sourceAccess(ImageOrg != NULL ? ImageOrg : this);
+    if (!sourceAccess.isLocked()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: unable to lock source image");
+        return;
+    }
+    if ((_angle == 0) && !doflip) {  // identity transform, the copy would leave the image unchanged
+        return;
+    }
+
+    int org_width, org_height;
+    float m[2][3];
+
+    float x_center = _centerx;
+    float y_center = _centery;
+    _angle = _angle / 180 * M_PI;
+
+    if (doflip)
+    {
+        org_width = width;
+        org_height = height;
+        height = org_width;
+        width = org_height;
+        x_center =  x_center - (org_width/2) + (org_height/2);
+        y_center =  y_center + (org_width/2) - (org_height/2);
+        if (ImageOrg)
+        {
+            ImageOrg->height = height;
+            ImageOrg->width = width;
+        }
+    }
+    else
+    {
+        org_width = width;
+        org_height = height;
+    }
+
+    m[0][0] = cos(_angle);
+    m[0][1] = sin(_angle);
+    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
+
+    m[1][0] = -m[0][1];
+    m[1][1] = m[0][0];
+    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
+
+    if (doflip)
+    {
+        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
+        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
+    }
+
+    size_t bufferSize = 0;
+    if (!getRotateBufferSize(width, height, channels, &bufferSize)) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: invalid dimensions or size overflow");
+        return;
+    }
+    const int memsize = static_cast<int>(bufferSize);
+    uint8_t* odata;
+    if (ImageTMP) {
+        odata = ImageTMP->RGBImageLock();
+    } else {
+        odata = static_cast<unsigned char*>(malloc_psram_heap(
+            std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    }
+    if (odata == NULL) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: temporary PSRAM allocation failed");
+        return;
+    }
+    
+
+    int x_source, y_source;
+    stbi_uc* p_target;
+    stbi_uc* p_source;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        if (ImageTMP) ImageTMP->RGBImageRelease();
+        else free_psram_heap(std::string(TAG) + "->odata", odata);
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: source image is unavailable");
+        return;
+    }
+
+    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+        {
+            p_target = odata + (channels * (y * width + x));
+
+            x_source = int(m[0][0] * x + m[0][1] * y);
+            y_source = int(m[1][0] * x + m[1][1] * y);
+
+            x_source += int(m[0][2]);
+            y_source += int(m[1][2]);
+
+            if ((x_source >= 0) && (x_source < org_width) && (y_source >= 0) && (y_source < org_height))
+            {
+                p_source = source + (channels * (y_source * org_width + x_source));
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = p_source[_channels];
+            }
+            else
+            {
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = FILL_VALUE;
+            }
+        }
+
+    //    memcpy(rgb_image, odata, memsize);
+    memCopy(odata, source, memsize);
+
+    if (!ImageTMP)
+    {
+        free_psram_heap(std::string(TAG) + "->odata", odata);
+    }
+    if (ImageTMP)
+        ImageTMP->RGBImageRelease();
+
+    RGBImageRelease();
+}
+
+
+
+void CRotateImage::RotateAntiAliasing(float _angle, int _centerx, int _centery)
+{
+    ScopedImageAccess sourceAccess(ImageOrg != NULL ? ImageOrg : this);
+    if (!sourceAccess.isLocked()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: unable to lock source image");
+        return;
+    }
+    int org_width, org_height;
+    float m[2][3];
+
+    float x_center = _centerx;
+    float y_center = _centery;
+    _angle = _angle / 180 * M_PI;
+
+    if (doflip)
+    {
+        org_width = width;
+        org_height = height;
+        height = org_width;
+        width = org_height;
+        x_center =  x_center - (org_width/2) + (org_height/2);
+        y_center =  y_center + (org_width/2) - (org_height/2);
+        if (ImageOrg)
+        {
+            ImageOrg->height = height;
+            ImageOrg->width = width;
+        }
+    }
+    else
+    {
+        org_width = width;
+        org_height = height;
+    }
+
+    m[0][0] = cos(_angle);
+    m[0][1] = sin(_angle);
+    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
+
+    m[1][0] = -m[0][1];
+    m[1][1] = m[0][0];
+    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
+
+    if (doflip)
+    {
+        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
+        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
+    }
+
+    size_t bufferSize = 0;
+    if (!getRotateBufferSize(width, height, channels, &bufferSize)) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: invalid dimensions or size overflow");
+        return;
+    }
+    const int memsize = static_cast<int>(bufferSize);
+    uint8_t* odata;
+    if (ImageTMP) {
+        odata = ImageTMP->RGBImageLock();
+    } else {
+        odata = static_cast<unsigned char*>(malloc_psram_heap(
+            std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    }
+    if (odata == NULL) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: temporary PSRAM allocation failed");
+        return;
+    }
+    
+
+    int x_source_1, y_source_1, x_source_2, y_source_2;
+    float x_source, y_source;
+    float quad_ul, quad_ur, quad_ol, quad_or;
+    stbi_uc* p_target;
+    stbi_uc *p_source_ul, *p_source_ur, *p_source_ol, *p_source_or;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        if (ImageTMP) ImageTMP->RGBImageRelease();
+        else free_psram_heap(std::string(TAG) + "->odata", odata);
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: source image is unavailable");
+        return;
+    }
+
+    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+        {
+            p_target = odata + (channels * (y * width + x));
+
+            x_source = (m[0][0] * x + m[0][1] * y);
+            y_source = (m[1][0] * x + m[1][1] * y);
+
+            x_source += (m[0][2]);
+            y_source += (m[1][2]);
+
+            x_source_1 = (int)x_source;
+            x_source_2 = x_source_1 + 1;
+            y_source_1 = (int)y_source;
+            y_source_2 = y_source_1 + 1;
+
+            quad_ul = (x_source_2 - x_source) * (y_source_2 - y_source);
+            quad_ur = (1- (x_source_2 - x_source)) * (y_source_2 - y_source);
+            quad_or = (x_source_2 - x_source) * (1-(y_source_2 - y_source));
+            quad_ol = (1- (x_source_2 - x_source)) * (1-(y_source_2 - y_source));
+
+
+            if ((x_source_1 >= 0) && (x_source_2 < org_width) && (y_source_1 >= 0) && (y_source_2 < org_height))
+            {
+                p_source_ul = source + (channels * (y_source_1 * org_width + x_source_1));
+                p_source_ur = source + (channels * (y_source_1 * org_width + x_source_2));
+                p_source_or = source + (channels * (y_source_2 * org_width + x_source_1));
+                p_source_ol = source + (channels * (y_source_2 * org_width + x_source_2));
+                for (int _channels = 0; _channels < channels; ++_channels)
+                {
+                    p_target[_channels] = (int)((float)p_source_ul[_channels] * quad_ul
+                                                + (float)p_source_ur[_channels] * quad_ur
+                                                + (float)p_source_or[_channels] * quad_or
+                                                + (float)p_source_ol[_channels] * quad_ol);
+                }
+            }
+            else
+            {
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = FILL_VALUE;
+            }
+        }
+
+    //    memcpy(rgb_image, odata, memsize);
+    memCopy(odata, source, memsize);
+
+    if (!ImageTMP)
+    {
+        free_psram_heap(std::string(TAG) + "->odata", odata);
+    }
+    if (ImageTMP)
+        ImageTMP->RGBImageRelease();
+
+    RGBImageRelease();
+}
+
+
+void CRotateImage::Rotate(float _angle)
+{
+    ScopedImageAccess sourceAccess(ImageOrg != NULL ? ImageOrg : this);
+    if (!sourceAccess.isLocked()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: unable to lock source image");
+        return;
+    }
+//    ESP_LOGD(TAG, "width %d, height %d", width, height);
+    Rotate(_angle, width / 2, height / 2);
+}
+
+void CRotateImage::RotateAntiAliasing(float _angle)
+{
+    ScopedImageAccess sourceAccess(ImageOrg != NULL ? ImageOrg : this);
+    if (!sourceAccess.isLocked()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: unable to lock source image");
+        return;
+    }
+//    ESP_LOGD(TAG, "width %d, height %d", width, height);
+    RotateAntiAliasing(_angle, width / 2, height / 2);
+}
+
+void CRotateImage::Translate(int _dx, int _dy)
+{
+    ScopedImageAccess sourceAccess(ImageOrg != NULL ? ImageOrg : this);
+    if (!sourceAccess.isLocked()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: unable to lock source image");
+        return;
+    }
+    if ((_dx == 0) && (_dy == 0)) {  // identity transform, the copy would leave the image unchanged
+        return;
+    }
+
+    size_t bufferSize = 0;
+    if (!getRotateBufferSize(width, height, channels, &bufferSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: invalid dimensions or size overflow");
+        return;
+    }
+    const int memsize = static_cast<int>(bufferSize);
+    uint8_t* odata;
+    if (ImageTMP) {
+        odata = ImageTMP->RGBImageLock();
+    } else {
+        odata = static_cast<unsigned char*>(malloc_psram_heap(
+            std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    }
+    if (odata == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: temporary PSRAM allocation failed");
+        return;
+    }
+
+
+
+    int x_source, y_source;
+    stbi_uc* p_target;
+    stbi_uc* p_source;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        if (ImageTMP) ImageTMP->RGBImageRelease();
+        else free_psram_heap(std::string(TAG) + "->odata", odata);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: source image is unavailable");
+        return;
+    }
+
+    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+        {
+            p_target = odata + (channels * (y * width + x));
+
+            x_source = x - _dx;
+            y_source = y - _dy;
+
+            if ((x_source >= 0) && (x_source < width) && (y_source >= 0) && (y_source < height))
+            {
+                p_source = source + (channels * (y_source * width + x_source));
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = p_source[_channels];
+            }
+            else
+            {
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = FILL_VALUE;
+            }
+        }
+
+    //    memcpy(rgb_image, odata, memsize);
+    memCopy(odata, source, memsize);
+    if (!ImageTMP)
+    {
+        free_psram_heap(std::string(TAG) + "->odata", odata);
+    }
+
+    if (ImageTMP)
+    {
+        ImageTMP->RGBImageRelease();
+    }
+    RGBImageRelease();
+
+}
+

+ 59 - 36
code/components/jomjol_mqtt/mqtt_outbox.c

@@ -3,6 +3,7 @@
 */
 #include "mqtt_outbox.h"
 #include <stdlib.h>
+#include <limits.h>
 #include <string.h>
 #include "sys/queue.h"
 #include "esp_log.h"
@@ -38,70 +39,84 @@ outbox_handle_t outbox_init(void)
 #else
     outbox_handle_t outbox = calloc(1, sizeof(struct outbox_list_t));
 #endif
-    //ESP_MEM_CHECK(TAG, outbox, return NULL);
+    if (outbox == NULL) {
+        ESP_LOGE(TAG, "Unable to allocate MQTT outbox");
+        return NULL;
+    }
     STAILQ_INIT(outbox);
     return outbox;
 }
 
 outbox_item_handle_t outbox_enqueue(outbox_handle_t outbox, outbox_message_handle_t message, outbox_tick_t tick)
 {
+    if (outbox == NULL || message == NULL || message->len < 0 || message->remaining_len < 0 ||
+        message->len > INT_MAX - message->remaining_len) return NULL;
+    const size_t totalLength = (size_t)message->len + (size_t)message->remaining_len;
+    if ((message->len > 0 && message->data == NULL) ||
+        (message->remaining_len > 0 && message->remaining_data == NULL)) return NULL;
 #ifdef USE_PSRAM
     outbox_item_handle_t item = heap_caps_calloc(1, sizeof(outbox_item_t), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
 #else
     outbox_item_handle_t item = calloc(1, sizeof(outbox_item_t));
 #endif
-    //ESP_MEM_CHECK(TAG, item, return NULL);
-    item->msg_id = message->msg_id;
-    item->msg_type = message->msg_type;
-    item->msg_qos = message->msg_qos;
-    item->tick = tick;
-    item->len =  message->len + message->remaining_len;
-    item->pending = QUEUED;
+    if (item == NULL) return NULL;
 #ifdef USE_PSRAM
-    item->buffer = heap_caps_malloc(message->len + message->remaining_len, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
+    item->buffer = heap_caps_malloc(totalLength == 0 ? 1 : totalLength, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
 #else
-    item->buffer = malloc(message->len + message->remaining_len);
+    item->buffer = malloc(totalLength == 0 ? 1 : totalLength);
 #endif
-    /*ESP_MEM_CHECK(TAG, item->buffer, {
+    if (item->buffer == NULL) {
+#ifdef USE_PSRAM
+        heap_caps_free(item);
+#else
         free(item);
+#endif
         return NULL;
-    });*/
-    memcpy(item->buffer, message->data, message->len);
-    if (message->remaining_data) {
-        memcpy(item->buffer + message->len, message->remaining_data, message->remaining_len);
     }
+    item->msg_id = message->msg_id;
+    item->msg_type = message->msg_type;
+    item->msg_qos = message->msg_qos;
+    item->tick = tick;
+    item->len = (int)totalLength;
+    item->pending = QUEUED;
+    if (message->len > 0) memcpy(item->buffer, message->data, (size_t)message->len);
+    if (message->remaining_len > 0) memcpy(item->buffer + message->len, message->remaining_data, (size_t)message->remaining_len);
     STAILQ_INSERT_TAIL(outbox, item, next);
-    ESP_LOGD(TAG, "ENQUEUE msgid=%d, msg_type=%d, len=%d, size=%d", message->msg_id, message->msg_type, message->len + message->remaining_len, outbox_get_size(outbox));
+    ESP_LOGD(TAG, "ENQUEUE msgid=%d, msg_type=%d, len=%d, size=%d", message->msg_id, message->msg_type, item->len, outbox_get_size(outbox));
     return item;
 }
 
 outbox_item_handle_t outbox_get(outbox_handle_t outbox, int msg_id)
 {
+    if (outbox == NULL) return NULL;
     outbox_item_handle_t item;
-    STAILQ_FOREACH(item, outbox, next) {
-        if (item->msg_id == msg_id) {
-            return item;
-        }
-    }
+    STAILQ_FOREACH(item, outbox, next) if (item->msg_id == msg_id) return item;
     return NULL;
 }
 
 outbox_item_handle_t outbox_dequeue(outbox_handle_t outbox, pending_state_t pending, outbox_tick_t *tick)
 {
+    if (outbox == NULL) return NULL;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
-        if (item->pending == pending) {
-            if (tick) {
-                *tick = item->tick;
-            }
-            return item;
-        }
+        if (item->pending == pending) { if (tick) *tick = item->tick; return item; }
     }
     return NULL;
 }
 
+uint8_t *outbox_item_get_data(outbox_item_handle_t item, size_t *len, uint16_t *msg_id, int *msg_type, int *qos)
+{
+    if (item == NULL) return NULL;
+    if (len != NULL) *len = (size_t)item->len;
+    if (msg_id != NULL) *msg_id = (uint16_t)item->msg_id;
+    if (msg_type != NULL) *msg_type = item->msg_type;
+    if (qos != NULL) *qos = item->msg_qos;
+    return (uint8_t*)item->buffer;
+}
+
 esp_err_t outbox_delete_item(outbox_handle_t outbox, outbox_item_handle_t item_to_delete)
 {
+    if (outbox == NULL || item_to_delete == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
         if (item == item_to_delete) {
@@ -133,6 +148,7 @@ uint8_t *outbox_item_get_data(outbox_item_handle_t item,  size_t *len, uint16_t
 
 esp_err_t outbox_delete(outbox_handle_t outbox, int msg_id, int msg_type)
 {
+    if (outbox == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         if (item->msg_id == msg_id && (0xFF & (item->msg_type)) == msg_type) {
@@ -153,6 +169,7 @@ esp_err_t outbox_delete(outbox_handle_t outbox, int msg_id, int msg_type)
 }
 esp_err_t outbox_delete_msgid(outbox_handle_t outbox, int msg_id)
 {
+    if (outbox == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         if (item->msg_id == msg_id) {
@@ -199,6 +216,7 @@ esp_err_t outbox_set_tick(outbox_handle_t outbox, int msg_id, outbox_tick_t tick
 
 esp_err_t outbox_delete_msgtype(outbox_handle_t outbox, int msg_type)
 {
+    if (outbox == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         if (item->msg_type == msg_type) {
@@ -217,6 +235,7 @@ esp_err_t outbox_delete_msgtype(outbox_handle_t outbox, int msg_type)
 }
 int outbox_delete_single_expired(outbox_handle_t outbox, outbox_tick_t current_tick, outbox_tick_t timeout)
 {
+    if (outbox == NULL) { return -1; }
     int msg_id = -1;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
@@ -246,6 +265,7 @@ int outbox_delete_single_expired(outbox_handle_t outbox, outbox_tick_t current_t
 
 int outbox_delete_expired(outbox_handle_t outbox, outbox_tick_t current_tick, outbox_tick_t timeout)
 {
+    if (outbox == NULL) { return 0; }
     int deleted_items = 0;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
@@ -267,32 +287,35 @@ int outbox_delete_expired(outbox_handle_t outbox, outbox_tick_t current_tick, ou
 
 int outbox_get_size(outbox_handle_t outbox)
 {
-    int siz = 0;
+    if (outbox == NULL) return 0;
+    int size = 0;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
-        // Suppressing "use after free" warning as this could happen only if queue is in inconsistent state
-        // which never happens if STAILQ interface used
-        siz += item->len; // NOLINT(clang-analyzer-unix.Malloc)
+        if (item->len > INT_MAX - size) return INT_MAX;
+        size += item->len;
     }
-    return siz;
+    return size;
 }
 
 void outbox_delete_all_items(outbox_handle_t outbox)
 {
+    if (outbox == NULL) return;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         STAILQ_REMOVE(outbox, item, outbox_item, next);
 #ifdef USE_PSRAM
-            heap_caps_free(item->buffer);
-            heap_caps_free(item);
+        heap_caps_free(item->buffer);
+        heap_caps_free(item);
 #else
-            free(item->buffer);
-            free(item);
+        free(item->buffer);
+        free(item);
 #endif
     }
 }
+
 void outbox_destroy(outbox_handle_t outbox)
 {
+    if (outbox == NULL) { return; }
     outbox_delete_all_items(outbox);
 
 #ifdef USE_PSRAM

+ 159 - 107
code/components/jomjol_tfliteclass/CTfLiteClass.cpp

@@ -6,6 +6,8 @@
 #include "../../include/defines.h"
 
 #include <sys/stat.h>
+#include <new>
+#include <limits.h>
 
 // #define DEBUG_DETAIL_ON
 
@@ -30,10 +32,12 @@ void CTfLiteClass::MakeStaticResolver()
 
 float CTfLiteClass::GetOutputValue(int nr)
 {
+    if (this->interpreter == nullptr || !lastInvokeSucceeded || nr < 0) return -1000.0f;
     TfLiteTensor* output2 = this->interpreter->output(0);
+    if (output2 == nullptr || output2->dims == nullptr || output2->dims->size < 2) return -1000.0f;
 
     int numeroutput = output2->dims->data[1];
-    if ((nr+1) > numeroutput)
+    if (nr >= numeroutput || output2->data.f == nullptr)
       return -1000;
 
     return output2->data.f[nr];
@@ -42,24 +46,25 @@ float CTfLiteClass::GetOutputValue(int nr)
 
 int CTfLiteClass::GetClassFromImageBasis(CImageBasis *rs)
 {
-    if (!LoadInputImageBasis(rs))
+    if (interpreter == nullptr || !LoadInputImageBasis(rs))
       return -1000;
 
     Invoke();
-
+    if (!lastInvokeSucceeded) return -1000;
     return GetOutClassification();
 }
 
 
 int CTfLiteClass::GetOutClassification(int _von, int _bis)
 {
+  if (interpreter == nullptr || !lastInvokeSucceeded) return -1;
   TfLiteTensor* output2 = interpreter->output(0);
 
   float zw_max;
   float zw;
   int zw_class;
 
-  if (output2 == NULL)
+  if (output2 == NULL || output2->dims == nullptr || output2->dims->size < 2 || output2->data.f == nullptr)
     return -1;
 
   int numeroutput = output2->dims->data[1];
@@ -71,7 +76,7 @@ int CTfLiteClass::GetOutClassification(int _von, int _bis)
   if (_von == -1)
     _von = 0;
 
-  if (_bis >= numeroutput)
+  if (_von < 0 || _bis < _von || _bis >= numeroutput)
   {
     ESP_LOGD(TAG, "NUMBER OF OUTPUT NEURONS does not match required classification!");
     return -1;
@@ -92,10 +97,15 @@ int CTfLiteClass::GetOutClassification(int _von, int _bis)
 }
 
 
-void CTfLiteClass::GetInputDimension(bool silent = false)
+void CTfLiteClass::GetInputDimension(bool silent)
 {
+  if (this->interpreter == nullptr) return;
   TfLiteTensor* input2 = this->interpreter->input(0);
+  if (input2 == nullptr || input2->dims == nullptr) return;
 
+  im_height = 0;
+  im_width = 0;
+  im_channel = 0;
   int numdim = input2->dims->size;
   if (!silent)  ESP_LOGD(TAG, "NumDimension: %d", numdim);
 
@@ -126,9 +136,12 @@ int CTfLiteClass::ReadInputDimenstion(int _dim)
 
 int CTfLiteClass::GetAnzOutPut(bool silent)
 {
+  if (this->interpreter == nullptr) return 0;
   TfLiteTensor* output2 = this->interpreter->output(0);
+  if (output2 == nullptr || output2->dims == nullptr) return 0;
 
   int numdim = output2->dims->size;
+  if (numdim < 2 || output2->data.f == nullptr) return 0;
   if (!silent) ESP_LOGD(TAG, "NumDimension: %d", numdim);
 
   int sizeofdim;
@@ -154,94 +167,116 @@ int CTfLiteClass::GetAnzOutPut(bool silent)
 
 void CTfLiteClass::Invoke()
 {
-    if (interpreter != nullptr)
-      interpreter->Invoke();
+    lastInvokeSucceeded = false;
+    if (interpreter == nullptr) return;
+    if (interpreter->Invoke() == kTfLiteOk) lastInvokeSucceeded = true;
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite Invoke() failed");
 }
 
 
 bool CTfLiteClass::LoadInputImageBasis(CImageBasis *rs)
 {
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - Start");
-    #endif
-
-    unsigned int w = rs->width;
-    unsigned int h = rs->height;
-    unsigned char red, green, blue;
-//    ESP_LOGD(TAG, "Image: %s size: %d x %d\n", _fn.c_str(), w, h);
-
-    input_i = 0;
-    float* input_data_ptr = (interpreter->input(0))->data.f;
-
-    for (int y = 0; y < h; ++y)
-        for (int x = 0; x < w; ++x)
-            {
-                red = rs->GetPixelColor(x, y, 0);
-                green = rs->GetPixelColor(x, y, 1);
-                blue = rs->GetPixelColor(x, y, 2);
-                *(input_data_ptr) = (float) red;
-                input_data_ptr++;
-                *(input_data_ptr) = (float) green;
-                input_data_ptr++;
-                *(input_data_ptr) = (float) blue;
-                input_data_ptr++;
-            }
-
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - done");
-    #endif
+    if (rs == nullptr || !rs->ImageOkay() || interpreter == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: image or interpreter is unavailable");
+        return false;
+    }
+
+    TfLiteTensor* inputTensor = interpreter->input(0);
+    if (inputTensor == nullptr || inputTensor->dims == nullptr ||
+        inputTensor->data.f == nullptr || inputTensor->type != kTfLiteFloat32 ||
+        inputTensor->dims->size < 4) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: input tensor is unavailable or not float32 image data");
+        return false;
+    }
+
+    const int imageWidth = rs->width;
+    const int imageHeight = rs->height;
+    if (imageWidth <= 0 || imageHeight <= 0 || rs->channels < 3) return false;
+
+    const int expectedHeight = inputTensor->dims->data[1];
+    const int expectedWidth = inputTensor->dims->data[2];
+    const int expectedChannels = inputTensor->dims->data[3];
+    if (expectedWidth != imageWidth || expectedHeight != imageHeight || expectedChannels != 3) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: image dimensions do not match model input tensor");
+        return false;
+    }
+
+    if (static_cast<size_t>(imageWidth) > SIZE_MAX / static_cast<size_t>(imageHeight)) return false;
+    const size_t pixelCount = static_cast<size_t>(imageWidth) * static_cast<size_t>(imageHeight);
+    if (pixelCount > SIZE_MAX / (3U * sizeof(float))) return false;
+    const size_t requiredBytes = pixelCount * 3U * sizeof(float);
+    if (inputTensor->bytes < requiredBytes) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: model input tensor buffer is smaller than the image");
+        return false;
+    }
+
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - Start");
+#endif
+
+    uint8_t* image = rs->RGBImageLock();
+    if (image == nullptr) return false;
+    float* inputData = inputTensor->data.f;
+    size_t outputIndex = 0;
+    for (int y = 0; y < imageHeight; ++y) {
+        for (int x = 0; x < imageWidth; ++x) {
+            const size_t sourceOffset =
+                (static_cast<size_t>(y) * static_cast<size_t>(imageWidth) +
+                 static_cast<size_t>(x)) * static_cast<size_t>(rs->channels);
+            inputData[outputIndex++] = static_cast<float>(image[sourceOffset]);
+            inputData[outputIndex++] = static_cast<float>(image[sourceOffset + 1]);
+            inputData[outputIndex++] = static_cast<float>(image[sourceOffset + 2]);
+        }
+    }
+    rs->RGBImageRelease();
 
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - done");
+#endif
     return true;
 }
 
 
-
 bool CTfLiteClass::MakeAllocate()
 {
+    if (!ownsSharedMemoryLease || tensor_arena == NULL || model == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "MakeAllocate: Tensor Arena lease or model is unavailable");
+        return false;
+    }
     MakeStaticResolver();
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTLiteClass::Alloc start");
-    #endif
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTLiteClass::Alloc start");
+#endif
 
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::MakeAllocate");
-    this->interpreter = new tflite::MicroInterpreter(this->model, resolver, this->tensor_arena, this->kTensorArenaSize);
-    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trying to load the model. If it crashes here, it ist most likely due to a corrupted model!");
+    delete this->interpreter;
+    this->interpreter = new (std::nothrow) tflite::MicroInterpreter(
+        this->model, resolver, this->tensor_arena, this->kTensorArenaSize);
+    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trying to load the model. If it crashes here, it is most likely due to a corrupted model!");
 
-    if (this->interpreter) 
-    {
-        TfLiteStatus allocate_status = this->interpreter->AllocateTensors();
-        if (allocate_status != kTfLiteOk) {
-            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "AllocateTensors() failed");
-
-            this->GetInputDimension();   
-            return false;
-        }
-    }
-    else 
-    {
+    if (this->interpreter == nullptr) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "new tflite::MicroInterpreter failed");
         LogFile.WriteHeapInfo("CTfLiteClass::MakeAllocate-new tflite::MicroInterpreter failed");
         return false;
     }
 
+    const TfLiteStatus allocate_status = this->interpreter->AllocateTensors();
+    if (allocate_status != kTfLiteOk) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "AllocateTensors() failed");
+        delete this->interpreter;
+        this->interpreter = nullptr;
+        return false;
+    }
+    lastInvokeSucceeded = false;
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTLiteClass::Alloc done");
-    #endif
-
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTLiteClass::Alloc done");
+#endif
     return true;
 }
 
 
-void CTfLiteClass::GetInputTensorSize()
-{
-#ifdef DEBUG_DETAIL_ON    
-    float *zw = this->input;
-    int test = sizeof(zw);
-    ESP_LOGD(TAG, "Input Tensor Dimension: %d", test);
-#endif
-}
 
 
 long CTfLiteClass::GetFileSize(std::string filename)
@@ -264,55 +299,54 @@ long CTfLiteClass::GetFileSize(std::string filename)
 bool CTfLiteClass::ReadFileToModel(std::string _fn)
 {
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::ReadFileToModel: " + _fn);
-    
-    long size = GetFileSize(_fn);
+    if (!ownsSharedMemoryLease || tensor_arena == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Tensor Arena shared-memory lease was not acquired");
+        return false;
+    }
 
-    if (size == -1)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Model file doesn't exist: " + _fn + "!");
+    const long size = GetFileSize(_fn);
+    if (size <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Model file is missing or empty: " + _fn);
         return false;
     }
-    else if(size > MAX_MODEL_SIZE) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to load model '" + _fn + "'! It does not fit in the reserved shared memory in PSRAM!");
+    if (static_cast<unsigned long>(size) > static_cast<unsigned long>(MAX_MODEL_SIZE)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Model file is larger than the reserved shared model region: " + _fn);
         return false;
     }
 
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Loading Model " + _fn + " /size: " + std::to_string(size) + " bytes...");
-
-#ifdef DEBUG_DETAIL_ON      
-        LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile start");
-#endif
+    FILE *pFile = fopen(_fn.c_str(), "rb");
+    if (pFile == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Could not open model file " + _fn);
+        return false;
+    }
 
-    modelfile = (unsigned char*)psram_get_shared_model_memory();
-  
-    if (modelfile != NULL)
-    {
-        FILE *pFile = fopen(_fn.c_str(), "rb"); // previously only "rb
-    
-        if (pFile != NULL)
-        {
-          fread(modelfile, 1, size, pFile);
-          fclose(pFile);
+    if (!modelMemoryClaimed) {
+        modelfile = static_cast<unsigned char*>(psram_get_shared_model_memory());
+        modelMemoryClaimed = (modelfile != NULL);
+    }
+    if (modelfile == NULL) {
+        fclose(pFile);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Unable to claim shared model memory");
+        LogFile.WriteHeapInfo("CTfLiteClass::ReadFileToModel");
+        return false;
+    }
 
 #ifdef DEBUG_DETAIL_ON
-          LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful");
+    LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile start");
 #endif
 
-          return true;
-        }
-        else
-        {
-          LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Model does not exist");
-          return false;
-        }
-    }   
-    else 
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Can't allocate enough memory: " + std::to_string(size));
-        LogFile.WriteHeapInfo("CTfLiteClass::ReadFileToModel");
-
+    const size_t bytesRead = fread(modelfile, 1, static_cast<size_t>(size), pFile);
+    const int closeResult = fclose(pFile);
+    if (bytesRead != static_cast<size_t>(size) || closeResult != 0) {
+        model = nullptr;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Short read or close error while loading " + _fn);
         return false;
     }
+
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful");
+#endif
+    return true;
 }
 
 
@@ -335,19 +369,37 @@ bool CTfLiteClass::LoadModel(std::string _fn)
 
 CTfLiteClass::CTfLiteClass()
 {
+    this->ownsSharedMemoryLease = false;
+    this->modelMemoryClaimed = false;
+    this->lastInvokeSucceeded = false;
     this->model = nullptr;
     this->modelfile = NULL;
     this->interpreter = nullptr;
     this->input = nullptr;
     this->output = nullptr;
     this->kTensorArenaSize = TENSOR_ARENA_SIZE;
-    this->tensor_arena = (uint8_t*)psram_get_shared_tensor_arena_memory();
+    this->im_height = 0;
+    this->im_width = 0;
+    this->im_channel = 0;
+    this->tensor_arena = static_cast<uint8_t*>(psram_get_shared_tensor_arena_memory());
+    this->ownsSharedMemoryLease = (this->tensor_arena != NULL);
+    if (!this->ownsSharedMemoryLease) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire shared Tensor Arena memory");
+        LogFile.WriteHeapInfo("CTfLiteClass constructor");
+    }
 }
 
 
 CTfLiteClass::~CTfLiteClass()
 {
-  delete this->interpreter;
-
-  psram_free_shared_tensor_arena_and_model_memory();
+    delete this->interpreter;
+    this->interpreter = nullptr;
+    if (ownsSharedMemoryLease) {
+        psram_free_shared_tensor_arena_and_model_memory();
+        ownsSharedMemoryLease = false;
+        modelMemoryClaimed = false;
+        lastInvokeSucceeded = false;
+        tensor_arena = nullptr;
+        modelfile = nullptr;
+    }
 }        

+ 4 - 1
code/components/jomjol_tfliteclass/CTfLiteClass.h

@@ -23,6 +23,9 @@ class CTfLiteClass
 
         int kTensorArenaSize;
         uint8_t *tensor_arena;
+        bool ownsSharedMemoryLease;
+        bool modelMemoryClaimed;
+        bool lastInvokeSucceeded;
 
         unsigned char *modelfile = NULL;
 
@@ -40,9 +43,9 @@ class CTfLiteClass
         ~CTfLiteClass();        
         bool LoadModel(std::string _fn);
         bool MakeAllocate();
-        void GetInputTensorSize();
         bool LoadInputImageBasis(CImageBasis *rs);
         void Invoke();
+        bool LastInvokeSucceeded() const { return lastInvokeSucceeded; }
         int GetAnzOutPut(bool silent = true);        
         int GetOutClassification(int _von = -1, int _bis = -1);
 

+ 0 - 10
code/components/jomjol_time_sntp/time_sntp.cpp

@@ -36,16 +36,6 @@ int LocalTimeToUTCOffsetSeconds;
 
 
 
-std::string ConvertTimeToString(time_t _time, const char * frm)
-{
-    struct tm timeinfo;
-    char strftime_buf[64];
-    localtime_r(&_time, &timeinfo);
-    strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
-
-    std::string result(strftime_buf);
-    return result;
-}
 
 
 std::string getCurrentTimeString(const char * frm)

+ 0 - 2
code/components/jomjol_time_sntp/time_sntp.h

@@ -17,8 +17,6 @@
 #include "esp_sntp.h"
 
 std::string getCurrentTimeString(const char * frm);
-std::string ConvertTimeToString(time_t _time, const char * frm);
-
 
 bool getTimeIsSet(void);
 bool getTimeWasNotSetAtBoot(void);

+ 4 - 0
code/components/jomjol_webhook/interface_webhook.cpp

@@ -112,6 +112,10 @@ bool WebhookPublish(std::vector<NumberPost*>* numbers)
 }
 
 void WebhookUploadPic(ImageData *Img) {
+    if (Img == NULL || Img->size == 0 || Img->size > MAX_JPG_SIZE) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic aborted: JPEG image buffer is unavailable or invalid");
+        return;
+    }
     if (_webhookURI.empty())
     {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WebhookUploadPic aborted: no Uri configured");

+ 12 - 2
code/main/server_main.cpp

@@ -347,9 +347,19 @@ esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
     filetosend = std::string(filename);
     ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
 
-    // Serve raw.jpg
+    // Only the test_take URL opts into temporary preview settings.
     if (filetosend == "raw.jpg")
-        return GetRawJPG(req); 
+    {
+        bool previewCapture = false;
+        char query[64] = "";
+        char preview[8] = "";
+        if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK &&
+            httpd_query_key_value(query, "preview", preview, sizeof(preview)) == ESP_OK)
+        {
+            previewCapture = (strcmp(preview, "1") == 0);
+        }
+        return GetRawJPG(req, previewCapture);
+    } 
 
     // Serve alg.jpg, alg_roi.jpg or digit and analog ROIs
     if (ESP_OK == GetJPG(filetosend, req))

Некоторые файлы не были показаны из-за большого количества измененных файлов