ClassControllCamera.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. #include "ClassControllCamera.h"
  2. #include "ClassLogFile.h"
  3. #include <stdio.h>
  4. #include "driver/gpio.h"
  5. #include "esp_timer.h"
  6. #include "esp_log.h"
  7. #include "Helper.h"
  8. #include "statusled.h"
  9. #include "CImageBasis.h"
  10. #include "psram.h"
  11. #include "server_ota.h"
  12. #include "../../include/defines.h"
  13. #include <esp_event.h>
  14. #include <esp_log.h>
  15. #include <esp_system.h>
  16. #include <nvs_flash.h>
  17. #include <sys/param.h>
  18. #include <string.h>
  19. #include <limits.h>
  20. #include <algorithm>
  21. #include <new>
  22. #include <sys/stat.h>
  23. #include "freertos/FreeRTOS.h"
  24. #include "freertos/task.h"
  25. #include "server_camera.h"
  26. #include "esp_camera.h"
  27. #include "esp_heap_caps.h"
  28. #include "driver/ledc.h"
  29. #include "MainFlowControl.h"
  30. #include "ov2640_sharpness.h"
  31. #include "ov2640_specialEffect.h"
  32. #include "ov2640_contrast_brightness.h"
  33. #if (ESP_IDF_VERSION_MAJOR >= 5)
  34. #include "soc/periph_defs.h"
  35. #include "esp_private/periph_ctrl.h"
  36. #include "soc/gpio_sig_map.h"
  37. #include "soc/gpio_periph.h"
  38. #include "soc/io_mux_reg.h"
  39. #include "esp_rom_gpio.h"
  40. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  41. #define gpio_matrix_in(a, b, c) esp_rom_gpio_connect_in_signal(a, b, c)
  42. #define gpio_matrix_out(a, b, c, d) esp_rom_gpio_connect_out_signal(a, b, c, d)
  43. #define ets_delay_us(a) esp_rom_delay_us(a)
  44. #endif
  45. camera_controll_config_temp_t CCstatus;
  46. CCamera Camera;
  47. static const char *TAG = "CAM";
  48. static int sensorValueOrDefault(int value, int fallback, int minimum, int maximum)
  49. {
  50. return (value < minimum || value > maximum) ? fallback : value;
  51. }
  52. static int sensorBooleanOrDefault(int value, int fallback)
  53. {
  54. return (value == 0 || value == 1) ? value : fallback;
  55. }
  56. static bool isSupportedFrameSize(int value)
  57. {
  58. switch (static_cast<framesize_t>(value))
  59. {
  60. case FRAMESIZE_QVGA:
  61. case FRAMESIZE_VGA:
  62. return true;
  63. default:
  64. return false;
  65. }
  66. }
  67. /* Camera live stream */
  68. #define PART_BOUNDARY "123456789000000000000987654321"
  69. static const char *_STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
  70. static const char *_STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
  71. static const char *_STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
  72. #define DEMO_IMAGE_SIZE 30000 // Max size of demo image in bytes
  73. // Camera module bus communications frequency.
  74. // Originally: config.xclk_freq_mhz = 20000000, but this lead to visual artifacts on many modules.
  75. // See https://github.com/espressif/esp32-camera/issues/150#issuecomment-726473652 et al.
  76. #if !defined(XCLK_FREQ_MHZ)
  77. // int xclk = 8;
  78. int xclk = 20; // Orginal value
  79. #else
  80. int xclk = XCLK_FREQ_MHZ;
  81. #endif
  82. static camera_config_t camera_config = {
  83. .pin_pwdn = CAM_PIN_PWDN,
  84. .pin_reset = CAM_PIN_RESET,
  85. .pin_xclk = CAM_PIN_XCLK,
  86. .pin_sccb_sda = CAM_PIN_SIOD,
  87. .pin_sccb_scl = CAM_PIN_SIOC,
  88. .pin_d7 = CAM_PIN_D7,
  89. .pin_d6 = CAM_PIN_D6,
  90. .pin_d5 = CAM_PIN_D5,
  91. .pin_d4 = CAM_PIN_D4,
  92. .pin_d3 = CAM_PIN_D3,
  93. .pin_d2 = CAM_PIN_D2,
  94. .pin_d1 = CAM_PIN_D1,
  95. .pin_d0 = CAM_PIN_D0,
  96. .pin_vsync = CAM_PIN_VSYNC,
  97. .pin_href = CAM_PIN_HREF,
  98. .pin_pclk = CAM_PIN_PCLK,
  99. .xclk_freq_hz = (xclk * 1000000),
  100. .ledc_timer = LEDC_TIMER_0, // LEDC timer to be used for generating XCLK
  101. .ledc_channel = LEDC_CHANNEL_0, // LEDC channel to be used for generating XCLK
  102. .pixel_format = PIXFORMAT_JPEG, // YUV422,GRAYSCALE,RGB565,JPEG
  103. .frame_size = FRAMESIZE_VGA, // QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  104. // .frame_size = FRAMESIZE_UXGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  105. .jpeg_quality = 12, // 0-63 lower number means higher quality
  106. .fb_count = 1, // if more than one, i2s runs in continuous mode. Use only with JPEG
  107. .fb_location = CAMERA_FB_IN_PSRAM, /*!< The location where the frame buffer will be allocated */
  108. .grab_mode = CAMERA_GRAB_LATEST, // only from new esp32cam version
  109. .sccb_i2c_port = 0, // unused when the SCCB pins are configured above
  110. };
  111. typedef struct
  112. {
  113. httpd_req_t *req;
  114. size_t len;
  115. } jpg_chunking_t;
  116. // The camera driver and sensor register access are not safe to use concurrently.
  117. // Recursive locking allows public methods to safely call other locked methods.
  118. class ScopedCameraLock
  119. {
  120. public:
  121. explicit ScopedCameraLock(SemaphoreHandle_t mutex, TickType_t timeout = pdMS_TO_TICKS(5000))
  122. : m_mutex(mutex),
  123. m_acquired(mutex != NULL && xSemaphoreTakeRecursive(mutex, timeout) == pdTRUE)
  124. {
  125. }
  126. ~ScopedCameraLock()
  127. {
  128. if (m_acquired)
  129. {
  130. xSemaphoreGiveRecursive(m_mutex);
  131. }
  132. }
  133. bool acquired() const { return m_acquired; }
  134. private:
  135. SemaphoreHandle_t m_mutex;
  136. bool m_acquired;
  137. };
  138. // Owns one camera framebuffer and returns it exactly once on every exit path.
  139. class ScopedCameraOperationLock
  140. {
  141. public:
  142. explicit ScopedCameraOperationLock(SemaphoreHandle_t mutex, TickType_t timeout = pdMS_TO_TICKS(5000))
  143. : m_mutex(mutex),
  144. m_acquired(mutex != NULL && xSemaphoreTakeRecursive(mutex, timeout) == pdTRUE)
  145. {
  146. }
  147. ~ScopedCameraOperationLock()
  148. {
  149. if (m_acquired) xSemaphoreGiveRecursive(m_mutex);
  150. }
  151. bool acquired() const { return m_acquired; }
  152. private:
  153. SemaphoreHandle_t m_mutex;
  154. bool m_acquired;
  155. };
  156. // Owns one camera framebuffer and returns it exactly once on every exit path.
  157. class ScopedCameraFrame
  158. {
  159. public:
  160. ScopedCameraFrame(camera_fb_t *frame, SemaphoreHandle_t cameraMutex)
  161. : m_frame(frame), m_cameraMutex(cameraMutex)
  162. {
  163. }
  164. ~ScopedCameraFrame() { release(); }
  165. ScopedCameraFrame(const ScopedCameraFrame &) = delete;
  166. ScopedCameraFrame &operator=(const ScopedCameraFrame &) = delete;
  167. camera_fb_t *get() const { return m_frame; }
  168. void release()
  169. {
  170. if (m_frame == NULL) return;
  171. // Frame return touches camera-driver state and must use the driver lock.
  172. ScopedCameraLock cameraLock(m_cameraMutex, portMAX_DELAY);
  173. if (!cameraLock.acquired())
  174. {
  175. ESP_LOGE(TAG, "Unable to lock camera driver to return framebuffer");
  176. return;
  177. }
  178. esp_camera_fb_return(m_frame);
  179. m_frame = NULL;
  180. }
  181. private:
  182. camera_fb_t *m_frame;
  183. SemaphoreHandle_t m_cameraMutex;
  184. };
  185. class ScopedCameraCaptureIndicators
  186. {
  187. public:
  188. ScopedCameraCaptureIndicators(CCamera &camera, bool statusLed, bool flashLed)
  189. : m_camera(camera), m_statusLed(statusLed), m_flashLed(flashLed)
  190. {
  191. if (m_statusLed) m_camera.SetCaptureStatusLedActive(true);
  192. if (m_flashLed) m_camera.SetCaptureFlashActive(true);
  193. }
  194. ~ScopedCameraCaptureIndicators()
  195. {
  196. if (m_flashLed) m_camera.SetCaptureFlashActive(false);
  197. if (m_statusLed) m_camera.SetCaptureStatusLedActive(false);
  198. }
  199. ScopedCameraCaptureIndicators(const ScopedCameraCaptureIndicators &) = delete;
  200. ScopedCameraCaptureIndicators &operator=(const ScopedCameraCaptureIndicators &) = delete;
  201. private:
  202. CCamera &m_camera;
  203. bool m_statusLed;
  204. bool m_flashLed;
  205. };
  206. CCamera::CCamera(void)
  207. : m_cameraMutex(xSemaphoreCreateRecursiveMutex()),
  208. m_cameraOperationMutex(xSemaphoreCreateRecursiveMutex()),
  209. m_driverInitialized(false),
  210. m_temporarySettingsActive(false),
  211. m_previewCapturePending(false),
  212. m_previewCaptureDelayMs(0),
  213. m_captureFlashUsers(0),
  214. m_captureStatusLedUsers(0),
  215. m_manualFlashOn(false),
  216. m_manualStatusLedOn(false)
  217. {
  218. #ifdef DEBUG_DETAIL_ON
  219. ESP_LOGD(TAG, "CreateClassCamera");
  220. #endif
  221. CCstatus.ImageQuality = camera_config.jpeg_quality;
  222. CCstatus.ImageFrameSize = camera_config.frame_size;
  223. CCstatus.CamXclkFreqMhz = xclk;
  224. CCstatus.ImageLedIntensity = SetLEDIntensity(LedIntensity);
  225. CCstatus.WaitBeforePicture = 2;
  226. SetImageWidthHeightFromResolution(CCstatus);
  227. ledc_init();
  228. }
  229. esp_err_t CCamera::InitCam(void)
  230. {
  231. // Driver teardown/reinitialization must not invalidate a leased framebuffer.
  232. ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
  233. if (!frameLease.acquired()) return ESP_ERR_TIMEOUT;
  234. ScopedCameraLock cameraLock(m_cameraMutex);
  235. if (!cameraLock.acquired())
  236. {
  237. ESP_LOGE(TAG, "InitCam: camera mutex unavailable");
  238. CCstatus.CameraInitSuccessful = false;
  239. return ESP_ERR_NO_MEM;
  240. }
  241. ESP_LOGD(TAG, "Init Camera");
  242. CCstatus.CameraInitSuccessful = false;
  243. // Release an earlier driver instance before resetting and reinitializing.
  244. if (m_driverInitialized)
  245. {
  246. const esp_err_t deinitResult = esp_camera_deinit();
  247. if (deinitResult != ESP_OK)
  248. {
  249. ESP_LOGE(TAG, "Camera deinitialization failed: %s", esp_err_to_name(deinitResult));
  250. return deinitResult;
  251. }
  252. m_driverInitialized = false;
  253. }
  254. PowerResetCamera();
  255. vTaskDelay(pdMS_TO_TICKS(200));
  256. const esp_err_t err = esp_camera_init(&camera_config);
  257. if (err != ESP_OK)
  258. {
  259. ESP_LOGE(TAG, "Camera Init Failed: %s", esp_err_to_name(err));
  260. return err;
  261. }
  262. m_driverInitialized = true;
  263. sensor_t *s = esp_camera_sensor_get();
  264. if (s == NULL)
  265. {
  266. ESP_LOGE(TAG, "Camera sensor handle is unavailable");
  267. }
  268. else
  269. {
  270. CCstatus.CamSensor_id = s->id.PID;
  271. switch (CCstatus.CamSensor_id)
  272. {
  273. case OV2640_PID:
  274. ESP_LOGI(TAG, "OV2640 camera module detected");
  275. CCstatus.CameraInitSuccessful = true;
  276. break;
  277. case OV3660_PID:
  278. ESP_LOGI(TAG, "OV3660 camera module detected");
  279. CCstatus.CameraInitSuccessful = true;
  280. break;
  281. case OV5640_PID:
  282. ESP_LOGI(TAG, "OV5640 camera module detected");
  283. CCstatus.CameraInitSuccessful = true;
  284. break;
  285. default:
  286. ESP_LOGE(TAG, "Camera module is unknown and not properly supported!");
  287. break;
  288. }
  289. }
  290. if (!CCstatus.CameraInitSuccessful)
  291. {
  292. const esp_err_t cleanupResult = esp_camera_deinit();
  293. if (cleanupResult != ESP_OK)
  294. {
  295. ESP_LOGE(TAG, "Failed to clean up unsupported camera: %s", esp_err_to_name(cleanupResult));
  296. }
  297. m_driverInitialized = (cleanupResult != ESP_OK);
  298. return ESP_FAIL;
  299. }
  300. return ESP_OK;
  301. }
  302. bool CCamera::testCamera(void)
  303. {
  304. ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
  305. if (!frameLease.acquired()) return false;
  306. ScopedCameraLock cameraLock(m_cameraMutex);
  307. if (!cameraLock.acquired())
  308. {
  309. ESP_LOGW(TAG, "testCamera: camera mutex unavailable");
  310. return false;
  311. }
  312. ScopedCameraFrame frame(esp_camera_fb_get(), m_cameraMutex);
  313. if (frame.get() == NULL)
  314. {
  315. ESP_LOGW(TAG, "testCamera: framebuffer capture failed");
  316. return false;
  317. }
  318. return true;
  319. }
  320. void CCamera::ledc_init(void)
  321. {
  322. #ifdef USE_PWM_LEDFLASH
  323. // Prepare and then apply the LEDC PWM timer configuration
  324. ledc_timer_config_t ledc_timer = {};
  325. ledc_timer.speed_mode = LEDC_MODE;
  326. ledc_timer.timer_num = LEDC_TIMER;
  327. ledc_timer.duty_resolution = LEDC_DUTY_RES;
  328. ledc_timer.freq_hz = LEDC_FREQUENCY; // Set output frequency at 5 kHz
  329. ledc_timer.clk_cfg = LEDC_AUTO_CLK;
  330. ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
  331. // Prepare and then apply the LEDC PWM channel configuration
  332. ledc_channel_config_t ledc_channel = {};
  333. ledc_channel.speed_mode = LEDC_MODE;
  334. ledc_channel.channel = LEDC_CHANNEL;
  335. ledc_channel.timer_sel = LEDC_TIMER;
  336. ledc_channel.intr_type = LEDC_INTR_DISABLE;
  337. ledc_channel.gpio_num = LEDC_OUTPUT_IO;
  338. ledc_channel.duty = 0; // Set duty to 0%
  339. ledc_channel.hpoint = 0;
  340. // ledc_channel.flags.output_invert = LEDC_OUTPUT_INVERT;
  341. ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
  342. #endif
  343. }
  344. int CCamera::SetLEDIntensity(int _intrel)
  345. {
  346. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  347. if (!operationLock.acquired()) return LedIntensity;
  348. ScopedCameraLock cameraLock(m_cameraMutex);
  349. if (!cameraLock.acquired()) return LedIntensity;
  350. LedIntensity = static_cast<int>(
  351. static_cast<float>(std::min(std::max(0, _intrel), 100)) / 100.0f * 8191.0f);
  352. if (m_manualFlashOn || m_captureFlashUsers > 0) UpdateFlashOutputLocked();
  353. ESP_LOGD(TAG, "Set led_intensity to %i of 8191", LedIntensity);
  354. return LedIntensity;
  355. }
  356. bool CCamera::getCameraInitSuccessful(void)
  357. {
  358. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  359. if (!operationLock.acquired()) return false;
  360. ScopedCameraLock cameraLock(m_cameraMutex);
  361. return cameraLock.acquired() && CCstatus.CameraInitSuccessful;
  362. }
  363. esp_err_t CCamera::setSensorDatenFromCCstatus(void)
  364. {
  365. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  366. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  367. ScopedCameraLock cameraLock(m_cameraMutex);
  368. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  369. const esp_err_t result = ApplySettings(CCstatus);
  370. if (result == ESP_OK)
  371. {
  372. m_temporarySettingsActive = false;
  373. m_previewCapturePending = false;
  374. m_previewCaptureDelayMs = 0;
  375. }
  376. return result;
  377. }
  378. esp_err_t CCamera::ApplySettings(CameraSettings &settings)
  379. {
  380. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  381. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  382. ScopedCameraLock cameraLock(m_cameraMutex);
  383. if (!cameraLock.acquired())
  384. {
  385. ESP_LOGW(TAG, "ApplySettings: camera mutex unavailable");
  386. return ESP_ERR_TIMEOUT;
  387. }
  388. if (!m_driverInitialized)
  389. {
  390. ESP_LOGW(TAG, "ApplySettings: camera driver is not initialized");
  391. return ESP_ERR_INVALID_STATE;
  392. }
  393. sensor_t *s = esp_camera_sensor_get();
  394. if (s == NULL)
  395. {
  396. ESP_LOGE(TAG, "ApplySettings: camera sensor unavailable");
  397. return ESP_FAIL;
  398. }
  399. if (settings.CamXclkFreqMhz < 1 || settings.CamXclkFreqMhz > 20)
  400. {
  401. settings.CamXclkFreqMhz = xclk;
  402. }
  403. SetImageWidthHeightFromResolution(settings);
  404. int firstError = s->set_xclk(s, camera_config.ledc_timer, settings.CamXclkFreqMhz);
  405. const auto recordError = [&firstError](int result)
  406. {
  407. if (firstError == 0 && result != 0) firstError = result;
  408. };
  409. recordError(s->set_framesize(s, settings.ImageFrameSize));
  410. SetCamContrastBrightness(s, settings.ImageContrast, settings.ImageBrightness);
  411. recordError(s->set_saturation(s, settings.ImageSaturation));
  412. recordError(s->set_quality(s, settings.ImageQuality));
  413. recordError(SetCamGainceiling(s, settings.ImageGainceiling));
  414. recordError(s->set_gain_ctrl(s, settings.ImageAgc));
  415. recordError(s->set_exposure_ctrl(s, settings.ImageAec));
  416. recordError(s->set_hmirror(s, settings.ImageHmirror));
  417. recordError(s->set_vflip(s, settings.ImageVflip));
  418. recordError(s->set_whitebal(s, settings.ImageAwb));
  419. recordError(s->set_aec2(s, settings.ImageAec2));
  420. recordError(s->set_aec_value(s, settings.ImageAecValue));
  421. SetCamSpecialEffect(s, settings.ImageSpecialEffect);
  422. recordError(s->set_wb_mode(s, settings.ImageWbMode));
  423. recordError(s->set_ae_level(s, settings.ImageAeLevel));
  424. recordError(s->set_dcw(s, settings.ImageDcw));
  425. recordError(s->set_bpc(s, settings.ImageBpc));
  426. recordError(s->set_wpc(s, settings.ImageWpc));
  427. recordError(s->set_awb_gain(s, settings.ImageAwbGain));
  428. recordError(s->set_agc_gain(s, settings.ImageAgcGain));
  429. recordError(s->set_raw_gma(s, settings.ImageRawGma));
  430. recordError(s->set_lenc(s, settings.ImageLenc));
  431. SetCamSharpness(settings.ImageAutoSharpness, settings.ImageSharpness);
  432. // The OV2640 driver does not implement denoise control and its set_denoise()
  433. // callback always returns -1, even when the requested level is zero. Treat
  434. // this unsupported optional control as a no-op instead of aborting camera setup.
  435. if (s->id.PID != OV2640_PID)
  436. {
  437. recordError(s->set_denoise(s, settings.ImageDenoiseLevel));
  438. }
  439. const esp_err_t geometryResult = SetQualityZoomSize(settings);
  440. if (geometryResult != ESP_OK) return geometryResult;
  441. LedIntensity = min(8191, max(0, settings.ImageLedIntensity));
  442. if (m_manualFlashOn || m_captureFlashUsers > 0) UpdateFlashOutputLocked();
  443. vTaskDelay(pdMS_TO_TICKS(100));
  444. return firstError == 0 ? ESP_OK : ESP_FAIL;
  445. }
  446. esp_err_t CCamera::ApplyPreviewSettings(const CameraSettings &settings)
  447. {
  448. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  449. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  450. ScopedCameraLock cameraLock(m_cameraMutex);
  451. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  452. CameraSettings previewSettings = settings;
  453. // Mark the hardware as temporary before applying: ApplySettings may fail after
  454. // changing some sensor registers, so the next normal operation must still restore CCstatus.
  455. m_temporarySettingsActive = true;
  456. const esp_err_t result = ApplySettings(previewSettings);
  457. if (result == ESP_OK)
  458. {
  459. m_previewCapturePending = true;
  460. const int waitSeconds = std::max(0, settings.WaitBeforePicture);
  461. m_previewCaptureDelayMs = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
  462. }
  463. else
  464. {
  465. m_previewCapturePending = false;
  466. m_previewCaptureDelayMs = 0;
  467. }
  468. return result;
  469. }
  470. esp_err_t CCamera::RestoreCommittedSettingsIfNeeded(void)
  471. {
  472. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  473. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  474. ScopedCameraLock cameraLock(m_cameraMutex);
  475. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  476. if (!m_temporarySettingsActive) return ESP_OK;
  477. const esp_err_t result = ApplySettings(CCstatus);
  478. if (result == ESP_OK)
  479. {
  480. m_temporarySettingsActive = false;
  481. m_previewCapturePending = false;
  482. m_previewCaptureDelayMs = 0;
  483. }
  484. return result;
  485. }
  486. esp_err_t CCamera::getSensorDatenToCCstatus(void)
  487. {
  488. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  489. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  490. ScopedCameraLock cameraLock(m_cameraMutex);
  491. if (!cameraLock.acquired())
  492. {
  493. ESP_LOGW(TAG, "getSensorDatenToCCstatus: camera mutex unavailable");
  494. return ESP_ERR_TIMEOUT;
  495. }
  496. sensor_t *s = esp_camera_sensor_get();
  497. if (s == NULL)
  498. {
  499. ESP_LOGE(TAG, "getSensorDatenToCCstatus: camera sensor unavailable");
  500. return ESP_FAIL;
  501. }
  502. CCstatus.CamSensor_id = s->id.PID;
  503. const int frameSize = static_cast<int>(s->status.framesize);
  504. CCstatus.ImageFrameSize = static_cast<framesize_t>(
  505. isSupportedFrameSize(frameSize) ? frameSize : static_cast<int>(FRAMESIZE_VGA));
  506. CCstatus.CamXclkFreqMhz = sensorValueOrDefault(
  507. static_cast<int>(s->xclk_freq_hz / 1000000U), xclk, 1, 20);
  508. CCstatus.ImageContrast = sensorValueOrDefault(s->status.contrast, 0, -2, 2);
  509. CCstatus.ImageBrightness = sensorValueOrDefault(s->status.brightness, 0, -2, 2);
  510. CCstatus.ImageSaturation = sensorValueOrDefault(s->status.saturation, 0, -2, 2);
  511. CCstatus.ImageQuality = sensorValueOrDefault(s->status.quality, 12, 6, 63);
  512. CCstatus.ImageGainceiling = static_cast<gainceiling_t>(
  513. sensorValueOrDefault(static_cast<int>(s->status.gainceiling), 0, 0, 6));
  514. CCstatus.ImageAgc = sensorBooleanOrDefault(s->status.agc, 1);
  515. CCstatus.ImageAec = sensorBooleanOrDefault(s->status.aec, 1);
  516. CCstatus.ImageHmirror = sensorBooleanOrDefault(s->status.hmirror, 0);
  517. CCstatus.ImageVflip = sensorBooleanOrDefault(s->status.vflip, 0);
  518. CCstatus.ImageAwb = sensorBooleanOrDefault(s->status.awb, 1);
  519. CCstatus.ImageAec2 = sensorBooleanOrDefault(s->status.aec2, 1);
  520. CCstatus.ImageAecValue = sensorValueOrDefault(s->status.aec_value, 600, 0, 1200);
  521. CCstatus.ImageSpecialEffect = sensorValueOrDefault(s->status.special_effect, 0, 0, 6);
  522. CCstatus.ImageWbMode = sensorValueOrDefault(s->status.wb_mode, 0, 0, 4);
  523. CCstatus.ImageAeLevel = (CCstatus.CamSensor_id == OV2640_PID)
  524. ? sensorValueOrDefault(s->status.ae_level, 0, -2, 2)
  525. : sensorValueOrDefault(s->status.ae_level, 0, -5, 5);
  526. CCstatus.ImageDcw = sensorBooleanOrDefault(s->status.dcw, 1);
  527. CCstatus.ImageBpc = sensorBooleanOrDefault(s->status.bpc, 1);
  528. CCstatus.ImageWpc = sensorBooleanOrDefault(s->status.wpc, 1);
  529. CCstatus.ImageAwbGain = sensorBooleanOrDefault(s->status.awb_gain, 1);
  530. CCstatus.ImageAgcGain = sensorValueOrDefault(s->status.agc_gain, 8, 0, 30);
  531. CCstatus.ImageRawGma = sensorBooleanOrDefault(s->status.raw_gma, 1);
  532. CCstatus.ImageLenc = sensorBooleanOrDefault(s->status.lenc, 1);
  533. CCstatus.ImageSharpness = (CCstatus.CamSensor_id == OV2640_PID)
  534. ? sensorValueOrDefault(s->status.sharpness, 0, -2, 2)
  535. : sensorValueOrDefault(s->status.sharpness, 0, -3, 3);
  536. CCstatus.ImageDenoiseLevel = (CCstatus.CamSensor_id == OV2640_PID)
  537. ? 0 : sensorValueOrDefault(s->status.denoise, 0, 0, 8);
  538. CCstatus.ImageLedIntensity = min(8191, max(0, LedIntensity));
  539. SetImageWidthHeightFromResolution(CCstatus);
  540. return ESP_OK;
  541. }
  542. // on the OV5640, gainceiling must be set with the real value (x2>>>gainceilingLevel = 2, .... x128>>>gainceilingLevel = 128)
  543. int CCamera::SetCamGainceiling(sensor_t *s, gainceiling_t gainceilingLevel)
  544. {
  545. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  546. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  547. ScopedCameraLock cameraLock(m_cameraMutex);
  548. if (!cameraLock.acquired())
  549. {
  550. ESP_LOGW(TAG, "SetCamGainceiling: camera mutex unavailable");
  551. return ESP_ERR_TIMEOUT;
  552. }
  553. if (s == NULL) return ESP_ERR_INVALID_ARG;
  554. if (s->id.PID == OV2640_PID)
  555. {
  556. return s->set_gainceiling(s, gainceilingLevel);
  557. }
  558. const int level = (1 << (static_cast<int>(gainceilingLevel) + 1));
  559. const int highResult = s->set_reg(s, 0x3A18, 0xFF, (level >> 8) & 3);
  560. const int lowResult = s->set_reg(s, 0x3A19, 0xFF, level & 0xFF);
  561. const int result = highResult != 0 ? highResult : lowResult;
  562. if (result == 0) s->status.gainceiling = gainceilingLevel;
  563. return result;
  564. }
  565. void CCamera::SetCamSharpness(bool autoSharpnessEnabled, int sharpnessLevel)
  566. {
  567. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  568. if (!operationLock.acquired()) return;
  569. ScopedCameraLock cameraLock(m_cameraMutex);
  570. if (!cameraLock.acquired())
  571. {
  572. ESP_LOGW(TAG, "SetCamSharpness: camera mutex unavailable");
  573. return;
  574. }
  575. sensor_t *s = esp_camera_sensor_get();
  576. if (s != NULL)
  577. {
  578. if (s->id.PID == OV2640_PID)
  579. {
  580. sharpnessLevel = min(2, max(-2, sharpnessLevel));
  581. // The OV2640 does not officially support sharpness, so the detour is made with the ov2640_sharpness.cpp.
  582. if (autoSharpnessEnabled)
  583. {
  584. ov2640_enable_auto_sharpness(s);
  585. }
  586. else
  587. {
  588. ov2640_set_sharpness(s, sharpnessLevel);
  589. }
  590. }
  591. else
  592. {
  593. sharpnessLevel = min(3, max(-3, sharpnessLevel));
  594. // for CAMERA_OV5640 and CAMERA_OV3660
  595. if (autoSharpnessEnabled)
  596. {
  597. // autoSharpness is not supported, default to zero
  598. s->set_sharpness(s, 0);
  599. }
  600. else
  601. {
  602. s->set_sharpness(s, sharpnessLevel);
  603. }
  604. }
  605. }
  606. else
  607. {
  608. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetCamSharpness, Failed to get Cam control structure");
  609. }
  610. }
  611. void CCamera::SetCamSpecialEffect(sensor_t *s, int specialEffect)
  612. {
  613. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  614. if (!operationLock.acquired()) return;
  615. ScopedCameraLock cameraLock(m_cameraMutex);
  616. if (!cameraLock.acquired())
  617. {
  618. ESP_LOGW(TAG, "SetCamSpecialEffect: camera mutex unavailable");
  619. return;
  620. }
  621. if (s == NULL) return;
  622. if (s->id.PID == OV2640_PID)
  623. {
  624. ov2640_set_special_effect(s, specialEffect);
  625. }
  626. else
  627. {
  628. s->set_special_effect(s, specialEffect);
  629. }
  630. }
  631. void CCamera::SetCamContrastBrightness(sensor_t *s, int _contrast, int _brightness)
  632. {
  633. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  634. if (!operationLock.acquired()) return;
  635. ScopedCameraLock cameraLock(m_cameraMutex);
  636. if (!cameraLock.acquired())
  637. {
  638. ESP_LOGW(TAG, "SetCamContrastBrightness: camera mutex unavailable");
  639. return;
  640. }
  641. if (s == NULL) return;
  642. if (s->id.PID == OV2640_PID)
  643. {
  644. ov2640_set_contrast_brightness(s, _contrast, _brightness);
  645. }
  646. else
  647. {
  648. s->set_contrast(s, _contrast); // -2 to 2
  649. s->set_brightness(s, _brightness); // -2 to 2
  650. }
  651. }
  652. // - It always zooms to the image center when offsets are zero
  653. // - if imageSize = 0 then the image is not zoomed
  654. // - if imageSize = max value, then the image is fully zoomed in
  655. // - a zoom step is >>> Width + 32 px / Height + 24 px
  656. void CCamera::SanitizeZoomParams(const CameraSettings &settings, int imageSize,
  657. int frameSizeX, int frameSizeY, int &imageWidth, int &imageHeight,
  658. int &zoomOffsetX, int &zoomOffsetY)
  659. {
  660. imageWidth = min(frameSizeX, max(1, settings.ImageWidth + imageSize * 32));
  661. imageHeight = min(frameSizeY, max(1, settings.ImageHeight + imageSize * 24));
  662. const int availableX = max(0, frameSizeX - imageWidth);
  663. const int availableY = max(0, frameSizeY - imageHeight);
  664. const int halfX = availableX / 2;
  665. const int halfY = availableY / 2;
  666. zoomOffsetX = halfX + min(halfX, max(-halfX, zoomOffsetX));
  667. zoomOffsetY = halfY + min(halfY, max(-halfY, zoomOffsetY));
  668. }
  669. esp_err_t CCamera::SetZoomSize(const CameraSettings &settings)
  670. {
  671. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  672. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  673. ScopedCameraLock cameraLock(m_cameraMutex);
  674. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  675. sensor_t *s = esp_camera_sensor_get();
  676. if (s == NULL) return ESP_FAIL;
  677. // The ESP32 pipeline is deliberately limited to VGA output. Sensor-side
  678. // windowing below performs zoom/cropping without creating larger RAM frames.
  679. CameraSettings outputSettings = settings;
  680. SetImageWidthHeightFromResolution(outputSettings);
  681. if (!outputSettings.ImageZoomEnabled)
  682. {
  683. return s->set_framesize(s, outputSettings.ImageFrameSize) == 0 ? ESP_OK : ESP_FAIL;
  684. }
  685. int frameSizeX = 0;
  686. int frameSizeY = 0;
  687. int maxZoom = 0;
  688. switch (s->id.PID)
  689. {
  690. case OV5640_PID:
  691. frameSizeX = 2592;
  692. frameSizeY = 1944;
  693. maxZoom = 59;
  694. break;
  695. case OV3660_PID:
  696. frameSizeX = 2048;
  697. frameSizeY = 1536;
  698. maxZoom = 43;
  699. break;
  700. case OV2640_PID:
  701. frameSizeX = 1600;
  702. frameSizeY = 1200;
  703. maxZoom = 29;
  704. break;
  705. default:
  706. ESP_LOGE(TAG, "SetZoomSize: unsupported sensor PID 0x%04x", s->id.PID);
  707. return ESP_ERR_NOT_SUPPORTED;
  708. }
  709. const int zoomSize = min(maxZoom, max(0, outputSettings.ImageZoomSize));
  710. const int zoomDelta = maxZoom - zoomSize;
  711. int imageWidth = outputSettings.ImageWidth;
  712. int imageHeight = outputSettings.ImageHeight;
  713. int offsetX = outputSettings.ImageZoomOffsetX;
  714. int offsetY = outputSettings.ImageZoomOffsetY;
  715. SanitizeZoomParams(outputSettings, zoomDelta, frameSizeX, frameSizeY,
  716. imageWidth, imageHeight, offsetX, offsetY);
  717. SetCamWindow(s, frameSizeX, frameSizeY, offsetX, offsetY,
  718. imageWidth, imageHeight, outputSettings.ImageWidth, outputSettings.ImageHeight,
  719. outputSettings.ImageVflip);
  720. return ESP_OK;
  721. }
  722. esp_err_t CCamera::SetQualityZoomSize(CameraSettings &settings)
  723. {
  724. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  725. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  726. ScopedCameraLock cameraLock(m_cameraMutex);
  727. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  728. sensor_t *s = esp_camera_sensor_get();
  729. if (s == NULL) return ESP_FAIL;
  730. SetImageWidthHeightFromResolution(settings);
  731. int quality = settings.ImageQuality;
  732. if (s->id.PID != OV2640_PID)
  733. {
  734. quality = min(63, max(8, quality));
  735. }
  736. settings.ImageQuality = quality;
  737. const int result = s->set_quality(s, quality);
  738. if (result != 0) return ESP_FAIL;
  739. return SetZoomSize(settings);
  740. }
  741. void CCamera::SetCamWindow(sensor_t *s, int frameSizeX, int frameSizeY, int xOffset, int yOffset, int xTotal, int yTotal, int xOutput, int yOutput, int imageVflip)
  742. {
  743. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  744. if (!operationLock.acquired()) return;
  745. ScopedCameraLock cameraLock(m_cameraMutex);
  746. if (!cameraLock.acquired())
  747. {
  748. ESP_LOGW(TAG, "SetCamWindow: camera mutex unavailable");
  749. return;
  750. }
  751. if (s == NULL) return;
  752. if (s->id.PID == OV2640_PID)
  753. {
  754. s->set_res_raw(s, 0, 0, 0, 0, xOffset, yOffset, xTotal, yTotal, xOutput, yOutput, false, false);
  755. }
  756. else
  757. {
  758. // for CAMERA_OV5640 and CAMERA_OV3660
  759. bool scale = !(xOutput == xTotal && yOutput == yTotal);
  760. bool binning = (xTotal >= (frameSizeX >> 1));
  761. if (imageVflip == true)
  762. {
  763. s->set_res_raw(s, xOffset, yOffset, xOffset + xTotal - 1, yOffset + yTotal - 1, 0, 0, frameSizeX, frameSizeY, xOutput, yOutput, scale, binning);
  764. }
  765. else
  766. {
  767. s->set_res_raw(s, xOffset, yOffset, xOffset + xTotal, yOffset + yTotal, 0, 0, frameSizeX, frameSizeY, xOutput, yOutput, scale, binning);
  768. }
  769. }
  770. }
  771. static size_t jpg_encode_stream(void *arg, size_t index, const void *data, size_t len)
  772. {
  773. jpg_chunking_t *j = (jpg_chunking_t *)arg;
  774. if (!index)
  775. {
  776. j->len = 0;
  777. }
  778. if (httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK)
  779. {
  780. return 0;
  781. }
  782. j->len += len;
  783. return len;
  784. }
  785. esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
  786. {
  787. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  788. if (!operationLock.acquired())
  789. {
  790. ESP_LOGW(TAG, "CaptureToBasisImage: camera operation lock unavailable");
  791. return ESP_ERR_TIMEOUT;
  792. }
  793. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  794. if (restoreResult != ESP_OK) return restoreResult;
  795. if (_Image == NULL || !_Image->ImageOkay())
  796. {
  797. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: target image is unavailable");
  798. return ESP_FAIL;
  799. }
  800. #ifdef DEBUG_DETAIL_ON
  801. LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
  802. #endif
  803. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  804. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  805. camera_fb_t *fb = NULL;
  806. {
  807. ScopedCameraLock cameraLock(m_cameraMutex);
  808. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  809. {
  810. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  811. }
  812. fb = esp_camera_fb_get();
  813. }
  814. if (fb == NULL)
  815. {
  816. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: camera capture failed");
  817. return ESP_FAIL;
  818. }
  819. ScopedCameraFrame frame(fb, m_cameraMutex);
  820. uint8_t *frameData = fb->buf;
  821. size_t frameLength = fb->len;
  822. uint8_t *demoData = NULL;
  823. bool demoBufferAllocated = false;
  824. if (CCstatus.DemoMode)
  825. {
  826. if (!loadNextDemoImage(&demoData, &frameLength))
  827. {
  828. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: could not load demo image");
  829. return ESP_FAIL;
  830. }
  831. frameData = demoData;
  832. demoBufferAllocated = true;
  833. }
  834. CImageBasis *tmpImage = new (std::nothrow) CImageBasis("tmpImage");
  835. const bool decoded = tmpImage != NULL &&
  836. frameLength <= static_cast<size_t>(INT_MAX) &&
  837. tmpImage->LoadFromMemory(frameData, static_cast<int>(frameLength));
  838. if (demoBufferAllocated) free_psram_heap("Demo image frame", demoData);
  839. frame.release();
  840. if (!decoded || tmpImage == NULL || !tmpImage->ImageOkay())
  841. {
  842. delete tmpImage;
  843. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: JPEG decode failed");
  844. LogFile.WriteHeapInfo("CaptureToBasisImage decode");
  845. return ESP_FAIL;
  846. }
  847. if (_Image->width != tmpImage->width || _Image->height != tmpImage->height ||
  848. _Image->channels != tmpImage->channels || tmpImage->channels != 3 ||
  849. tmpImage->width <= 0 || tmpImage->height <= 0 ||
  850. static_cast<size_t>(tmpImage->width) > SIZE_MAX / static_cast<size_t>(tmpImage->height) ||
  851. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) > SIZE_MAX / 3U)
  852. {
  853. delete tmpImage;
  854. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded dimensions do not match target image");
  855. return ESP_FAIL;
  856. }
  857. const size_t expectedBytes =
  858. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) * 3U;
  859. if (expectedBytes > static_cast<size_t>(INT_MAX))
  860. {
  861. delete tmpImage;
  862. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image is too large");
  863. return ESP_FAIL;
  864. }
  865. uint8_t *source = tmpImage->RGBImageLock();
  866. if (source == NULL)
  867. {
  868. delete tmpImage;
  869. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image lock failed");
  870. return ESP_FAIL;
  871. }
  872. const bool copied = _Image->CopyFromMemory(source, static_cast<int>(expectedBytes));
  873. tmpImage->RGBImageRelease();
  874. delete tmpImage;
  875. #ifdef DEBUG_DETAIL_ON
  876. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  877. #endif
  878. return copied ? ESP_OK : ESP_FAIL;
  879. }
  880. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  881. {
  882. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  883. if (!operationLock.acquired())
  884. {
  885. ESP_LOGW(TAG, "CaptureToFile: camera operation lock unavailable");
  886. return ESP_ERR_TIMEOUT;
  887. }
  888. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  889. if (restoreResult != ESP_OK) return restoreResult;
  890. const CameraSettings captureSettings = static_cast<const CameraSettings &>(CCstatus);
  891. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  892. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  893. camera_fb_t *fb = NULL;
  894. {
  895. ScopedCameraLock cameraLock(m_cameraMutex);
  896. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  897. {
  898. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  899. }
  900. fb = esp_camera_fb_get();
  901. }
  902. if (fb == NULL)
  903. {
  904. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  905. "Check camera module and/or proper electrical connection");
  906. return ESP_FAIL;
  907. }
  908. ScopedCameraFrame frame(fb, m_cameraMutex);
  909. #ifdef DEBUG_DETAIL_ON
  910. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  911. #endif
  912. nm = FormatFileName(nm);
  913. #ifdef DEBUG_DETAIL_ON
  914. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  915. #endif
  916. const string fileType = toUpper(getFileType(nm));
  917. uint8_t *buffer = NULL;
  918. size_t bufferLength = 0;
  919. bool bufferNeedsFree = false;
  920. bool captureOkay = false;
  921. if (fileType == "BMP")
  922. {
  923. bufferNeedsFree = true;
  924. captureOkay = frame2bmp(fb, &buffer, &bufferLength) &&
  925. buffer != NULL && bufferLength > 0;
  926. }
  927. else if (fileType == "JPG")
  928. {
  929. if (fb->format == PIXFORMAT_JPEG)
  930. {
  931. buffer = fb->buf;
  932. bufferLength = fb->len;
  933. captureOkay = buffer != NULL && bufferLength > 0;
  934. }
  935. else
  936. {
  937. bufferNeedsFree = true;
  938. captureOkay = frame2jpg(fb, captureSettings.ImageQuality, &buffer, &bufferLength) &&
  939. buffer != NULL && bufferLength > 0;
  940. if (!captureOkay) ESP_LOGE(TAG, "JPEG compression failed");
  941. }
  942. }
  943. if (captureOkay)
  944. {
  945. FILE *fp = fopen(nm.c_str(), "wb");
  946. if (fp == NULL)
  947. {
  948. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  949. captureOkay = false;
  950. }
  951. else
  952. {
  953. const size_t written = fwrite(buffer, 1, bufferLength, fp);
  954. const int closeResult = fclose(fp);
  955. if (written != bufferLength || closeResult != 0)
  956. {
  957. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: incomplete write to " + nm);
  958. captureOkay = false;
  959. }
  960. }
  961. }
  962. else
  963. {
  964. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: unsupported image format or conversion failed");
  965. }
  966. if (bufferNeedsFree && buffer != NULL) free(buffer);
  967. // Return the frame under the short driver lock; SD access above does not
  968. // need to hold that lock.
  969. frame.release();
  970. return captureOkay ? ESP_OK : ESP_FAIL;
  971. }
  972. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay, bool previewCapture)
  973. {
  974. if (req == NULL) return ESP_ERR_INVALID_ARG;
  975. uint8_t *responseData = NULL;
  976. size_t responseLength = 0;
  977. bool responseInPsram = false;
  978. esp_err_t captureResult = ESP_OK;
  979. const int64_t captureStart = esp_timer_get_time();
  980. {
  981. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  982. if (!operationLock.acquired())
  983. {
  984. httpd_resp_set_status(req, "503 Service Unavailable");
  985. httpd_resp_send(req, "Camera is busy", HTTPD_RESP_USE_STRLEN);
  986. return ESP_ERR_TIMEOUT;
  987. }
  988. bool useTemporaryPreview = false;
  989. {
  990. ScopedCameraLock cameraLock(m_cameraMutex);
  991. if (!cameraLock.acquired())
  992. {
  993. captureResult = ESP_ERR_TIMEOUT;
  994. }
  995. else
  996. {
  997. useTemporaryPreview =
  998. previewCapture && m_temporarySettingsActive && m_previewCapturePending;
  999. if (useTemporaryPreview) delay = m_previewCaptureDelayMs;
  1000. }
  1001. }
  1002. if (captureResult == ESP_OK && !useTemporaryPreview)
  1003. {
  1004. captureResult = RestoreCommittedSettingsIfNeeded();
  1005. if (captureResult == ESP_OK && previewCapture)
  1006. {
  1007. const int waitSeconds = std::max(0, CCstatus.WaitBeforePicture);
  1008. delay = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
  1009. }
  1010. }
  1011. if (captureResult == ESP_OK)
  1012. {
  1013. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  1014. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  1015. camera_fb_t *fb = NULL;
  1016. {
  1017. ScopedCameraLock cameraLock(m_cameraMutex);
  1018. if (!cameraLock.acquired())
  1019. {
  1020. captureResult = ESP_ERR_TIMEOUT;
  1021. }
  1022. else
  1023. {
  1024. {
  1025. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1026. }
  1027. fb = esp_camera_fb_get();
  1028. }
  1029. }
  1030. if (captureResult == ESP_OK && fb == NULL)
  1031. {
  1032. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: camera capture failed");
  1033. captureResult = ESP_FAIL;
  1034. }
  1035. if (captureResult == ESP_OK)
  1036. {
  1037. ScopedCameraFrame frame(fb, m_cameraMutex);
  1038. if (CCstatus.DemoMode)
  1039. {
  1040. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  1041. if (!loadNextDemoImage(&responseData, &responseLength))
  1042. {
  1043. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: could not load demo image");
  1044. captureResult = ESP_FAIL;
  1045. }
  1046. else
  1047. {
  1048. responseInPsram = true;
  1049. }
  1050. }
  1051. else if (fb->format == PIXFORMAT_JPEG)
  1052. {
  1053. if (fb->buf == NULL || fb->len == 0)
  1054. {
  1055. captureResult = ESP_FAIL;
  1056. }
  1057. else
  1058. {
  1059. responseData = static_cast<uint8_t *>(malloc_psram_heap(
  1060. "HTTP JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1061. if (responseData == NULL)
  1062. {
  1063. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: unable to allocate JPEG copy");
  1064. captureResult = ESP_ERR_NO_MEM;
  1065. }
  1066. else
  1067. {
  1068. memcpy(responseData, fb->buf, fb->len);
  1069. responseLength = fb->len;
  1070. responseInPsram = true;
  1071. }
  1072. }
  1073. }
  1074. else if (!frame2jpg(fb, 80, &responseData, &responseLength) ||
  1075. responseData == NULL || responseLength == 0)
  1076. {
  1077. if (responseData != NULL)
  1078. {
  1079. free(responseData);
  1080. responseData = NULL;
  1081. }
  1082. captureResult = ESP_FAIL;
  1083. }
  1084. frame.release();
  1085. }
  1086. if (captureResult == ESP_OK && useTemporaryPreview)
  1087. {
  1088. ScopedCameraLock cameraLock(m_cameraMutex);
  1089. if (cameraLock.acquired()) m_previewCapturePending = false;
  1090. else captureResult = ESP_ERR_TIMEOUT;
  1091. }
  1092. }
  1093. }
  1094. const int64_t captureEnd = esp_timer_get_time();
  1095. if (captureResult == ESP_OK && responseData != NULL && responseLength > 0)
  1096. {
  1097. captureResult = httpd_resp_set_type(req, "image/jpeg");
  1098. if (captureResult == ESP_OK)
  1099. {
  1100. captureResult = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  1101. }
  1102. if (captureResult == ESP_OK)
  1103. {
  1104. captureResult = httpd_resp_send(req, reinterpret_cast<const char *>(responseData),
  1105. static_cast<ssize_t>(responseLength));
  1106. }
  1107. }
  1108. else if (captureResult == ESP_OK)
  1109. {
  1110. captureResult = ESP_FAIL;
  1111. }
  1112. if (responseData != NULL)
  1113. {
  1114. if (responseInPsram)
  1115. {
  1116. free_psram_heap("HTTP image response", responseData);
  1117. }
  1118. else
  1119. {
  1120. free(responseData);
  1121. }
  1122. }
  1123. ESP_LOGI(TAG, "HTTP JPEG capture: %uKB %ums",
  1124. static_cast<unsigned int>(responseLength / 1024),
  1125. static_cast<unsigned int>((captureEnd - captureStart) / 1000));
  1126. if (captureResult != ESP_OK)
  1127. {
  1128. // The socket may already have started a response; only send the
  1129. // fallback status for failures that occurred before response setup.
  1130. if (responseData == NULL || responseLength == 0)
  1131. httpd_resp_send_500(req);
  1132. }
  1133. return captureResult;
  1134. }
  1135. esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
  1136. {
  1137. if (req == NULL) return ESP_ERR_INVALID_ARG;
  1138. {
  1139. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1140. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  1141. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  1142. if (restoreResult != ESP_OK) return restoreResult;
  1143. }
  1144. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
  1145. ScopedCameraCaptureIndicators indicators(*this, FlashlightOn, FlashlightOn);
  1146. esp_err_t result = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  1147. if (result == ESP_OK)
  1148. {
  1149. result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1150. }
  1151. // One warmup frame lets exposure and white balance settle before streaming.
  1152. if (result == ESP_OK)
  1153. {
  1154. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1155. if (!operationLock.acquired())
  1156. {
  1157. result = ESP_ERR_TIMEOUT;
  1158. }
  1159. else
  1160. {
  1161. ScopedCameraLock cameraLock(m_cameraMutex);
  1162. if (!cameraLock.acquired())
  1163. {
  1164. result = ESP_ERR_TIMEOUT;
  1165. }
  1166. else
  1167. {
  1168. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1169. }
  1170. }
  1171. }
  1172. char partBuffer[64];
  1173. while (result == ESP_OK)
  1174. {
  1175. const int64_t frameStart = esp_timer_get_time();
  1176. uint8_t *frameData = NULL;
  1177. size_t frameLength = 0;
  1178. bool frameDataInPsram = false;
  1179. {
  1180. // Reserve the camera only long enough to acquire and detach a frame.
  1181. // Network transmission below uses the independent copy and owns no
  1182. // camera-driver or framebuffer resources.
  1183. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1184. if (!operationLock.acquired())
  1185. {
  1186. result = ESP_ERR_TIMEOUT;
  1187. }
  1188. else
  1189. {
  1190. camera_fb_t *fb = NULL;
  1191. {
  1192. ScopedCameraLock cameraLock(m_cameraMutex);
  1193. if (!cameraLock.acquired())
  1194. {
  1195. result = ESP_ERR_TIMEOUT;
  1196. }
  1197. else
  1198. {
  1199. fb = esp_camera_fb_get();
  1200. }
  1201. }
  1202. if (result == ESP_OK && fb == NULL)
  1203. {
  1204. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
  1205. result = ESP_FAIL;
  1206. }
  1207. if (result == ESP_OK)
  1208. {
  1209. ScopedCameraFrame frame(fb, m_cameraMutex);
  1210. if (fb->format == PIXFORMAT_JPEG)
  1211. {
  1212. if (fb->buf == NULL || fb->len == 0)
  1213. {
  1214. result = ESP_FAIL;
  1215. }
  1216. else
  1217. {
  1218. frameData = static_cast<uint8_t *>(malloc_psram_heap(
  1219. "Live stream JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1220. if (frameData == NULL)
  1221. {
  1222. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: JPEG copy allocation failed");
  1223. result = ESP_ERR_NO_MEM;
  1224. }
  1225. else
  1226. {
  1227. memcpy(frameData, fb->buf, fb->len);
  1228. frameLength = fb->len;
  1229. frameDataInPsram = true;
  1230. }
  1231. }
  1232. }
  1233. else if (!frame2jpg(fb, 80, &frameData, &frameLength) ||
  1234. frameData == NULL || frameLength == 0)
  1235. {
  1236. if (frameData != NULL)
  1237. {
  1238. free(frameData);
  1239. frameData = NULL;
  1240. }
  1241. result = ESP_FAIL;
  1242. }
  1243. frame.release();
  1244. }
  1245. }
  1246. }
  1247. // All camera resources are released before any potentially blocking
  1248. // socket operation. A slow or disconnected client cannot starve the flow.
  1249. if (result == ESP_OK)
  1250. {
  1251. const int headerLength = snprintf(partBuffer, sizeof(partBuffer), _STREAM_PART,
  1252. static_cast<unsigned int>(frameLength));
  1253. if (headerLength < 0 || static_cast<size_t>(headerLength) >= sizeof(partBuffer))
  1254. {
  1255. result = ESP_FAIL;
  1256. }
  1257. else
  1258. {
  1259. result = httpd_resp_send_chunk(req, partBuffer, static_cast<size_t>(headerLength));
  1260. }
  1261. if (result == ESP_OK)
  1262. {
  1263. result = httpd_resp_send_chunk(req, reinterpret_cast<const char *>(frameData),
  1264. static_cast<ssize_t>(frameLength));
  1265. }
  1266. if (result == ESP_OK)
  1267. {
  1268. result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1269. }
  1270. }
  1271. if (frameData != NULL)
  1272. {
  1273. if (frameDataInPsram) free_psram_heap("Live stream JPEG copy", frameData);
  1274. else free(frameData);
  1275. }
  1276. if (result != ESP_OK) break;
  1277. const int64_t frameEnd = esp_timer_get_time();
  1278. ESP_LOGD(TAG, "Stream frame: %uKB %ums",
  1279. static_cast<unsigned int>(frameLength / 1024),
  1280. static_cast<unsigned int>((frameEnd - frameStart) / 1000));
  1281. const int64_t frameDurationMs = (frameEnd - frameStart) / 1000;
  1282. if (CAM_LIVESTREAM_REFRESHRATE > frameDurationMs)
  1283. {
  1284. const TickType_t delayTicks =
  1285. pdMS_TO_TICKS(CAM_LIVESTREAM_REFRESHRATE - frameDurationMs);
  1286. vTaskDelay(delayTicks);
  1287. }
  1288. }
  1289. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
  1290. return result;
  1291. }
  1292. void CCamera::UpdateFlashOutputLocked(void)
  1293. {
  1294. const bool active = m_manualFlashOn || m_captureFlashUsers > 0;
  1295. #ifdef USE_PWM_LEDFLASH
  1296. const uint32_t duty = active ? static_cast<uint32_t>(LedIntensity) : 0U;
  1297. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty));
  1298. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  1299. #else
  1300. // The camera owns the board flash LED independently of the user GPIO handler.
  1301. gpio_pad_select_gpio(FLASH_GPIO);
  1302. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  1303. gpio_set_level(FLASH_GPIO, active ? 1 : 0);
  1304. #endif
  1305. }
  1306. void CCamera::UpdateStatusLedOutputLocked(void)
  1307. {
  1308. if (xHandle_task_StatusLED != NULL) return;
  1309. const bool active = m_manualStatusLedOn || m_captureStatusLedUsers > 0;
  1310. gpio_pad_select_gpio(BLINK_GPIO);
  1311. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  1312. // The on-board status LED is active-low.
  1313. gpio_set_level(BLINK_GPIO, active ? 0 : 1);
  1314. }
  1315. void CCamera::SetCaptureFlashActive(bool active)
  1316. {
  1317. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1318. if (!operationLock.acquired()) return;
  1319. ScopedCameraLock cameraLock(m_cameraMutex);
  1320. if (!cameraLock.acquired()) return;
  1321. if (active)
  1322. {
  1323. if (m_captureFlashUsers < UINT32_MAX) ++m_captureFlashUsers;
  1324. }
  1325. else if (m_captureFlashUsers > 0)
  1326. {
  1327. --m_captureFlashUsers;
  1328. }
  1329. UpdateFlashOutputLocked();
  1330. }
  1331. void CCamera::SetCaptureStatusLedActive(bool active)
  1332. {
  1333. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1334. if (!operationLock.acquired()) return;
  1335. ScopedCameraLock cameraLock(m_cameraMutex);
  1336. if (!cameraLock.acquired()) return;
  1337. if (active)
  1338. {
  1339. if (m_captureStatusLedUsers < UINT32_MAX) ++m_captureStatusLedUsers;
  1340. }
  1341. else if (m_captureStatusLedUsers > 0)
  1342. {
  1343. --m_captureStatusLedUsers;
  1344. }
  1345. UpdateStatusLedOutputLocked();
  1346. }
  1347. void CCamera::LightOnOff(bool status)
  1348. {
  1349. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1350. if (!operationLock.acquired()) return;
  1351. ScopedCameraLock cameraLock(m_cameraMutex);
  1352. if (!cameraLock.acquired())
  1353. {
  1354. ESP_LOGW(TAG, "LightOnOff: camera mutex unavailable");
  1355. return;
  1356. }
  1357. m_manualFlashOn = status;
  1358. UpdateFlashOutputLocked();
  1359. }
  1360. void CCamera::LEDOnOff(bool status)
  1361. {
  1362. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1363. if (!operationLock.acquired()) return;
  1364. ScopedCameraLock cameraLock(m_cameraMutex);
  1365. if (!cameraLock.acquired()) return;
  1366. m_manualStatusLedOn = status;
  1367. UpdateStatusLedOutputLocked();
  1368. }
  1369. void CCamera::SetImageWidthHeightFromResolution(CameraSettings &settings)
  1370. {
  1371. switch (settings.ImageFrameSize)
  1372. {
  1373. case FRAMESIZE_QVGA:
  1374. settings.ImageWidth = 320;
  1375. settings.ImageHeight = 240;
  1376. break;
  1377. case FRAMESIZE_VGA:
  1378. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1379. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1380. break;
  1381. default:
  1382. // Higher resolutions overload the ESP32 image-processing pipeline.
  1383. // Zoom is implemented by sensor-side windowing, while the output stays VGA.
  1384. ESP_LOGW(TAG, "Frame size %d exceeds the supported VGA limit; forcing VGA",
  1385. static_cast<int>(settings.ImageFrameSize));
  1386. settings.ImageFrameSize = FRAMESIZE_VGA;
  1387. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1388. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1389. break;
  1390. }
  1391. }
  1392. void CCamera::useDemoMode(void)
  1393. {
  1394. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1395. if (!operationLock.acquired()) return;
  1396. char line[50];
  1397. m_demoFiles.clear();
  1398. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  1399. if (fd == NULL) {
  1400. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: '/sdcard/demo/files.txt' is missing!");
  1401. CCstatus.DemoMode = false;
  1402. return;
  1403. }
  1404. while (fgets(line, sizeof(line), fd) != NULL) {
  1405. size_t length = strlen(line);
  1406. while (length > 0 && (line[length-1] == '\n' || line[length-1] == '\r')) line[--length] = '\0';
  1407. if (length > 0) m_demoFiles.push_back(line);
  1408. }
  1409. fclose(fd);
  1410. if (m_demoFiles.empty()) {
  1411. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: files.txt contains no image names");
  1412. CCstatus.DemoMode = false;
  1413. return;
  1414. }
  1415. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(m_demoFiles.size()) + " files) instead of real camera image!");
  1416. for (const auto& file : m_demoFiles) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  1417. CCstatus.DemoMode = true;
  1418. }
  1419. bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
  1420. {
  1421. if (data == NULL || length == NULL || m_demoFiles.empty()) return false;
  1422. *data = NULL;
  1423. *length = 0;
  1424. const size_t index = static_cast<size_t>(getCountFlowRounds()) % m_demoFiles.size();
  1425. const std::string filename = "/sdcard/demo/" + m_demoFiles[index];
  1426. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + filename + " as demo image");
  1427. FILE *fp = fopen(filename.c_str(), "rb");
  1428. if (fp == NULL) return false;
  1429. const long fileSize = GetFileSize(filename);
  1430. if (fileSize <= 0 || fileSize > DEMO_IMAGE_SIZE) {
  1431. fclose(fp);
  1432. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image has invalid size: " + std::to_string(fileSize));
  1433. return false;
  1434. }
  1435. uint8_t *buffer = static_cast<uint8_t*>(malloc_psram_heap(
  1436. "Demo image frame", static_cast<size_t>(fileSize), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1437. if (buffer == NULL) {
  1438. fclose(fp);
  1439. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image PSRAM allocation failed");
  1440. return false;
  1441. }
  1442. const size_t readBytes = fread(buffer, 1, static_cast<size_t>(fileSize), fp);
  1443. const bool readOkay = (readBytes == static_cast<size_t>(fileSize)) && (ferror(fp) == 0);
  1444. fclose(fp);
  1445. if (!readOkay) {
  1446. free_psram_heap("Demo image frame (short read)", buffer);
  1447. return false;
  1448. }
  1449. *data = buffer;
  1450. *length = readBytes;
  1451. return true;
  1452. }
  1453. long CCamera::GetFileSize(std::string filename)
  1454. {
  1455. struct stat stat_buf;
  1456. long rc = stat(filename.c_str(), &stat_buf);
  1457. return rc == 0 ? stat_buf.st_size : -1;
  1458. }