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

Harden image locking, camera buffers, and ROI lifetimes

SybexXx 2 дней назад
Родитель
Сommit
f67d2ea2de

+ 82 - 86
code/components/jomjol_controlcamera/ClassControllCamera.cpp

@@ -21,6 +21,8 @@
 #include <nvs_flash.h>
 #include <sys/param.h>
 #include <string.h>
+#include <limits.h>
+#include <new>
 #include <sys/stat.h>
 
 #include "freertos/FreeRTOS.h"
@@ -633,105 +635,87 @@ static size_t jpg_encode_stream(void *arg, size_t index, const void *data, size_
 
 esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
 {
+    if (_Image == NULL || !_Image->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: target image is unavailable");
+        return ESP_FAIL;
+    }
+
 #ifdef DEBUG_DETAIL_ON
     LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
 #endif
 
-    _Image->EmptyImage(); // Delete previous stored raw image -> black image
-
-    LEDOnOff(true); // Status-LED on
-
-    if (delay > 0)
-    {
-        LightOnOff(true); // Flash-LED on
-        const TickType_t xDelay = delay / portTICK_PERIOD_MS;
-        vTaskDelay(xDelay);
+    LEDOnOff(true);
+    if (delay > 0) {
+        LightOnOff(true);
+        vTaskDelay(pdMS_TO_TICKS(delay));
     }
 
-#ifdef DEBUG_DETAIL_ON
-    LogFile.WriteHeapInfo("CaptureToBasisImage - After LightOn");
-#endif
-
+    camera_fb_t *warmup = esp_camera_fb_get();
+    if (warmup != NULL) esp_camera_fb_return(warmup);
     camera_fb_t *fb = esp_camera_fb_get();
-    esp_camera_fb_return(fb);
-    fb = esp_camera_fb_get();
-
-    if (!fb)
-    {
-        LEDOnOff(false);   // Status-LED off
-        LightOnOff(false); // Flash-LED off
-
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "is not working anymore (CaptureToBasisImage) - most probably caused "
-                                                "by a hardware problem (instablility, ...). System will reboot.");
-        doReboot();
-
+    if (fb == NULL) {
+        LEDOnOff(false);
+        LightOnOff(false);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: camera capture failed");
         return ESP_FAIL;
     }
 
-    if (CCstatus.DemoMode)
-    {
-        // Use images stored on SD-Card instead of camera image
-        /* Replace Framebuffer with image from SD-Card */
-        loadNextDemoImage(fb);
-    }
-
-    CImageBasis *tmpImage = new CImageBasis("tmpImage");
-
-    if (tmpImage)
-    {
-        tmpImage->LoadFromMemory(fb->buf, fb->len);
-    }
-    else
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: Can't allocate tmpImage");
+    uint8_t *frameData = fb->buf;
+    size_t frameLength = fb->len;
+    if (CCstatus.DemoMode && !loadNextDemoImage(&frameData, &frameLength)) {
+        esp_camera_fb_return(fb);
+        LEDOnOff(false);
+        LightOnOff(false);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: could not load demo image");
+        return ESP_FAIL;
     }
 
+    CImageBasis *tmpImage = new (std::nothrow) CImageBasis("tmpImage");
+    bool decoded = tmpImage != NULL && frameLength <= static_cast<size_t>(INT_MAX) &&
+                   tmpImage->LoadFromMemory(frameData, static_cast<int>(frameLength));
     esp_camera_fb_return(fb);
 
-#ifdef DEBUG_DETAIL_ON
-    LogFile.WriteHeapInfo("CaptureToBasisImage - After fb_get");
-#endif
-
-    LEDOnOff(false); // Status-LED off
+    LEDOnOff(false);
+    if (delay > 0) LightOnOff(false);
 
-    if (delay > 0)
-    {
-        LightOnOff(false); // Flash-LED off
+    if (!decoded || tmpImage == NULL || !tmpImage->ImageOkay()) {
+        delete tmpImage;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: JPEG decode failed");
+        LogFile.WriteHeapInfo("CaptureToBasisImage decode");
+        return ESP_FAIL;
     }
 
-    //    TickType_t xDelay = 1000 / portTICK_PERIOD_MS;
-    //    vTaskDelay( xDelay );  // wait for power to recover
-
-#ifdef DEBUG_DETAIL_ON
-    LogFile.WriteHeapInfo("CaptureToBasisImage - After LoadFromMemory");
-#endif
-
-    if (tmpImage == NULL)
-    {
-        return ESP_OK;
+    size_t expectedBytes = 0;
+    if (_Image->width != tmpImage->width || _Image->height != tmpImage->height ||
+        _Image->channels != tmpImage->channels || tmpImage->channels != 3 ||
+        tmpImage->width <= 0 || tmpImage->height <= 0 ||
+        static_cast<size_t>(tmpImage->width) > SIZE_MAX / static_cast<size_t>(tmpImage->height) ||
+        static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) > SIZE_MAX / 3U) {
+        delete tmpImage;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded dimensions do not match target image");
+        return ESP_FAIL;
+    }
+    expectedBytes = static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) * 3U;
+    if (expectedBytes > static_cast<size_t>(INT_MAX)) {
+        delete tmpImage;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image is too large");
+        return ESP_FAIL;
     }
 
-    int channels = 3;
-    int width = CCstatus.ImageWidth;
-    int height = CCstatus.ImageHeight;
-
-#ifdef DEBUG_DETAIL_ON
-    std::string _zw = "Targetimage: " + std::to_string((int)_Image->rgb_image) + " Size: " + std::to_string(_Image->width) + ", " + std::to_string(_Image->height);
-    _zw = _zw + " tmpImage: " + std::to_string((int)tmpImage->rgb_image) + " Size: " + std::to_string(tmpImage->width) + ", " + std::to_string(tmpImage->height);
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, _zw);
-#endif
-
-    // Both images are packed RGB888 with the same dimensions: copy the whole frame at once
-    // (the former per-pixel, column-by-column loop took ~2 s on an ESP32-CAM)
-    memcpy(_Image->rgb_image, tmpImage->rgb_image, width * height * channels);
-
+    uint8_t *source = tmpImage->RGBImageLock();
+    if (source == NULL) {
+        delete tmpImage;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image lock failed");
+        return ESP_FAIL;
+    }
+    const bool copied = _Image->CopyFromMemory(source, static_cast<int>(expectedBytes));
+    tmpImage->RGBImageRelease();
     delete tmpImage;
 
 #ifdef DEBUG_DETAIL_ON
     LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
 #endif
-
-    return ESP_OK;
+    return copied ? ESP_OK : ESP_FAIL;
 }
 
 esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
@@ -880,12 +864,16 @@ esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay)
     {
         if (CCstatus.DemoMode)
         {
-            // Use images stored on SD-Card instead of camera image
             LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
-            /* Replace Framebuffer with image from SD-Card */
-            loadNextDemoImage(fb);
-
-            res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
+            uint8_t *demoData = NULL;
+            size_t demoLength = 0;
+            if (loadNextDemoImage(&demoData, &demoLength)) {
+                fb_len = demoLength;
+                res = httpd_resp_send(req, (const char *)demoData, demoLength);
+            } else {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: could not load demo image");
+                res = ESP_FAIL;
+            }
         }
         else
         {
@@ -1213,11 +1201,16 @@ void CCamera::useDemoMode(void)
     CCstatus.DemoMode = true;
 }
 
-bool CCamera::loadNextDemoImage(camera_fb_t *fb)
+bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
 {
-    if (fb == NULL || demoImage == NULL || demoFiles.empty()) return false;
-    const std::string filename = "/sdcard/demo/" + demoFiles[static_cast<size_t>(getCountFlowRounds()) % demoFiles.size()];
+    if (data == NULL || length == NULL || demoImage == NULL || demoFiles.empty()) return false;
+    *data = NULL;
+    *length = 0;
+
+    const size_t index = static_cast<size_t>(getCountFlowRounds()) % demoFiles.size();
+    const std::string filename = "/sdcard/demo/" + demoFiles[index];
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + filename + " as demo image");
+
     FILE *fp = fopen(filename.c_str(), "rb");
     if (fp == NULL) return false;
     const long fileSize = GetFileSize(filename);
@@ -1227,13 +1220,16 @@ bool CCamera::loadNextDemoImage(camera_fb_t *fb)
         return false;
     }
     const size_t readBytes = fread(demoImage, 1, static_cast<size_t>(fileSize), fp);
