ClassControllCamera.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  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. // The camera driver and sensor register access are not safe to use concurrently.
  112. // Recursive locking allows public methods to safely call other locked methods.
  113. class ScopedCameraLock
  114. {
  115. public:
  116. explicit ScopedCameraLock(SemaphoreHandle_t mutex, TickType_t timeout = pdMS_TO_TICKS(5000))
  117. : m_mutex(mutex),
  118. m_acquired(mutex != NULL && xSemaphoreTakeRecursive(mutex, timeout) == pdTRUE)
  119. {
  120. }
  121. ~ScopedCameraLock()
  122. {
  123. if (m_acquired)
  124. {
  125. xSemaphoreGiveRecursive(m_mutex);
  126. }
  127. }
  128. bool acquired() const { return m_acquired; }
  129. private:
  130. SemaphoreHandle_t m_mutex;
  131. bool m_acquired;
  132. };
  133. // Serializes complete camera operations while the driver mutex is released
  134. // during image decoding, file I/O and network transmission.
  135. class ScopedCameraOperationLock
  136. {
  137. public:
  138. explicit ScopedCameraOperationLock(SemaphoreHandle_t mutex, TickType_t timeout = pdMS_TO_TICKS(5000))
  139. : m_mutex(mutex),
  140. m_acquired(mutex != NULL && xSemaphoreTakeRecursive(mutex, timeout) == pdTRUE)
  141. {
  142. }
  143. ~ScopedCameraOperationLock()
  144. {
  145. release();
  146. }
  147. bool acquired() const { return m_acquired; }
  148. void release()
  149. {
  150. if (m_acquired)
  151. {
  152. xSemaphoreGiveRecursive(m_mutex);
  153. m_acquired = false;
  154. }
  155. }
  156. private:
  157. SemaphoreHandle_t m_mutex;
  158. bool m_acquired;
  159. };
  160. // Owns one camera framebuffer and returns it exactly once on every exit path.
  161. class ScopedCameraFrame
  162. {
  163. public:
  164. ScopedCameraFrame(camera_fb_t *frame, SemaphoreHandle_t cameraMutex)
  165. : m_frame(frame), m_cameraMutex(cameraMutex)
  166. {
  167. }
  168. ~ScopedCameraFrame() { release(); }
  169. ScopedCameraFrame(const ScopedCameraFrame &) = delete;
  170. ScopedCameraFrame &operator=(const ScopedCameraFrame &) = delete;
  171. camera_fb_t *get() const { return m_frame; }
  172. void release()
  173. {
  174. if (m_frame == NULL) return;
  175. // Frame return touches camera-driver state and must use the driver lock.
  176. ScopedCameraLock cameraLock(m_cameraMutex, portMAX_DELAY);
  177. if (!cameraLock.acquired())
  178. {
  179. ESP_LOGE(TAG, "Unable to lock camera driver to return framebuffer");
  180. return;
  181. }
  182. esp_camera_fb_return(m_frame);
  183. m_frame = NULL;
  184. }
  185. private:
  186. camera_fb_t *m_frame;
  187. SemaphoreHandle_t m_cameraMutex;
  188. };
  189. class ScopedCameraCaptureIndicators
  190. {
  191. public:
  192. ScopedCameraCaptureIndicators(CCamera &camera, bool statusLed, bool flashLed)
  193. : m_camera(camera), m_statusLed(statusLed), m_flashLed(flashLed)
  194. {
  195. if (m_statusLed) m_camera.SetCaptureStatusLedActive(true);
  196. if (m_flashLed) m_camera.SetCaptureFlashActive(true);
  197. }
  198. ~ScopedCameraCaptureIndicators()
  199. {
  200. release();
  201. }
  202. void release()
  203. {
  204. if (m_flashLed)
  205. {
  206. m_camera.SetCaptureFlashActive(false);
  207. m_flashLed = false;
  208. }
  209. if (m_statusLed)
  210. {
  211. m_camera.SetCaptureStatusLedActive(false);
  212. m_statusLed = false;
  213. }
  214. }
  215. ScopedCameraCaptureIndicators(const ScopedCameraCaptureIndicators &) = delete;
  216. ScopedCameraCaptureIndicators &operator=(const ScopedCameraCaptureIndicators &) = delete;
  217. private:
  218. CCamera &m_camera;
  219. bool m_statusLed;
  220. bool m_flashLed;
  221. };
  222. CCamera::CCamera(void)
  223. : m_cameraMutex(xSemaphoreCreateRecursiveMutex()),
  224. m_cameraOperationMutex(xSemaphoreCreateRecursiveMutex()),
  225. m_driverInitialized(false),
  226. m_temporarySettingsActive(false),
  227. m_previewCapturePending(false),
  228. m_previewCaptureDelayMs(0),
  229. m_captureFlashUsers(0),
  230. m_captureStatusLedUsers(0),
  231. m_manualFlashOn(false),
  232. m_manualStatusLedOn(false)
  233. {
  234. #ifdef DEBUG_DETAIL_ON
  235. ESP_LOGD(TAG, "CreateClassCamera");
  236. #endif
  237. CCstatus.ImageQuality = camera_config.jpeg_quality;
  238. CCstatus.ImageFrameSize = camera_config.frame_size;
  239. CCstatus.CamXclkFreqMhz = xclk;
  240. // The global camera object can be constructed before task scheduling is
  241. // fully available. Initialize the PWM value without taking its runtime mutexes.
  242. LedIntensity = static_cast<int>(
  243. static_cast<float>(std::min(std::max(0, LedIntensity), 100)) / 100.0f * 8191.0f);
  244. CCstatus.ImageLedIntensity = 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. esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
  792. {
  793. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  794. if (!operationLock.acquired())
  795. {
  796. ESP_LOGW(TAG, "CaptureToBasisImage: camera operation lock unavailable");
  797. return ESP_ERR_TIMEOUT;
  798. }
  799. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  800. if (restoreResult != ESP_OK) return restoreResult;
  801. if (_Image == NULL || !_Image->ImageOkay())
  802. {
  803. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: target image is unavailable");
  804. return ESP_FAIL;
  805. }
  806. #ifdef DEBUG_DETAIL_ON
  807. LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
  808. #endif
  809. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  810. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  811. camera_fb_t *fb = NULL;
  812. {
  813. ScopedCameraLock cameraLock(m_cameraMutex);
  814. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  815. {
  816. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  817. }
  818. fb = esp_camera_fb_get();
  819. }
  820. if (fb == NULL)
  821. {
  822. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: camera capture failed");
  823. return ESP_FAIL;
  824. }
  825. ScopedCameraFrame frame(fb, m_cameraMutex);
  826. uint8_t *frameData = fb->buf;
  827. size_t frameLength = fb->len;
  828. uint8_t *demoData = NULL;
  829. bool demoBufferAllocated = false;
  830. if (CCstatus.DemoMode)
  831. {
  832. if (!loadNextDemoImage(&demoData, &frameLength))
  833. {
  834. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: could not load demo image");
  835. return ESP_FAIL;
  836. }
  837. frameData = demoData;
  838. demoBufferAllocated = true;
  839. }
  840. CImageBasis *tmpImage = new (std::nothrow) CImageBasis("tmpImage");
  841. const bool decoded = tmpImage != NULL &&
  842. frameLength <= static_cast<size_t>(INT_MAX) &&
  843. tmpImage->LoadFromMemory(frameData, static_cast<int>(frameLength));
  844. if (demoBufferAllocated) free_psram_heap("Demo image frame", demoData);
  845. frame.release();
  846. indicators.release();
  847. operationLock.release();
  848. if (!decoded || tmpImage == NULL || !tmpImage->ImageOkay())
  849. {
  850. delete tmpImage;
  851. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: JPEG decode failed");
  852. LogFile.WriteHeapInfo("CaptureToBasisImage decode");
  853. return ESP_FAIL;
  854. }
  855. if (_Image->width != tmpImage->width || _Image->height != tmpImage->height ||
  856. _Image->channels != tmpImage->channels || tmpImage->channels != 3 ||
  857. tmpImage->width <= 0 || tmpImage->height <= 0 ||
  858. static_cast<size_t>(tmpImage->width) > SIZE_MAX / static_cast<size_t>(tmpImage->height) ||
  859. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) > SIZE_MAX / 3U)
  860. {
  861. delete tmpImage;
  862. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded dimensions do not match target image");
  863. return ESP_FAIL;
  864. }
  865. const size_t expectedBytes =
  866. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) * 3U;
  867. if (expectedBytes > static_cast<size_t>(INT_MAX))
  868. {
  869. delete tmpImage;
  870. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image is too large");
  871. return ESP_FAIL;
  872. }
  873. uint8_t *source = tmpImage->RGBImageLock();
  874. if (source == NULL)
  875. {
  876. delete tmpImage;
  877. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image lock failed");
  878. return ESP_FAIL;
  879. }
  880. const bool copied = _Image->CopyFromMemory(source, static_cast<int>(expectedBytes));
  881. tmpImage->RGBImageRelease();
  882. delete tmpImage;
  883. #ifdef DEBUG_DETAIL_ON
  884. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  885. #endif
  886. return copied ? ESP_OK : ESP_FAIL;
  887. }
  888. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  889. {
  890. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  891. if (!operationLock.acquired())
  892. {
  893. ESP_LOGW(TAG, "CaptureToFile: camera operation lock unavailable");
  894. return ESP_ERR_TIMEOUT;
  895. }
  896. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  897. if (restoreResult != ESP_OK) return restoreResult;
  898. const CameraSettings captureSettings = static_cast<const CameraSettings &>(CCstatus);
  899. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  900. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  901. camera_fb_t *fb = NULL;
  902. {
  903. ScopedCameraLock cameraLock(m_cameraMutex);
  904. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  905. {
  906. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  907. }
  908. fb = esp_camera_fb_get();
  909. }
  910. if (fb == NULL)
  911. {
  912. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  913. "Check camera module and/or proper electrical connection");
  914. return ESP_FAIL;
  915. }
  916. ScopedCameraFrame frame(fb, m_cameraMutex);
  917. #ifdef DEBUG_DETAIL_ON
  918. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  919. #endif
  920. nm = FormatFileName(nm);
  921. #ifdef DEBUG_DETAIL_ON
  922. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  923. #endif
  924. const string fileType = toUpper(getFileType(nm));
  925. uint8_t *buffer = NULL;
  926. size_t bufferLength = 0;
  927. bool bufferNeedsFree = false;
  928. bool bufferInPsram = false;
  929. bool captureOkay = false;
  930. if (fileType == "BMP")
  931. {
  932. bufferNeedsFree = true;
  933. captureOkay = frame2bmp(fb, &buffer, &bufferLength) &&
  934. buffer != NULL && bufferLength > 0;
  935. }
  936. else if (fileType == "JPG")
  937. {
  938. if (fb->format == PIXFORMAT_JPEG)
  939. {
  940. if (fb->buf != NULL && fb->len > 0)
  941. {
  942. buffer = static_cast<uint8_t *>(malloc_psram_heap(
  943. "Capture file JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  944. if (buffer != NULL)
  945. {
  946. memcpy(buffer, fb->buf, fb->len);
  947. bufferLength = fb->len;
  948. bufferNeedsFree = true;
  949. bufferInPsram = true;
  950. captureOkay = true;
  951. }
  952. }
  953. }
  954. else
  955. {
  956. bufferNeedsFree = true;
  957. captureOkay = frame2jpg(fb, captureSettings.ImageQuality, &buffer, &bufferLength) &&
  958. buffer != NULL && bufferLength > 0;
  959. if (!captureOkay) ESP_LOGE(TAG, "JPEG compression failed");
  960. }
  961. }
  962. // The buffer is now independent of the camera framebuffer. Release both
  963. // camera leases before opening or writing the SD-card file.
  964. frame.release();
  965. indicators.release();
  966. operationLock.release();
  967. if (captureOkay)
  968. {
  969. FILE *fp = fopen(nm.c_str(), "wb");
  970. if (fp == NULL)
  971. {
  972. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  973. captureOkay = false;
  974. }
  975. else
  976. {
  977. const size_t written = fwrite(buffer, 1, bufferLength, fp);
  978. const int closeResult = fclose(fp);
  979. if (written != bufferLength || closeResult != 0)
  980. {
  981. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: incomplete write to " + nm);
  982. captureOkay = false;
  983. }
  984. }
  985. }
  986. else
  987. {
  988. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: unsupported image format, allocation or conversion failed");
  989. }
  990. if (bufferNeedsFree && buffer != NULL)
  991. {
  992. if (bufferInPsram) free_psram_heap("Capture file JPEG copy", buffer);
  993. else free(buffer);
  994. }
  995. return captureOkay ? ESP_OK : ESP_FAIL;
  996. }
  997. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay, bool previewCapture)
  998. {
  999. if (req == NULL) return ESP_ERR_INVALID_ARG;
  1000. uint8_t *responseData = NULL;
  1001. size_t responseLength = 0;
  1002. bool responseInPsram = false;
  1003. bool responseStarted = false;
  1004. esp_err_t captureResult = ESP_OK;
  1005. const int64_t captureStart = esp_timer_get_time();
  1006. {
  1007. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1008. if (!operationLock.acquired())
  1009. {
  1010. httpd_resp_set_status(req, "503 Service Unavailable");
  1011. httpd_resp_send(req, "Camera is busy", HTTPD_RESP_USE_STRLEN);
  1012. return ESP_ERR_TIMEOUT;
  1013. }
  1014. bool useTemporaryPreview = false;
  1015. {
  1016. ScopedCameraLock cameraLock(m_cameraMutex);
  1017. if (!cameraLock.acquired())
  1018. {
  1019. captureResult = ESP_ERR_TIMEOUT;
  1020. }
  1021. else
  1022. {
  1023. useTemporaryPreview =
  1024. previewCapture && m_temporarySettingsActive && m_previewCapturePending;
  1025. if (useTemporaryPreview) delay = m_previewCaptureDelayMs;
  1026. }
  1027. }
  1028. if (captureResult == ESP_OK && !useTemporaryPreview)
  1029. {
  1030. captureResult = RestoreCommittedSettingsIfNeeded();
  1031. if (captureResult == ESP_OK && previewCapture)
  1032. {
  1033. const int waitSeconds = std::max(0, CCstatus.WaitBeforePicture);
  1034. delay = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
  1035. }
  1036. }
  1037. if (captureResult == ESP_OK)
  1038. {
  1039. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  1040. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  1041. camera_fb_t *fb = NULL;
  1042. {
  1043. ScopedCameraLock cameraLock(m_cameraMutex);
  1044. if (!cameraLock.acquired())
  1045. {
  1046. captureResult = ESP_ERR_TIMEOUT;
  1047. }
  1048. else
  1049. {
  1050. {
  1051. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1052. }
  1053. fb = esp_camera_fb_get();
  1054. }
  1055. }
  1056. if (captureResult == ESP_OK && fb == NULL)
  1057. {
  1058. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: camera capture failed");
  1059. captureResult = ESP_FAIL;
  1060. }
  1061. if (captureResult == ESP_OK)
  1062. {
  1063. ScopedCameraFrame frame(fb, m_cameraMutex);
  1064. if (CCstatus.DemoMode)
  1065. {
  1066. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  1067. if (!loadNextDemoImage(&responseData, &responseLength))
  1068. {
  1069. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: could not load demo image");
  1070. captureResult = ESP_FAIL;
  1071. }
  1072. else
  1073. {
  1074. responseInPsram = true;
  1075. }
  1076. }
  1077. else if (fb->format == PIXFORMAT_JPEG)
  1078. {
  1079. if (fb->buf == NULL || fb->len == 0)
  1080. {
  1081. captureResult = ESP_FAIL;
  1082. }
  1083. else
  1084. {
  1085. responseData = static_cast<uint8_t *>(malloc_psram_heap(
  1086. "HTTP JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1087. if (responseData == NULL)
  1088. {
  1089. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: unable to allocate JPEG copy");
  1090. captureResult = ESP_ERR_NO_MEM;
  1091. }
  1092. else
  1093. {
  1094. memcpy(responseData, fb->buf, fb->len);
  1095. responseLength = fb->len;
  1096. responseInPsram = true;
  1097. }
  1098. }
  1099. }
  1100. else if (!frame2jpg(fb, 80, &responseData, &responseLength) ||
  1101. responseData == NULL || responseLength == 0)
  1102. {
  1103. if (responseData != NULL)
  1104. {
  1105. free(responseData);
  1106. responseData = NULL;
  1107. }
  1108. captureResult = ESP_FAIL;
  1109. }
  1110. frame.release();
  1111. }
  1112. if (captureResult == ESP_OK && useTemporaryPreview)
  1113. {
  1114. ScopedCameraLock cameraLock(m_cameraMutex);
  1115. if (cameraLock.acquired()) m_previewCapturePending = false;
  1116. else captureResult = ESP_ERR_TIMEOUT;
  1117. }
  1118. }
  1119. }
  1120. const int64_t captureEnd = esp_timer_get_time();
  1121. if (captureResult == ESP_OK && responseData != NULL && responseLength > 0)
  1122. {
  1123. captureResult = httpd_resp_set_type(req, "image/jpeg");
  1124. if (captureResult == ESP_OK)
  1125. {
  1126. captureResult = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  1127. }
  1128. if (captureResult == ESP_OK)
  1129. {
  1130. responseStarted = true;
  1131. captureResult = httpd_resp_send(req, reinterpret_cast<const char *>(responseData),
  1132. static_cast<ssize_t>(responseLength));
  1133. }
  1134. }
  1135. else if (captureResult == ESP_OK)
  1136. {
  1137. captureResult = ESP_FAIL;
  1138. }
  1139. if (responseData != NULL)
  1140. {
  1141. if (responseInPsram)
  1142. {
  1143. free_psram_heap("HTTP image response", responseData);
  1144. }
  1145. else
  1146. {
  1147. free(responseData);
  1148. }
  1149. responseData = NULL;
  1150. }
  1151. ESP_LOGI(TAG, "HTTP JPEG capture: %uKB %ums",
  1152. static_cast<unsigned int>(responseLength / 1024),
  1153. static_cast<unsigned int>((captureEnd - captureStart) / 1000));
  1154. if (captureResult != ESP_OK && !responseStarted)
  1155. {
  1156. httpd_resp_send_500(req);
  1157. }
  1158. return captureResult;
  1159. }
  1160. esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
  1161. {
  1162. if (req == NULL) return ESP_ERR_INVALID_ARG;
  1163. {
  1164. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1165. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  1166. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  1167. if (restoreResult != ESP_OK) return restoreResult;
  1168. }
  1169. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
  1170. ScopedCameraCaptureIndicators indicators(*this, FlashlightOn, FlashlightOn);
  1171. esp_err_t result = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  1172. if (result == ESP_OK)
  1173. {
  1174. result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1175. }
  1176. // One warmup frame lets exposure and white balance settle before streaming.
  1177. if (result == ESP_OK)
  1178. {
  1179. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1180. if (!operationLock.acquired())
  1181. {
  1182. result = ESP_ERR_TIMEOUT;
  1183. }
  1184. else
  1185. {
  1186. ScopedCameraLock cameraLock(m_cameraMutex);
  1187. if (!cameraLock.acquired())
  1188. {
  1189. result = ESP_ERR_TIMEOUT;
  1190. }
  1191. else
  1192. {
  1193. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1194. }
  1195. }
  1196. }
  1197. char partBuffer[64];
  1198. uint8_t *frameCopyBuffer = NULL;
  1199. size_t frameCopyCapacity = 0;
  1200. while (result == ESP_OK)
  1201. {
  1202. const int64_t frameStart = esp_timer_get_time();
  1203. uint8_t *frameData = NULL;
  1204. size_t frameLength = 0;
  1205. bool frameDataOwned = false;
  1206. {
  1207. // Reserve the camera only long enough to acquire and detach a frame.
  1208. // Network transmission below uses the independent copy and owns no
  1209. // camera-driver or framebuffer resources.
  1210. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1211. if (!operationLock.acquired())
  1212. {
  1213. result = ESP_ERR_TIMEOUT;
  1214. }
  1215. else
  1216. {
  1217. camera_fb_t *fb = NULL;
  1218. {
  1219. ScopedCameraLock cameraLock(m_cameraMutex);
  1220. if (!cameraLock.acquired())
  1221. {
  1222. result = ESP_ERR_TIMEOUT;
  1223. }
  1224. else
  1225. {
  1226. fb = esp_camera_fb_get();
  1227. }
  1228. }
  1229. if (result == ESP_OK && fb == NULL)
  1230. {
  1231. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
  1232. result = ESP_FAIL;
  1233. }
  1234. if (result == ESP_OK)
  1235. {
  1236. ScopedCameraFrame frame(fb, m_cameraMutex);
  1237. if (fb->format == PIXFORMAT_JPEG)
  1238. {
  1239. if (fb->buf == NULL || fb->len == 0)
  1240. {
  1241. result = ESP_FAIL;
  1242. }
  1243. else
  1244. {
  1245. if (fb->len > frameCopyCapacity)
  1246. {
  1247. uint8_t *newBuffer = static_cast<uint8_t *>(realloc_psram_heap(
  1248. "Live stream JPEG copy", frameCopyBuffer, fb->len,
  1249. MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1250. if (newBuffer == NULL)
  1251. {
  1252. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: JPEG copy buffer growth failed");
  1253. result = ESP_ERR_NO_MEM;
  1254. }
  1255. else
  1256. {
  1257. frameCopyBuffer = newBuffer;
  1258. frameCopyCapacity = fb->len;
  1259. }
  1260. }
  1261. if (result == ESP_OK)
  1262. {
  1263. memcpy(frameCopyBuffer, fb->buf, fb->len);
  1264. frameData = frameCopyBuffer;
  1265. frameLength = fb->len;
  1266. }
  1267. }
  1268. }
  1269. else
  1270. {
  1271. if (!frame2jpg(fb, 80, &frameData, &frameLength) ||
  1272. frameData == NULL || frameLength == 0)
  1273. {
  1274. if (frameData != NULL)
  1275. {
  1276. free(frameData);
  1277. frameData = NULL;
  1278. }
  1279. result = ESP_FAIL;
  1280. }
  1281. else
  1282. {
  1283. frameDataOwned = true;
  1284. }
  1285. }
  1286. frame.release();
  1287. }
  1288. }
  1289. }
  1290. // All camera resources are released before any potentially blocking
  1291. // socket operation. A slow or disconnected client cannot starve the flow.
  1292. if (result == ESP_OK)
  1293. {
  1294. const int headerLength = snprintf(partBuffer, sizeof(partBuffer), _STREAM_PART,
  1295. static_cast<unsigned int>(frameLength));
  1296. if (headerLength < 0 || static_cast<size_t>(headerLength) >= sizeof(partBuffer))
  1297. {
  1298. result = ESP_FAIL;
  1299. }
  1300. else
  1301. {
  1302. result = httpd_resp_send_chunk(req, partBuffer, static_cast<size_t>(headerLength));
  1303. }
  1304. if (result == ESP_OK)
  1305. {
  1306. result = httpd_resp_send_chunk(req, reinterpret_cast<const char *>(frameData),
  1307. static_cast<ssize_t>(frameLength));
  1308. }
  1309. if (result == ESP_OK)
  1310. {
  1311. result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1312. }
  1313. }
  1314. if (frameDataOwned && frameData != NULL) free(frameData);
  1315. if (result != ESP_OK) break;
  1316. const int64_t frameEnd = esp_timer_get_time();
  1317. ESP_LOGD(TAG, "Stream frame: %uKB %ums",
  1318. static_cast<unsigned int>(frameLength / 1024),
  1319. static_cast<unsigned int>((frameEnd - frameStart) / 1000));
  1320. const int64_t frameDurationMs = (frameEnd - frameStart) / 1000;
  1321. if (CAM_LIVESTREAM_REFRESHRATE > frameDurationMs)
  1322. {
  1323. const TickType_t delayTicks =
  1324. pdMS_TO_TICKS(CAM_LIVESTREAM_REFRESHRATE - frameDurationMs);
  1325. vTaskDelay(delayTicks);
  1326. }
  1327. }
  1328. if (frameCopyBuffer != NULL)
  1329. free_psram_heap("Live stream JPEG copy", frameCopyBuffer);
  1330. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
  1331. return result;
  1332. }
  1333. void CCamera::UpdateFlashOutputLocked(void)
  1334. {
  1335. const bool active = m_manualFlashOn || m_captureFlashUsers > 0;
  1336. #ifdef USE_PWM_LEDFLASH
  1337. const uint32_t duty = active ? static_cast<uint32_t>(LedIntensity) : 0U;
  1338. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty));
  1339. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  1340. #else
  1341. // The camera owns the board flash LED independently of the user GPIO handler.
  1342. gpio_pad_select_gpio(FLASH_GPIO);
  1343. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  1344. gpio_set_level(FLASH_GPIO, active ? 1 : 0);
  1345. #endif
  1346. }
  1347. void CCamera::UpdateStatusLedOutputLocked(void)
  1348. {
  1349. if (xHandle_task_StatusLED != NULL) return;
  1350. const bool active = m_manualStatusLedOn || m_captureStatusLedUsers > 0;
  1351. gpio_pad_select_gpio(BLINK_GPIO);
  1352. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  1353. // The on-board status LED is active-low.
  1354. gpio_set_level(BLINK_GPIO, active ? 0 : 1);
  1355. }
  1356. void CCamera::SetCaptureFlashActive(bool active)
  1357. {
  1358. // Indicator reference counts must always be balanced, even during long captures.
  1359. ScopedCameraOperationLock operationLock(m_cameraOperationMutex, portMAX_DELAY);
  1360. if (!operationLock.acquired()) return;
  1361. ScopedCameraLock cameraLock(m_cameraMutex, portMAX_DELAY);
  1362. if (!cameraLock.acquired()) return;
  1363. if (active)
  1364. {
  1365. if (m_captureFlashUsers < UINT32_MAX) ++m_captureFlashUsers;
  1366. }
  1367. else if (m_captureFlashUsers > 0)
  1368. {
  1369. --m_captureFlashUsers;
  1370. }
  1371. UpdateFlashOutputLocked();
  1372. }
  1373. void CCamera::SetCaptureStatusLedActive(bool active)
  1374. {
  1375. // Indicator reference counts must always be balanced, even during long captures.
  1376. ScopedCameraOperationLock operationLock(m_cameraOperationMutex, portMAX_DELAY);
  1377. if (!operationLock.acquired()) return;
  1378. ScopedCameraLock cameraLock(m_cameraMutex, portMAX_DELAY);
  1379. if (!cameraLock.acquired()) return;
  1380. if (active)
  1381. {
  1382. if (m_captureStatusLedUsers < UINT32_MAX) ++m_captureStatusLedUsers;
  1383. }
  1384. else if (m_captureStatusLedUsers > 0)
  1385. {
  1386. --m_captureStatusLedUsers;
  1387. }
  1388. UpdateStatusLedOutputLocked();
  1389. }
  1390. void CCamera::LightOnOff(bool status)
  1391. {
  1392. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1393. if (!operationLock.acquired()) return;
  1394. ScopedCameraLock cameraLock(m_cameraMutex);
  1395. if (!cameraLock.acquired())
  1396. {
  1397. ESP_LOGW(TAG, "LightOnOff: camera mutex unavailable");
  1398. return;
  1399. }
  1400. m_manualFlashOn = status;
  1401. UpdateFlashOutputLocked();
  1402. }
  1403. void CCamera::LEDOnOff(bool status)
  1404. {
  1405. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1406. if (!operationLock.acquired()) return;
  1407. ScopedCameraLock cameraLock(m_cameraMutex);
  1408. if (!cameraLock.acquired()) return;
  1409. m_manualStatusLedOn = status;
  1410. UpdateStatusLedOutputLocked();
  1411. }
  1412. void CCamera::SetImageWidthHeightFromResolution(CameraSettings &settings)
  1413. {
  1414. switch (settings.ImageFrameSize)
  1415. {
  1416. case FRAMESIZE_QVGA:
  1417. settings.ImageWidth = 320;
  1418. settings.ImageHeight = 240;
  1419. break;
  1420. case FRAMESIZE_VGA:
  1421. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1422. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1423. break;
  1424. default:
  1425. // Higher resolutions overload the ESP32 image-processing pipeline.
  1426. // Zoom is implemented by sensor-side windowing, while the output stays VGA.
  1427. ESP_LOGW(TAG, "Frame size %d exceeds the supported VGA limit; forcing VGA",
  1428. static_cast<int>(settings.ImageFrameSize));
  1429. settings.ImageFrameSize = FRAMESIZE_VGA;
  1430. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1431. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1432. break;
  1433. }
  1434. }
  1435. void CCamera::useDemoMode(void)
  1436. {
  1437. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1438. if (!operationLock.acquired()) return;
  1439. char line[50];
  1440. m_demoFiles.clear();
  1441. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  1442. if (fd == NULL) {
  1443. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: '/sdcard/demo/files.txt' is missing!");
  1444. CCstatus.DemoMode = false;
  1445. return;
  1446. }
  1447. while (fgets(line, sizeof(line), fd) != NULL) {
  1448. size_t length = strlen(line);
  1449. while (length > 0 && (line[length-1] == '\n' || line[length-1] == '\r')) line[--length] = '\0';
  1450. if (length > 0) m_demoFiles.push_back(line);
  1451. }
  1452. fclose(fd);
  1453. if (m_demoFiles.empty()) {
  1454. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: files.txt contains no image names");
  1455. CCstatus.DemoMode = false;
  1456. return;
  1457. }
  1458. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(m_demoFiles.size()) + " files) instead of real camera image!");
  1459. for (const auto& file : m_demoFiles) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  1460. CCstatus.DemoMode = true;
  1461. }
  1462. bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
  1463. {
  1464. if (data == NULL || length == NULL || m_demoFiles.empty()) return false;
  1465. *data = NULL;
  1466. *length = 0;
  1467. const size_t index = static_cast<size_t>(getCountFlowRounds()) % m_demoFiles.size();
  1468. const std::string filename = "/sdcard/demo/" + m_demoFiles[index];
  1469. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + filename + " as demo image");
  1470. FILE *fp = fopen(filename.c_str(), "rb");
  1471. if (fp == NULL) return false;
  1472. const long fileSize = GetFileSize(filename);
  1473. if (fileSize <= 0 || fileSize > DEMO_IMAGE_SIZE) {
  1474. fclose(fp);
  1475. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image has invalid size: " + std::to_string(fileSize));
  1476. return false;
  1477. }
  1478. uint8_t *buffer = static_cast<uint8_t*>(malloc_psram_heap(
  1479. "Demo image frame", static_cast<size_t>(fileSize), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1480. if (buffer == NULL) {
  1481. fclose(fp);
  1482. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image PSRAM allocation failed");
  1483. return false;
  1484. }
  1485. const size_t readBytes = fread(buffer, 1, static_cast<size_t>(fileSize), fp);
  1486. const bool readOkay = (readBytes == static_cast<size_t>(fileSize)) && (ferror(fp) == 0);
  1487. fclose(fp);
  1488. if (!readOkay) {
  1489. free_psram_heap("Demo image frame (short read)", buffer);
  1490. return false;
  1491. }
  1492. *data = buffer;
  1493. *length = readBytes;
  1494. return true;
  1495. }
  1496. long CCamera::GetFileSize(std::string filename)
  1497. {
  1498. struct stat stat_buf;
  1499. long rc = stat(filename.c_str(), &stat_buf);
  1500. return rc == 0 ? stat_buf.st_size : -1;
  1501. }