Bladeren bron

Harden PSRAM and memory ownership paths

SybexXx 3 dagen geleden
bovenliggende
commit
e5a12ab071

+ 33 - 58
code/components/jomjol_controlcamera/ClassControllCamera.cpp

@@ -28,6 +28,7 @@
 
 
 #include "server_camera.h"
 #include "server_camera.h"
 #include "esp_camera.h"
 #include "esp_camera.h"
+#include "esp_heap_caps.h"
 
 
 #include "driver/ledc.h"
 #include "driver/ledc.h"
 #include "MainFlowControl.h"
 #include "MainFlowControl.h"
@@ -1180,82 +1181,56 @@ std::vector<std::string> demoFiles;
 void CCamera::useDemoMode(void)
 void CCamera::useDemoMode(void)
 {
 {
     char line[50];
     char line[50];
-
+    demoFiles.clear();
     FILE *fd = fopen("/sdcard/demo/files.txt", "r");
     FILE *fd = fopen("/sdcard/demo/files.txt", "r");
-
-    if (!fd)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode, the folder '/sdcard/demo/' does not contain the needed files!");
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "See Details on https://jomjol.github.io/AI-on-the-edge-device-docs/Demo-Mode!");
+    if (fd == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: '/sdcard/demo/files.txt' is missing!");
+        CCstatus.DemoMode = false;
         return;
         return;
     }
     }
-
-    demoImage = (uint8_t *)malloc(DEMO_IMAGE_SIZE);
-
-    if (demoImage == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire required memory for demo image!");
+    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);
         fclose(fd);
+        CCstatus.DemoMode = false;
         return;
         return;
     }
     }
-
-    while (fgets(line, sizeof(line), fd) != NULL)
-    {
-        line[strlen(line) - 1] = '\0';
-        demoFiles.push_back(line);
+    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';
+        if (length > 0) demoFiles.push_back(line);
     }
     }
-
     fclose(fd);
     fclose(fd);
-
-    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(demoFiles.size()) + " files) instead of real camera image!");
-
-    for (auto file : demoFiles)
-    {
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
+    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;
     }
     }
-
+    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(demoFiles.size()) + " files) instead of real camera image!");
+    for (const auto& file : demoFiles) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
     CCstatus.DemoMode = true;
     CCstatus.DemoMode = true;
 }
 }
 
 
 bool CCamera::loadNextDemoImage(camera_fb_t *fb)
 bool CCamera::loadNextDemoImage(camera_fb_t *fb)
 {
 {
-    char filename[50];
-    int readBytes;
-    long fileSize;
-
-    snprintf(filename, sizeof(filename), "/sdcard/demo/%s", demoFiles[getCountFlowRounds() % demoFiles.size()].c_str());
-
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + std::string(filename) + " as demo image");
-
-    /* Inject saved image */
-
-    FILE *fp = fopen(filename, "rb");
-
-    if (!fp)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + std::string(filename) + "!");
-        return false;
-    }
-
-    fileSize = GetFileSize(filename);
-
-    if (fileSize > DEMO_IMAGE_SIZE)
-    {
-        char buf[100];
-        snprintf(buf, sizeof(buf), "Demo Image (%d bytes) is larger than provided buffer (%d bytes)!", (int)fileSize, DEMO_IMAGE_SIZE);
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, std::string(buf));
+    if (fb == NULL || demoImage == NULL || demoFiles.empty()) return false;
+    const std::string filename = "/sdcard/demo/" + demoFiles[static_cast<size_t>(getCountFlowRounds()) % demoFiles.size()];
+    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);
+    if (fileSize <= 0 || fileSize > DEMO_IMAGE_SIZE) {
         fclose(fp);
         fclose(fp);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image has invalid size: " + std::to_string(fileSize));
         return false;
         return false;
     }
     }
-
-    readBytes = fread(demoImage, 1, DEMO_IMAGE_SIZE, fp);
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "read " + std::to_string(readBytes) + " bytes");
+    const size_t readBytes = fread(demoImage, 1, static_cast<size_t>(fileSize), fp);
     fclose(fp);
     fclose(fp);
-
-    fb->buf = demoImage; // Update pointer
-    fb->len = readBytes;
-    // ToDo do we also need to set height, width, format and timestamp?
-
+    if (readBytes != static_cast<size_t>(fileSize)) return false;
+    fb->buf = demoImage;
+    fb->len = static_cast<int>(readBytes);
     return true;
     return true;
 }
 }
 
 

+ 245 - 134
code/components/jomjol_helper/psram.cpp

@@ -2,210 +2,321 @@
 #include "../../include/defines.h"
 #include "../../include/defines.h"
 #include "psram.h"
 #include "psram.h"
 
 
-static const char* TAG = "PSRAM";
-
-using namespace std;
+#include <cstring>
+#include <stdint.h>
+#include <stdio.h>
+#include <limits.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/portmacro.h"
 
 
+static const char* TAG = "PSRAM";
 
 
-void *shared_region = NULL;
-uint32_t allocatedBytesForSTBI = 0;
-std::string sharedMemoryInUseFor = "";
-
+namespace {
+enum class SharedMemoryUser : uint8_t { None, TakeImage, Aligning, Digitization };
+static const uint32_t STBI_SHARED_BLOCK_MAGIC = 0x53544249;
+static const size_t STBI_ALIGNMENT = 16;
+struct alignas(16) StbiSharedBlockHeader {
+    size_t size;
+    uint32_t magic;
+    uint8_t reserved[STBI_ALIGNMENT - sizeof(size_t) - sizeof(uint32_t)];
+};
+static_assert(sizeof(StbiSharedBlockHeader) == STBI_ALIGNMENT, "STBI shared allocation header must preserve alignment");
+static portMUX_TYPE sharedMemoryMux = portMUX_INITIALIZER_UNLOCKED;
+static uint8_t* sharedRegion = nullptr;
+static size_t allocatedBytesForSTBI = 0;
+static SharedMemoryUser sharedMemoryUser = SharedMemoryUser::None;
+static bool tensorArenaClaimed = false;
+static bool modelMemoryClaimed = false;
+
+static bool getSharedRegionSize(size_t* size) {
+    if (size == nullptr) return false;
+    const size_t arenaSize = static_cast<size_t>(TENSOR_ARENA_SIZE);
+    const size_t modelSize = static_cast<size_t>(MAX_MODEL_SIZE);
+    if (arenaSize == 0 || modelSize == 0 || arenaSize > SIZE_MAX - modelSize) return false;
+    *size = arenaSize + modelSize;
+    return true;
+}
+static const char* sharedMemoryUserName(SharedMemoryUser user) {
+    switch (user) {
+        case SharedMemoryUser::TakeImage: return "TakeImage";
+        case SharedMemoryUser::Aligning: return "Aligning";
+        case SharedMemoryUser::Digitization: return "Digitization";
+        default: return "";
+    }
+}
+static bool isInsideSharedRegionLocked(const void* ptr, size_t regionSize) {
+    if (ptr == nullptr || sharedRegion == nullptr) return false;
+    const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
+    const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
+    return address >= begin && (address - begin) < regionSize;
+}
+static bool alignStbiOffset(size_t value, size_t* aligned) {
+    if (aligned == nullptr || value > SIZE_MAX - (STBI_ALIGNMENT - 1)) return false;
+    *aligned = (value + STBI_ALIGNMENT - 1) & ~(STBI_ALIGNMENT - 1);
+    return true;
+}
+} // namespace
 
 
-/** Reserve a large block in the PSRAM which will be shared between the different steps.
- * Each step uses it differently but only wiuthin itself. */
 bool reserve_psram_shared_region(void) {
 bool reserve_psram_shared_region(void) {
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + 
-            std::to_string(TENSOR_ARENA_SIZE + MAX_MODEL_SIZE) + " bytes)...");
-    shared_region = malloc_psram_heap("Shared PSRAM region", TENSOR_ARENA_SIZE + MAX_MODEL_SIZE, 
-            MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
-
-    if (shared_region == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocating shared PSRAM region!");
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid shared PSRAM region size");
         return false;
         return false;
     }
     }
-    else {
-        return true;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    const bool alreadyReserved = (sharedRegion != nullptr);
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (alreadyReserved) return true;
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + std::to_string(regionSize) + " bytes)...");
+    uint8_t* candidate = static_cast<uint8_t*>(malloc_psram_heap("Shared PSRAM region", regionSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (candidate == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate shared PSRAM region!");
+        return false;
     }
     }
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedRegion == nullptr) { sharedRegion = candidate; candidate = nullptr; }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (candidate != nullptr) free_psram_heap("Unused duplicate shared PSRAM region", candidate);
+    return true;
 }
 }
 
 
