CImageBasis.cpp 30 KB

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