CImageBasis.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. #include "CImageBasis.h"
  2. #include "Helper.h"
  3. #include "psram.h"
  4. #include "ClassLogFile.h"
  5. #include "server_ota.h"
  6. #include <esp_log.h>
  7. #include "freertos/FreeRTOS.h"
  8. #include "freertos/semphr.h"
  9. #include "freertos/portmacro.h"
  10. #include "../../include/defines.h"
  11. #include "esp_system.h"
  12. #include <cstring>
  13. #include <limits.h>
  14. #include <math.h>
  15. #include <algorithm>
  16. using namespace std;
  17. static const char *TAG = "C IMG BASIS";
  18. static SemaphoreHandle_t s_imageAccessMutex = nullptr;
  19. static portMUX_TYPE s_imageMutexInitMux = portMUX_INITIALIZER_UNLOCKED;
  20. static SemaphoreHandle_t getImageAccessMutex()
  21. {
  22. portENTER_CRITICAL(&s_imageMutexInitMux);
  23. SemaphoreHandle_t mutex = s_imageAccessMutex;
  24. portEXIT_CRITICAL(&s_imageMutexInitMux);
  25. if (mutex != nullptr) return mutex;
  26. SemaphoreHandle_t candidate = xSemaphoreCreateRecursiveMutex();
  27. if (candidate == nullptr) return nullptr;
  28. portENTER_CRITICAL(&s_imageMutexInitMux);
  29. if (s_imageAccessMutex == nullptr) {
  30. s_imageAccessMutex = candidate;
  31. candidate = nullptr;
  32. }
  33. mutex = s_imageAccessMutex;
  34. portEXIT_CRITICAL(&s_imageMutexInitMux);
  35. if (candidate != nullptr) vSemaphoreDelete(candidate);
  36. return mutex;
  37. }
  38. static bool lockImageAccess(int waitSeconds = 60)
  39. {
  40. SemaphoreHandle_t mutex = getImageAccessMutex();
  41. if (mutex == nullptr) return false;
  42. TickType_t waitTicks = portMAX_DELAY;
  43. if (waitSeconds >= 0) {
  44. const uint64_t waitMs = static_cast<uint64_t>(waitSeconds) * 1000ULL;
  45. waitTicks = pdMS_TO_TICKS(waitMs > UINT32_MAX ? UINT32_MAX : static_cast<uint32_t>(waitMs));
  46. }
  47. return xSemaphoreTakeRecursive(mutex, waitTicks) == pdTRUE;
  48. }
  49. static void unlockImageAccess()
  50. {
  51. SemaphoreHandle_t mutex = getImageAccessMutex();
  52. if (mutex != nullptr) (void)xSemaphoreGiveRecursive(mutex);
  53. }
  54. static bool getImageBufferSize(int width, int height, int channels, size_t* size)
  55. {
  56. if (size == nullptr || width <= 0 || height <= 0 || channels <= 0) return false;
  57. const size_t w = static_cast<size_t>(width);
  58. const size_t h = static_cast<size_t>(height);
  59. const size_t c = static_cast<size_t>(channels);
  60. if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
  61. const size_t total = w * h * c;
  62. if (total > static_cast<size_t>(INT_MAX)) return false;
  63. *size = total;
  64. return true;
  65. }
  66. static void releaseOwnedImageBuffer(const std::string& tag, const std::string& name,
  67. uint8_t* image, int size, bool sharedLease)
  68. {
  69. if (image == nullptr) return;
  70. if (sharedLease) psram_free_shared_temp_image_memory();
  71. else if (size == 0) stbi_image_free(image);
  72. else free_psram_heap(tag + " (" + name + ", " + std::to_string(size) + ")", image);
  73. }
  74. //#define DEBUG_DETAIL_ON
  75. uint8_t * CImageBasis::RGBImageLock(int _waitmaxsec)
  76. {
  77. if (!lockImageAccess(_waitmaxsec)) {
  78. ESP_LOGW(TAG, "Timed out waiting for image access lock");
  79. return NULL;
  80. }
  81. if (rgb_image == NULL) {
  82. unlockImageAccess();
  83. return NULL;
  84. }
  85. return rgb_image;
  86. }
  87. void CImageBasis::RGBImageRelease()
  88. {
  89. unlockImageAccess();
  90. }
  91. bool CImageBasis::SetIndepended()
  92. {
  93. size_t size = 0;
  94. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return false;
  95. uint8_t* independent = static_cast<uint8_t*>(malloc_psram_heap(
  96. std::string(TAG) + "->SetIndepended (" + name + ")", size,
  97. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  98. if (independent == nullptr) {
  99. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetIndepended: PSRAM allocation failed");
  100. return false;
  101. }
  102. uint8_t* source = RGBImageLock();
  103. if (source == nullptr) {
  104. free_psram_heap(std::string(TAG) + "->SetIndepended failed (" + name + ")", independent);
  105. return false;
  106. }
  107. memCopy(source, independent, static_cast<int>(size));
  108. uint8_t* previous = rgb_image;
  109. const bool previousExternal = externalImage;
  110. const int previousSize = memsize;
  111. const bool previousSharedLease = ownsSharedTempImageLease;
  112. rgb_image = independent;
  113. memsize = static_cast<int>(size);
  114. externalImage = false;
  115. ownsSharedTempImageLease = false;
  116. if (!previousExternal) {
  117. releaseOwnedImageBuffer(std::string(TAG) + "->SetIndepended old", name,
  118. previous, previousSize, previousSharedLease);
  119. }
  120. RGBImageRelease();
  121. return true;
  122. }
  123. void writejpghelp(void *context, void *data, int size)
  124. {
  125. ImageData* output = static_cast<ImageData*>(context);
  126. if (output == nullptr || data == nullptr || size <= 0 || output->size > MAX_JPG_SIZE) return;
  127. if (static_cast<size_t>(size) > (MAX_JPG_SIZE - output->size)) {
  128. output->size = MAX_JPG_SIZE + 1U;
  129. return;
  130. }
  131. std::memcpy(output->data + output->size, data, static_cast<size_t>(size));
  132. output->size += static_cast<size_t>(size);
  133. }
  134. ImageData* CImageBasis::writeToMemoryAsJPG(const int quality)
  135. {
  136. ImageData* ii = new (std::nothrow) ImageData;
  137. if (ii == nullptr) {
  138. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: PSRAM allocation failed");
  139. return nullptr;
  140. }
  141. writeToMemoryAsJPG(ii, quality);
  142. if (ii->size == 0) {
  143. delete ii;
  144. return nullptr;
  145. }
  146. return ii;
  147. }
  148. void CImageBasis::writeToMemoryAsJPG(ImageData* i, const int quality)
  149. {
  150. if (i == nullptr || !ImageOkay()) return;
  151. i->size = 0;
  152. uint8_t* image = RGBImageLock();
  153. if (image == nullptr) {
  154. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: image is unavailable or locked");
  155. return;
  156. }
  157. const int success = stbi_write_jpg_to_func(writejpghelp, i, width, height, channels, image, quality);
  158. RGBImageRelease();
  159. if (i->size > MAX_JPG_SIZE) {
  160. i->size = 0;
  161. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: Creation aborted! JPG size > preallocated buffer: " + std::to_string(MAX_JPG_SIZE));
  162. } else if (!success) {
  163. i->size = 0;
  164. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "writeToMemoryAsJPG: JPEG encoder failed");
  165. }
  166. }
  167. struct SendJPGHTTP
  168. {
  169. httpd_req_t *req;
  170. esp_err_t res;
  171. char *buf;
  172. size_t size = 0;
  173. };
  174. static void flushJPGHTTPBuffer(SendJPGHTTP* send)
  175. {
  176. if (send == nullptr || send->res != ESP_OK || send->size == 0) return;
  177. if (httpd_resp_send_chunk(send->req, send->buf, send->size) != ESP_OK) {
  178. ESP_LOGE(TAG, "File sending failed!");
  179. send->res = ESP_FAIL;
  180. }
  181. send->size = 0;
  182. }
  183. inline void writejpgtohttphelp(void *context, void *data, int size)
  184. {
  185. SendJPGHTTP* send = static_cast<SendJPGHTTP*>(context);
  186. if (send == nullptr || data == nullptr || size <= 0 || send->res != ESP_OK) return;
  187. const uint8_t* source = static_cast<const uint8_t*>(data);
  188. size_t remaining = static_cast<size_t>(size);
  189. while (remaining > 0 && send->res == ESP_OK) {
  190. if (send->size >= HTTP_BUFFER_SENT) {
  191. flushJPGHTTPBuffer(send);
  192. if (send->res != ESP_OK) return;
  193. }
  194. const size_t available = HTTP_BUFFER_SENT - send->size;
  195. const size_t copySize = std::min(available, remaining);
  196. std::memcpy(send->buf + send->size, source, copySize);
  197. send->size += copySize;
  198. source += copySize;
  199. remaining -= copySize;
  200. }
  201. }
  202. esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
  203. {
  204. if (_req == nullptr || !ImageOkay()) return ESP_FAIL;
  205. SendJPGHTTP send;
  206. send.req = _req; send.res = ESP_OK; send.size = 0;
  207. send.buf = static_cast<char*>(malloc_internal_heap("JPEG HTTP stream buffer", HTTP_BUFFER_SENT, MALLOC_CAP_8BIT));
  208. if (send.buf == nullptr) return ESP_ERR_NO_MEM;
  209. uint8_t* image = RGBImageLock();
  210. if (image == nullptr) {
  211. free_internal_heap("JPEG HTTP stream buffer", send.buf);
  212. return ESP_FAIL;
  213. }
  214. const int encoded = stbi_write_jpg_to_func(writejpgtohttphelp, &send, width, height, channels, image, quality);
  215. if (!encoded && send.res == ESP_OK) send.res = ESP_FAIL;
  216. flushJPGHTTPBuffer(&send);
  217. RGBImageRelease();
  218. free_internal_heap("JPEG HTTP stream buffer", send.buf);
  219. return send.res;
  220. }
  221. bool CImageBasis::CopyFromMemory(uint8_t* _source, int _size)
  222. {
  223. size_t expected = 0;
  224. if (_source == nullptr || rgb_image == nullptr || _size < 0 ||
  225. !getImageBufferSize(width, height, channels, &expected) ||
  226. expected != static_cast<size_t>(_size)) {
  227. ESP_LOGE(TAG, "Cannot copy image from memory - sizes do not match: should be %u, but is %d",
  228. static_cast<unsigned int>(expected), _size);
  229. return false;
  230. }
  231. uint8_t* image = RGBImageLock();
  232. if (image == nullptr) return false;
  233. memCopy(_source, image, _size);
  234. RGBImageRelease();
  235. return true;
  236. }
  237. void CImageBasis::memCopy(uint8_t* _source, uint8_t* _target, int _size)
  238. {
  239. #ifdef _ESP32_PSRAM
  240. for (int i = 0; i < _size; ++i)
  241. *(_target + i) = *(_source + i);
  242. #else
  243. memcpy(_target, _source, _size);
  244. #endif
  245. }
  246. bool CImageBasis::isInImage(int x, int y)
  247. {
  248. if ((x < 0) || (x > width - 1))
  249. return false;
  250. if ((y < 0) || (y > height- 1))
  251. return false;
  252. return true;
  253. }
  254. void CImageBasis::setPixelColor(int x, int y, int r, int g, int b)
  255. {
  256. size_t imageSize = 0;
  257. if (rgb_image == nullptr || !isInImage(x, y) ||
  258. !getImageBufferSize(width, height, channels, &imageSize)) return;
  259. uint8_t* image = RGBImageLock();
  260. if (image == nullptr) return;
  261. const size_t offset = static_cast<size_t>(channels) *
  262. (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
  263. if (offset >= imageSize) { RGBImageRelease(); return; }
  264. uint8_t* pixel = image + offset;
  265. pixel[0] = static_cast<uint8_t>(r);
  266. if (channels > 2) { pixel[1] = static_cast<uint8_t>(g); pixel[2] = static_cast<uint8_t>(b); }
  267. RGBImageRelease();
  268. }
  269. void CImageBasis::drawRect(int x, int y, int dx, int dy, int r, int g, int b, int thickness)
  270. {
  271. int zwx1, zwx2, zwy1, zwy2;
  272. int _x, _y, _thick;
  273. zwx1 = x - thickness + 1;
  274. zwx2 = x + dx + thickness - 1;
  275. zwy1 = y;
  276. zwy2 = y;
  277. if (RGBImageLock() == nullptr) return;
  278. for (_thick = 0; _thick < thickness; _thick++)
  279. for (_x = zwx1; _x <= zwx2; ++_x)
  280. for (_y = zwy1; _y <= zwy2; _y++)
  281. if (isInImage(_x, _y))
  282. setPixelColor(_x, _y - _thick, r, g, b);
  283. zwx1 = x - thickness + 1;
  284. zwx2 = x + dx + thickness - 1;
  285. zwy1 = y + dy;
  286. zwy2 = y + dy;
  287. for (_thick = 0; _thick < thickness; _thick++)
  288. for (_x = zwx1; _x <= zwx2; ++_x)
  289. for (_y = zwy1; _y <= zwy2; _y++)
  290. if (isInImage(_x, _y))
  291. setPixelColor(_x, _y + _thick, r, g, b);
  292. zwx1 = x;
  293. zwx2 = x;
  294. zwy1 = y;
  295. zwy2 = y + dy;
  296. for (_thick = 0; _thick < thickness; _thick++)
  297. for (_x = zwx1; _x <= zwx2; ++_x)
  298. for (_y = zwy1; _y <= zwy2; _y++)
  299. if (isInImage(_x, _y))
  300. setPixelColor(_x - _thick, _y, r, g, b);
  301. zwx1 = x + dx;
  302. zwx2 = x + dx;
  303. zwy1 = y;
  304. zwy2 = y + dy;
  305. for (_thick = 0; _thick < thickness; _thick++)
  306. for (_x = zwx1; _x <= zwx2; ++_x)
  307. for (_y = zwy1; _y <= zwy2; _y++)
  308. if (isInImage(_x, _y))
  309. setPixelColor(_x + _thick, _y, r, g, b);
  310. RGBImageRelease();
  311. }
  312. void CImageBasis::drawLine(int x1, int y1, int x2, int y2, int r, int g, int b, int thickness)
  313. {
  314. int _x, _y, _thick;
  315. int _zwy1, _zwy2;
  316. thickness = (thickness-1) / 2;
  317. if (RGBImageLock() == nullptr) return;
  318. for (_thick = 0; _thick <= thickness; ++_thick)
  319. for (_x = x1 - _thick; _x <= x2 + _thick; ++_x)
  320. {
  321. if (x2 == x1)
  322. {
  323. _zwy1 = y1;
  324. _zwy2 = y2;
  325. }
  326. else
  327. {
  328. _zwy1 = (y2 - y1) * (float)(_x - x1) / (float)(x2 - x1) + y1;
  329. _zwy2 = (y2 - y1) * (float)(_x + 1 - x1) / (float)(x2 - x1) + y1;
  330. }
  331. for (_y = _zwy1 - _thick; _y <= _zwy2 + _thick; _y++)
  332. if (isInImage(_x, _y))
  333. setPixelColor(_x, _y, r, g, b);
  334. }
  335. RGBImageRelease();
  336. }
  337. void CImageBasis::drawEllipse(int x1, int y1, int radx, int rady, int r, int g, int b, int thickness)
  338. {
  339. float deltarad, aktrad;
  340. int _thick, _x, _y;
  341. int rad = radx;
  342. if (rady > radx)
  343. rad = rady;
  344. deltarad = 1 / (4 * M_PI * (rad + thickness - 1));
  345. if (RGBImageLock() == nullptr) return;
  346. for (aktrad = 0; aktrad <= (2 * M_PI); aktrad += deltarad)
  347. for (_thick = 0; _thick < thickness; ++_thick)
  348. {
  349. _x = sin(aktrad) * (radx + _thick) + x1;
  350. _y = cos(aktrad) * (rady + _thick) + y1;
  351. if (isInImage(_x, _y))
  352. setPixelColor(_x, _y, r, g, b);
  353. }
  354. RGBImageRelease();
  355. }
  356. void CImageBasis::drawCircle(int x1, int y1, int rad, int r, int g, int b, int thickness)
  357. {
  358. float deltarad, aktrad;
  359. int _thick, _x, _y;
  360. deltarad = 1 / (4 * M_PI * (rad + thickness - 1));
  361. if (RGBImageLock() == nullptr) return;
  362. for (aktrad = 0; aktrad <= (2 * M_PI); aktrad += deltarad)
  363. for (_thick = 0; _thick < thickness; ++_thick)
  364. {
  365. _x = sin(aktrad) * (rad + _thick) + x1;
  366. _y = cos(aktrad) * (rad + _thick) + y1;
  367. if (isInImage(_x, _y))
  368. setPixelColor(_x, _y, r, g, b);
  369. }
  370. RGBImageRelease();
  371. }
  372. CImageBasis::CImageBasis(string _name)
  373. {
  374. name = _name;
  375. externalImage = false;
  376. rgb_image = NULL;
  377. width = 0;
  378. height = 0;
  379. channels = 0;
  380. islocked = false;
  381. }
  382. void CImageBasis::CreateEmptyImage(int _width, int _height, int _channels)
  383. {
  384. if (_width <= 0 || _height <= 0 || _channels <= 0 || name == "tmpImage") return;
  385. size_t newSize = 0;
  386. if (!getImageBufferSize(_width, _height, _channels, &newSize)) return;
  387. uint8_t* newImage = static_cast<uint8_t*>(malloc_psram_heap(
  388. std::string(TAG) + "->CImageBasis (" + name + ")", newSize,
  389. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  390. if (newImage == nullptr) {
  391. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CreateEmptyImage: allocation failed");
  392. LogFile.WriteHeapInfo("CreateEmptyImage");
  393. return;
  394. }
  395. std::memset(newImage, 0, newSize);
  396. if (!lockImageAccess()) {
  397. free_psram_heap(std::string(TAG) + "->CImageBasis (lock failed)", newImage);
  398. return;
  399. }
  400. if (rgb_image != nullptr && !externalImage) {
  401. releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis old", name,
  402. rgb_image, memsize, ownsSharedTempImageLease);
  403. }
  404. rgb_image = newImage;
  405. width = _width;
  406. height = _height;
  407. channels = _channels;
  408. bpp = _channels;
  409. memsize = static_cast<int>(newSize);
  410. externalImage = false;
  411. ownsSharedTempImageLease = false;
  412. unlockImageAccess();
  413. }
  414. void CImageBasis::EmptyImage()
  415. {
  416. size_t size = 0;
  417. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
  418. uint8_t* image = RGBImageLock();
  419. if (image == nullptr) return;
  420. std::memset(image, 0, size);
  421. RGBImageRelease();
  422. }
  423. bool CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
  424. {
  425. if (_buffer == NULL || len <= 0) {
  426. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: invalid input buffer");
  427. return false;
  428. }
  429. // tmpImage is used for camera frames. Inspect dimensions before decoding so
  430. // an unexpected high-resolution JPEG cannot allocate a large temporary buffer.
  431. if (name == "tmpImage") {
  432. int inputWidth = 0, inputHeight = 0, inputChannels = 0;
  433. if (!stbi_info_from_memory(_buffer, len, &inputWidth, &inputHeight, &inputChannels) ||
  434. inputWidth <= 0 || inputHeight <= 0 ||
  435. inputWidth > CAMERA_MAX_FRAME_WIDTH || inputHeight > CAMERA_MAX_FRAME_HEIGHT) {
  436. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  437. "LoadFromMemory: tmpImage JPEG exceeds the VGA limit or has invalid dimensions");
  438. return false;
  439. }
  440. }
  441. int newWidth = 0, newHeight = 0, sourceChannels = 0;
  442. uint8_t* decoded = stbi_load_from_memory(_buffer, len, &newWidth, &newHeight,
  443. &sourceChannels, STBI_rgb);
  444. size_t decodedSize = 0;
  445. if (decoded == NULL || !getImageBufferSize(newWidth, newHeight, STBI_rgb, &decodedSize)) {
  446. if (decoded != NULL) stbi_image_free(decoded);
  447. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: image decode failed or returned invalid dimensions");
  448. LogFile.WriteHeapInfo("LoadFromMemory");
  449. return false;
  450. }
  451. if (!lockImageAccess()) {
  452. stbi_image_free(decoded);
  453. return false;
  454. }
  455. if (rgb_image != NULL && !externalImage) {
  456. releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
  457. rgb_image, memsize, ownsSharedTempImageLease);
  458. }
  459. rgb_image = decoded;
  460. width = newWidth;
  461. height = newHeight;
  462. channels = STBI_rgb;
  463. bpp = sourceChannels;
  464. memsize = 0;
  465. externalImage = false;
  466. ownsSharedTempImageLease = false;
  467. unlockImageAccess();
  468. ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
  469. return true;
  470. }
  471. void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom)
  472. {
  473. size_t inputSize = 0;
  474. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &inputSize) ||
  475. static_cast<unsigned int>(cropLeft) + cropRight >= static_cast<unsigned int>(width) ||
  476. static_cast<unsigned int>(cropTop) + cropBottom >= static_cast<unsigned int>(height)) return;
  477. uint8_t* image = RGBImageLock();
  478. if (image == nullptr) return;
  479. const int oldWidth = width;
  480. const int oldHeight = height;
  481. const size_t rowBytes = static_cast<size_t>(oldWidth) * static_cast<size_t>(channels);
  482. const size_t firstRow = static_cast<size_t>(cropTop) * rowBytes;
  483. const size_t endRow = static_cast<size_t>(oldHeight - cropBottom) * rowBytes;
  484. const unsigned int maxX = static_cast<unsigned int>(oldWidth) - cropRight;
  485. const unsigned int newWidth = static_cast<unsigned int>(oldWidth) - cropLeft - cropRight;
  486. const unsigned int newHeight = static_cast<unsigned int>(oldHeight) - cropTop - cropBottom;
  487. size_t writeIndex = 0;
  488. for (size_t i = 0; i < inputSize; i += static_cast<size_t>(channels)) {
  489. const unsigned int x = static_cast<unsigned int>((i / static_cast<size_t>(channels)) % static_cast<size_t>(oldWidth));
  490. if (i < firstRow || i >= endRow || x < cropLeft || x >= maxX) continue;
  491. const size_t pixelBytes = static_cast<size_t>(channels);
  492. if (i > inputSize || pixelBytes > inputSize - i || writeIndex > inputSize ||
  493. pixelBytes > inputSize - writeIndex) {
  494. RGBImageRelease();
  495. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "crop_image: computed crop bounds exceeded image buffer");
  496. return;
  497. }
  498. std::memmove(image + writeIndex, image + i, pixelBytes);
  499. writeIndex += pixelBytes;
  500. }
  501. width = static_cast<int>(newWidth);
  502. height = static_cast<int>(newHeight);
  503. RGBImageRelease();
  504. }
  505. CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
  506. {
  507. name = _name;
  508. islocked = false;
  509. externalImage = false;
  510. rgb_image = NULL;
  511. width = height = channels = bpp = 0;
  512. memsize = 0;
  513. ownsSharedTempImageLease = false;
  514. if (_copyfrom == NULL || !_copyfrom->ImageOkay()) {
  515. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: source image is not available");
  516. return;
  517. }
  518. size_t imageSize = 0;
  519. if (!getImageBufferSize(_copyfrom->width, _copyfrom->height, _copyfrom->channels, &imageSize)) {
  520. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: invalid source dimensions");
  521. return;
  522. }
  523. if (name == "tmpImage" &&
  524. (_copyfrom->width > CAMERA_MAX_FRAME_WIDTH ||
  525. _copyfrom->height > CAMERA_MAX_FRAME_HEIGHT ||
  526. _copyfrom->channels != 3)) {
  527. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  528. "CImageBasis-Copyfrom: tmpImage must be RGB and must not exceed the VGA limit (" +
  529. std::to_string(_copyfrom->width) + "x" + std::to_string(_copyfrom->height) +
  530. ", channels: " + std::to_string(_copyfrom->channels) + ")");
  531. return;
  532. }
  533. width = _copyfrom->width;
  534. height = _copyfrom->height;
  535. channels = _copyfrom->channels;
  536. bpp = _copyfrom->bpp;
  537. #ifdef DEBUG_DETAIL_ON
  538. LogFile.WriteHeapInfo("CImageBasis_copyfrom - Start");
  539. #endif
  540. uint8_t* source = _copyfrom->RGBImageLock();
  541. if (source == NULL) {
  542. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: source image is locked");
  543. return;
  544. }
  545. if (name == "tmpImage") {
  546. // tmpImage is an in-place VGA workspace. Do not silently add a second,
  547. // larger PSRAM allocation when the shared workspace cannot be leased.
  548. rgb_image = static_cast<uint8_t*>(psram_reserve_shared_tmp_image_memory(imageSize));
  549. ownsSharedTempImageLease = (rgb_image != NULL);
  550. memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
  551. } else {
  552. rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
  553. std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
  554. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  555. memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
  556. }
  557. if (rgb_image == NULL) {
  558. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
  559. LogFile.WriteHeapInfo("CImageBasis-Copyfrom");
  560. _copyfrom->RGBImageRelease();
  561. return;
  562. }
  563. memCopy(source, rgb_image, static_cast<int>(imageSize));
  564. _copyfrom->RGBImageRelease();
  565. #ifdef DEBUG_DETAIL_ON
  566. LogFile.WriteHeapInfo("CImageBasis_copyfrom - done");
  567. #endif
  568. }
  569. CImageBasis::CImageBasis(string _name, int _width, int _height, int _channels)
  570. {
  571. name = _name;
  572. islocked = false;
  573. externalImage = false;
  574. ownsSharedTempImageLease = false;
  575. rgb_image = NULL;
  576. width = height = channels = bpp = 0;
  577. memsize = 0;
  578. size_t imageSize = 0;
  579. if (!getImageBufferSize(_width, _height, _channels, &imageSize)) {
  580. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: invalid image dimensions");
  581. return;
  582. }
  583. #ifdef DEBUG_DETAIL_ON
  584. LogFile.WriteHeapInfo("CImageBasis_width,height,ch - Start");
  585. #endif
  586. rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
  587. std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
  588. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  589. if (rgb_image == NULL) {
  590. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
  591. LogFile.WriteHeapInfo("CImageBasis-width,height,ch");
  592. return;
  593. }
  594. width = _width;
  595. height = _height;
  596. channels = _channels;
  597. bpp = _channels;
  598. memsize = static_cast<int>(imageSize);
  599. #ifdef DEBUG_DETAIL_ON
  600. LogFile.WriteHeapInfo("CImageBasis_width,height,ch - done");
  601. #endif
  602. }
  603. CImageBasis::CImageBasis(string _name, std::string _image)
  604. {
  605. name = _name;
  606. islocked = false;
  607. channels = STBI_rgb;
  608. width = height = bpp = 0;
  609. memsize = 0;
  610. externalImage = false;
  611. ownsSharedTempImageLease = false;
  612. rgb_image = NULL;
  613. filename = _image;
  614. if (file_size(_image.c_str()) == 0) {
  615. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _image + " is empty!");
  616. return;
  617. }
  618. #ifdef DEBUG_DETAIL_ON
  619. LogFile.WriteHeapInfo("CImageBasis_image - Start");
  620. #endif
  621. int loadedWidth = 0, loadedHeight = 0, sourceChannels = 0;
  622. uint8_t* loaded = stbi_load(_image.c_str(), &loadedWidth, &loadedHeight,
  623. &sourceChannels, STBI_rgb);
  624. size_t imageSize = 0;
  625. if (loaded == NULL || !getImageBufferSize(loadedWidth, loadedHeight, STBI_rgb, &imageSize)) {
  626. if (loaded != NULL) stbi_image_free(loaded);
  627. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-image: Failed to load valid image " + _image);
  628. LogFile.WriteHeapInfo("CImageBasis-image");
  629. return;
  630. }
  631. if (!lockImageAccess()) {
  632. stbi_image_free(loaded);
  633. return;
  634. }
  635. rgb_image = loaded;
  636. width = loadedWidth;
  637. height = loadedHeight;
  638. bpp = sourceChannels;
  639. unlockImageAccess();
  640. #ifdef DEBUG_DETAIL_ON
  641. std::string zw = "CImageBasis after load " + _image;
  642. ESP_LOGD(TAG, "%s", zw.c_str());
  643. ESP_LOGD(TAG, "w %d, h %d, b %d, c %d", width, height, bpp, channels);
  644. LogFile.WriteHeapInfo("CImageBasis_image - done");
  645. #endif
  646. }
  647. bool CImageBasis::ImageOkay(){
  648. if (!lockImageAccess()) return false;
  649. size_t imageSize = 0;
  650. const bool okay = rgb_image != NULL && getImageBufferSize(width, height, channels, &imageSize);
  651. unlockImageAccess();
  652. return okay;
  653. }
  654. CImageBasis::CImageBasis(string _name, uint8_t* _rgb_image, int _channels, int _width, int _height, int _bpp)
  655. {
  656. name = _name;
  657. islocked = false;
  658. rgb_image = _rgb_image;
  659. channels = _channels;
  660. width = _width;
  661. height = _height;
  662. bpp = _bpp;
  663. externalImage = true;
  664. }
  665. void CImageBasis::Negative(void)
  666. {
  667. size_t size = 0;
  668. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
  669. uint8_t* image = RGBImageLock();
  670. if (image == nullptr) return;
  671. for (size_t i = 0; i < size; i += static_cast<size_t>(channels))
  672. for (int c = 0; c < channels; ++c) image[i + static_cast<size_t>(c)] = 255 - image[i + static_cast<size_t>(c)];
  673. RGBImageRelease();
  674. }
  675. void CImageBasis::Contrast(float _contrast)
  676. {
  677. size_t imageSize = 0;
  678. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
  679. uint8_t* image = RGBImageLock();
  680. if (image == nullptr) return;
  681. const float contrast = (_contrast / 100) + 1;
  682. const float intercept = 128 * (1 - contrast);
  683. for (int y = 0; y < height; ++y) {
  684. for (int x = 0; x < width; ++x) {
  685. const size_t offset = static_cast<size_t>(channels) *
  686. (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
  687. uint8_t* pixel = image + offset;
  688. for (int channel = 0; channel < channels; ++channel)
  689. pixel[channel] = static_cast<uint8_t>(std::min(255, std::max(0,
  690. static_cast<int>(pixel[channel] * contrast + intercept))));
  691. }
  692. }
  693. RGBImageRelease();
  694. }
  695. CImageBasis::~CImageBasis()
  696. {
  697. if (!lockImageAccess(-1)) {
  698. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Destructor could not acquire image lock");
  699. return;
  700. }
  701. if (!externalImage && rgb_image != NULL) {
  702. releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
  703. rgb_image, memsize, ownsSharedTempImageLease);
  704. }
  705. rgb_image = NULL;
  706. ownsSharedTempImageLease = false;
  707. unlockImageAccess();
  708. }
  709. void CImageBasis::SaveToFile(std::string _imageout)
  710. {
  711. size_t imageSize = 0;
  712. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
  713. const string typ = getFileType(_imageout);
  714. uint8_t* image = RGBImageLock();
  715. if (image == nullptr) return;
  716. if ((typ == "jpg") || (typ == "JPG")) stbi_write_jpg(_imageout.c_str(), width, height, channels, image, 0);
  717. #ifndef STBI_ONLY_JPEG
  718. if ((typ == "bmp") || (typ == "BMP")) stbi_write_bmp(_imageout.c_str(), width, height, channels, image);
  719. #endif
  720. RGBImageRelease();
  721. }
  722. void CImageBasis::Resize(int _new_dx, int _new_dy)
  723. {
  724. if (rgb_image == NULL || name == "tmpImage") {
  725. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: not possible for image " + name);
  726. return;
  727. }
  728. size_t newSize = 0;
  729. if (!getImageBufferSize(_new_dx, _new_dy, channels, &newSize)) {
  730. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: invalid target dimensions");
  731. return;
  732. }
  733. uint8_t* source = RGBImageLock();
  734. if (source == NULL) return;
  735. uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
  736. std::string(TAG) + "->CImageBasis Resize (" + name + ")", newSize,
  737. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  738. if (output == NULL) {
  739. RGBImageRelease();
  740. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: PSRAM allocation failed: " + std::to_string(newSize));
  741. return;
  742. }
  743. const int resized = stbir_resize_uint8(source, width, height, 0,
  744. output, _new_dx, _new_dy, 0, channels);
  745. if (resized == 0) {
  746. RGBImageRelease();
  747. free_psram_heap(std::string(TAG) + "->CImageBasis Resize (failed)", output);
  748. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: stb resize failed");
  749. return;
  750. }
  751. if (!externalImage) {
  752. releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis Resize old", name,
  753. rgb_image, memsize, ownsSharedTempImageLease);
  754. }
  755. rgb_image = output;
  756. memsize = static_cast<int>(newSize);
  757. externalImage = false;
  758. ownsSharedTempImageLease = false;
  759. width = _new_dx;
  760. height = _new_dy;
  761. RGBImageRelease();
  762. }
  763. bool CImageBasis::Resize(int _new_dx, int _new_dy, CImageBasis *_target)
  764. {
  765. if (_target == this || _target == NULL || rgb_image == NULL || !_target->ImageOkay() ||
  766. _target->height != _new_dy || _target->width != _new_dx ||
  767. _target->channels != channels) {
  768. ESP_LOGE(TAG, "Resize - Target image size does not fit or is unavailable!");
  769. return false;
  770. }
  771. size_t sourceSize = 0, targetSize = 0;
  772. if (!getImageBufferSize(width, height, channels, &sourceSize) ||
  773. !getImageBufferSize(_new_dx, _new_dy, channels, &targetSize)) {
  774. ESP_LOGE(TAG, "Resize - Invalid source or target dimensions");
  775. return false;
  776. }
  777. uint8_t* source = RGBImageLock();
  778. if (source == NULL) return false;
  779. uint8_t* target = _target->RGBImageLock();
  780. if (target == NULL) {
  781. RGBImageRelease();
  782. return false;
  783. }
  784. const int resized = stbir_resize_uint8(source, width, height, 0,
  785. target, _new_dx, _new_dy, 0, channels);
  786. _target->RGBImageRelease();
  787. RGBImageRelease();
  788. if (resized == 0) ESP_LOGE(TAG, "Resize - stb resize failed");
  789. return resized != 0;
  790. }