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

Merge pull request #2 from SybexX/fix/alignment-http-locks-and-alg-roi-publication

Fix alignment HTTP blocking and publish complete ROI JPEG snapshots
SybexXx 1 день назад
Родитель
Сommit
f1341a40da

+ 117 - 15
code/components/jomjol_flowcontroll/ClassFlowAlignment.cpp

@@ -10,6 +10,7 @@
 #include "psram.h"
 #include "../../include/defines.h"
 #include <new>
+#include <cstring>
 
 static const char *TAG = "ALIGN";
 
@@ -30,7 +31,11 @@ void ClassFlowAlignment::SetInitialParameter(void)
     ownsImageBasis = false;
     ImageTMP = NULL;
 #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    AlgROIMutex = xSemaphoreCreateMutex();
     AlgROI = new (std::nothrow) ImageData;
+    if (AlgROIMutex == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to create AlgROI publication mutex");
+    }
 #endif
     previousElement = NULL;
     disabled = false;
@@ -69,11 +74,98 @@ ClassFlowAlignment::~ClassFlowAlignment()
         ownsImageBasis = false;
     }
 #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
-    delete AlgROI;
-    AlgROI = NULL;
+    if (AlgROIMutex != NULL) {
+        (void)xSemaphoreTake(AlgROIMutex, portMAX_DELAY);
+        delete AlgROI;
+        AlgROI = NULL;
+        (void)xSemaphoreGive(AlgROIMutex);
+        vSemaphoreDelete(AlgROIMutex);
+        AlgROIMutex = NULL;
+    } else {
+        delete AlgROI;
+        AlgROI = NULL;
+    }
 #endif
 }
 
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+bool ClassFlowAlignment::PublishAlgROI(const ImageData *image)
+{
+    if (image == NULL || image->size == 0 || image->size > MAX_JPG_SIZE ||
+        AlgROIMutex == NULL) return false;
+
+    if (xSemaphoreTake(AlgROIMutex, portMAX_DELAY) != pdTRUE) return false;
+
+    if (AlgROI == NULL) AlgROI = new (std::nothrow) ImageData;
+    if (AlgROI == NULL) {
+        (void)xSemaphoreGive(AlgROIMutex);
+        return false;
+    }
+
+    // Keep the last complete JPEG visible until the replacement is fully copied.
+    std::memcpy(AlgROI->data, image->data, image->size);
+    AlgROI->size = image->size;
+
+    (void)xSemaphoreGive(AlgROIMutex);
+    return true;
+}
+
+esp_err_t ClassFlowAlignment::SendAlgROIToHTTP(httpd_req_t *req)
+{
+    if (req == NULL || AlgROIMutex == NULL) return ESP_ERR_INVALID_ARG;
+
+    // Copy under the publication mutex, then release it before network I/O.
+    // A slow browser must never stall the flow task publishing the next frame.
+    ImageData *snapshot = new (std::nothrow) ImageData;
+    if (snapshot == NULL) return ESP_ERR_NO_MEM;
+
+    if (xSemaphoreTake(AlgROIMutex, pdMS_TO_TICKS(250)) != pdTRUE) {
+        delete snapshot;
+        return ESP_ERR_TIMEOUT;
+    }
+
+    if (AlgROI == NULL || AlgROI->size == 0 || AlgROI->size > MAX_JPG_SIZE) {
+        (void)xSemaphoreGive(AlgROIMutex);
+        delete snapshot;
+        return ESP_ERR_NOT_FOUND;
+    }
+
+    std::memcpy(snapshot->data, AlgROI->data, AlgROI->size);
+    snapshot->size = AlgROI->size;
+    (void)xSemaphoreGive(AlgROIMutex);
+
+    esp_err_t result = httpd_resp_set_type(req, "image/jpeg");
+    if (result == ESP_OK) {
+        result = httpd_resp_send(req, (const char *)snapshot->data, snapshot->size);
+    }
+    delete snapshot;
+    return result;
+}
+
+ImageData *ClassFlowAlignment::GetAlgROICopy(void)
+{
+    if (AlgROIMutex == NULL) return NULL;
+    ImageData *copy = new (std::nothrow) ImageData;
+    if (copy == NULL) return NULL;
+
+    if (xSemaphoreTake(AlgROIMutex, pdMS_TO_TICKS(1000)) != pdTRUE) {
+        delete copy;
+        return NULL;
+    }
+
+    if (AlgROI == NULL || AlgROI->size == 0 || AlgROI->size > MAX_JPG_SIZE) {
+        (void)xSemaphoreGive(AlgROIMutex);
+        delete copy;
+        return NULL;
+    }
+
+    std::memcpy(copy->data, AlgROI->data, AlgROI->size);
+    copy->size = AlgROI->size;
+    (void)xSemaphoreGive(AlgROIMutex);
+    return copy;
+}
+#endif
+
 bool ClassFlowAlignment::ReadParameter(FILE *pfile, string &aktparamgraph)
 {
     std::vector<string> splitted;
@@ -196,12 +288,16 @@ bool ClassFlowAlignment::doFlow(string time)
     }
 
 #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);
