ClassControllCamera.cpp 55 KB

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