+    const bool readOkay = (readBytes == static_cast<size_t>(fileSize)) && (ferror(fp) == 0);
     fclose(fp);
-    if (readBytes != static_cast<size_t>(fileSize)) return false;
-    fb->buf = demoImage;
-    fb->len = static_cast<int>(readBytes);
+    if (!readOkay) return false;
+
+    *data = demoImage;
+    *length = readBytes;
     return true;
 }
 
+
 long CCamera::GetFileSize(std::string filename)
 {
     struct stat stat_buf;

+ 1 - 1
code/components/jomjol_controlcamera/ClassControllCamera.h

@@ -73,7 +73,7 @@ class CCamera
 {
 protected:
     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);

+ 51 - 5
code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

@@ -38,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 = "";    
 
@@ -387,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]);
@@ -416,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;
+            }
         }
     }
 
@@ -463,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);

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

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

@@ -6,6 +6,7 @@
 #include "freertos/task.h"
 
 #include <sys/stat.h>
+#include <new>
 
 #ifdef __cplusplus
 extern "C" {
@@ -839,26 +840,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
     }

+ 32 - 13
code/components/jomjol_flowcontroll/ClassFlowTakeImage.cpp

@@ -34,23 +34,21 @@ esp_err_t ClassFlowTakeImage::camera_capture(void)
     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 || !rawImage->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "takePictureWithFlash: raw image 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)