+    // Encode into a private temporary buffer, then publish the complete JPEG.
+    // HTTP readers never observe a buffer while the encoder is modifying it.
+    ImageData *initialPreview = ImageBasis->writeToMemoryAsJPG(90);
+    if (initialPreview != NULL) {
+        if (!PublishAlgROI(initialPreview)) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to publish initial ROI preview");
+        }
+        delete initialPreview;
     } else {
-        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "AlgROI PSRAM allocation failed; continuing without in-memory ROI JPEG");
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to create initial ROI preview");
         LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
     }
 #endif
@@ -283,15 +379,21 @@ bool ClassFlowAlignment::doFlow(string time)
     } // 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);
-        }
+    // 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);
+    flowctrl.DigitDrawROI(ImageTMP);
+    flowctrl.AnalogDrawROI(ImageTMP);
+    ImageData *alignedPreview = ImageTMP->writeToMemoryAsJPG(90);
+    if (alignedPreview != NULL) {
+        if (!PublishAlgROI(alignedPreview)) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to publish aligned ROI preview");
+        }
+        delete alignedPreview;
+    } else {
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to create aligned ROI preview");
     }
 #endif
 

+ 11 - 0
code/components/jomjol_flowcontroll/ClassFlowAlignment.h

@@ -8,6 +8,11 @@
 #include "CAlignAndCutImage.h"
 #include "CFindTemplate.h"
 
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+#include "freertos/FreeRTOS.h"
+#include "freertos/semphr.h"
+#endif
+
 #include <string>
 
 using namespace std;
@@ -26,6 +31,10 @@ protected:
     std::string FileStoreRefAlignment;
     float SAD_criteria;
     bool ownsImageBasis;
+#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
+    SemaphoreHandle_t AlgROIMutex;
+    bool PublishAlgROI(const ImageData *image);
+#endif
 
     void SetInitialParameter(void);
     bool LoadReferenceAlignmentValues(void);
@@ -35,6 +44,8 @@ public:
     CImageBasis *ImageBasis, *ImageTMP;
 #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
     ImageData *AlgROI;
+    esp_err_t SendAlgROIToHTTP(httpd_req_t *req);
+    ImageData *GetAlgROICopy(void);
 #endif
 
     ClassFlowAlignment(std::vector<ClassFlow *> *lfc);

+ 12 - 14
code/components/jomjol_flowcontroll/ClassFlowControll.cpp