-
-
 /*******************************************************************
 /*******************************************************************
  * Memory used in Take Image (STBI)
  * Memory used in Take Image (STBI)
  *******************************************************************/
  *******************************************************************/
 bool psram_init_shared_memory_for_take_image_step(void) {
 bool psram_init_shared_memory_for_take_image_step(void) {
-    if (sharedMemoryInUseFor != "") {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
+    SharedMemoryUser currentUser;
+    bool success = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
+        allocatedBytesForSTBI = 0;
+        sharedMemoryUser = SharedMemoryUser::TakeImage;
+        success = true;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (!success) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, sharedRegion == nullptr ?
+            "Shared PSRAM region is not initialized" :
+            "Shared memory in PSRAM already in use for " + std::string(sharedMemoryUserName(currentUser)) + "!");
         return false;
         return false;
     }
     }
-
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init shared memory for step 'Take Image' (STBI buffers)");
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init shared memory for step 'Take Image' (STBI buffers)");
-    allocatedBytesForSTBI = 0;
-    sharedMemoryInUseFor = "TakeImage";
-
     return true;
     return true;
 }
 }
 
 
-
 void psram_deinit_shared_memory_for_take_image_step(void) {
 void psram_deinit_shared_memory_for_take_image_step(void) {
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Deinit shared memory for step 'Take Image' (STBI buffers)");
-    allocatedBytesForSTBI = 0;
-    sharedMemoryInUseFor = "";
+    bool released = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedMemoryUser == SharedMemoryUser::TakeImage) {
+        allocatedBytesForSTBI = 0;
+        sharedMemoryUser = SharedMemoryUser::None;
+        released = true;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Deinit shared memory for step 'Take Image' (STBI buffers)");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched STBI shared-memory release");
 }
 }
 
 
-
 void *psram_reserve_shared_stbi_memory(size_t size) {
 void *psram_reserve_shared_stbi_memory(size_t size) {
-    /* Only large buffers should be placed in the shared PSRAM 
-     * If we also place all smaller STBI buffers here, we get artefacts for some reasons. */
-    if (size >= 100000) {
-        if ((allocatedBytesForSTBI + size) > TENSOR_ARENA_SIZE + MAX_MODEL_SIZE) { // Check if it still fits in the shared region
-            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM too small (STBI) to fit additional " + 
-                    std::to_string(size) + " bytes! Available: " + std::to_string(TENSOR_ARENA_SIZE + MAX_MODEL_SIZE - allocatedBytesForSTBI) + " bytes!");
-
-            return NULL;
-        }
-        
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating memory (" + std::to_string(size) + " bytes) for STBI (use shared memory in PSRAM)...");
-        allocatedBytesForSTBI += size;
-        return (uint8_t *)shared_region + allocatedBytesForSTBI - size;
-    }
-    else { // Normal PSRAM
-        return malloc_psram_heap("STBI", size, MALLOC_CAP_SPIRAM);
+    if (size == 0) return nullptr;
+    if (size < 100000) return malloc_psram_heap("STBI", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) return nullptr;
+    size_t userOffset = 0, endOffset = 0, available = 0;
+    void* result = nullptr;
+    SharedMemoryUser currentUser = SharedMemoryUser::None;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::TakeImage &&
+        allocatedBytesForSTBI <= SIZE_MAX - sizeof(StbiSharedBlockHeader) &&
+        alignStbiOffset(allocatedBytesForSTBI + sizeof(StbiSharedBlockHeader), &userOffset) &&
+        userOffset <= regionSize && size <= regionSize - userOffset) {
+        endOffset = userOffset + size;
+        StbiSharedBlockHeader* header = reinterpret_cast<StbiSharedBlockHeader*>(sharedRegion + userOffset - sizeof(StbiSharedBlockHeader));
+        header->size = size;
+        header->magic = STBI_SHARED_BLOCK_MAGIC;
+        std::memset(header->reserved, 0, sizeof(header->reserved));
+        result = sharedRegion + userOffset;
+        allocatedBytesForSTBI = endOffset;
+    } else if (allocatedBytesForSTBI <= regionSize) available = regionSize - allocatedBytesForSTBI;
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result != nullptr) {
+        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in shared PSRAM for STBI");
+        return result;
     }
     }
+    LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared STBI PSRAM unavailable for " + std::to_string(size) +
+        " bytes (owner: " + sharedMemoryUserName(currentUser) + ", available: " + std::to_string(available) +
+        " bytes); falling back to PSRAM heap");
+    return malloc_psram_heap("STBI fallback", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
 }
 }
 
 
-
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize) {
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize) {
-    char buf[20];
-    sprintf(buf, "%p", ptr);
-    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "STBI requested realloc for " + std::string(buf) + " but this is currently unsupported!");
-    return NULL;
-}
-
-
-void psram_free_shared_stbi_memory(void *p) {
-    if ((p >= shared_region) && (p <= ((uint8_t *)shared_region + allocatedBytesForSTBI))) { // was allocated inside the shared memory
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Part of shared memory used for STBI (PSRAM, part of shared memory) is free again");
+    if (ptr == nullptr) return psram_reserve_shared_stbi_memory(newsize);
+    if (newsize == 0) { psram_free_shared_stbi_memory(ptr); return nullptr; }
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) return nullptr;
+    size_t oldSize = 0;
+    bool sharedPointer = false, validSharedHeader = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    sharedPointer = isInsideSharedRegionLocked(ptr, regionSize);
+    if (sharedPointer) {
+        const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
+        const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
+        if ((address - begin) >= sizeof(StbiSharedBlockHeader)) {
+            const StbiSharedBlockHeader* header = reinterpret_cast<const StbiSharedBlockHeader*>(static_cast<const uint8_t*>(ptr) - sizeof(StbiSharedBlockHeader));
+            if (header->magic == STBI_SHARED_BLOCK_MAGIC) { oldSize = header->size; validSharedHeader = true; }
+        }
     }
     }
