Przeglądaj źródła

Complete camera demo ownership and flow cleanup hardening

SybexXx 3 dni temu
rodzic
commit
e4f5b818a2

+ 38 - 27
code/components/jomjol_controlcamera/ClassControllCamera.cpp

@@ -9,6 +9,7 @@
 #include "Helper.h"
 #include "statusled.h"
 #include "CImageBasis.h"
+#include "psram.h"
 
 #include "server_ota.h"
 #include "server_GPIO.h"
@@ -63,7 +64,6 @@ static const char *_STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary="
 static const char *_STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
 static const char *_STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
 
-uint8_t *demoImage = NULL;    // Buffer holding the demo image in bytes
 #define DEMO_IMAGE_SIZE 30000 // Max size of demo image in bytes
 
 // Camera module bus communications frequency.
@@ -662,17 +662,24 @@ esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
 
     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;
+    uint8_t *demoData = NULL;
+    bool demoBufferAllocated = false;
+    if (CCstatus.DemoMode) {
+        if (!loadNextDemoImage(&demoData, &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;
+        }
+        frameData = demoData;
+        demoBufferAllocated = true;
     }
 
     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));
+    if (demoBufferAllocated) free_psram_heap("Demo image frame", demoData);
     esp_camera_fb_return(fb);
 
     LEDOnOff(false);
@@ -731,9 +738,9 @@ esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
         vTaskDelay(xDelay);
     }
 
+    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)
     {
@@ -836,9 +843,9 @@ esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay)
         vTaskDelay(xDelay);
     }
 
