Pārlūkot izejas kodu

Harden remaining image and TFLite memory call sites

SybexXx 3 dienas atpakaļ
vecāks
revīzija
a783ccb594

+ 41 - 4
code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

@@ -715,8 +715,19 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                     {
                         float f1 = 0, f2 = 0;
 
-                        tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);        
+                        if (!tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image)) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CNN input image could not be copied into Tensor Arena");
+                            continue;
+                        }
                         tflite->Invoke();
+                        if (!tflite->LastInvokeSucceeded()) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite inference failed");
+                            continue;
+                        }
                         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "After Invoke");
 
                         f1 = tflite->GetOutputValue(0);
@@ -739,8 +750,12 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                 case Digit:
                     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CNN Type: Digit");
                     {
-                        GENERAL[n]->ROI[roi]->result_klasse = 0;
                         GENERAL[n]->ROI[roi]->result_klasse = tflite->GetClassFromImageBasis(GENERAL[n]->ROI[roi]->image);
+                        if (GENERAL[n]->ROI[roi]->result_klasse < 0) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Digit inference failed for ROI " + GENERAL[n]->ROI[roi]->name);
+                            continue;
+                        }
                         ESP_LOGD(TAG, "General result (Digit)%i: %d", roi, GENERAL[n]->ROI[roi]->result_klasse);
 
                         if (isLogImage) {
@@ -764,8 +779,19 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                         float _fit;
                         float _result_save_file;
 
-                        tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);        
+                        if (!tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image)) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CNN input image could not be copied into Tensor Arena");
+                            continue;
+                        }
                         tflite->Invoke();
+                        if (!tflite->LastInvokeSucceeded()) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite inference failed");
+                            continue;
+                        }
                         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "After Invoke");
 
                         _num = tflite->GetOutClassification(0, 9);
@@ -835,8 +861,19 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
                         int _num;
                         float _result_save_file;
                         
-                        tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);        
+                        if (!tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image)) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CNN input image could not be copied into Tensor Arena");
+                            continue;
+                        }
                         tflite->Invoke();
+                        if (!tflite->LastInvokeSucceeded()) {
+                            GENERAL[n]->ROI[roi]->isReject = true;
+                            GENERAL[n]->ROI[roi]->result_float = -1;
+                            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite inference failed");
+                            continue;
+                        }
     
                         _num = tflite->GetOutClassification();
                         

+ 12 - 4
code/components/jomjol_flowcontroll/ClassFlowTakeImage.cpp

@@ -4,6 +4,7 @@
 #include <regex>
 
 #include "ClassFlowTakeImage.h"
+#include <new>
 #include "Helper.h"
 #include "ClassLogFile.h"
 
@@ -600,15 +601,22 @@ esp_err_t ClassFlowTakeImage::SendRawJPG(httpd_req_t *req)
 
 ImageData *ClassFlowTakeImage::SendRawImage(void)
 {
-    CImageBasis *zw = new CImageBasis("SendRawImage", rawImage);
-    ImageData *id;
-    int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
+    if (rawImage == NULL || !rawImage->ImageOkay()) return NULL;
+    CImageBasis *zw = new (std::nothrow) CImageBasis("SendRawImage", rawImage);
+    if (zw == NULL || !zw->ImageOkay()) {
+        delete zw;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SendRawImage: unable to allocate an image copy");
+        return NULL;
+    }
+
+    const int flash_duration = static_cast<int>(CCstatus.WaitBeforePicture * 1000);
     Camera.CaptureToBasisImage(zw, flash_duration);
     time(&TimeImageTaken);
     localtime(&TimeImageTaken);
 
-    id = zw->writeToMemoryAsJPG();
+    ImageData *id = zw->writeToMemoryAsJPG();
     delete zw;
+    // The caller owns the returned ImageData and must release it with delete.
     return id;
 }
 

+ 34 - 19
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -197,9 +197,10 @@ esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
 
 bool CImageBasis::CopyFromMemory(uint8_t* _source, int _size)
 {
-    if (_source == nullptr || rgb_image == nullptr || _size < 0 || width <= 0 || height <= 0 || channels <= 0) return false;
-    const size_t expected = static_cast<size_t>(width) * static_cast<size_t>(height) * static_cast<size_t>(channels);
-    if (expected > INT_MAX || expected != static_cast<size_t>(_size)) {
+    size_t expected = 0;
+    if (_source == nullptr || rgb_image == nullptr || _size < 0 ||
+        !getImageBufferSize(width, height, channels, &expected) ||
+        expected != static_cast<size_t>(_size)) {
         ESP_LOGE(TAG, "Cannot copy image from memory - sizes do not match: should be %u, but is %d",
                  static_cast<unsigned int>(expected), _size);
         return false;
@@ -214,9 +215,12 @@ bool CImageBasis::CopyFromMemory(uint8_t* _source, int _size)
 
 uint8_t CImageBasis::GetPixelColor(int x, int y, int ch)
 {
-    if (rgb_image == nullptr || !isInImage(x, y) || ch < 0 || ch >= channels) return 0;
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !isInImage(x, y) || ch < 0 || ch >= channels ||
+        !getImageBufferSize(width, height, channels, &imageSize)) 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)];
 }
 