-    else { // Normal PSRAM
-        free_psram_heap("STBI", p);
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (!sharedPointer) return realloc_psram_heap("STBI", ptr, newsize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (!validSharedHeader) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "STBI realloc received an unknown shared-region pointer");
+        return nullptr;
     }
     }
+    void* replacement = psram_reserve_shared_stbi_memory(newsize);
+    if (replacement == nullptr) return nullptr;
+    std::memcpy(replacement, ptr, oldSize < newsize ? oldSize : newsize);
+    return replacement;
 }
 }
 
 
-
+void psram_free_shared_stbi_memory(void *ptr) {
+    if (ptr == nullptr) return;
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize)) { free_psram_heap("STBI", ptr); return; }
+    portENTER_CRITICAL(&sharedMemoryMux);
+    const bool isShared = isInsideSharedRegionLocked(ptr, regionSize);
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (!isShared) free_psram_heap("STBI", ptr);
+}
 
 
 /*******************************************************************
 /*******************************************************************
- * Memory used in Aligning Step 
- * During this step we only use the shared part of the PSRAM
- * for the tmpImage. 
+ * Memory used in Aligning Step
  *******************************************************************/
  *******************************************************************/
 void *psram_reserve_shared_tmp_image_memory(void) {
 void *psram_reserve_shared_tmp_image_memory(void) {
-    if (sharedMemoryInUseFor != "") {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
-        return NULL;
+    size_t regionSize = 0;
+    if (!getSharedRegionSize(&regionSize) || static_cast<size_t>(IMAGE_SIZE) > regionSize) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tmpImage does not fit in the reserved shared PSRAM region");
+        return nullptr;
+    }
+    SharedMemoryUser currentUser;
+    void* result = nullptr;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
+        sharedMemoryUser = SharedMemoryUser::Aligning;
+        result = sharedRegion;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM unavailable for tmpImage (owner: " +
+            std::string(sharedMemoryUserName(currentUser)) + ")");
+        return nullptr;
     }
     }
-
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(IMAGE_SIZE) + " bytes, use shared memory in PSRAM)...");
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(IMAGE_SIZE) + " bytes, use shared memory in PSRAM)...");
-    sharedMemoryInUseFor = "Aligning";
-    return shared_region; // Use 1th part of the shared memory for the tmpImage (only user)
+    return result;
 }
 }
 
 
-
 void psram_free_shared_temp_image_memory(void) {
 void psram_free_shared_temp_image_memory(void) {
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for tmpImage (PSRAM, part of shared memory) is free again");
-    sharedMemoryInUseFor = "";
+    bool released = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedMemoryUser == SharedMemoryUser::Aligning) { sharedMemoryUser = SharedMemoryUser::None; released = true; }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for tmpImage is free again");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched tmpImage shared-memory release");
 }
 }
 
 
-
-
 /*******************************************************************
 /*******************************************************************
  * Memory used in Digitization Steps
  * Memory used in Digitization Steps
- * During this step we only use the shared part of the PSRAM for the
- * Tensor Arena and one of the Models.
- * The shared memory is large enough for the largest model and the
- * Tensor Arena. Therefore we do not need to monitor the usage.
  *******************************************************************/
  *******************************************************************/
 void *psram_get_shared_tensor_arena_memory(void) {
 void *psram_get_shared_tensor_arena_memory(void) {
-    if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Model")) {
-        sharedMemoryInUseFor = "Digitization_Tensor";
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes, use shared memory in PSRAM)...");
-        return shared_region; // Use 1th part of the shared memory for Tensor
-    }
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
-        return NULL;
+    bool unavailable = false, duplicateClaim = false;
+    void* result = nullptr;
+    SharedMemoryUser currentUser;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
+    else if (tensorArenaClaimed) duplicateClaim = true;
+    else { sharedMemoryUser = SharedMemoryUser::Digitization; tensorArenaClaimed = true; result = sharedRegion; }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Tensor Arena shared memory was claimed more than once" :
+            (unavailable ? "Shared PSRAM is unavailable for Tensor Arena (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Tensor Arena allocation failed"));
+        return nullptr;
     }
     }
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes in shared PSRAM)...");
+    return result;
 }
 }
 
 
-
 void *psram_get_shared_model_memory(void) {
 void *psram_get_shared_model_memory(void) {
-    if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Tensor")) {
-        sharedMemoryInUseFor = "Digitization_Model";
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes, use shared memory in PSRAM)...");
-        return (uint8_t *)shared_region + TENSOR_ARENA_SIZE; // Use 2nd part of the shared memory (after Tensor Arena) for the model
-    }
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM already in use for " + sharedMemoryInUseFor + "!");
-        return NULL;
+    bool unavailable = false, duplicateClaim = false;
+    void* result = nullptr;
+    SharedMemoryUser currentUser;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    currentUser = sharedMemoryUser;
+    if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
+    else if (modelMemoryClaimed) duplicateClaim = true;
+    else { sharedMemoryUser = SharedMemoryUser::Digitization; modelMemoryClaimed = true; result = sharedRegion + static_cast<size_t>(TENSOR_ARENA_SIZE); }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (result == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Model shared memory was claimed more than once" :
+            (unavailable ? "Shared PSRAM is unavailable for Model (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Model allocation failed"));
+        return nullptr;
     }
     }
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes in shared PSRAM)...");
+    return result;
 }
 }
 
 
-
 void psram_free_shared_tensor_arena_and_model_memory(void) {
 void psram_free_shared_tensor_arena_and_model_memory(void) {
-    sharedMemoryInUseFor = "";
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for Tensor Arena and model (PSRAM, part of shared memory) is free again");
+    bool released = false;
+    portENTER_CRITICAL(&sharedMemoryMux);
+    if (sharedMemoryUser == SharedMemoryUser::Digitization) {
+        tensorArenaClaimed = false; modelMemoryClaimed = false;
+        sharedMemoryUser = SharedMemoryUser::None; released = true;
+    }
+    portEXIT_CRITICAL(&sharedMemoryMux);
+    if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for Tensor Arena and model is free again");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched Tensor Arena/Model shared-memory release");
 }
 }
 
 
-
-
 /*******************************************************************
 /*******************************************************************
- * General
+ * General PSRAM heap wrappers
  *******************************************************************/
  *******************************************************************/
 void *malloc_psram_heap(std::string name, size_t size, uint32_t caps) {
 void *malloc_psram_heap(std::string name, size_t size, uint32_t caps) {
-	void *ptr;
-
-	ptr = heap_caps_malloc(size, caps);
-    if (ptr != NULL) {
-	    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + to_string(size) + " bytes in PSRAM for '" + name + "'");
-	}
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    if (size == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM allocation for '" + name + "'");
+        return nullptr;
     }
     }