@@ -518,8 +516,19 @@ 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);
 
-    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;
 }
@@ -567,7 +576,7 @@ bool ClassFlowTakeImage::doFlow(string zwtime)
         CFstatus.changedCameraSettings = false;
     }
 
-    takePictureWithFlash(flash_duration);
+    const bool captured = takePictureWithFlash(flash_duration);
 
 #ifdef WIFITURNOFF
     esp_wifi_start();
@@ -577,6 +586,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();
@@ -610,7 +625,11 @@ ImageData *ClassFlowTakeImage::SendRawImage(void)
     }
 
     const int flash_duration = static_cast<int>(CCstatus.WaitBeforePicture * 1000);
-    Camera.CaptureToBasisImage(zw, flash_duration);
+    if (Camera.CaptureToBasisImage(zw, flash_duration) != ESP_OK) {
+        delete zw;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SendRawImage: camera capture failed");
+        return NULL;
+    }
     time(&TimeImageTaken);
     localtime(&TimeImageTaken);
 

+ 1 - 1
code/components/jomjol_flowcontroll/ClassFlowTakeImage.h

@@ -16,7 +16,7 @@ protected:
     string namerawimage;
 
     esp_err_t camera_capture(void);
-    void takePictureWithFlash(int flash_duration);
+    bool takePictureWithFlash(int flash_duration);
 
     void SetInitialParameter(void);
 

+ 11 - 1
code/components/jomjol_image_proc/CAlignAndCutImage.cpp

@@ -73,7 +73,15 @@ 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;
+    }
+    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;
@@ -245,5 +253,7 @@ CImageBasis* CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy)
         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;
 }

+ 155 - 74
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -5,6 +5,9 @@
 #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"
@@ -20,6 +23,48 @@ using namespace std;
 
 static const char *TAG = "C IMG BASIS";
 
