CImageBasis.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  527. "CImageBasis-Copyfrom: tmpImage exceeds the VGA limit (" +
  528. std::to_string(_copyfrom->width) + "x" + std::to_string(_copyfrom->height) + ")");
  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. // tmpImage is an in-place VGA workspace. Do not silently add a second,
  545. // larger PSRAM allocation when the shared workspace cannot be leased.
  546. rgb_image = static_cast<uint8_t*>(psram_reserve_shared_tmp_image_memory(imageSize));
  547. ownsSharedTempImageLease = (rgb_image != NULL);
  548. memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
  549. } else {
  550. rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
  551. std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
  552. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  553. memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
  554. }
  555. if (rgb_image == NULL) {
  556. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
  557. LogFile.WriteHeapInfo("CImageBasis-Copyfrom");
  558. _copyfrom->RGBImageRelease();
  559. return;
  560. }
  561. memCopy(source, rgb_image, static_cast<int>(imageSize));
  562. _copyfrom->RGBImageRelease();
  563. #ifdef DEBUG_DETAIL_ON
  564. LogFile.WriteHeapInfo("CImageBasis_copyfrom - done");
  565. #endif
  566. }
  567. CImageBasis::CImageBasis(string _name, int _width, int _height, int _channels)
  568. {
  569. name = _name;
  570. islocked = false;
  571. externalImage = false;
  572. ownsSharedTempImageLease = false;
  573. rgb_image = NULL;
  574. width = height = channels = bpp = 0;
  575. memsize = 0;
  576. size_t imageSize = 0;
  577. if (!getImageBufferSize(_width, _height, _channels, &imageSize)) {
  578. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: invalid image dimensions");
  579. return;
  580. }
  581. #ifdef DEBUG_DETAIL_ON
  582. LogFile.WriteHeapInfo("CImageBasis_width,height,ch - Start");
  583. #endif
  584. rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
  585. std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
  586. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  587. if (rgb_image == NULL) {
  588. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
  589. LogFile.WriteHeapInfo("CImageBasis-width,height,ch");
  590. return;
  591. }
  592. width = _width;
  593. height = _height;
  594. channels = _channels;
  595. bpp = _channels;
  596. memsize = static_cast<int>(imageSize);
  597. #ifdef DEBUG_DETAIL_ON
  598. LogFile.WriteHeapInfo("CImageBasis_width,height,ch - done");
  599. #endif
  600. }
  601. CImageBasis::CImageBasis(string _name, std::string _image)
  602. {
  603. name = _name;
  604. islocked = false;
  605. channels = STBI_rgb;
  606. width = height = bpp = 0;
  607. memsize = 0;
  608. externalImage = false;
  609. ownsSharedTempImageLease = false;
  610. rgb_image = NULL;
  611. filename = _image;
  612. if (file_size(_image.c_str()) == 0) {
  613. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _image + " is empty!");
  614. return;
  615. }
  616. #ifdef DEBUG_DETAIL_ON
  617. LogFile.WriteHeapInfo("CImageBasis_image - Start");
  618. #endif
  619. int loadedWidth = 0, loadedHeight = 0, sourceChannels = 0;
  620. uint8_t* loaded = stbi_load(_image.c_str(), &loadedWidth, &loadedHeight,
  621. &sourceChannels, STBI_rgb);
  622. size_t imageSize = 0;
  623. if (loaded == NULL || !getImageBufferSize(loadedWidth, loadedHeight, STBI_rgb, &imageSize)) {
  624. if (loaded != NULL) stbi_image_free(loaded);
  625. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-image: Failed to load valid image " + _image);
  626. LogFile.WriteHeapInfo("CImageBasis-image");
  627. return;
  628. }
  629. if (!lockImageAccess()) {
  630. stbi_image_free(loaded);
  631. return;
  632. }
  633. rgb_image = loaded;
  634. width = loadedWidth;
  635. height = loadedHeight;
  636. bpp = sourceChannels;
  637. unlockImageAccess();
  638. #ifdef DEBUG_DETAIL_ON
  639. std::string zw = "CImageBasis after load " + _image;
  640. ESP_LOGD(TAG, "%s", zw.c_str());
  641. ESP_LOGD(TAG, "w %d, h %d, b %d, c %d", width, height, bpp, channels);
  642. LogFile.WriteHeapInfo("CImageBasis_image - done");
  643. #endif
  644. }
  645. bool CImageBasis::ImageOkay(){
  646. if (!lockImageAccess()) return false;
  647. size_t imageSize = 0;
  648. const bool okay = rgb_image != NULL && getImageBufferSize(width, height, channels, &imageSize);
  649. unlockImageAccess();
  650. return okay;
  651. }
  652. CImageBasis::CImageBasis(string _name, uint8_t* _rgb_image, int _channels, int _width, int _height, int _bpp)
  653. {
  654. name = _name;
  655. islocked = false;
  656. rgb_image = _rgb_image;
  657. channels = _channels;
  658. width = _width;
  659. height = _height;
  660. bpp = _bpp;
  661. externalImage = true;
  662. }
  663. void CImageBasis::Negative(void)
  664. {
  665. size_t size = 0;
  666. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return;
  667. uint8_t* image = RGBImageLock();
  668. if (image == nullptr) return;
  669. for (size_t i = 0; i < size; i += static_cast<size_t>(channels))
  670. for (int c = 0; c < channels; ++c) image[i + static_cast<size_t>(c)] = 255 - image[i + static_cast<size_t>(c)];
  671. RGBImageRelease();
  672. }
  673. void CImageBasis::Contrast(float _contrast)
  674. {
  675. size_t imageSize = 0;
  676. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
  677. uint8_t* image = RGBImageLock();
  678. if (image == nullptr) return;
  679. const float contrast = (_contrast / 100) + 1;
  680. const float intercept = 128 * (1 - contrast);
  681. for (int y = 0; y < height; ++y) {
  682. for (int x = 0; x < width; ++x) {
  683. const size_t offset = static_cast<size_t>(channels) *
  684. (static_cast<size_t>(y) * static_cast<size_t>(width) + static_cast<size_t>(x));
  685. uint8_t* pixel = image + offset;
  686. for (int channel = 0; channel < channels; ++channel)
  687. pixel[channel] = static_cast<uint8_t>(std::min(255, std::max(0,
  688. static_cast<int>(pixel[channel] * contrast + intercept))));
  689. }
  690. }
  691. RGBImageRelease();
  692. }
  693. CImageBasis::~CImageBasis()
  694. {
  695. if (!lockImageAccess(-1)) {
  696. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Destructor could not acquire image lock");
  697. return;
  698. }
  699. if (!externalImage && rgb_image != NULL) {
  700. releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
  701. rgb_image, memsize, ownsSharedTempImageLease);
  702. }
  703. rgb_image = NULL;
  704. ownsSharedTempImageLease = false;
  705. unlockImageAccess();
  706. }
  707. void CImageBasis::SaveToFile(std::string _imageout)
  708. {
  709. size_t imageSize = 0;
  710. if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &imageSize)) return;
  711. const string typ = getFileType(_imageout);
  712. uint8_t* image = RGBImageLock();
  713. if (image == nullptr) return;
  714. if ((typ == "jpg") || (typ == "JPG")) stbi_write_jpg(_imageout.c_str(), width, height, channels, image, 0);
  715. #ifndef STBI_ONLY_JPEG
  716. if ((typ == "bmp") || (typ == "BMP")) stbi_write_bmp(_imageout.c_str(), width, height, channels, image);
  717. #endif
  718. RGBImageRelease();
  719. }
  720. void CImageBasis::Resize(int _new_dx, int _new_dy)
  721. {
  722. if (rgb_image == NULL || name == "tmpImage") {
  723. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: not possible for image " + name);
  724. return;
  725. }
  726. size_t newSize = 0;
  727. if (!getImageBufferSize(_new_dx, _new_dy, channels, &newSize)) {
  728. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: invalid target dimensions");
  729. return;
  730. }
  731. uint8_t* source = RGBImageLock();
  732. if (source == NULL) return;
  733. uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
  734. std::string(TAG) + "->CImageBasis Resize (" + name + ")", newSize,
  735. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  736. if (output == NULL) {
  737. RGBImageRelease();
  738. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: PSRAM allocation failed: " + std::to_string(newSize));
  739. return;
  740. }
  741. const int resized = stbir_resize_uint8(source, width, height, 0,
  742. output, _new_dx, _new_dy, 0, channels);
  743. if (resized == 0) {
  744. RGBImageRelease();
  745. free_psram_heap(std::string(TAG) + "->CImageBasis Resize (failed)", output);
  746. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: stb resize failed");
  747. return;
  748. }
  749. if (!externalImage) {
  750. releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis Resize old", name,
  751. rgb_image, memsize, ownsSharedTempImageLease);
  752. }
  753. rgb_image = output;
  754. memsize = static_cast<int>(newSize);
  755. externalImage = false;
  756. ownsSharedTempImageLease = false;
  757. width = _new_dx;
  758. height = _new_dy;
  759. RGBImageRelease();
  760. }
  761. bool CImageBasis::Resize(int _new_dx, int _new_dy, CImageBasis *_target)
  762. {
  763. if (_target == this || _target == NULL || rgb_image == NULL || !_target->ImageOkay() ||
  764. _target->height != _new_dy || _target->width != _new_dx ||
  765. _target->channels != channels) {
  766. ESP_LOGE(TAG, "Resize - Target image size does not fit or is unavailable!");
  767. return false;
  768. }
  769. size_t sourceSize = 0, targetSize = 0;
  770. if (!getImageBufferSize(width, height, channels, &sourceSize) ||
  771. !getImageBufferSize(_new_dx, _new_dy, channels, &targetSize)) {
  772. ESP_LOGE(TAG, "Resize - Invalid source or target dimensions");
  773. return false;
  774. }
  775. uint8_t* source = RGBImageLock();
  776. if (source == NULL) return false;
  777. uint8_t* target = _target->RGBImageLock();
  778. if (target == NULL) {
  779. RGBImageRelease();
  780. return false;
  781. }
  782. const int resized = stbir_resize_uint8(source, width, height, 0,
  783. target, _new_dx, _new_dy, 0, channels);
  784. _target->RGBImageRelease();
  785. RGBImageRelease();
  786. if (resized == 0) ESP_LOGE(TAG, "Resize - stb resize failed");
  787. return resized != 0;
  788. }