-
-	return ptr;
+    void* ptr = heap_caps_malloc(size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    return ptr;
 }
 }
 
 
-
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
-	ptr = heap_caps_realloc(ptr, size, caps);
-    if (ptr != NULL) {
-	    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + to_string(size) + " bytes in PSRAM for '" + name + "'");
-	}
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + to_string(size) + " bytes in PSRAM for '" + name + "'!");
-    }
-
-	return ptr;
+    void* resized = heap_caps_realloc(ptr, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
+    else if (size != 0) LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    return resized;
 }
 }
 
 
-
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps) {
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps) {
-	void *ptr;
-
-	ptr = heap_caps_calloc(n, size, caps);
-    if (ptr != NULL) {
-	    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Allocated " + to_string(size) + " bytes in PSRAM for '" + name + "'");
-	}
-    else {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + to_string(size) + " bytes in PSRAM for '" + name + "'!");
+    if (size != 0 && n > SIZE_MAX / size) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM calloc size overflow for '" + name + "'");
+        return nullptr;
     }
     }
-
-	return ptr;
+    const size_t totalSize = n * size;
+    if (totalSize == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM calloc for '" + name + "'");
+        return nullptr;
+    }
+    void* ptr = heap_caps_calloc(n, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'!");
+    return ptr;
 }
 }
 
 
-
 void free_psram_heap(std::string name, void *ptr) {
 void free_psram_heap(std::string name, void *ptr) {
+    if (ptr == nullptr) return;
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing memory in PSRAM used for '" + name + "'...");
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing memory in PSRAM used for '" + name + "'...");
     heap_caps_free(ptr);
     heap_caps_free(ptr);
 }
 }

+ 4 - 16
code/components/jomjol_helper/psram.h

@@ -1,35 +1,23 @@
 #pragma once
 #pragma once
 #ifndef PSRAM_h
 #ifndef PSRAM_h
 #define PSRAM_h
 #define PSRAM_h
-
+#include <stddef.h>
+#include <stdint.h>
+#include <string>
 #include "esp_heap_caps.h"
 #include "esp_heap_caps.h"
-
-
 bool reserve_psram_shared_region(void);
 bool reserve_psram_shared_region(void);
-
-
-/* Memory used in Take Image Step */
 bool psram_init_shared_memory_for_take_image_step(void);
 bool psram_init_shared_memory_for_take_image_step(void);
 void psram_deinit_shared_memory_for_take_image_step(void);
 void psram_deinit_shared_memory_for_take_image_step(void);
 void *psram_reserve_shared_stbi_memory(size_t size);
 void *psram_reserve_shared_stbi_memory(size_t size);
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize);
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize);
-void psram_free_shared_stbi_memory(void *p);
-
-
-/* Memory used in Aligning Step */
+void psram_free_shared_stbi_memory(void *ptr);
 void *psram_reserve_shared_tmp_image_memory(void);
 void *psram_reserve_shared_tmp_image_memory(void);
 void psram_free_shared_temp_image_memory(void);
 void psram_free_shared_temp_image_memory(void);
-
-/* Memory used in Digitization Steps */
 void *psram_get_shared_tensor_arena_memory(void);
 void *psram_get_shared_tensor_arena_memory(void);
 void *psram_get_shared_model_memory(void);
 void *psram_get_shared_model_memory(void);
 void psram_free_shared_tensor_arena_and_model_memory(void);
 void psram_free_shared_tensor_arena_and_model_memory(void);
-
-/* General */
 void *malloc_psram_heap(std::string name, size_t size, uint32_t caps);
 void *malloc_psram_heap(std::string name, size_t size, uint32_t caps);
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps);
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps);
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps);
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps);
-
 void free_psram_heap(std::string name, void *ptr);
 void free_psram_heap(std::string name, void *ptr);
-
 #endif // PSRAM_h
 #endif // PSRAM_h

+ 164 - 220
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -10,6 +10,7 @@
 #include "esp_system.h"
 #include "esp_system.h"
 
 
 #include <cstring>
 #include <cstring>
+#include <limits.h>
 
 
 #include <math.h>
 #include <math.h>
 #include <algorithm>
 #include <algorithm>
@@ -19,7 +20,6 @@ using namespace std;
 
 
 static const char *TAG = "C IMG BASIS";
 static const char *TAG = "C IMG BASIS";
 
 
-bool jpgFileTooLarge = false;   // JPG creation verfication
 
 
 
 
 //#define DEBUG_DETAIL_ON
 //#define DEBUG_DETAIL_ON
@@ -63,55 +63,47 @@ uint8_t * CImageBasis::RGBImageGet()
 
 
 void writejpghelp(void *context, void *data, int size)
 void writejpghelp(void *context, void *data, int size)
 {
 {
-//    ESP_LOGD(TAG, "Size all: %d, size %d", ((ImageData*)context)->size, size);
-    ImageData* _zw = (ImageData*) context;
-    uint8_t *voidstart = _zw->data;
-    uint8_t *datastart = (uint8_t*) data;
-    
-    if ((_zw->size < MAX_JPG_SIZE)) {   // Abort copy to prevent buffer overflow
-        voidstart += _zw->size;
-
-        for (int i = 0; i < size; ++i)
-            *(voidstart + i) = *(datastart + i);
-
-        _zw->size += size;
-    }
-    else {
-        jpgFileTooLarge = true;
+    ImageData* output = static_cast<ImageData*>(context);
+    if (output == nullptr || data == nullptr || size <= 0 || output->size > MAX_JPG_SIZE) return;
+    if (static_cast<size_t>(size) > (MAX_JPG_SIZE - output->size)) {
+        output->size = MAX_JPG_SIZE + 1U;
+        return;
     }
     }
+    std::memcpy(output->data + output->size, data, static_cast<size_t>(size));
+    output->size += static_cast<size_t>(size);
 }
 }
 
 
 
 
 ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
 ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
 {
 {
-    ImageData* ii = new ImageData;
-
-    RGBImageLock();
-    stbi_write_jpg_to_func(writejpghelp, ii, width, height, channels, rgb_image, quality);
-    RGBImageRelease();
-
-    if (jpgFileTooLarge) {
-        jpgFileTooLarge = false;
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: Creation aborted! JPG size > preallocated buffer: " + std::to_string(MAX_JPG_SIZE));
+    ImageData* ii = new (std::nothrow) ImageData;
+    if (ii == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: PSRAM allocation failed");
+        return nullptr;
     }
     }
+    writeToMemoryAsJPG(ii, quality);
     return ii;
     return ii;
 }
 }
 
 
 
 
 void CImageBasis::writeToMemoryAsJPG(ImageData* i, const int quality)
 void CImageBasis::writeToMemoryAsJPG(ImageData* i, const int quality)
 {
 {
-    ImageData* ii = new ImageData;
-    
-    RGBImageLock();
-    stbi_write_jpg_to_func(writejpghelp, ii, width, height, channels, rgb_image, quality);
+    if (i == nullptr) return;
+    i->size = 0;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: image is unavailable or locked");
+        return;
+    }
+    const int success = stbi_write_jpg_to_func(writejpghelp, i, width, height, channels, image, quality);
     RGBImageRelease();
     RGBImageRelease();
-
-    if (jpgFileTooLarge) {
-        jpgFileTooLarge = false;
+    if (i->size > MAX_JPG_SIZE) {
+        i->size = 0;
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: Creation aborted! JPG size > preallocated buffer: " + std::to_string(MAX_JPG_SIZE));
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: Creation aborted! JPG size > preallocated buffer: " + std::to_string(MAX_JPG_SIZE));
+    } else if (!success) {
+        i->size = 0;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: JPEG encoder failed");
     }
     }
-    memCopy((uint8_t*) ii, (uint8_t*) i, sizeof(ImageData));
-    delete ii;
 }
 }
 
 
 
 