@@ -246,11 +250,14 @@ bool CImageBasis::isInImage(int x, int y)
 
 void CImageBasis::setPixelColor(int x, int y, int r, int g, int b)
 {
-    if (rgb_image == nullptr || !isInImage(x, y) || channels <= 0) return;
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !isInImage(x, y) ||
+        !getImageBufferSize(width, height, channels, &imageSize)) return;
     uint8_t* image = RGBImageLock();
     if (image == nullptr) return;
     const size_t offset = static_cast<size_t>(channels) *
         (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
+    if (offset >= imageSize) { RGBImageRelease(); return; }
     uint8_t* pixel = image + offset;
     pixel[0] = static_cast<uint8_t>(r);
     if (channels > 2) { pixel[1] = static_cast<uint8_t>(g); pixel[2] = static_cast<uint8_t>(b); }
@@ -432,10 +439,10 @@ void CImageBasis::CreateEmptyImage(int _width, int _height, int _channels)
 
 void CImageBasis::EmptyImage()
 {
-    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) return;
+    size_t size = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
     uint8_t* image = RGBImageLock();
     if (image == nullptr) return;
-    const size_t size = static_cast<size_t>(width) * static_cast<size_t>(height) * static_cast<size_t>(channels);
     std::memset(image, 0, size);
     RGBImageRelease();
 }
@@ -477,21 +484,26 @@ void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 
 void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom)
 {
-    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0 ||
+    size_t inputSize = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &inputSize) ||
         static_cast<unsigned int>(cropLeft) + cropRight >= static_cast<unsigned int>(width) ||
         static_cast<unsigned int>(cropTop) + cropBottom >= static_cast<unsigned int>(height)) return;
-    const unsigned int top = static_cast<unsigned int>(cropTop) * static_cast<unsigned int>(width) * static_cast<unsigned int>(channels);
-    const unsigned int bottom = (static_cast<unsigned int>(width) * static_cast<unsigned int>(height) -
-        static_cast<unsigned int>(cropBottom) * static_cast<unsigned int>(width)) * static_cast<unsigned int>(channels);
+
+    const size_t rowBytes = static_cast<size_t>(width) * 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;
     size_t writeIndex = 0;
-    const size_t inputSize = static_cast<size_t>(width) * static_cast<size_t>(height) * static_cast<size_t>(channels);
+
     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));
-        if (i < top || i >= bottom || x < cropLeft || x >= maxX) continue;
-        for (int channel = 0; channel < channels; ++channel) rgb_image[writeIndex++] = rgb_image[i + static_cast<size_t>(channel)];
+        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)];
+        }
     }
     width = static_cast<int>(newWidth);
     height = static_cast<int>(newHeight);
@@ -644,7 +656,8 @@ CImageBasis::CImageBasis(string _name, std::string _image)
 
 
 bool CImageBasis::ImageOkay(){
-    return rgb_image != NULL;
+    size_t imageSize = 0;
+    return rgb_image != NULL && getImageBufferSize(width, height, channels, &imageSize);
 }
 
 
