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

Audit PSRAM lease ownership across flow and inference call sites

SybexXx 4 дней назад
Родитель
Сommit
c89455d24d

+ 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);	
 	

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

@@ -1,379 +1,402 @@
-#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) {
+        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);
+    }
+}

+ 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

+ 5 - 2
code/components/jomjol_flowcontroll/ClassFlowTakeImage.cpp

@@ -540,7 +540,10 @@ 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);
 
@@ -581,7 +584,7 @@ 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;
 }

+ 20 - 13
code/components/jomjol_flowcontroll/MainFlowControl.cpp

@@ -1,4 +1,5 @@
 #include "MainFlowControl.h"
+#include <new>
 
 #include <string>
 #include <vector>
@@ -939,22 +940,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
         {

+ 74 - 61
code/components/jomjol_tfliteclass/CTfLiteClass.cpp

@@ -198,38 +198,39 @@ bool CTfLiteClass::LoadInputImageBasis(CImageBasis *rs)
 
 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;
+    }
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTLiteClass::Alloc done");
-    #endif
-
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTLiteClass::Alloc done");
+#endif
     return true;
 }
 
@@ -264,55 +265,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 +335,32 @@ bool CTfLiteClass::LoadModel(std::string _fn)
 
 CTfLiteClass::CTfLiteClass()
 {
+    this->ownsSharedMemoryLease = false;
+    this->modelMemoryClaimed = 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->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;
+        tensor_arena = nullptr;
+        modelfile = nullptr;
+    }
 }        

+ 2 - 0
code/components/jomjol_tfliteclass/CTfLiteClass.h

@@ -23,6 +23,8 @@ class CTfLiteClass
 
         int kTensorArenaSize;
         uint8_t *tensor_arena;
+        bool ownsSharedMemoryLease;
+        bool modelMemoryClaimed;
 
         unsigned char *modelfile = NULL;