@@ -119,75 +111,81 @@ struct SendJPGHTTP
 {
 {
     httpd_req_t *req;
     httpd_req_t *req;
     esp_err_t res;
     esp_err_t res;
-    char buf[HTTP_BUFFER_SENT];
-    int size = 0;
+    char *buf;
+    size_t size = 0;
 };
 };
-
-
+static void flushJPGHTTPBuffer(SendJPGHTTP* send)
+{
+    if (send == nullptr || send->res != ESP_OK || send->size == 0) return;
+    if (httpd_resp_send_chunk(send->req, send->buf, send->size) != ESP_OK) {
+        ESP_LOGE(TAG, "File sending failed!");
+        send->res = ESP_FAIL;
+    }
+    send->size = 0;
+}
 inline void writejpgtohttphelp(void *context, void *data, int size)
 inline void writejpgtohttphelp(void *context, void *data, int size)
 {
 {
-    SendJPGHTTP* _send = (SendJPGHTTP*) context;
-    if ((_send->size + size) >= HTTP_BUFFER_SENT)     // data no longer fits in buffer
-    {
-        if (httpd_resp_send_chunk(_send->req, _send->buf, _send->size) != ESP_OK) 
-        {
-                    ESP_LOGE(TAG, "File sending failed!");
-                    _send->res = ESP_FAIL;  
+    SendJPGHTTP* send = static_cast<SendJPGHTTP*>(context);
+    if (send == nullptr || data == nullptr || size <= 0 || send->res != ESP_OK) return;
+    const uint8_t* source = static_cast<const uint8_t*>(data);
+    size_t remaining = static_cast<size_t>(size);
+    while (remaining > 0 && send->res == ESP_OK) {
+        if (send->size >= HTTP_BUFFER_SENT) {
+            flushJPGHTTPBuffer(send);
+            if (send->res != ESP_OK) return;
         }
         }
-        _send->size = 0;      
+        const size_t available = HTTP_BUFFER_SENT - send->size;
+        const size_t copySize = std::min(available, remaining);
+        std::memcpy(send->buf + send->size, source, copySize);
+        send->size += copySize;
+        source += copySize;
+        remaining -= copySize;
     }
     }
-    std::memcpy((void*) (&(_send->buf[0]) + _send->size), data, size);
-    _send->size+= size;
-} 
-
-
+}
 esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
 esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
 {
 {
-    SendJPGHTTP ii;
-    ii.req = _req;
-    ii.res = ESP_OK;
-    ii.size = 0;
-
-    RGBImageLock();
-    stbi_write_jpg_to_func(writejpgtohttphelp, &ii, width, height, channels, rgb_image, quality);
-
-    if (ii.size > 0)
-    {
-        if (httpd_resp_send_chunk(_req, (char*) ii.buf, ii.size) != ESP_OK)             //still send the rest
-        {
-            ESP_LOGE(TAG, "File sending failed!");
-            ii.res = ESP_FAIL;  
-        }
+    if (_req == nullptr) 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));
+    if (send.buf == nullptr) return ESP_ERR_NO_MEM;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) {
+        free_psram_heap("JPEG HTTP stream buffer", send.buf);
+        return ESP_FAIL;
     }
     }
-
+    const int encoded = stbi_write_jpg_to_func(writejpgtohttphelp, &send, width, height, channels, image, quality);
+    if (!encoded && send.res == ESP_OK) send.res = ESP_FAIL;
+    flushJPGHTTPBuffer(&send);
     RGBImageRelease();
     RGBImageRelease();
-
-    return ii.res;
-}  
+    free_psram_heap("JPEG HTTP stream buffer", send.buf);
+    return send.res;
+}
 
 
 
 
 bool CImageBasis::CopyFromMemory(uint8_t* _source, int _size)
 bool CImageBasis::CopyFromMemory(uint8_t* _source, int _size)
 {
 {
-    int gr = height * width * channels;
-    if (gr != _size)            // Size does not fit
-    {
-        ESP_LOGE(TAG, "Cannot copy image from memory - sizes do not match: should be %d, but is %d", _size, gr);
+    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)) {
+        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;
         return false;
     }
     }
-
-    RGBImageLock();
-    memCopy(_source, rgb_image, _size);
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return false;
+    memCopy(_source, image, _size);
     RGBImageRelease();
     RGBImageRelease();
-
     return true;
     return true;
 }
 }
 
 
 
 
 uint8_t CImageBasis::GetPixelColor(int x, int y, int ch)
 uint8_t CImageBasis::GetPixelColor(int x, int y, int ch)
 {
 {
-    stbi_uc* p_source;
-    p_source = rgb_image + (channels * (y * width + x));
-    return p_source[ch];
+    if (rgb_image == nullptr || !isInImage(x, y) || ch < 0 || ch >= channels) 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));
+    return rgb_image[offset + static_cast<size_t>(ch)];
 }
 }
 
 
 
 
@@ -216,16 +214,14 @@ bool CImageBasis::isInImage(int x, int y)
 
 
 void CImageBasis::setPixelColor(int x, int y, int r, int g, int b)
 void CImageBasis::setPixelColor(int x, int y, int r, int g, int b)
 {
 {
-    stbi_uc* p_source;
-
-    RGBImageLock();
-    p_source = rgb_image + (channels * (y * width + x));
-    p_source[0] = r;
-    if ( channels > 2)
-    {
-        p_source[1] = g;
-        p_source[2] = b;
-    }
+    if (rgb_image == nullptr || !isInImage(x, y) || channels <= 0) 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));
+    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); }
     RGBImageRelease();
     RGBImageRelease();
 }
 }
 
 