@@ -663,10 +676,10 @@ CImageBasis::CImageBasis(string _name, uint8_t* _rgb_image, int _channels, int _
 
 void CImageBasis::Negative(void)
 {
-    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) return;
+    size_t size = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
     uint8_t* image = RGBImageLock();
     if (image == nullptr) return;
-    const size_t size = static_cast<size_t>(width) * static_cast<size_t>(height) * static_cast<size_t>(channels);
     for (size_t i = 0; i < size; i += static_cast<size_t>(channels))
         for (int c = 0; c < channels; ++c) image[i + static_cast<size_t>(c)] = 255 - image[i + static_cast<size_t>(c)];
     RGBImageRelease();
@@ -675,7 +688,8 @@ void CImageBasis::Negative(void)
 
 void CImageBasis::Contrast(float _contrast)
 {
-    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) return;
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
     uint8_t* image = RGBImageLock();
     if (image == nullptr) return;
     const float contrast = (_contrast / 100) + 1;
@@ -707,7 +721,8 @@ CImageBasis::~CImageBasis()
 
 void CImageBasis::SaveToFile(std::string _imageout)
 {
-    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) return;
+    size_t imageSize = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
     const string typ = getFileType(_imageout);
     uint8_t* image = RGBImageLock();
     if (image == nullptr) return;

+ 13 - 8
code/components/jomjol_tfliteclass/CTfLiteClass.cpp

@@ -32,12 +32,12 @@ void CTfLiteClass::MakeStaticResolver()
 
 float CTfLiteClass::GetOutputValue(int nr)
 {
-    if (this->interpreter == nullptr || nr < 0) return -1000.0f;
+    if (this->interpreter == nullptr || !lastInvokeSucceeded || nr < 0) return -1000.0f;
     TfLiteTensor* output2 = this->interpreter->output(0);
     if (output2 == nullptr || output2->dims == nullptr || output2->dims->size < 2) return -1000.0f;
 
     int numeroutput = output2->dims->data[1];
-    if ((nr+1) > numeroutput)
+    if (nr >= numeroutput || output2->data.f == nullptr)
       return -1000;
 
     return output2->data.f[nr];
@@ -50,20 +50,21 @@ int CTfLiteClass::GetClassFromImageBasis(CImageBasis *rs)
       return -1000;
 
     Invoke();
-
+    if (!lastInvokeSucceeded) return -1000;
     return GetOutClassification();
 }
 
 
 int CTfLiteClass::GetOutClassification(int _von, int _bis)
 {
+  if (interpreter == nullptr || !lastInvokeSucceeded) return -1;
   TfLiteTensor* output2 = interpreter->output(0);
 
   float zw_max;
   float zw;
   int zw_class;
 
-  if (output2 == NULL)
+  if (output2 == NULL || output2->dims == nullptr || output2->dims->size < 2 || output2->data.f == nullptr)
     return -1;
 
   int numeroutput = output2->dims->data[1];
@@ -75,7 +76,7 @@ int CTfLiteClass::GetOutClassification(int _von, int _bis)
   if (_von == -1)
     _von = 0;
 
-  if (_bis >= numeroutput)
+  if (_von < 0 || _bis < _von || _bis >= numeroutput)
   {
     ESP_LOGD(TAG, "NUMBER OF OUTPUT NEURONS does not match required classification!");
     return -1;
@@ -140,6 +141,7 @@ int CTfLiteClass::GetAnzOutPut(bool silent)
   if (output2 == nullptr || output2->dims == nullptr) return 0;
 
   int numdim = output2->dims->size;
+  if (numdim < 2 || output2->data.f == nullptr) return 0;
   if (!silent) ESP_LOGD(TAG, "NumDimension: %d", numdim);
 
   int sizeofdim;
@@ -165,10 +167,10 @@ int CTfLiteClass::GetAnzOutPut(bool silent)
 
 void CTfLiteClass::Invoke()
 {
+    lastInvokeSucceeded = false;
     if (interpreter == nullptr) return;
-    if (interpreter->Invoke() != kTfLiteOk) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite Invoke() failed");
-    }
+    if (interpreter->Invoke() == kTfLiteOk) lastInvokeSucceeded = true;
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite Invoke() failed");
 }
 
 
@@ -266,6 +268,7 @@ bool CTfLiteClass::MakeAllocate()
         this->interpreter = nullptr;
         return false;
     }
+    lastInvokeSucceeded = false;
 
 #ifdef DEBUG_DETAIL_ON
     LogFile.WriteHeapInfo("CTLiteClass::Alloc done");
@@ -376,6 +379,7 @@ CTfLiteClass::CTfLiteClass()
 {
     this->ownsSharedMemoryLease = false;
     this->modelMemoryClaimed = false;
+    this->lastInvokeSucceeded = false;
     this->model = nullptr;
     this->modelfile = NULL;
     this->interpreter = nullptr;
@@ -402,6 +406,7 @@ CTfLiteClass::~CTfLiteClass()
         psram_free_shared_tensor_arena_and_model_memory();
         ownsSharedMemoryLease = false;
         modelMemoryClaimed = false;
+        lastInvokeSucceeded = false;
         tensor_arena = nullptr;
         modelfile = nullptr;
     }

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

@@ -45,6 +45,7 @@ class CTfLiteClass
         void GetInputTensorSize();
         bool LoadInputImageBasis(CImageBasis *rs);
         void Invoke();
+        bool LastInvokeSucceeded() const { return lastInvokeSucceeded; }
         int GetAnzOutPut(bool silent = true);        
         int GetOutClassification(int _von = -1, int _bis = -1);