@@ -806,7 +806,7 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 */
             }
             else if (status.find("Take Image") != -1) {
-                if (flowalignment && flowalignment->AlgROI) {
+                if (flowalignment != NULL) {
                     std::string filename = "/sdcard/html/Flowstate_take_image.jpg";
                     result = send_file(req, filename);
                     /*
@@ -847,21 +847,19 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 }
             }
             else {
-                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 is unavailable -> alg.jpg is going to be served!");
-                    if (flowalignment && flowalignment->ImageBasis && flowalignment->ImageBasis->ImageOkay()) {
-                        _send = flowalignment->ImageBasis;
-                    }
-                    else {
-                        httpd_resp_send(req, NULL, 0);
-                        return ESP_OK;
+                if (flowalignment != NULL) {
+                    result = flowalignment->SendAlgROIToHTTP(req);
+                    if (result != ESP_ERR_NOT_FOUND && result != ESP_ERR_TIMEOUT) {
+                        return result;
                     }
                 }
+
+                // A missing preview must not fall back to ImageBasis: that would
+                // make the single HTTP server task wait on the global image lock.
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "ClassFlowControll::GetJPGStream: ROI preview is not ready");
+                httpd_resp_set_status(req, "503 Service Unavailable");
+                httpd_resp_set_type(req, "text/plain");
+                return httpd_resp_send(req, "ROI preview not ready", HTTPD_RESP_USE_STRLEN);
             }
         #else
             if (!flowalignment) {

+ 6 - 2
code/components/jomjol_flowcontroll/ClassFlowWebhook.cpp

@@ -169,8 +169,12 @@ bool ClassFlowWebhook::doFlow(string zwtime)
         bool numbersWithError = WebhookPublish(flowpostprocessing->GetNumbers());
 
         #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
-            if ((WebhookUploadImg == 1 || (WebhookUploadImg != 0 && numbersWithError)) && flowAlignment && flowAlignment->AlgROI) {
-                WebhookUploadPic(flowAlignment->AlgROI);
+            if ((WebhookUploadImg == 1 || (WebhookUploadImg != 0 && numbersWithError)) && flowAlignment) {
+                ImageData *roiImage = flowAlignment->GetAlgROICopy();
+                if (roiImage != NULL) {
+                    WebhookUploadPic(roiImage);
+                    delete roiImage;
+                }
             }
         #endif
     }

+ 36 - 36
code/components/jomjol_image_proc/CAlignAndCutImage.cpp

@@ -16,22 +16,6 @@
 
 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)
@@ -82,16 +66,41 @@ bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
     int r0_x, r0_y, r1_x, r1_y;
     bool isSimilar1, isSimilar2;
 
-    if (_temp1 == NULL || _temp2 == NULL || rgb_image == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: source image or reference is unavailable");
+    if (_temp1 == NULL || _temp2 == NULL || rgb_image == NULL ||
+        ImageTMP == NULL || !ImageTMP->ImageOkay() ||
+        ImageTMP->width != width || ImageTMP->height != height ||
+        ImageTMP->channels != channels) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: source image or snapshot workspace is unavailable");
+        return false;
+    }
+
+    // Copy the source while briefly holding the image lock. The template search
+    // then reads only this immutable snapshot and does not block HTTP image access.
+    size_t snapshotSize = 0;
+    if (!getCutBufferSize(width, height, channels, &snapshotSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: invalid source image dimensions");
+        return false;
+    }
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: unable to lock source image for snapshot");
         return false;
     }
-    ScopedImageAccess sourceAccess(this);
-    if (!sourceAccess.isLocked()) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: unable to lock source image");
+
+    uint8_t* snapshot = ImageTMP->RGBImageLock();
+    if (snapshot == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: unable to lock snapshot workspace");
         return false;
     }
-    CFindTemplate* ft = new (std::nothrow) CFindTemplate("align", rgb_image, channels, width, height, bpp);
+
+    std::memcpy(snapshot, source, snapshotSize);
+    ImageTMP->RGBImageRelease();
+    RGBImageRelease();
+
+    CFindTemplate* ft = new (std::nothrow) CFindTemplate(
+        "align", snapshot, channels, width, height, bpp);
     if (ft == NULL) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Align: unable to allocate template matcher");
         return false;
@@ -100,16 +109,16 @@ bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
     r0_x = _temp1->target_x;
     r0_y = _temp1->target_y;
     ESP_LOGD(TAG, "Before ft->FindTemplate(_temp1); %s", _temp1->image_file.c_str());
-    isSimilar1 = ft->FindTemplate(_temp1);
+    isSimilar1 = ft->FindTemplate(_temp1, true);
     _temp1->width = ft->tpl_width;
-    _temp1->height = ft->tpl_height; 
+    _temp1->height = ft->tpl_height;
 
     r1_x = _temp2->target_x;
     r1_y = _temp2->target_y;
     ESP_LOGD(TAG, "Before ft->FindTemplate(_temp2); %s", _temp2->image_file.c_str());
-    isSimilar2 = ft->FindTemplate(_temp2);
+    isSimilar2 = ft->FindTemplate(_temp2, true);
     _temp2->width = ft->tpl_width;
-    _temp2->height = ft->tpl_height; 
+    _temp2->height = ft->tpl_height;
 
     delete ft;
 
@@ -124,20 +133,11 @@ bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
 
     float w_org, w_ist, d_winkel;
 
-	w_org = atan2((float)(_temp2->found_y - _temp1->found_y), (float)(_temp2->found_x - _temp1->found_x));
+    w_org = atan2((float)(_temp2->found_y - _temp1->found_y), (float)(_temp2->found_x - _temp1->found_x));
     w_ist = atan2((float)(r1_y - r0_y), (float)(r1_x - r0_x));
 
     d_winkel = (w_ist - w_org) * 180 / M_PI;
 
-/*#ifdef DEBUG_DETAIL_ON
-    std::string zw = "\tdx:\t" + std::to_string(dx) + "\tdy:\t" + std::to_string(dy) + "\td_winkel:\t" + std::to_string(d_winkel);
-    zw = zw + "\tt1_x_y:\t" + std::to_string(_temp1->found_x) + "\t" + std::to_string(_temp1->found_y);
-    zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(_temp1->fastalg_min) + "\t" + std::to_string(_temp1->fastalg_avg) + "\t" + std::to_string(_temp1->fastalg_max) + "\t"+ std::to_string(_temp1->fastalg_SAD);
-    zw = zw + "\tt2_x_y:\t" + std::to_string(_temp2->found_x) + "\t" + std::to_string(_temp2->found_y);
-    zw = zw + "\tpara2_found_min_avg_max:\t" + std::to_string(_temp2->fastalg_min) + "\t" + std::to_string(_temp2->fastalg_avg) + "\t" + std::to_string(_temp2->fastalg_max) + "\t"+ std::to_string(_temp2->fastalg_SAD);
-    LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
-#endif*/
-
     CRotateImage rt("Align", this, ImageTMP);
     rt.Translate(dx, dy);
     rt.Rotate(d_winkel, _temp1->target_x, _temp1->target_y);

+ 15 - 9
code/components/jomjol_image_proc/CFindTemplate.cpp

@@ -29,7 +29,7 @@ static bool getTemplateBufferSize(int width, int height, int channels, size_t* s
 // #define DEBUG_DETAIL_ON  
 
 
-bool CFindTemplate::FindTemplate(RefInfo *_ref)
+bool CFindTemplate::FindTemplate(RefInfo *_ref, bool sourceIsStableSnapshot)
 {
     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");
@@ -54,11 +54,17 @@ bool CFindTemplate::FindTemplate(RefInfo *_ref)
         return false;
     }
 
-    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;
+    // Alignment passes an immutable copy in the shared tmpImage workspace.
+    // Searching that snapshot must not hold the global image mutex for seconds.
+    uint8_t* source = rgb_image;
+    const bool sourceLocked = !sourceIsStableSnapshot;
+    if (sourceLocked) {
+        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) {
@@ -81,7 +87,7 @@ bool CFindTemplate::FindTemplate(RefInfo *_ref)
 
     if (ow_stop < ow_start || oh_stop < oh_start) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: search window does not intersect source image");
-        RGBImageRelease();
+        if (sourceLocked) RGBImageRelease();
         stbi_image_free(rgb_template);
         return false;
     }
@@ -100,7 +106,7 @@ bool CFindTemplate::FindTemplate(RefInfo *_ref)
 #endif
         _ref->found_x = _ref->fastalg_x;
         _ref->found_y = _ref->fastalg_y;
-        RGBImageRelease();
+        if (sourceLocked) RGBImageRelease();
         stbi_image_free(rgb_template);
         return true;
     }
@@ -154,7 +160,7 @@ bool CFindTemplate::FindTemplate(RefInfo *_ref)
     _ref->fastalg_max = max;
     _ref->fastalg_SAD = SAD;
 
-    RGBImageRelease();
+    if (sourceLocked) RGBImageRelease();
     stbi_image_free(rgb_template);
     return false;
 }

+ 1 - 1
code/components/jomjol_image_proc/CFindTemplate.h

@@ -34,7 +34,7 @@ class CFindTemplate : public CImageBasis
         int tpl_width, tpl_height, tpl_bpp;    
         CFindTemplate(std::string name, uint8_t* _rgb_image, int _channels, int _width, int _height, int _bpp) : CImageBasis(name, _rgb_image, _channels, _width, _height, _bpp) {};
 
-        bool FindTemplate(RefInfo *_ref);
+        bool FindTemplate(RefInfo *_ref, bool sourceIsStableSnapshot = false);
 
         bool CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _starty, int &min, float &avg, int &max, float &SAD, float _SADold, float _SADcrit);
 };

+ 3 - 3
code/main/server_main.cpp

@@ -457,12 +457,12 @@ httpd_handle_t start_webserver(void)
     httpd_handle_t server = NULL;
     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
 
-    config.task_priority = tskIDLE_PRIORITY+3; // previously -> 2022-12-11: tskIDLE_PRIORITY+1; 2021-09-24: tskIDLE_PRIORITY+5
-    config.stack_size = 12288; // previously -> 2023-01-02: 32768
+    config.task_priority = tskIDLE_PRIORITY+5; // Tested: higher server priority improves Web-UI responsiveness under load
+    config.stack_size = 8 * 2048; // 16 KB; tested with image and OTA requests
     config.core_id = 1; // previously -> 2023-01-02: 0, 2022-12-11: tskNO_AFFINITY;
     config.server_port = 80;
     config.ctrl_port = 32768;
-    config.max_open_sockets = 5; //20210921 --> previously 7   
+    config.max_open_sockets = 7; // Tested: allow more simultaneous Web-UI connections
     config.max_uri_handlers = 41; // Make sure this fits all URI handlers. Memory usage in bytes: 6*max_uri_handlers
     config.max_resp_headers = 8;                        
     config.backlog_conn = 5;