@@ -375,47 +371,34 @@ CImageBasis::CImageBasis(string _name)
 
 
 void CImageBasis::CreateEmptyImage(int _width, int _height, int _channels)
 void CImageBasis::CreateEmptyImage(int _width, int _height, int _channels)
 {
 {
-    bpp = _channels;
-    width = _width;
-    height = _height;
-    channels = _channels;
-
-    RGBImageLock();
-
-    #ifdef DEBUG_DETAIL_ON 
+    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;
+    uint8_t* newImage = static_cast<uint8_t*>(malloc_psram_heap(
+        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");
         LogFile.WriteHeapInfo("CreateEmptyImage");
-    #endif
-
-    memsize = width * height * channels;
-
-    rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
-
-    if (rgb_image == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CreateEmptyImage: Can't allocate enough memory: " + std::to_string(memsize));
-        LogFile.WriteHeapInfo("CreateEmptyImage");
-        RGBImageRelease();
         return;
         return;
     }
     }
-
-    // One contiguous memset instead of a per-pixel, column-by-column loop through PSRAM
-    memset(rgb_image, 0, width * height * channels);
-
-    RGBImageRelease();
+    if (rgb_image != nullptr && !externalImage) stbi_image_free(rgb_image);
+    rgb_image = newImage;
+    width = _width; height = _height; channels = _channels; bpp = _channels;
+    memsize = static_cast<int>(newSize);
+    externalImage = false;
+    std::memset(rgb_image, 0, newSize);
 }
 }
 
 
 
 
 void CImageBasis::EmptyImage()
 void CImageBasis::EmptyImage()
 {
 {
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("EmptyImage");
-    #endif
-
-    RGBImageLock();
-
-    // One contiguous memset instead of a per-pixel, column-by-column loop through PSRAM
-    memset(rgb_image, 0, width * height * channels);
-
+    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) 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();
     RGBImageRelease();
 }
 }
 
 
@@ -423,22 +406,18 @@ void CImageBasis::EmptyImage()
 void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 {
 {
     RGBImageLock();
     RGBImageLock();
-
-    if (rgb_image != NULL) {
-        stbi_image_free(rgb_image);
-        //free_psram_heap(std::string(TAG) + "->rgb_image (LoadFromMemory)", rgb_image);
+    if (rgb_image != NULL && !externalImage) {
+        if (name == "tmpImage" && memsize > 0) psram_free_shared_temp_image_memory();
+        else stbi_image_free(rgb_image);
     }
     }
-
     rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, STBI_rgb);
     rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, STBI_rgb);
+    memsize = 0;
+    externalImage = false;
     bpp = channels;
     bpp = channels;
     ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
     ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
-    
-    if ((width * height * channels) == 0)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image with size 0 loaded --> reboot to be done! "
-                "Check that your camera module is working and connected properly.");
+    if ((width * height * channels) == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image with size 0 loaded --> reboot to be done! Check that your camera module is working and connected properly.");
         LogFile.WriteHeapInfo("LoadFromMemory");
         LogFile.WriteHeapInfo("LoadFromMemory");
-
         doReboot();
         doReboot();
     }
     }
     RGBImageRelease();
     RGBImageRelease();
@@ -447,39 +426,24 @@ void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 
 
 void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom)
 void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom)
 {
 {
-    unsigned int maxTopIndex = cropTop * width * channels;
-    unsigned int minBottomIndex = ((width*height) - (cropBottom * width)) * channels;
-    unsigned short maxX = width - cropRight; // In pixels
-    unsigned short newWidth = width - cropLeft - cropRight;
-    unsigned short newHeight = height - cropTop - cropBottom;
-
-    unsigned int writeIndex = 0;
-    // Loop over all bytes
-    for (int i = 0; i < width * height * channels; i += channels) {
-        // Calculate current X, Y pixel position
-        int x = (i/channels) % width;
-
-        // Crop from the top
-        if (i < maxTopIndex) { continue; }
-
-        // Crop from the bottom
-        if (i > minBottomIndex) { continue; }
-
-        // Crop from the left
-        if (x <= cropLeft) { continue; }
-
-        // Crop from the right
-        if (x > maxX) { continue; }
-
-        // If we get here, keep the pixels
-        for (int c = 0; c < channels; c++) {
-            rgb_image[writeIndex++] = rgb_image[i+c];
-        }
+    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0 ||
+        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 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)];
     }
     }
-
-    // Set the new dimensions of the framebuffer for further use.
-    width = newWidth;
-    height = newHeight;
+    width = static_cast<int>(newWidth);
+    height = static_cast<int>(newHeight);
 }
 }
 
 
 
 
@@ -624,36 +588,33 @@ CImageBasis::CImageBasis(string _name, uint8_t* _rgb_image, int _channels, int _
 
 
 void CImageBasis::Negative(void)
 void CImageBasis::Negative(void)
 {
 {
-    RGBImageLock();
-
-    for (int i = 0; i < width * height * channels; i += channels) {
-        for (int c = 0; c < channels; c++) {
-            rgb_image[i+c] = 255 - rgb_image[i+c];
-        }
-    }
-
+    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) 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();
     RGBImageRelease();
 }
 }
 
 
 
 
-void CImageBasis::Contrast(float _contrast)  //input range [-100..100]
-{
-    stbi_uc* p_source;
-    
-    float contrast = (_contrast/100) + 1;  //convert to decimal & shift range: [0..2]
-    float intercept = 128 * (1 - contrast);
-
-    RGBImageLock();
-
-
-    for (int x = 0; x < width; ++x)
-        for (int y = 0; y < height; ++y)
-        {
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_source[_channels] = (uint8_t) std::min(255, std::max(0, (int) (p_source[_channels] * contrast + intercept)));
+void CImageBasis::Contrast(float _contrast)
+{
+    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) return;
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    const float contrast = (_contrast / 100) + 1;
+    const float intercept = 128 * (1 - contrast);
+    for (int y = 0; y < height; ++y) {
+        for (int x = 0; x < width; ++x) {
+            const size_t offset = static_cast<size_t>(channels) *
+                (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
+            uint8_t* pixel = image + offset;
+            for (int channel = 0; channel < channels; ++channel)
+                pixel[channel] = static_cast<uint8_t>(std::min(255, std::max(0,
+                    static_cast<int>(pixel[channel] * contrast + intercept))));
         }
         }
-
+    }
     RGBImageRelease();
     RGBImageRelease();
 }
 }
 
 
@@ -661,43 +622,26 @@ void CImageBasis::Contrast(float _contrast)  //input range [-100..100]
 CImageBasis::~CImageBasis()
 CImageBasis::~CImageBasis()
 {
 {
     RGBImageLock();
     RGBImageLock();
-
-
     if (!externalImage) {
     if (!externalImage) {
-        if (name == "tmpImage") { // This image should be placed in the shared part of PSRAM
-            psram_free_shared_temp_image_memory();
-        }
-        else { // All other images are much smaller and can go into the normal PSRAM region
-            //stbi_image_free(rgb_image);
-            if (memsize == 0) {
-                LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Not freeing (" + name + " as there was never PSRAM allocated for it)");
-            }
-            else {
-                free_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ", " + to_string(memsize) + ")", rgb_image);
-            }
-        }
+        if (name == "tmpImage") {
+            if (memsize == 0) stbi_image_free(rgb_image);
+            else psram_free_shared_temp_image_memory();
+        } else if (memsize == 0) stbi_image_free(rgb_image);
+        else free_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ", " + to_string(memsize) + ")", rgb_image);
     }
     }
