ClassControllCamera.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  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. indicators.release();
  861. operationLock.release();
  862. if (!decoded || tmpImage == NULL || !tmpImage->ImageOkay())
  863. {
  864. delete tmpImage;
  865. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: JPEG decode failed");
  866. LogFile.WriteHeapInfo("CaptureToBasisImage decode");
  867. return ESP_FAIL;
  868. }
  869. if (_Image->width != tmpImage->width || _Image->height != tmpImage->height ||
  870. _Image->channels != tmpImage->channels || tmpImage->channels != 3 ||
  871. tmpImage->width <= 0 || tmpImage->height <= 0 ||
  872. static_cast<size_t>(tmpImage->width) > SIZE_MAX / static_cast<size_t>(tmpImage->height) ||
  873. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) > SIZE_MAX / 3U)
  874. {
  875. delete tmpImage;
  876. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded dimensions do not match target image");
  877. return ESP_FAIL;
  878. }
  879. const size_t expectedBytes =
  880. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) * 3U;
  881. if (expectedBytes > static_cast<size_t>(INT_MAX))
  882. {
  883. delete tmpImage;
  884. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image is too large");
  885. return ESP_FAIL;
  886. }
  887. uint8_t *source = tmpImage->RGBImageLock();
  888. if (source == NULL)
  889. {
  890. delete tmpImage;
  891. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image lock failed");
  892. return ESP_FAIL;
  893. }
  894. const bool copied = _Image->CopyFromMemory(source, static_cast<int>(expectedBytes));
  895. tmpImage->RGBImageRelease();
  896. delete tmpImage;
  897. #ifdef DEBUG_DETAIL_ON
  898. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  899. #endif
  900. return copied ? ESP_OK : ESP_FAIL;
  901. }
  902. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  903. {
  904. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  905. if (!operationLock.acquired())
  906. {
  907. ESP_LOGW(TAG, "CaptureToFile: camera operation lock unavailable");
  908. return ESP_ERR_TIMEOUT;
  909. }
  910. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  911. if (restoreResult != ESP_OK) return restoreResult;
  912. const CameraSettings captureSettings = static_cast<const CameraSettings &>(CCstatus);
  913. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  914. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  915. camera_fb_t *fb = NULL;
  916. {
  917. ScopedCameraLock cameraLock(m_cameraMutex);
  918. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  919. {
  920. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  921. }
  922. fb = esp_camera_fb_get();
  923. }
  924. if (fb == NULL)
  925. {
  926. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  927. "Check camera module and/or proper electrical connection");
  928. return ESP_FAIL;
  929. }
  930. ScopedCameraFrame frame(fb, m_cameraMutex);
  931. #ifdef DEBUG_DETAIL_ON
  932. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  933. #endif
  934. nm = FormatFileName(nm);
  935. #ifdef DEBUG_DETAIL_ON
  936. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  937. #endif
  938. const string fileType = toUpper(getFileType(nm));
  939. uint8_t *buffer = NULL;
  940. size_t bufferLength = 0;
  941. bool bufferNeedsFree = false;
  942. bool bufferInPsram = false;
  943. bool captureOkay = false;
  944. if (fileType == "BMP")
  945. {
  946. bufferNeedsFree = true;
  947. captureOkay = frame2bmp(fb, &buffer, &bufferLength) &&
  948. buffer != NULL && bufferLength > 0;
  949. }
  950. else if (fileType == "JPG")
  951. {
  952. if (fb->format == PIXFORMAT_JPEG)
  953. {
  954. if (fb->buf != NULL && fb->len > 0)
  955. {
  956. buffer = static_cast<uint8_t *>(malloc_psram_heap(
  957. "Capture file JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  958. if (buffer != NULL)
  959. {
  960. memcpy(buffer, fb->buf, fb->len);
  961. bufferLength = fb->len;
  962. bufferNeedsFree = true;
  963. bufferInPsram = true;
  964. captureOkay = true;
  965. }
  966. }
  967. }
  968. else
  969. {
  970. bufferNeedsFree = true;
  971. captureOkay = frame2jpg(fb, captureSettings.ImageQuality, &buffer, &bufferLength) &&
  972. buffer != NULL && bufferLength > 0;
  973. if (!captureOkay) ESP_LOGE(TAG, "JPEG compression failed");
  974. }
  975. }
  976. // The buffer is now independent of the camera framebuffer. Release both
  977. // camera leases before opening or writing the SD-card file.
  978. frame.release();
  979. indicators.release();
  980. operationLock.release();
  981. if (captureOkay)
  982. {
  983. FILE *fp = fopen(nm.c_str(), "wb");
  984. if (fp == NULL)
  985. {
  986. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  987. captureOkay = false;
  988. }
  989. else
  990. {
  991. const size_t written = fwrite(buffer, 1, bufferLength, fp);
  992. const int closeResult = fclose(fp);
  993. if (written != bufferLength || closeResult != 0)
  994. {
  995. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: incomplete write to " + nm);
  996. captureOkay = false;
  997. }
  998. }
  999. }
  1000. else
  1001. {
  1002. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: unsupported image format, allocation or conversion failed");
  1003. }
  1004. if (bufferNeedsFree && buffer != NULL)
  1005. {
  1006. if (bufferInPsram) free_psram_heap("Capture file JPEG copy", buffer);
  1007. else free(buffer);
  1008. }
  1009. return captureOkay ? ESP_OK : ESP_FAIL;
  1010. }
  1011. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay, bool previewCapture)
  1012. {
  1013. if (req == NULL) return ESP_ERR_INVALID_ARG;
  1014. uint8_t *responseData = NULL;
  1015. size_t responseLength = 0;
  1016. bool responseInPsram = false;
  1017. esp_err_t captureResult = ESP_OK;
  1018. const int64_t captureStart = esp_timer_get_time();
  1019. {
  1020. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1021. if (!operationLock.acquired())
  1022. {
  1023. httpd_resp_set_status(req, "503 Service Unavailable");
  1024. httpd_resp_send(req, "Camera is busy", HTTPD_RESP_USE_STRLEN);
  1025. return ESP_ERR_TIMEOUT;
  1026. }
  1027. bool useTemporaryPreview = false;
  1028. {
  1029. ScopedCameraLock cameraLock(m_cameraMutex);
  1030. if (!cameraLock.acquired())
  1031. {
  1032. captureResult = ESP_ERR_TIMEOUT;
  1033. }
  1034. else
  1035. {
  1036. useTemporaryPreview =
  1037. previewCapture && m_temporarySettingsActive && m_previewCapturePending;
  1038. if (useTemporaryPreview) delay = m_previewCaptureDelayMs;
  1039. }
  1040. }
  1041. if (captureResult == ESP_OK && !useTemporaryPreview)
  1042. {
  1043. captureResult = RestoreCommittedSettingsIfNeeded();
  1044. if (captureResult == ESP_OK && previewCapture)
  1045. {
  1046. const int waitSeconds = std::max(0, CCstatus.WaitBeforePicture);
  1047. delay = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
  1048. }
  1049. }
  1050. if (captureResult == ESP_OK)
  1051. {
  1052. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  1053. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  1054. camera_fb_t *fb = NULL;
  1055. {
  1056. ScopedCameraLock cameraLock(m_cameraMutex);
  1057. if (!cameraLock.acquired())
  1058. {
  1059. captureResult = ESP_ERR_TIMEOUT;
  1060. }
  1061. else
  1062. {
  1063. {
  1064. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1065. }
  1066. fb = esp_camera_fb_get();
  1067. }
  1068. }
  1069. if (captureResult == ESP_OK && fb == NULL)
  1070. {
  1071. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: camera capture failed");
  1072. captureResult = ESP_FAIL;
  1073. }
  1074. if (captureResult == ESP_OK)
  1075. {
  1076. ScopedCameraFrame frame(fb, m_cameraMutex);
  1077. if (CCstatus.DemoMode)
  1078. {
  1079. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  1080. if (!loadNextDemoImage(&responseData, &responseLength))
  1081. {
  1082. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: could not load demo image");
  1083. captureResult = ESP_FAIL;
  1084. }
  1085. else
  1086. {
  1087. responseInPsram = true;
  1088. }
  1089. }
  1090. else if (fb->format == PIXFORMAT_JPEG)
  1091. {
  1092. if (fb->buf == NULL || fb->len == 0)
  1093. {
  1094. captureResult = ESP_FAIL;
  1095. }
  1096. else
  1097. {
  1098. responseData = static_cast<uint8_t *>(malloc_psram_heap(
  1099. "HTTP JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1100. if (responseData == NULL)
  1101. {
  1102. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: unable to allocate JPEG copy");
  1103. captureResult = ESP_ERR_NO_MEM;
  1104. }
  1105. else
  1106. {
  1107. memcpy(responseData, fb->buf, fb->len);
  1108. responseLength = fb->len;
  1109. responseInPsram = true;
  1110. }
  1111. }
  1112. }
  1113. else if (!frame2jpg(fb, 80, &responseData, &responseLength) ||
  1114. responseData == NULL || responseLength == 0)
  1115. {
  1116. if (responseData != NULL)
  1117. {
  1118. free(responseData);
  1119. responseData = NULL;
  1120. }
  1121. captureResult = ESP_FAIL;
  1122. }
  1123. frame.release();
  1124. }
  1125. if (captureResult == ESP_OK && useTemporaryPreview)
  1126. {
  1127. ScopedCameraLock cameraLock(m_cameraMutex);
  1128. if (cameraLock.acquired()) m_previewCapturePending = false;
  1129. else captureResult = ESP_ERR_TIMEOUT;
  1130. }
  1131. }
  1132. }
  1133. const int64_t captureEnd = esp_timer_get_time();
  1134. if (captureResult == ESP_OK && responseData != NULL && responseLength > 0)
  1135. {
  1136. captureResult = httpd_resp_set_type(req, "image/jpeg");
  1137. if (captureResult == ESP_OK)
  1138. {
  1139. captureResult = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  1140. }
  1141. if (captureResult == ESP_OK)
  1142. {
  1143. captureResult = httpd_resp_send(req, reinterpret_cast<const char *>(responseData),
  1144. static_cast<ssize_t>(responseLength));
  1145. }
  1146. }
  1147. else if (captureResult == ESP_OK)
  1148. {
  1149. captureResult = ESP_FAIL;
  1150. }
  1151. if (responseData != NULL)
  1152. {
  1153. if (responseInPsram)
  1154. {
  1155. free_psram_heap("HTTP image response", responseData);
  1156. }
  1157. else
  1158. {
  1159. free(responseData);
  1160. }
  1161. }
  1162. ESP_LOGI(TAG, "HTTP JPEG capture: %uKB %ums",
  1163. static_cast<unsigned int>(responseLength / 1024),
  1164. static_cast<unsigned int>((captureEnd - captureStart) / 1000));
  1165. if (captureResult != ESP_OK)
  1166. {
  1167. // The socket may already have started a response; only send the
  1168. // fallback status for failures that occurred before response setup.
  1169. if (responseData == NULL || responseLength == 0)
  1170. httpd_resp_send_500(req);
  1171. }
  1172. return captureResult;
  1173. }
  1174. esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
  1175. {
  1176. if (req == NULL) return ESP_ERR_INVALID_ARG;
  1177. {
  1178. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1179. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  1180. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  1181. if (restoreResult != ESP_OK) return restoreResult;
  1182. }
  1183. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
  1184. ScopedCameraCaptureIndicators indicators(*this, FlashlightOn, FlashlightOn);
  1185. esp_err_t result = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  1186. if (result == ESP_OK)
  1187. {
  1188. result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1189. }
  1190. // One warmup frame lets exposure and white balance settle before streaming.
  1191. if (result == ESP_OK)
  1192. {
  1193. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1194. if (!operationLock.acquired())
  1195. {
  1196. result = ESP_ERR_TIMEOUT;
  1197. }
  1198. else
  1199. {
  1200. ScopedCameraLock cameraLock(m_cameraMutex);
  1201. if (!cameraLock.acquired())
  1202. {
  1203. result = ESP_ERR_TIMEOUT;
  1204. }
  1205. else
  1206. {
  1207. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1208. }
  1209. }
  1210. }
  1211. char partBuffer[64];
  1212. uint8_t *frameCopyBuffer = NULL;
  1213. size_t frameCopyCapacity = 0;
  1214. while (result == ESP_OK)
  1215. {
  1216. const int64_t frameStart = esp_timer_get_time();
  1217. uint8_t *frameData = NULL;
  1218. size_t frameLength = 0;
  1219. bool frameDataOwned = false;
  1220. {
  1221. // Reserve the camera only long enough to acquire and detach a frame.
  1222. // Network transmission below uses the independent copy and owns no
  1223. // camera-driver or framebuffer resources.
  1224. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1225. if (!operationLock.acquired())
  1226. {
  1227. result = ESP_ERR_TIMEOUT;
  1228. }
  1229. else
  1230. {
  1231. camera_fb_t *fb = NULL;
  1232. {
  1233. ScopedCameraLock cameraLock(m_cameraMutex);
  1234. if (!cameraLock.acquired())
  1235. {
  1236. result = ESP_ERR_TIMEOUT;
  1237. }
  1238. else
  1239. {
  1240. fb = esp_camera_fb_get();
  1241. }
  1242. }
  1243. if (result == ESP_OK && fb == NULL)
  1244. {
  1245. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
  1246. result = ESP_FAIL;
  1247. }
  1248. if (result == ESP_OK)
  1249. {
  1250. ScopedCameraFrame frame(fb, m_cameraMutex);
  1251. if (fb->format == PIXFORMAT_JPEG)
  1252. {
  1253. if (fb->buf == NULL || fb->len == 0)
  1254. {
  1255. result = ESP_FAIL;
  1256. }
  1257. else
  1258. {
  1259. if (fb->len > frameCopyCapacity)
  1260. {
  1261. uint8_t *newBuffer = static_cast<uint8_t *>(malloc_psram_heap(
  1262. "Live stream JPEG copy", fb->len, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1263. if (newBuffer == NULL)
  1264. {
  1265. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: JPEG copy allocation failed");
  1266. result = ESP_ERR_NO_MEM;
  1267. }
  1268. else
  1269. {
  1270. if (frameCopyBuffer != NULL)
  1271. free_psram_heap("Live stream JPEG copy", frameCopyBuffer);
  1272. frameCopyBuffer = newBuffer;
  1273. frameCopyCapacity = fb->len;
  1274. }
  1275. }
  1276. if (result == ESP_OK)
  1277. {
  1278. memcpy(frameCopyBuffer, fb->buf, fb->len);
  1279. frameData = frameCopyBuffer;
  1280. frameLength = fb->len;
  1281. }
  1282. }
  1283. }
  1284. else
  1285. {
  1286. if (!frame2jpg(fb, 80, &frameData, &frameLength) ||
  1287. frameData == NULL || frameLength == 0)
  1288. {
  1289. if (frameData != NULL)
  1290. {
  1291. free(frameData);
  1292. frameData = NULL;
  1293. }
  1294. result = ESP_FAIL;
  1295. }
  1296. else
  1297. {
  1298. frameDataOwned = true;
  1299. }
  1300. }
  1301. frame.release();
  1302. }
  1303. }
  1304. }
  1305. // All camera resources are released before any potentially blocking
  1306. // socket operation. A slow or disconnected client cannot starve the flow.
  1307. if (result == ESP_OK)
  1308. {
  1309. const int headerLength = snprintf(partBuffer, sizeof(partBuffer), _STREAM_PART,
  1310. static_cast<unsigned int>(frameLength));
  1311. if (headerLength < 0 || static_cast<size_t>(headerLength) >= sizeof(partBuffer))
  1312. {
  1313. result = ESP_FAIL;
  1314. }
  1315. else
  1316. {
  1317. result = httpd_resp_send_chunk(req, partBuffer, static_cast<size_t>(headerLength));
  1318. }
  1319. if (result == ESP_OK)
  1320. {
  1321. result = httpd_resp_send_chunk(req, reinterpret_cast<const char *>(frameData),
  1322. static_cast<ssize_t>(frameLength));
  1323. }
  1324. if (result == ESP_OK)
  1325. {
  1326. result = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1327. }
  1328. }
  1329. if (frameDataOwned && frameData != NULL) free(frameData);
  1330. if (result != ESP_OK) break;
  1331. const int64_t frameEnd = esp_timer_get_time();
  1332. ESP_LOGD(TAG, "Stream frame: %uKB %ums",
  1333. static_cast<unsigned int>(frameLength / 1024),
  1334. static_cast<unsigned int>((frameEnd - frameStart) / 1000));
  1335. const int64_t frameDurationMs = (frameEnd - frameStart) / 1000;
  1336. if (CAM_LIVESTREAM_REFRESHRATE > frameDurationMs)
  1337. {
  1338. const TickType_t delayTicks =
  1339. pdMS_TO_TICKS(CAM_LIVESTREAM_REFRESHRATE - frameDurationMs);
  1340. vTaskDelay(delayTicks);
  1341. }
  1342. }
  1343. if (frameCopyBuffer != NULL)
  1344. free_psram_heap("Live stream JPEG copy", frameCopyBuffer);
  1345. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
  1346. return result;
  1347. }
  1348. void CCamera::UpdateFlashOutputLocked(void)
  1349. {
  1350. const bool active = m_manualFlashOn || m_captureFlashUsers > 0;
  1351. #ifdef USE_PWM_LEDFLASH
  1352. const uint32_t duty = active ? static_cast<uint32_t>(LedIntensity) : 0U;
  1353. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty));
  1354. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  1355. #else
  1356. // The camera owns the board flash LED independently of the user GPIO handler.
  1357. gpio_pad_select_gpio(FLASH_GPIO);
  1358. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  1359. gpio_set_level(FLASH_GPIO, active ? 1 : 0);
  1360. #endif
  1361. }
  1362. void CCamera::UpdateStatusLedOutputLocked(void)
  1363. {
  1364. if (xHandle_task_StatusLED != NULL) return;
  1365. const bool active = m_manualStatusLedOn || m_captureStatusLedUsers > 0;
  1366. gpio_pad_select_gpio(BLINK_GPIO);
  1367. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  1368. // The on-board status LED is active-low.
  1369. gpio_set_level(BLINK_GPIO, active ? 0 : 1);
  1370. }
  1371. void CCamera::SetCaptureFlashActive(bool active)
  1372. {
  1373. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1374. if (!operationLock.acquired()) return;
  1375. ScopedCameraLock cameraLock(m_cameraMutex);
  1376. if (!cameraLock.acquired()) return;
  1377. if (active)
  1378. {
  1379. if (m_captureFlashUsers < UINT32_MAX) ++m_captureFlashUsers;
  1380. }
  1381. else if (m_captureFlashUsers > 0)
  1382. {
  1383. --m_captureFlashUsers;
  1384. }
  1385. UpdateFlashOutputLocked();
  1386. }
  1387. void CCamera::SetCaptureStatusLedActive(bool active)
  1388. {
  1389. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1390. if (!operationLock.acquired()) return;
  1391. ScopedCameraLock cameraLock(m_cameraMutex);
  1392. if (!cameraLock.acquired()) return;
  1393. if (active)
  1394. {
  1395. if (m_captureStatusLedUsers < UINT32_MAX) ++m_captureStatusLedUsers;
  1396. }
  1397. else if (m_captureStatusLedUsers > 0)
  1398. {
  1399. --m_captureStatusLedUsers;
  1400. }
  1401. UpdateStatusLedOutputLocked();
  1402. }
  1403. void CCamera::LightOnOff(bool status)
  1404. {
  1405. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1406. if (!operationLock.acquired()) return;
  1407. ScopedCameraLock cameraLock(m_cameraMutex);
  1408. if (!cameraLock.acquired())
  1409. {
  1410. ESP_LOGW(TAG, "LightOnOff: camera mutex unavailable");
  1411. return;
  1412. }
  1413. m_manualFlashOn = status;
  1414. UpdateFlashOutputLocked();
  1415. }
  1416. void CCamera::LEDOnOff(bool status)
  1417. {
  1418. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1419. if (!operationLock.acquired()) return;
  1420. ScopedCameraLock cameraLock(m_cameraMutex);
  1421. if (!cameraLock.acquired()) return;
  1422. m_manualStatusLedOn = status;
  1423. UpdateStatusLedOutputLocked();
  1424. }
  1425. void CCamera::SetImageWidthHeightFromResolution(CameraSettings &settings)
  1426. {
  1427. switch (settings.ImageFrameSize)
  1428. {
  1429. case FRAMESIZE_QVGA:
  1430. settings.ImageWidth = 320;
  1431. settings.ImageHeight = 240;
  1432. break;
  1433. case FRAMESIZE_VGA:
  1434. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1435. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1436. break;
  1437. default:
  1438. // Higher resolutions overload the ESP32 image-processing pipeline.
  1439. // Zoom is implemented by sensor-side windowing, while the output stays VGA.
  1440. ESP_LOGW(TAG, "Frame size %d exceeds the supported VGA limit; forcing VGA",
  1441. static_cast<int>(settings.ImageFrameSize));
  1442. settings.ImageFrameSize = FRAMESIZE_VGA;
  1443. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1444. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1445. break;
  1446. }
  1447. }
  1448. void CCamera::useDemoMode(void)
  1449. {
  1450. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1451. if (!operationLock.acquired()) return;
  1452. char line[50];
  1453. m_demoFiles.clear();
  1454. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  1455. if (fd == NULL) {
  1456. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: '/sdcard/demo/files.txt' is missing!");
  1457. CCstatus.DemoMode = false;
  1458. return;
  1459. }
  1460. while (fgets(line, sizeof(line), fd) != NULL) {
  1461. size_t length = strlen(line);
  1462. while (length > 0 && (line[length-1] == '\n' || line[length-1] == '\r')) line[--length] = '\0';
  1463. if (length > 0) m_demoFiles.push_back(line);
  1464. }
  1465. fclose(fd);
  1466. if (m_demoFiles.empty()) {
  1467. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: files.txt contains no image names");
  1468. CCstatus.DemoMode = false;
  1469. return;
  1470. }
  1471. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(m_demoFiles.size()) + " files) instead of real camera image!");
  1472. for (const auto& file : m_demoFiles) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  1473. CCstatus.DemoMode = true;
  1474. }
  1475. bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
  1476. {
  1477. if (data == NULL || length == NULL || m_demoFiles.empty()) return false;
  1478. *data = NULL;
  1479. *length = 0;
  1480. const size_t index = static_cast<size_t>(getCountFlowRounds()) % m_demoFiles.size();
  1481. const std::string filename = "/sdcard/demo/" + m_demoFiles[index];
  1482. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + filename + " as demo image");
  1483. FILE *fp = fopen(filename.c_str(), "rb");
  1484. if (fp == NULL) return false;
  1485. const long fileSize = GetFileSize(filename);
  1486. if (fileSize <= 0 || fileSize > DEMO_IMAGE_SIZE) {
  1487. fclose(fp);
  1488. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image has invalid size: " + std::to_string(fileSize));
  1489. return false;
  1490. }
  1491. uint8_t *buffer = static_cast<uint8_t*>(malloc_psram_heap(
  1492. "Demo image frame", static_cast<size_t>(fileSize), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1493. if (buffer == NULL) {
  1494. fclose(fp);
  1495. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image PSRAM allocation failed");
  1496. return false;
  1497. }
  1498. const size_t readBytes = fread(buffer, 1, static_cast<size_t>(fileSize), fp);
  1499. const bool readOkay = (readBytes == static_cast<size_t>(fileSize)) && (ferror(fp) == 0);
  1500. fclose(fp);
  1501. if (!readOkay) {
  1502. free_psram_heap("Demo image frame (short read)", buffer);
  1503. return false;
  1504. }
  1505. *data = buffer;
  1506. *length = readBytes;
  1507. return true;
  1508. }
  1509. long CCamera::GetFileSize(std::string filename)
  1510. {
  1511. struct stat stat_buf;
  1512. long rc = stat(filename.c_str(), &stat_buf);
  1513. return rc == 0 ? stat_buf.st_size : -1;
  1514. }