+    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)
     {
@@ -870,6 +877,7 @@ esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay)
             if (loadNextDemoImage(&demoData, &demoLength)) {
                 fb_len = demoLength;
                 res = httpd_resp_send(req, (const char *)demoData, demoLength);
+                free_psram_heap("Demo image HTTP frame", demoData);
             } else {
                 LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: could not load demo image");
                 res = ESP_FAIL;
@@ -910,7 +918,7 @@ esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
     esp_err_t res = ESP_OK;
     size_t fb_len = 0;
     int64_t fr_start;
-    char *part_buf[64];
+    char part_buf[64];
 
     // wenn die Kameraeinstellungen durch Erstellen eines neuen Referenzbildes verändert wurden, müssen sie neu gesetzt werden
     if (CFstatus.changedCameraSettings)
@@ -937,9 +945,9 @@ esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
     while (1)
     {
         fr_start = esp_timer_get_time();
+        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)
         {
@@ -1176,13 +1184,6 @@ void CCamera::useDemoMode(void)
         CCstatus.DemoMode = false;
         return;
     }
-    if (demoImage == NULL) demoImage = static_cast<uint8_t*>(heap_caps_malloc(DEMO_IMAGE_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
-    if (demoImage == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire PSRAM for demo image!");
-        fclose(fd);
-        CCstatus.DemoMode = false;
-        return;
-    }
     while (fgets(line, sizeof(line), fd) != NULL) {
         size_t length = strlen(line);
         while (length > 0 && (line[length-1] == '\n' || line[length-1] == '\r')) line[--length] = '\0';
@@ -1191,8 +1192,6 @@ void CCamera::useDemoMode(void)
     fclose(fd);
     if (demoFiles.empty()) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: files.txt contains no image names");
-        heap_caps_free(demoImage);
-        demoImage = NULL;
         CCstatus.DemoMode = false;
         return;
     }
@@ -1203,7 +1202,7 @@ void CCamera::useDemoMode(void)
 
 bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
 {
-    if (data == NULL || length == NULL || demoImage == NULL || demoFiles.empty()) return false;
+    if (data == NULL || length == NULL || demoFiles.empty()) return false;
     *data = NULL;
     *length = 0;
 
@@ -1219,12 +1218,24 @@ bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image has invalid size: " + std::to_string(fileSize));
         return false;
     }
-    const size_t readBytes = fread(demoImage, 1, static_cast<size_t>(fileSize), fp);
+
+    uint8_t *buffer = static_cast<uint8_t*>(malloc_psram_heap(
+        "Demo image frame", static_cast<size_t>(fileSize), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (buffer == NULL) {
+        fclose(fp);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image PSRAM allocation failed");
+        return false;
+    }
+
+    const size_t readBytes = fread(buffer, 1, static_cast<size_t>(fileSize), fp);
     const bool readOkay = (readBytes == static_cast<size_t>(fileSize)) && (ferror(fp) == 0);
     fclose(fp);
-    if (!readOkay) return false;
+    if (!readOkay) {
+        free_psram_heap("Demo image frame (short read)", buffer);
+        return false;
+    }
 
-    *data = demoImage;
+    *data = buffer;
     *length = readBytes;
     return true;
 }

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

@@ -984,7 +984,11 @@ std::vector<HTMLInfo*> ClassFlowCNNGeneral::GetHTMLInfo() {
                 }
             }
 
-            HTMLInfo *zw = new HTMLInfo;
+            HTMLInfo *zw = new (std::nothrow) HTMLInfo;
+            if (zw == NULL) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate ROI HTML metadata");
+                continue;
+            }
             if (GENERAL[_ana]->name == "default") {
                 zw->filename = GENERAL[_ana]->ROI[i]->name + ".jpg";
                 zw->filename_org = GENERAL[_ana]->ROI[i]->name + ".jpg";

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

@@ -205,14 +205,36 @@ bool ClassFlowControll::StartMQTTService()
 }
 #endif //ENABLE_MQTT
 
+ClassFlowControll::ClassFlowControll()
+{
+    SetInitialParameter();
+}
+
+ClassFlowControll::~ClassFlowControll()
+{
+    // Destroy dependants before the flows they reference (PostProcessing, CNN,
+    // Alignment, then TakeImage), so borrowed image pointers remain valid.
+    for (auto it = FlowControll.rbegin(); it != FlowControll.rend(); ++it) {
+        delete *it;
+    }
+    FlowControll.clear();
+    flowpostprocessing = NULL;
+    flowdigit = NULL;
+    flowanalog = NULL;
+    flowalignment = NULL;
+    flowtakeimage = NULL;
+}
+
 void ClassFlowControll::SetInitialParameter(void)
 {
     AutoStart = true;
     SetupModeActive = false;
-    AutoInterval = 10; // Minutes
+    AutoInterval = 10;
     flowdigit = NULL;
     flowanalog = NULL;
     flowpostprocessing = NULL;
+    flowalignment = NULL;
+    flowtakeimage = NULL;
     disabled = false;
     aktRunNr = 0;
     setStatus("Flow task not yet created", "Flow task not yet created");
@@ -236,55 +258,57 @@ ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
     _type = trim(_type);
 
     if (toUpper(_type).compare("[TAKEIMAGE]") == 0) {
-        cfc = new ClassFlowTakeImage(&FlowControll);
+        cfc = new (std::nothrow) ClassFlowTakeImage(&FlowControll);
         flowtakeimage = (ClassFlowTakeImage*) cfc;
     }
 	
     if (toUpper(_type).compare("[ALIGNMENT]") == 0) {
-        cfc = new ClassFlowAlignment(&FlowControll);
+        cfc = new (std::nothrow) ClassFlowAlignment(&FlowControll);
         flowalignment = (ClassFlowAlignment*) cfc;
     }
 	
     if (toUpper(_type).compare("[ANALOG]") == 0) {
-        cfc = new ClassFlowCNNGeneral(flowalignment);
+        cfc = new (std::nothrow) ClassFlowCNNGeneral(flowalignment);
         flowanalog = (ClassFlowCNNGeneral*) cfc;
     }
 	
     if (toUpper(_type).compare(0, 7, "[DIGITS") == 0) {
-        cfc = new ClassFlowCNNGeneral(flowalignment);
+        cfc = new (std::nothrow) ClassFlowCNNGeneral(flowalignment);
         flowdigit = (ClassFlowCNNGeneral*) cfc;
     }
 	
     #ifdef ENABLE_MQTT
         if (toUpper(_type).compare("[MQTT]") == 0) {
-            cfc = new ClassFlowMQTT(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowMQTT(&FlowControll);
         }
     #endif //ENABLE_MQTT
 	
     #ifdef ENABLE_INFLUXDB
         if (toUpper(_type).compare("[INFLUXDB]") == 0) {
-            cfc = new ClassFlowInfluxDB(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowInfluxDB(&FlowControll);
         }
 
         if (toUpper(_type).compare("[INFLUXDBV2]") == 0) {
-            cfc = new ClassFlowInfluxDBv2(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowInfluxDBv2(&FlowControll);
         }
     #endif //ENABLE_INFLUXDB
 	
     #ifdef ENABLE_WEBHOOK
         if (toUpper(_type).compare("[WEBHOOK]") == 0) {
-            cfc = new ClassFlowWebhook(&FlowControll);
+            cfc = new (std::nothrow) ClassFlowWebhook(&FlowControll);
         }
     #endif //ENABLE_WEBHOOK
 
     if (toUpper(_type).compare("[POSTPROCESSING]") == 0) {
-        cfc = new ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit); 
+        cfc = new (std::nothrow) ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit); 
         flowpostprocessing = (ClassFlowPostProcessing*) cfc;
     }
 
-    if (cfc) {                           
-        // Attached only if it is not [AutoTimer], because this is for FlowControll
+    if (cfc) {
         FlowControll.push_back(cfc);
+    } else if (_type != "[AUTOTIMER]" && _type != "[DATALOGGING]" &&
+               _type != "[DEBUG]" && _type != "[SYSTEM]") {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate flow component " + _type);
     }
 
     if (toUpper(_type).compare("[AUTOTIMER]") == 0) {

+ 2 - 0
code/components/jomjol_flowcontroll/ClassFlowControll.h

@@ -46,6 +46,8 @@ protected:
 	int aktRunNr;
 
 public:
+	ClassFlowControll();
+	~ClassFlowControll() override;
 	bool SetupModeActive;
 
 	void InitFlow(std::string config);

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

@@ -36,8 +36,16 @@ esp_err_t ClassFlowTakeImage::camera_capture(void)
 
 bool ClassFlowTakeImage::takePictureWithFlash(int flash_duration)
 {
-    if (rawImage == NULL || !rawImage->ImageOkay()) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "takePictureWithFlash: raw image buffer is unavailable");
+    if (rawImage == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "takePictureWithFlash: raw image object is unavailable");
+        return false;
+    }
+    if (rawImage->width != CCstatus.ImageWidth || rawImage->height != CCstatus.ImageHeight ||
+        rawImage->channels != 3) {
+        rawImage->CreateEmptyImage(CCstatus.ImageWidth, CCstatus.ImageHeight, 3);
+    }
+    if (!rawImage->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "takePictureWithFlash: raw image PSRAM buffer is unavailable");
         return false;
     }
 

+ 3 - 3
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -188,7 +188,7 @@ ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
 
 void CImageBasis::writeToMemoryAsJPG(ImageData* i, const int quality)
 {
-    if (i == nullptr) return;
+    if (i == nullptr || !ImageOkay()) return;
     i->size = 0;
     uint8_t* image = RGBImageLock();
     if (image == nullptr) {
@@ -244,7 +244,7 @@ inline void writejpgtohttphelp(void *context, void *data, int size)
 }
 esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
 {
-    if (_req == nullptr) return ESP_FAIL;
+    if (_req == nullptr || !ImageOkay()) return ESP_FAIL;
     SendJPGHTTP send;
     send.req = _req; send.res = ESP_OK; send.size = 0;
     send.buf = static_cast<char*>(malloc_psram_heap("JPEG HTTP stream buffer", HTTP_BUFFER_SENT, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
@@ -892,7 +892,7 @@ void CImageBasis::Resize(int _new_dx, int _new_dy)
 
 void CImageBasis::Resize(int _new_dx, int _new_dy, CImageBasis *_target)
 {
-    if (_target == NULL || rgb_image == NULL || !_target->ImageOkay() ||
+    if (_target == this || _target == NULL || rgb_image == NULL || !_target->ImageOkay() ||
         _target->height != _new_dy || _target->width != _new_dx ||
         _target->channels != channels) {
         ESP_LOGE(TAG, "Resize - Target image size does not fit or is unavailable!");