ClassControllCamera.cpp 57 KB

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