-
     RGBImageRelease();
     RGBImageRelease();
 }
 }
 
 
 
 
 void CImageBasis::SaveToFile(std::string _imageout)
 void CImageBasis::SaveToFile(std::string _imageout)
 {
 {
-    string typ = getFileType(_imageout);
-
-    RGBImageLock();
-
-    if ((typ == "jpg") || (typ == "JPG"))       // CAUTION PROBLEMATIC IN ESP32
-    {
-        stbi_write_jpg(_imageout.c_str(), width, height, channels, rgb_image, 0);
-    }
- 
+    if (rgb_image == nullptr || width <= 0 || height <= 0 || channels <= 0) return;
+    const string typ = getFileType(_imageout);
+    uint8_t* image = RGBImageLock();
+    if (image == nullptr) return;
+    if ((typ == "jpg") || (typ == "JPG")) stbi_write_jpg(_imageout.c_str(), width, height, channels, image, 0);
 #ifndef STBI_ONLY_JPEG
 #ifndef STBI_ONLY_JPEG
-    if ((typ == "bmp") || (typ == "BMP"))
-    {
-        stbi_write_bmp(_imageout.c_str(), width, height, channels, rgb_image);
-    }
+    if ((typ == "bmp") || (typ == "BMP")) stbi_write_bmp(_imageout.c_str(), width, height, channels, image);
 #endif
 #endif
     RGBImageRelease();
     RGBImageRelease();
 }
 }

+ 14 - 0
code/components/jomjol_image_proc/CImageBasis.h

@@ -4,6 +4,9 @@
 #define CIMAGEBASIS_H
 #define CIMAGEBASIS_H
 
 
 #include <stdint.h>
 #include <stdint.h>
+#include <stddef.h>
+#include <new>
+#include <stdlib.h>
 #include <string>
 #include <string>
 #include <esp_http_server.h>
 #include <esp_http_server.h>
 
 
@@ -21,6 +24,17 @@ struct ImageData
 {
 {
     uint8_t data[MAX_JPG_SIZE];
     uint8_t data[MAX_JPG_SIZE];
     size_t size = 0;
     size_t size = 0;
+
+    static void* operator new(size_t size) {
+        void* ptr = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+        if (ptr == nullptr) abort();
+        return ptr;
+    }
+    static void* operator new(size_t size, const std::nothrow_t&) noexcept {
+        return heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
+    }
+    static void operator delete(void* ptr) noexcept { heap_caps_free(ptr); }
+    static void operator delete(void* ptr, const std::nothrow_t&) noexcept { heap_caps_free(ptr); }
 };
 };
 
 
 
 

+ 59 - 36
code/components/jomjol_mqtt/mqtt_outbox.c

@@ -3,6 +3,7 @@
 */
 */
 #include "mqtt_outbox.h"
 #include "mqtt_outbox.h"
 #include <stdlib.h>
 #include <stdlib.h>
+#include <limits.h>
 #include <string.h>
 #include <string.h>
 #include "sys/queue.h"
 #include "sys/queue.h"
 #include "esp_log.h"
 #include "esp_log.h"
@@ -38,70 +39,84 @@ outbox_handle_t outbox_init(void)
 #else
 #else
     outbox_handle_t outbox = calloc(1, sizeof(struct outbox_list_t));
     outbox_handle_t outbox = calloc(1, sizeof(struct outbox_list_t));
 #endif
 #endif