+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;
+
+    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;
+}
+
+static bool lockImageAccess(int waitSeconds = 60)
+{
+    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;
+}
+
+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;
@@ -49,36 +94,27 @@ static void releaseOwnedImageBuffer(const std::string& tag, const std::string& n
 
 uint8_t * CImageBasis::RGBImageLock(int _waitmaxsec)
 {
-    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;
-        }
+    if (!lockImageAccess(_waitmaxsec)) {
+        ESP_LOGW(TAG, "Timed out waiting for image access lock");
+        return NULL;
     }
-
-    if (islocked)
+    if (rgb_image == NULL) {
+        unlockImageAccess();
         return NULL;
-
+    }
     return rgb_image;
 }
 
 
 void CImageBasis::RGBImageRelease()
 {
-    islocked = false;
+    unlockImageAccess();
 }
 
 
 uint8_t * CImageBasis::RGBImageGet()
 {
+    // Compatibility accessor only. Callers must hold RGBImageLock() while using this pointer.
     return rgb_image;
 }
 
@@ -87,8 +123,6 @@ bool CImageBasis::SetIndepended()
     size_t size = 0;
     if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return false;
 
-    // The current buffer may belong to the camera or to the shared tmpImage
-    // lease. Never just flip the ownership flag: first make an independent copy.
     uint8_t* independent = static_cast<uint8_t*>(malloc_psram_heap(
         std::string(TAG) + "->SetIndepended (" + name + ")", size,
         MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
@@ -103,7 +137,6 @@ bool CImageBasis::SetIndepended()
         return false;
     }
     memCopy(source, independent, static_cast<int>(size));
-    RGBImageRelease();
 
     uint8_t* previous = rgb_image;
     const bool previousExternal = externalImage;
@@ -119,6 +152,7 @@ bool CImageBasis::SetIndepended()
         releaseOwnedImageBuffer(std::string(TAG) + "->SetIndepended old", name,
                                 previous, previousSize, previousSharedLease);
     }
+    RGBImageRelease();
     return true;
 }
 
@@ -144,6 +178,10 @@ ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
         return nullptr;
     }
     writeToMemoryAsJPG(ii, quality);
+    if (ii->size == 0) {
+        delete ii;
+        return nullptr;
+    }
     return ii;
 }
 
@@ -248,10 +286,15 @@ uint8_t CImageBasis::GetPixelColor(int x, int y, int ch)
     size_t imageSize = 0;
     if (rgb_image == nullptr || !isInImage(x, y) || ch < 0 || ch >= channels ||
         !getImageBufferSize(width, height, channels, &imageSize)) return 0;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return 0;
     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 || static_cast<size_t>(ch) >= imageSize - offset) return 0;
-    return rgb_image[offset + static_cast<size_t>(ch)];
+    uint8_t value = 0;
+    if (offset <= imageSize && static_cast<size_t>(ch) < imageSize - offset)
+        value = image[offset + static_cast<size_t>(ch)];
+    RGBImageRelease();
+    return value;
 }
 
 
@@ -305,7 +348,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)
@@ -353,7 +396,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)
@@ -389,7 +432,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)
@@ -411,7 +454,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)
@@ -441,29 +484,34 @@ CImageBasis::CImageBasis(string _name)
 void CImageBasis::CreateEmptyImage(int _width, int _height, int _channels)
 {
     if (_width <= 0 || _height <= 0 || _channels <= 0 || name == "tmpImage") return;
-    const size_t w = static_cast<size_t>(_width), h = static_cast<size_t>(_height), c = static_cast<size_t>(_channels);
-    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return;
-    const size_t newSize = w * h * c;
-    if (newSize > INT_MAX) 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));
+        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");
         return;
     }
+    std::memset(newImage, 0, newSize);
+    if (!lockImageAccess()) {
+        free_psram_heap(std::string(TAG) + "->CImageBasis (lock failed)", newImage);
+        return;
+    }
     if (rgb_image != nullptr && !externalImage) {
-        if (memsize == 0) {
-            stbi_image_free(rgb_image);
-        } else {
-            free_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ", " + std::to_string(memsize) + ")", rgb_image);
-        }
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis old", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
     }
     rgb_image = newImage;
-    width = _width; height = _height; channels = _channels; bpp = _channels;
+    width = _width;
+    height = _height;
+    channels = _channels;
+    bpp = _channels;
     memsize = static_cast<int>(newSize);
     externalImage = false;
