ClassControllCamera.cpp 57 KB

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