-    //ESP_MEM_CHECK(TAG, outbox, return NULL);
+    if (outbox == NULL) {
+        ESP_LOGE(TAG, "Unable to allocate MQTT outbox");
+        return NULL;
+    }
     STAILQ_INIT(outbox);
     STAILQ_INIT(outbox);
     return outbox;
     return outbox;
 }
 }
 
 
 outbox_item_handle_t outbox_enqueue(outbox_handle_t outbox, outbox_message_handle_t message, outbox_tick_t tick)
 outbox_item_handle_t outbox_enqueue(outbox_handle_t outbox, outbox_message_handle_t message, outbox_tick_t tick)
 {
 {
+    if (outbox == NULL || message == NULL || message->len < 0 || message->remaining_len < 0 ||
+        message->len > INT_MAX - message->remaining_len) return NULL;
+    const size_t totalLength = (size_t)message->len + (size_t)message->remaining_len;
+    if ((message->len > 0 && message->data == NULL) ||
+        (message->remaining_len > 0 && message->remaining_data == NULL)) return NULL;
 #ifdef USE_PSRAM
 #ifdef USE_PSRAM
     outbox_item_handle_t item = heap_caps_calloc(1, sizeof(outbox_item_t), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
     outbox_item_handle_t item = heap_caps_calloc(1, sizeof(outbox_item_t), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
 #else
 #else
     outbox_item_handle_t item = calloc(1, sizeof(outbox_item_t));
     outbox_item_handle_t item = calloc(1, sizeof(outbox_item_t));
 #endif
 #endif
-    //ESP_MEM_CHECK(TAG, item, return NULL);
-    item->msg_id = message->msg_id;
-    item->msg_type = message->msg_type;
-    item->msg_qos = message->msg_qos;
-    item->tick = tick;
-    item->len =  message->len + message->remaining_len;
-    item->pending = QUEUED;
+    if (item == NULL) return NULL;
 #ifdef USE_PSRAM
 #ifdef USE_PSRAM
-    item->buffer = heap_caps_malloc(message->len + message->remaining_len, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
+    item->buffer = heap_caps_malloc(totalLength == 0 ? 1 : totalLength, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
 #else
 #else
-    item->buffer = malloc(message->len + message->remaining_len);
+    item->buffer = malloc(totalLength == 0 ? 1 : totalLength);
 #endif
 #endif
-    /*ESP_MEM_CHECK(TAG, item->buffer, {
+    if (item->buffer == NULL) {
+#ifdef USE_PSRAM
+        heap_caps_free(item);
+#else
         free(item);
         free(item);
+#endif
         return NULL;
         return NULL;
-    });*/
-    memcpy(item->buffer, message->data, message->len);
-    if (message->remaining_data) {
-        memcpy(item->buffer + message->len, message->remaining_data, message->remaining_len);
     }
     }
+    item->msg_id = message->msg_id;
+    item->msg_type = message->msg_type;
+    item->msg_qos = message->msg_qos;
+    item->tick = tick;
+    item->len = (int)totalLength;
+    item->pending = QUEUED;
+    if (message->len > 0) memcpy(item->buffer, message->data, (size_t)message->len);
+    if (message->remaining_len > 0) memcpy(item->buffer + message->len, message->remaining_data, (size_t)message->remaining_len);
     STAILQ_INSERT_TAIL(outbox, item, next);
     STAILQ_INSERT_TAIL(outbox, item, next);
-    ESP_LOGD(TAG, "ENQUEUE msgid=%d, msg_type=%d, len=%d, size=%d", message->msg_id, message->msg_type, message->len + message->remaining_len, outbox_get_size(outbox));
+    ESP_LOGD(TAG, "ENQUEUE msgid=%d, msg_type=%d, len=%d, size=%d", message->msg_id, message->msg_type, item->len, outbox_get_size(outbox));
     return item;
     return item;
 }
 }
 
 
 outbox_item_handle_t outbox_get(outbox_handle_t outbox, int msg_id)
 outbox_item_handle_t outbox_get(outbox_handle_t outbox, int msg_id)
 {
 {
+    if (outbox == NULL) return NULL;
     outbox_item_handle_t item;
     outbox_item_handle_t item;
-    STAILQ_FOREACH(item, outbox, next) {
-        if (item->msg_id == msg_id) {
-            return item;
-        }
-    }
+    STAILQ_FOREACH(item, outbox, next) if (item->msg_id == msg_id) return item;
     return NULL;
     return NULL;
 }
 }
 
 
 outbox_item_handle_t outbox_dequeue(outbox_handle_t outbox, pending_state_t pending, outbox_tick_t *tick)
 outbox_item_handle_t outbox_dequeue(outbox_handle_t outbox, pending_state_t pending, outbox_tick_t *tick)
 {
 {
+    if (outbox == NULL) return NULL;
     outbox_item_handle_t item;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
     STAILQ_FOREACH(item, outbox, next) {
-        if (item->pending == pending) {
-            if (tick) {
-                *tick = item->tick;
-            }
-            return item;
-        }
+        if (item->pending == pending) { if (tick) *tick = item->tick; return item; }
     }
     }
     return NULL;
     return NULL;
 }
 }
 
 
+uint8_t *outbox_item_get_data(outbox_item_handle_t item, size_t *len, uint16_t *msg_id, int *msg_type, int *qos)
+{
+    if (item == NULL) return NULL;
+    if (len != NULL) *len = (size_t)item->len;
+    if (msg_id != NULL) *msg_id = (uint16_t)item->msg_id;
+    if (msg_type != NULL) *msg_type = item->msg_type;
+    if (qos != NULL) *qos = item->msg_qos;
+    return (uint8_t*)item->buffer;
+}
+
 esp_err_t outbox_delete_item(outbox_handle_t outbox, outbox_item_handle_t item_to_delete)
 esp_err_t outbox_delete_item(outbox_handle_t outbox, outbox_item_handle_t item_to_delete)
 {
 {
+    if (outbox == NULL || item_to_delete == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
     STAILQ_FOREACH(item, outbox, next) {
         if (item == item_to_delete) {
         if (item == item_to_delete) {
@@ -133,6 +148,7 @@ uint8_t *outbox_item_get_data(outbox_item_handle_t item,  size_t *len, uint16_t
 
 
 esp_err_t outbox_delete(outbox_handle_t outbox, int msg_id, int msg_type)
 esp_err_t outbox_delete(outbox_handle_t outbox, int msg_id, int msg_type)
 {
 {
+    if (outbox == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item, tmp;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         if (item->msg_id == msg_id && (0xFF & (item->msg_type)) == msg_type) {
         if (item->msg_id == msg_id && (0xFF & (item->msg_type)) == msg_type) {
@@ -153,6 +169,7 @@ esp_err_t outbox_delete(outbox_handle_t outbox, int msg_id, int msg_type)
 }
 }
 esp_err_t outbox_delete_msgid(outbox_handle_t outbox, int msg_id)
 esp_err_t outbox_delete_msgid(outbox_handle_t outbox, int msg_id)
 {
 {
+    if (outbox == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item, tmp;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         if (item->msg_id == msg_id) {
         if (item->msg_id == msg_id) {
@@ -199,6 +216,7 @@ esp_err_t outbox_set_tick(outbox_handle_t outbox, int msg_id, outbox_tick_t tick
 
 
 esp_err_t outbox_delete_msgtype(outbox_handle_t outbox, int msg_type)
 esp_err_t outbox_delete_msgtype(outbox_handle_t outbox, int msg_type)
 {
 {
+    if (outbox == NULL) { return ESP_FAIL; }
     outbox_item_handle_t item, tmp;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         if (item->msg_type == msg_type) {
         if (item->msg_type == msg_type) {
@@ -217,6 +235,7 @@ esp_err_t outbox_delete_msgtype(outbox_handle_t outbox, int msg_type)
 }
 }
 int outbox_delete_single_expired(outbox_handle_t outbox, outbox_tick_t current_tick, outbox_tick_t timeout)
 int outbox_delete_single_expired(outbox_handle_t outbox, outbox_tick_t current_tick, outbox_tick_t timeout)
 {
 {
+    if (outbox == NULL) { return -1; }
     int msg_id = -1;
     int msg_id = -1;
     outbox_item_handle_t item;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
     STAILQ_FOREACH(item, outbox, next) {
@@ -246,6 +265,7 @@ int outbox_delete_single_expired(outbox_handle_t outbox, outbox_tick_t current_t
 
 
 int outbox_delete_expired(outbox_handle_t outbox, outbox_tick_t current_tick, outbox_tick_t timeout)
 int outbox_delete_expired(outbox_handle_t outbox, outbox_tick_t current_tick, outbox_tick_t timeout)
 {
 {
+    if (outbox == NULL) { return 0; }
     int deleted_items = 0;
     int deleted_items = 0;
     outbox_item_handle_t item, tmp;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
@@ -267,32 +287,35 @@ int outbox_delete_expired(outbox_handle_t outbox, outbox_tick_t current_tick, ou
 
 
 int outbox_get_size(outbox_handle_t outbox)
 int outbox_get_size(outbox_handle_t outbox)
 {
 {
-    int siz = 0;
+    if (outbox == NULL) return 0;
+    int size = 0;
     outbox_item_handle_t item;
     outbox_item_handle_t item;
     STAILQ_FOREACH(item, outbox, next) {
     STAILQ_FOREACH(item, outbox, next) {
-        // Suppressing "use after free" warning as this could happen only if queue is in inconsistent state
-        // which never happens if STAILQ interface used
-        siz += item->len; // NOLINT(clang-analyzer-unix.Malloc)
+        if (item->len > INT_MAX - size) return INT_MAX;
+        size += item->len;
     }
     }
-    return siz;
+    return size;
 }
 }
 
 
 void outbox_delete_all_items(outbox_handle_t outbox)
 void outbox_delete_all_items(outbox_handle_t outbox)
 {
 {
+    if (outbox == NULL) return;
     outbox_item_handle_t item, tmp;
     outbox_item_handle_t item, tmp;
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
     STAILQ_FOREACH_SAFE(item, outbox, next, tmp) {
         STAILQ_REMOVE(outbox, item, outbox_item, next);
         STAILQ_REMOVE(outbox, item, outbox_item, next);
 #ifdef USE_PSRAM
 #ifdef USE_PSRAM
-            heap_caps_free(item->buffer);
-            heap_caps_free(item);
+        heap_caps_free(item->buffer);
+        heap_caps_free(item);
 #else
 #else
-            free(item->buffer);
-            free(item);
+        free(item->buffer);
+        free(item);
 #endif
 #endif
     }
     }
 }
 }
+
 void outbox_destroy(outbox_handle_t outbox)
 void outbox_destroy(outbox_handle_t outbox)
 {
 {
+    if (outbox == NULL) { return; }
     outbox_delete_all_items(outbox);
     outbox_delete_all_items(outbox);
 
 
 #ifdef USE_PSRAM
 #ifdef USE_PSRAM