-    std::memset(rgb_image, 0, newSize);
+    ownsSharedTempImageLease = false;
+    unlockImageAccess();
 }
 
 
@@ -478,11 +526,11 @@ void CImageBasis::EmptyImage()
 }
 
 
-void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
+bool CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 {
     if (_buffer == NULL || len <= 0) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: invalid input buffer");
-        return;
+        return false;
     }
 
     int newWidth = 0, newHeight = 0, sourceChannels = 0;
@@ -493,9 +541,13 @@ void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
         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;
+        return false;
     }
 
+    if (!lockImageAccess()) {
+        stbi_image_free(decoded);
+        return false;
+    }
     if (rgb_image != NULL && !externalImage) {
         releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
                                 rgb_image, memsize, ownsSharedTempImageLease);
@@ -508,7 +560,9 @@ void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
     memsize = 0;
     externalImage = false;
     ownsSharedTempImageLease = false;
+    unlockImageAccess();
     ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
+    return true;
 }
 
 
@@ -519,24 +573,34 @@ void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight,
         static_cast<unsigned int>(cropLeft) + cropRight >= static_cast<unsigned int>(width) ||
         static_cast<unsigned int>(cropTop) + cropBottom >= static_cast<unsigned int>(height)) return;
 
-    const size_t rowBytes = static_cast<size_t>(width) * static_cast<size_t>(channels);
+    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>(height - cropBottom) * rowBytes;
-    const unsigned int maxX = static_cast<unsigned int>(width) - cropRight;
-    const unsigned int newWidth = static_cast<unsigned int>(width) - cropLeft - cropRight;
-    const unsigned int newHeight = static_cast<unsigned int>(height) - cropTop - cropBottom;
+    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>(width));
+        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;
-        for (int channel = 0; channel < channels; ++channel) {
-            if (i + static_cast<size_t>(channel) >= inputSize) return;
-            rgb_image[writeIndex++] = rgb_image[i + static_cast<size_t>(channel)];
+        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;
     }
     width = static_cast<int>(newWidth);
     height = static_cast<int>(newHeight);
+    RGBImageRelease();
 }
 
 
@@ -647,8 +711,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) {
@@ -656,38 +724,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
+    if (!lockImageAccess()) {
+        stbi_image_free(loaded);
+        return;
+    }
+    rgb_image = loaded;
+    width = loadedWidth;
+    height = loadedHeight;
+    bpp = sourceChannels;
+    unlockImageAccess();
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_image - done");
-    #endif
+#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(){
+    if (!lockImageAccess()) return false;
     size_t imageSize = 0;
-    return rgb_image != NULL && getImageBufferSize(width, height, channels, &imageSize);
+    const bool okay = rgb_image != NULL && getImageBufferSize(width, height, channels, &imageSize);
+    unlockImageAccess();
+    return okay;
 }
 
 
@@ -740,12 +815,17 @@ void CImageBasis::Contrast(float _contrast)
 
 CImageBasis::~CImageBasis()
 {
+    if (!lockImageAccess(-1)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Destructor could not acquire image lock");
+        return;
+    }
     if (!externalImage && rgb_image != NULL) {
         releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
                                 rgb_image, memsize, ownsSharedTempImageLease);
     }
     rgb_image = NULL;
     ownsSharedTempImageLease = false;
+    unlockImageAccess();
 }
 
 
@@ -789,8 +869,8 @@ void CImageBasis::Resize(int _new_dx, int _new_dy)
 
     const int resized = stbir_resize_uint8(source, width, height, 0,
                                             output, _new_dx, _new_dy, 0, channels);
-    RGBImageRelease();
     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;
@@ -806,6 +886,7 @@ void CImageBasis::Resize(int _new_dx, int _new_dy)
     ownsSharedTempImageLease = false;
     width = _new_dx;
     height = _new_dy;
+    RGBImageRelease();
 }
 
 

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

@@ -92,7 +92,7 @@ class CImageBasis
         void 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);