ClassControllCamera.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. #include "ClassControllCamera.h"
  2. #include "ClassLogFile.h"
  3. #include <stdio.h>
  4. #include "driver/gpio.h"
  5. #include "esp_timer.h"
  6. #include "esp_log.h"
  7. #include "Helper.h"
  8. #include "statusled.h"
  9. #include "CImageBasis.h"
  10. #include "psram.h"
  11. #include "server_ota.h"
  12. #include "../../include/defines.h"
  13. #include <esp_event.h>
  14. #include <esp_log.h>
  15. #include <esp_system.h>
  16. #include <nvs_flash.h>
  17. #include <sys/param.h>
  18. #include <string.h>
  19. #include <limits.h>
  20. #include <algorithm>
  21. #include <new>
  22. #include <sys/stat.h>
  23. #include "freertos/FreeRTOS.h"
  24. #include "freertos/task.h"
  25. #include "server_camera.h"
  26. #include "esp_camera.h"
  27. #include "esp_heap_caps.h"
  28. #include "driver/ledc.h"
  29. #include "MainFlowControl.h"
  30. #include "ov2640_sharpness.h"
  31. #include "ov2640_specialEffect.h"
  32. #include "ov2640_contrast_brightness.h"
  33. #if (ESP_IDF_VERSION_MAJOR >= 5)
  34. #include "soc/periph_defs.h"
  35. #include "esp_private/periph_ctrl.h"
  36. #include "soc/gpio_sig_map.h"
  37. #include "soc/gpio_periph.h"
  38. #include "soc/io_mux_reg.h"
  39. #include "esp_rom_gpio.h"
  40. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  41. #define gpio_matrix_in(a, b, c) esp_rom_gpio_connect_in_signal(a, b, c)
  42. #define gpio_matrix_out(a, b, c, d) esp_rom_gpio_connect_out_signal(a, b, c, d)
  43. #define ets_delay_us(a) esp_rom_delay_us(a)
  44. #endif
  45. camera_controll_config_temp_t CCstatus;
  46. CCamera Camera;
  47. static const char *TAG = "CAM";
  48. static int sensorValueOrDefault(int value, int fallback, int minimum, int maximum)
  49. {
  50. return (value < minimum || value > maximum) ? fallback : value;
  51. }
  52. static int sensorBooleanOrDefault(int value, int fallback)
  53. {
  54. return (value == 0 || value == 1) ? value : fallback;
  55. }
  56. static bool isSupportedFrameSize(int value)
  57. {
  58. switch (static_cast<framesize_t>(value))
  59. {
  60. case FRAMESIZE_QVGA:
  61. case FRAMESIZE_VGA:
  62. return true;
  63. default:
  64. return false;
  65. }
  66. }
  67. /* Camera live stream */
  68. #define PART_BOUNDARY "123456789000000000000987654321"
  69. static const char *_STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
  70. static const char *_STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
  71. static const char *_STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
  72. #define DEMO_IMAGE_SIZE 30000 // Max size of demo image in bytes
  73. // Camera module bus communications frequency.
  74. // Originally: config.xclk_freq_mhz = 20000000, but this lead to visual artifacts on many modules.
  75. // See https://github.com/espressif/esp32-camera/issues/150#issuecomment-726473652 et al.
  76. #if !defined(XCLK_FREQ_MHZ)
  77. // int xclk = 8;
  78. int xclk = 20; // Orginal value
  79. #else
  80. int xclk = XCLK_FREQ_MHZ;
  81. #endif
  82. static camera_config_t camera_config = {
  83. .pin_pwdn = CAM_PIN_PWDN,
  84. .pin_reset = CAM_PIN_RESET,
  85. .pin_xclk = CAM_PIN_XCLK,
  86. .pin_sccb_sda = CAM_PIN_SIOD,
  87. .pin_sccb_scl = CAM_PIN_SIOC,
  88. .pin_d7 = CAM_PIN_D7,
  89. .pin_d6 = CAM_PIN_D6,
  90. .pin_d5 = CAM_PIN_D5,
  91. .pin_d4 = CAM_PIN_D4,
  92. .pin_d3 = CAM_PIN_D3,
  93. .pin_d2 = CAM_PIN_D2,
  94. .pin_d1 = CAM_PIN_D1,
  95. .pin_d0 = CAM_PIN_D0,
  96. .pin_vsync = CAM_PIN_VSYNC,
  97. .pin_href = CAM_PIN_HREF,
  98. .pin_pclk = CAM_PIN_PCLK,
  99. .xclk_freq_hz = (xclk * 1000000),
  100. .ledc_timer = LEDC_TIMER_0, // LEDC timer to be used for generating XCLK
  101. .ledc_channel = LEDC_CHANNEL_0, // LEDC channel to be used for generating XCLK
  102. .pixel_format = PIXFORMAT_JPEG, // YUV422,GRAYSCALE,RGB565,JPEG
  103. .frame_size = FRAMESIZE_VGA, // QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  104. // .frame_size = FRAMESIZE_UXGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  105. .jpeg_quality = 12, // 0-63 lower number means higher quality
  106. .fb_count = 1, // if more than one, i2s runs in continuous mode. Use only with JPEG
  107. .fb_location = CAMERA_FB_IN_PSRAM, /*!< The location where the frame buffer will be allocated */
  108. .grab_mode = CAMERA_GRAB_LATEST, // only from new esp32cam version
  109. .sccb_i2c_port = 0, // unused when the SCCB pins are configured above
  110. };
  111. typedef struct
  112. {
  113. httpd_req_t *req;
  114. size_t len;
  115. } jpg_chunking_t;
  116. // The camera driver and sensor register access are not safe to use concurrently.
  117. // Recursive locking allows public methods to safely call other locked methods.
  118. class ScopedCameraLock
  119. {
  120. public:
  121. explicit ScopedCameraLock(SemaphoreHandle_t mutex, TickType_t timeout = pdMS_TO_TICKS(5000))
  122. : m_mutex(mutex),
  123. m_acquired(mutex != NULL && xSemaphoreTakeRecursive(mutex, timeout) == pdTRUE)
  124. {
  125. }
  126. ~ScopedCameraLock()
  127. {
  128. if (m_acquired)
  129. {
  130. xSemaphoreGiveRecursive(m_mutex);
  131. }
  132. }
  133. bool acquired() const { return m_acquired; }
  134. private:
  135. SemaphoreHandle_t m_mutex;
  136. bool m_acquired;
  137. };
  138. // Owns one camera framebuffer and returns it exactly once on every exit path.
  139. class ScopedCameraOperationLock
  140. {
  141. public:
  142. explicit ScopedCameraOperationLock(SemaphoreHandle_t mutex, TickType_t timeout = pdMS_TO_TICKS(5000))
  143. : m_mutex(mutex),
  144. m_acquired(mutex != NULL && xSemaphoreTakeRecursive(mutex, timeout) == pdTRUE)
  145. {
  146. }
  147. ~ScopedCameraOperationLock()
  148. {
  149. if (m_acquired) xSemaphoreGiveRecursive(m_mutex);
  150. }
  151. bool acquired() const { return m_acquired; }
  152. private:
  153. SemaphoreHandle_t m_mutex;
  154. bool m_acquired;
  155. };
  156. // Owns one camera framebuffer and returns it exactly once on every exit path.
  157. class ScopedCameraFrame
  158. {
  159. public:
  160. ScopedCameraFrame(camera_fb_t *frame, SemaphoreHandle_t cameraMutex)
  161. : m_frame(frame), m_cameraMutex(cameraMutex)
  162. {
  163. }
  164. ~ScopedCameraFrame() { release(); }
  165. ScopedCameraFrame(const ScopedCameraFrame &) = delete;
  166. ScopedCameraFrame &operator=(const ScopedCameraFrame &) = delete;
  167. camera_fb_t *get() const { return m_frame; }
  168. void release()
  169. {
  170. if (m_frame == NULL) return;
  171. // Frame return touches camera-driver state and must use the driver lock.
  172. ScopedCameraLock cameraLock(m_cameraMutex, portMAX_DELAY);
  173. if (!cameraLock.acquired())
  174. {
  175. ESP_LOGE(TAG, "Unable to lock camera driver to return framebuffer");
  176. return;
  177. }
  178. esp_camera_fb_return(m_frame);
  179. m_frame = NULL;
  180. }
  181. private:
  182. camera_fb_t *m_frame;
  183. SemaphoreHandle_t m_cameraMutex;
  184. };
  185. class ScopedCameraCaptureIndicators
  186. {
  187. public:
  188. ScopedCameraCaptureIndicators(CCamera &camera, bool statusLed, bool flashLed)
  189. : m_camera(camera), m_statusLed(statusLed), m_flashLed(flashLed)
  190. {
  191. if (m_statusLed) m_camera.SetCaptureStatusLedActive(true);
  192. if (m_flashLed) m_camera.SetCaptureFlashActive(true);
  193. }
  194. ~ScopedCameraCaptureIndicators()
  195. {
  196. if (m_flashLed) m_camera.SetCaptureFlashActive(false);
  197. if (m_statusLed) m_camera.SetCaptureStatusLedActive(false);
  198. }
  199. ScopedCameraCaptureIndicators(const ScopedCameraCaptureIndicators &) = delete;
  200. ScopedCameraCaptureIndicators &operator=(const ScopedCameraCaptureIndicators &) = delete;
  201. private:
  202. CCamera &m_camera;
  203. bool m_statusLed;
  204. bool m_flashLed;
  205. };
  206. CCamera::CCamera(void)
  207. : m_cameraMutex(xSemaphoreCreateRecursiveMutex()),
  208. m_cameraOperationMutex(xSemaphoreCreateRecursiveMutex()),
  209. m_driverInitialized(false),
  210. m_temporarySettingsActive(false),
  211. m_previewCapturePending(false),
  212. m_previewCaptureDelayMs(0),
  213. m_captureFlashUsers(0),
  214. m_captureStatusLedUsers(0),
  215. m_manualFlashOn(false),
  216. m_manualStatusLedOn(false)
  217. {
  218. #ifdef DEBUG_DETAIL_ON
  219. ESP_LOGD(TAG, "CreateClassCamera");
  220. #endif
  221. CCstatus.ImageQuality = camera_config.jpeg_quality;
  222. CCstatus.ImageFrameSize = camera_config.frame_size;
  223. CCstatus.CamXclkFreqMhz = xclk;
  224. CCstatus.ImageLedIntensity = SetLEDIntensity(LedIntensity);
  225. CCstatus.WaitBeforePicture = 2;
  226. SetImageWidthHeightFromResolution(CCstatus);
  227. ledc_init();
  228. }
  229. esp_err_t CCamera::InitCam(void)
  230. {
  231. // Driver teardown/reinitialization must not invalidate a leased framebuffer.
  232. ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
  233. if (!frameLease.acquired()) return ESP_ERR_TIMEOUT;
  234. ScopedCameraLock cameraLock(m_cameraMutex);
  235. if (!cameraLock.acquired())
  236. {
  237. ESP_LOGE(TAG, "InitCam: camera mutex unavailable");
  238. CCstatus.CameraInitSuccessful = false;
  239. return ESP_ERR_NO_MEM;
  240. }
  241. ESP_LOGD(TAG, "Init Camera");
  242. CCstatus.CameraInitSuccessful = false;
  243. // Release an earlier driver instance before resetting and reinitializing.
  244. if (m_driverInitialized)
  245. {
  246. const esp_err_t deinitResult = esp_camera_deinit();
  247. if (deinitResult != ESP_OK)
  248. {
  249. ESP_LOGE(TAG, "Camera deinitialization failed: %s", esp_err_to_name(deinitResult));
  250. return deinitResult;
  251. }
  252. m_driverInitialized = false;
  253. }
  254. PowerResetCamera();
  255. vTaskDelay(pdMS_TO_TICKS(200));
  256. const esp_err_t err = esp_camera_init(&camera_config);
  257. if (err != ESP_OK)
  258. {
  259. ESP_LOGE(TAG, "Camera Init Failed: %s", esp_err_to_name(err));
  260. return err;
  261. }
  262. m_driverInitialized = true;
  263. sensor_t *s = esp_camera_sensor_get();
  264. if (s == NULL)
  265. {
  266. ESP_LOGE(TAG, "Camera sensor handle is unavailable");
  267. }
  268. else
  269. {
  270. CCstatus.CamSensor_id = s->id.PID;
  271. switch (CCstatus.CamSensor_id)
  272. {
  273. case OV2640_PID:
  274. ESP_LOGI(TAG, "OV2640 camera module detected");
  275. CCstatus.CameraInitSuccessful = true;
  276. break;
  277. case OV3660_PID:
  278. ESP_LOGI(TAG, "OV3660 camera module detected");
  279. CCstatus.CameraInitSuccessful = true;
  280. break;
  281. case OV5640_PID:
  282. ESP_LOGI(TAG, "OV5640 camera module detected");
  283. CCstatus.CameraInitSuccessful = true;
  284. break;
  285. default:
  286. ESP_LOGE(TAG, "Camera module is unknown and not properly supported!");
  287. break;
  288. }
  289. }
  290. if (!CCstatus.CameraInitSuccessful)
  291. {
  292. const esp_err_t cleanupResult = esp_camera_deinit();
  293. if (cleanupResult != ESP_OK)
  294. {
  295. ESP_LOGE(TAG, "Failed to clean up unsupported camera: %s", esp_err_to_name(cleanupResult));
  296. }
  297. m_driverInitialized = (cleanupResult != ESP_OK);
  298. return ESP_FAIL;
  299. }
  300. return ESP_OK;
  301. }
  302. bool CCamera::testCamera(void)
  303. {
  304. ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
  305. if (!frameLease.acquired()) return false;
  306. ScopedCameraLock cameraLock(m_cameraMutex);
  307. if (!cameraLock.acquired())
  308. {
  309. ESP_LOGW(TAG, "testCamera: camera mutex unavailable");
  310. return false;
  311. }
  312. ScopedCameraFrame frame(esp_camera_fb_get(), m_cameraMutex);
  313. if (frame.get() == NULL)
  314. {
  315. ESP_LOGW(TAG, "testCamera: framebuffer capture failed");
  316. return false;
  317. }
  318. return true;
  319. }
  320. void CCamera::ledc_init(void)
  321. {
  322. #ifdef USE_PWM_LEDFLASH
  323. // Prepare and then apply the LEDC PWM timer configuration
  324. ledc_timer_config_t ledc_timer = {};
  325. ledc_timer.speed_mode = LEDC_MODE;
  326. ledc_timer.timer_num = LEDC_TIMER;
  327. ledc_timer.duty_resolution = LEDC_DUTY_RES;
  328. ledc_timer.freq_hz = LEDC_FREQUENCY; // Set output frequency at 5 kHz
  329. ledc_timer.clk_cfg = LEDC_AUTO_CLK;
  330. ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
  331. // Prepare and then apply the LEDC PWM channel configuration
  332. ledc_channel_config_t ledc_channel = {};
  333. ledc_channel.speed_mode = LEDC_MODE;
  334. ledc_channel.channel = LEDC_CHANNEL;
  335. ledc_channel.timer_sel = LEDC_TIMER;
  336. ledc_channel.intr_type = LEDC_INTR_DISABLE;
  337. ledc_channel.gpio_num = LEDC_OUTPUT_IO;
  338. ledc_channel.duty = 0; // Set duty to 0%
  339. ledc_channel.hpoint = 0;
  340. // ledc_channel.flags.output_invert = LEDC_OUTPUT_INVERT;
  341. ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
  342. #endif
  343. }
  344. int CCamera::SetLEDIntensity(int _intrel)
  345. {
  346. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  347. if (!operationLock.acquired()) return LedIntensity;
  348. ScopedCameraLock cameraLock(m_cameraMutex);
  349. if (!cameraLock.acquired()) return LedIntensity;
  350. LedIntensity = static_cast<int>(
  351. static_cast<float>(std::min(std::max(0, _intrel), 100)) / 100.0f * 8191.0f);
  352. UpdateFlashOutputLocked();
  353. ESP_LOGD(TAG, "Set led_intensity to %i of 8191", LedIntensity);
  354. return LedIntensity;
  355. }
  356. bool CCamera::getCameraInitSuccessful(void)
  357. {
  358. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  359. if (!operationLock.acquired()) return false;
  360. ScopedCameraLock cameraLock(m_cameraMutex);
  361. return cameraLock.acquired() && CCstatus.CameraInitSuccessful;
  362. }
  363. esp_err_t CCamera::setSensorDatenFromCCstatus(void)
  364. {
  365. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  366. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  367. ScopedCameraLock cameraLock(m_cameraMutex);
  368. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  369. const esp_err_t result = ApplySettings(CCstatus);
  370. if (result == ESP_OK)
  371. {
  372. m_temporarySettingsActive = false;
  373. m_previewCapturePending = false;
  374. m_previewCaptureDelayMs = 0;
  375. }
  376. return result;
  377. }
  378. esp_err_t CCamera::ApplySettings(CameraSettings &settings)
  379. {
  380. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  381. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  382. ScopedCameraLock cameraLock(m_cameraMutex);
  383. if (!cameraLock.acquired())
  384. {
  385. ESP_LOGW(TAG, "ApplySettings: camera mutex unavailable");
  386. return ESP_ERR_TIMEOUT;
  387. }
  388. if (!m_driverInitialized)
  389. {
  390. ESP_LOGW(TAG, "ApplySettings: camera driver is not initialized");
  391. return ESP_ERR_INVALID_STATE;
  392. }
  393. sensor_t *s = esp_camera_sensor_get();
  394. if (s == NULL)
  395. {
  396. ESP_LOGE(TAG, "ApplySettings: camera sensor unavailable");
  397. return ESP_FAIL;
  398. }
  399. if (settings.CamXclkFreqMhz < 1 || settings.CamXclkFreqMhz > 20)
  400. {
  401. settings.CamXclkFreqMhz = xclk;
  402. }
  403. SetImageWidthHeightFromResolution(settings);
  404. int firstError = s->set_xclk(s, camera_config.ledc_timer, settings.CamXclkFreqMhz);
  405. const auto recordError = [&firstError](int result)
  406. {
  407. if (firstError == 0 && result != 0) firstError = result;
  408. };
  409. recordError(s->set_framesize(s, settings.ImageFrameSize));
  410. SetCamContrastBrightness(s, settings.ImageContrast, settings.ImageBrightness);
  411. recordError(s->set_saturation(s, settings.ImageSaturation));
  412. recordError(s->set_quality(s, settings.ImageQuality));
  413. recordError(SetCamGainceiling(s, settings.ImageGainceiling));
  414. recordError(s->set_gain_ctrl(s, settings.ImageAgc));
  415. recordError(s->set_exposure_ctrl(s, settings.ImageAec));
  416. recordError(s->set_hmirror(s, settings.ImageHmirror));
  417. recordError(s->set_vflip(s, settings.ImageVflip));
  418. recordError(s->set_whitebal(s, settings.ImageAwb));
  419. recordError(s->set_aec2(s, settings.ImageAec2));
  420. recordError(s->set_aec_value(s, settings.ImageAecValue));
  421. SetCamSpecialEffect(s, settings.ImageSpecialEffect);
  422. recordError(s->set_wb_mode(s, settings.ImageWbMode));
  423. recordError(s->set_ae_level(s, settings.ImageAeLevel));
  424. recordError(s->set_dcw(s, settings.ImageDcw));
  425. recordError(s->set_bpc(s, settings.ImageBpc));
  426. recordError(s->set_wpc(s, settings.ImageWpc));
  427. recordError(s->set_awb_gain(s, settings.ImageAwbGain));
  428. recordError(s->set_agc_gain(s, settings.ImageAgcGain));
  429. recordError(s->set_raw_gma(s, settings.ImageRawGma));
  430. recordError(s->set_lenc(s, settings.ImageLenc));
  431. SetCamSharpness(settings.ImageAutoSharpness, settings.ImageSharpness);
  432. // The OV2640 driver does not implement denoise control and its set_denoise()
  433. // callback always returns -1, even when the requested level is zero. Treat
  434. // this unsupported optional control as a no-op instead of aborting camera setup.
  435. if (s->id.PID != OV2640_PID)
  436. {
  437. recordError(s->set_denoise(s, settings.ImageDenoiseLevel));
  438. }
  439. const esp_err_t geometryResult = SetQualityZoomSize(settings);
  440. if (geometryResult != ESP_OK) return geometryResult;
  441. LedIntensity = min(8191, max(0, settings.ImageLedIntensity));
  442. vTaskDelay(pdMS_TO_TICKS(100));
  443. return firstError == 0 ? ESP_OK : ESP_FAIL;
  444. }
  445. esp_err_t CCamera::ApplyPreviewSettings(const CameraSettings &settings)
  446. {
  447. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  448. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  449. ScopedCameraLock cameraLock(m_cameraMutex);
  450. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  451. CameraSettings previewSettings = settings;
  452. // Mark the hardware as temporary before applying: ApplySettings may fail after
  453. // changing some sensor registers, so the next normal operation must still restore CCstatus.
  454. m_temporarySettingsActive = true;
  455. const esp_err_t result = ApplySettings(previewSettings);
  456. if (result == ESP_OK)
  457. {
  458. m_previewCapturePending = true;
  459. const int waitSeconds = std::max(0, settings.WaitBeforePicture);
  460. m_previewCaptureDelayMs = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
  461. }
  462. else
  463. {
  464. m_previewCapturePending = false;
  465. m_previewCaptureDelayMs = 0;
  466. }
  467. return result;
  468. }
  469. esp_err_t CCamera::RestoreCommittedSettingsIfNeeded(void)
  470. {
  471. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  472. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  473. ScopedCameraLock cameraLock(m_cameraMutex);
  474. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  475. if (!m_temporarySettingsActive) return ESP_OK;
  476. const esp_err_t result = ApplySettings(CCstatus);
  477. if (result == ESP_OK)
  478. {
  479. m_temporarySettingsActive = false;
  480. m_previewCapturePending = false;
  481. m_previewCaptureDelayMs = 0;
  482. }
  483. return result;
  484. }
  485. esp_err_t CCamera::getSensorDatenToCCstatus(void)
  486. {
  487. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  488. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  489. ScopedCameraLock cameraLock(m_cameraMutex);
  490. if (!cameraLock.acquired())
  491. {
  492. ESP_LOGW(TAG, "getSensorDatenToCCstatus: camera mutex unavailable");
  493. return ESP_ERR_TIMEOUT;
  494. }
  495. sensor_t *s = esp_camera_sensor_get();
  496. if (s == NULL)
  497. {
  498. ESP_LOGE(TAG, "getSensorDatenToCCstatus: camera sensor unavailable");
  499. return ESP_FAIL;
  500. }
  501. CCstatus.CamSensor_id = s->id.PID;
  502. const int frameSize = static_cast<int>(s->status.framesize);
  503. CCstatus.ImageFrameSize = static_cast<framesize_t>(
  504. isSupportedFrameSize(frameSize) ? frameSize : static_cast<int>(FRAMESIZE_VGA));
  505. CCstatus.CamXclkFreqMhz = sensorValueOrDefault(
  506. static_cast<int>(s->xclk_freq_hz / 1000000U), xclk, 1, 20);
  507. CCstatus.ImageContrast = sensorValueOrDefault(s->status.contrast, 0, -2, 2);
  508. CCstatus.ImageBrightness = sensorValueOrDefault(s->status.brightness, 0, -2, 2);
  509. CCstatus.ImageSaturation = sensorValueOrDefault(s->status.saturation, 0, -2, 2);
  510. CCstatus.ImageQuality = sensorValueOrDefault(s->status.quality, 12, 6, 63);
  511. CCstatus.ImageGainceiling = static_cast<gainceiling_t>(
  512. sensorValueOrDefault(static_cast<int>(s->status.gainceiling), 0, 0, 6));
  513. CCstatus.ImageAgc = sensorBooleanOrDefault(s->status.agc, 1);
  514. CCstatus.ImageAec = sensorBooleanOrDefault(s->status.aec, 1);
  515. CCstatus.ImageHmirror = sensorBooleanOrDefault(s->status.hmirror, 0);
  516. CCstatus.ImageVflip = sensorBooleanOrDefault(s->status.vflip, 0);
  517. CCstatus.ImageAwb = sensorBooleanOrDefault(s->status.awb, 1);
  518. CCstatus.ImageAec2 = sensorBooleanOrDefault(s->status.aec2, 1);
  519. CCstatus.ImageAecValue = sensorValueOrDefault(s->status.aec_value, 600, 0, 1200);
  520. CCstatus.ImageSpecialEffect = sensorValueOrDefault(s->status.special_effect, 0, 0, 6);
  521. CCstatus.ImageWbMode = sensorValueOrDefault(s->status.wb_mode, 0, 0, 4);
  522. CCstatus.ImageAeLevel = (CCstatus.CamSensor_id == OV2640_PID)
  523. ? sensorValueOrDefault(s->status.ae_level, 0, -2, 2)
  524. : sensorValueOrDefault(s->status.ae_level, 0, -5, 5);
  525. CCstatus.ImageDcw = sensorBooleanOrDefault(s->status.dcw, 1);
  526. CCstatus.ImageBpc = sensorBooleanOrDefault(s->status.bpc, 1);
  527. CCstatus.ImageWpc = sensorBooleanOrDefault(s->status.wpc, 1);
  528. CCstatus.ImageAwbGain = sensorBooleanOrDefault(s->status.awb_gain, 1);
  529. CCstatus.ImageAgcGain = sensorValueOrDefault(s->status.agc_gain, 8, 0, 30);
  530. CCstatus.ImageRawGma = sensorBooleanOrDefault(s->status.raw_gma, 1);
  531. CCstatus.ImageLenc = sensorBooleanOrDefault(s->status.lenc, 1);
  532. CCstatus.ImageSharpness = (CCstatus.CamSensor_id == OV2640_PID)
  533. ? sensorValueOrDefault(s->status.sharpness, 0, -2, 2)
  534. : sensorValueOrDefault(s->status.sharpness, 0, -3, 3);
  535. CCstatus.ImageDenoiseLevel = (CCstatus.CamSensor_id == OV2640_PID)
  536. ? 0 : sensorValueOrDefault(s->status.denoise, 0, 0, 8);
  537. CCstatus.ImageLedIntensity = min(8191, max(0, LedIntensity));
  538. SetImageWidthHeightFromResolution(CCstatus);
  539. return ESP_OK;
  540. }
  541. // on the OV5640, gainceiling must be set with the real value (x2>>>gainceilingLevel = 2, .... x128>>>gainceilingLevel = 128)
  542. int CCamera::SetCamGainceiling(sensor_t *s, gainceiling_t gainceilingLevel)
  543. {
  544. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  545. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  546. ScopedCameraLock cameraLock(m_cameraMutex);
  547. if (!cameraLock.acquired())
  548. {
  549. ESP_LOGW(TAG, "SetCamGainceiling: camera mutex unavailable");
  550. return ESP_ERR_TIMEOUT;
  551. }
  552. if (s == NULL) return ESP_ERR_INVALID_ARG;
  553. if (s->id.PID == OV2640_PID)
  554. {
  555. return s->set_gainceiling(s, gainceilingLevel);
  556. }
  557. const int level = (1 << (static_cast<int>(gainceilingLevel) + 1));
  558. const int highResult = s->set_reg(s, 0x3A18, 0xFF, (level >> 8) & 3);
  559. const int lowResult = s->set_reg(s, 0x3A19, 0xFF, level & 0xFF);
  560. const int result = highResult != 0 ? highResult : lowResult;
  561. if (result == 0) s->status.gainceiling = gainceilingLevel;
  562. return result;
  563. }
  564. void CCamera::SetCamSharpness(bool autoSharpnessEnabled, int sharpnessLevel)
  565. {
  566. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  567. if (!operationLock.acquired()) return;
  568. ScopedCameraLock cameraLock(m_cameraMutex);
  569. if (!cameraLock.acquired())
  570. {
  571. ESP_LOGW(TAG, "SetCamSharpness: camera mutex unavailable");
  572. return;
  573. }
  574. sensor_t *s = esp_camera_sensor_get();
  575. if (s != NULL)
  576. {
  577. if (s->id.PID == OV2640_PID)
  578. {
  579. sharpnessLevel = min(2, max(-2, sharpnessLevel));
  580. // The OV2640 does not officially support sharpness, so the detour is made with the ov2640_sharpness.cpp.
  581. if (autoSharpnessEnabled)
  582. {
  583. ov2640_enable_auto_sharpness(s);
  584. }
  585. else
  586. {
  587. ov2640_set_sharpness(s, sharpnessLevel);
  588. }
  589. }
  590. else
  591. {
  592. sharpnessLevel = min(3, max(-3, sharpnessLevel));
  593. // for CAMERA_OV5640 and CAMERA_OV3660
  594. if (autoSharpnessEnabled)
  595. {
  596. // autoSharpness is not supported, default to zero
  597. s->set_sharpness(s, 0);
  598. }
  599. else
  600. {
  601. s->set_sharpness(s, sharpnessLevel);
  602. }
  603. }
  604. }
  605. else
  606. {
  607. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetCamSharpness, Failed to get Cam control structure");
  608. }
  609. }
  610. void CCamera::SetCamSpecialEffect(sensor_t *s, int specialEffect)
  611. {
  612. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  613. if (!operationLock.acquired()) return;
  614. ScopedCameraLock cameraLock(m_cameraMutex);
  615. if (!cameraLock.acquired())
  616. {
  617. ESP_LOGW(TAG, "SetCamSpecialEffect: camera mutex unavailable");
  618. return;
  619. }
  620. if (s == NULL) return;
  621. if (s->id.PID == OV2640_PID)
  622. {
  623. ov2640_set_special_effect(s, specialEffect);
  624. }
  625. else
  626. {
  627. s->set_special_effect(s, specialEffect);
  628. }
  629. }
  630. void CCamera::SetCamContrastBrightness(sensor_t *s, int _contrast, int _brightness)
  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, "SetCamContrastBrightness: camera mutex unavailable");
  638. return;
  639. }
  640. if (s == NULL) return;
  641. if (s->id.PID == OV2640_PID)
  642. {
  643. ov2640_set_contrast_brightness(s, _contrast, _brightness);
  644. }
  645. else
  646. {
  647. s->set_contrast(s, _contrast); // -2 to 2
  648. s->set_brightness(s, _brightness); // -2 to 2
  649. }
  650. }
  651. // - It always zooms to the image center when offsets are zero
  652. // - if imageSize = 0 then the image is not zoomed
  653. // - if imageSize = max value, then the image is fully zoomed in
  654. // - a zoom step is >>> Width + 32 px / Height + 24 px
  655. void CCamera::SanitizeZoomParams(const CameraSettings &settings, int imageSize,
  656. int frameSizeX, int frameSizeY, int &imageWidth, int &imageHeight,
  657. int &zoomOffsetX, int &zoomOffsetY)
  658. {
  659. imageWidth = min(frameSizeX, max(1, settings.ImageWidth + imageSize * 32));
  660. imageHeight = min(frameSizeY, max(1, settings.ImageHeight + imageSize * 24));
  661. const int availableX = max(0, frameSizeX - imageWidth);
  662. const int availableY = max(0, frameSizeY - imageHeight);
  663. const int halfX = availableX / 2;
  664. const int halfY = availableY / 2;
  665. zoomOffsetX = halfX + min(halfX, max(-halfX, zoomOffsetX));
  666. zoomOffsetY = halfY + min(halfY, max(-halfY, zoomOffsetY));
  667. }
  668. esp_err_t CCamera::SetZoomSize(const CameraSettings &settings)
  669. {
  670. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  671. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  672. ScopedCameraLock cameraLock(m_cameraMutex);
  673. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  674. sensor_t *s = esp_camera_sensor_get();
  675. if (s == NULL) return ESP_FAIL;
  676. // The ESP32 pipeline is deliberately limited to VGA output. Sensor-side
  677. // windowing below performs zoom/cropping without creating larger RAM frames.
  678. CameraSettings outputSettings = settings;
  679. SetImageWidthHeightFromResolution(outputSettings);
  680. if (!outputSettings.ImageZoomEnabled)
  681. {
  682. return s->set_framesize(s, outputSettings.ImageFrameSize) == 0 ? ESP_OK : ESP_FAIL;
  683. }
  684. int frameSizeX = 0;
  685. int frameSizeY = 0;
  686. int maxZoom = 0;
  687. switch (s->id.PID)
  688. {
  689. case OV5640_PID:
  690. frameSizeX = 2592;
  691. frameSizeY = 1944;
  692. maxZoom = 59;
  693. break;
  694. case OV3660_PID:
  695. frameSizeX = 2048;
  696. frameSizeY = 1536;
  697. maxZoom = 43;
  698. break;
  699. case OV2640_PID:
  700. frameSizeX = 1600;
  701. frameSizeY = 1200;
  702. maxZoom = 29;
  703. break;
  704. default:
  705. ESP_LOGE(TAG, "SetZoomSize: unsupported sensor PID 0x%04x", s->id.PID);
  706. return ESP_ERR_NOT_SUPPORTED;
  707. }
  708. const int zoomSize = min(maxZoom, max(0, outputSettings.ImageZoomSize));
  709. const int zoomDelta = maxZoom - zoomSize;
  710. int imageWidth = outputSettings.ImageWidth;
  711. int imageHeight = outputSettings.ImageHeight;
  712. int offsetX = outputSettings.ImageZoomOffsetX;
  713. int offsetY = outputSettings.ImageZoomOffsetY;
  714. SanitizeZoomParams(outputSettings, zoomDelta, frameSizeX, frameSizeY,
  715. imageWidth, imageHeight, offsetX, offsetY);
  716. SetCamWindow(s, frameSizeX, frameSizeY, offsetX, offsetY,
  717. imageWidth, imageHeight, outputSettings.ImageWidth, outputSettings.ImageHeight,
  718. outputSettings.ImageVflip);
  719. return ESP_OK;
  720. }
  721. esp_err_t CCamera::SetQualityZoomSize(CameraSettings &settings)
  722. {
  723. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  724. if (!operationLock.acquired()) return ESP_ERR_TIMEOUT;
  725. ScopedCameraLock cameraLock(m_cameraMutex);
  726. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  727. sensor_t *s = esp_camera_sensor_get();
  728. if (s == NULL) return ESP_FAIL;
  729. SetImageWidthHeightFromResolution(settings);
  730. int quality = settings.ImageQuality;
  731. if (s->id.PID != OV2640_PID)
  732. {
  733. quality = min(63, max(8, quality));
  734. }
  735. settings.ImageQuality = quality;
  736. const int result = s->set_quality(s, quality);
  737. if (result != 0) return ESP_FAIL;
  738. return SetZoomSize(settings);
  739. }
  740. void CCamera::SetCamWindow(sensor_t *s, int frameSizeX, int frameSizeY, int xOffset, int yOffset, int xTotal, int yTotal, int xOutput, int yOutput, int imageVflip)
  741. {
  742. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  743. if (!operationLock.acquired()) return;
  744. ScopedCameraLock cameraLock(m_cameraMutex);
  745. if (!cameraLock.acquired())
  746. {
  747. ESP_LOGW(TAG, "SetCamWindow: camera mutex unavailable");
  748. return;
  749. }
  750. if (s == NULL) return;
  751. if (s->id.PID == OV2640_PID)
  752. {
  753. s->set_res_raw(s, 0, 0, 0, 0, xOffset, yOffset, xTotal, yTotal, xOutput, yOutput, false, false);
  754. }
  755. else
  756. {
  757. // for CAMERA_OV5640 and CAMERA_OV3660
  758. bool scale = !(xOutput == xTotal && yOutput == yTotal);
  759. bool binning = (xTotal >= (frameSizeX >> 1));
  760. if (imageVflip == true)
  761. {
  762. s->set_res_raw(s, xOffset, yOffset, xOffset + xTotal - 1, yOffset + yTotal - 1, 0, 0, frameSizeX, frameSizeY, xOutput, yOutput, scale, binning);
  763. }
  764. else
  765. {
  766. s->set_res_raw(s, xOffset, yOffset, xOffset + xTotal, yOffset + yTotal, 0, 0, frameSizeX, frameSizeY, xOutput, yOutput, scale, binning);
  767. }
  768. }
  769. }
  770. static size_t jpg_encode_stream(void *arg, size_t index, const void *data, size_t len)
  771. {
  772. jpg_chunking_t *j = (jpg_chunking_t *)arg;
  773. if (!index)
  774. {
  775. j->len = 0;
  776. }
  777. if (httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK)
  778. {
  779. return 0;
  780. }
  781. j->len += len;
  782. return len;
  783. }
  784. esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
  785. {
  786. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  787. if (!operationLock.acquired())
  788. {
  789. ESP_LOGW(TAG, "CaptureToBasisImage: camera operation lock unavailable");
  790. return ESP_ERR_TIMEOUT;
  791. }
  792. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  793. if (restoreResult != ESP_OK) return restoreResult;
  794. if (_Image == NULL || !_Image->ImageOkay())
  795. {
  796. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: target image is unavailable");
  797. return ESP_FAIL;
  798. }
  799. #ifdef DEBUG_DETAIL_ON
  800. LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
  801. #endif
  802. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  803. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  804. camera_fb_t *fb = NULL;
  805. {
  806. ScopedCameraLock cameraLock(m_cameraMutex);
  807. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  808. {
  809. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  810. }
  811. fb = esp_camera_fb_get();
  812. }
  813. if (fb == NULL)
  814. {
  815. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: camera capture failed");
  816. return ESP_FAIL;
  817. }
  818. ScopedCameraFrame frame(fb, m_cameraMutex);
  819. uint8_t *frameData = fb->buf;
  820. size_t frameLength = fb->len;
  821. uint8_t *demoData = NULL;
  822. bool demoBufferAllocated = false;
  823. if (CCstatus.DemoMode)
  824. {
  825. if (!loadNextDemoImage(&demoData, &frameLength))
  826. {
  827. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: could not load demo image");
  828. return ESP_FAIL;
  829. }
  830. frameData = demoData;
  831. demoBufferAllocated = true;
  832. }
  833. CImageBasis *tmpImage = new (std::nothrow) CImageBasis("tmpImage");
  834. const bool decoded = tmpImage != NULL &&
  835. frameLength <= static_cast<size_t>(INT_MAX) &&
  836. tmpImage->LoadFromMemory(frameData, static_cast<int>(frameLength));
  837. if (demoBufferAllocated) free_psram_heap("Demo image frame", demoData);
  838. frame.release();
  839. if (!decoded || tmpImage == NULL || !tmpImage->ImageOkay())
  840. {
  841. delete tmpImage;
  842. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: JPEG decode failed");
  843. LogFile.WriteHeapInfo("CaptureToBasisImage decode");
  844. return ESP_FAIL;
  845. }
  846. if (_Image->width != tmpImage->width || _Image->height != tmpImage->height ||
  847. _Image->channels != tmpImage->channels || tmpImage->channels != 3 ||
  848. tmpImage->width <= 0 || tmpImage->height <= 0 ||
  849. static_cast<size_t>(tmpImage->width) > SIZE_MAX / static_cast<size_t>(tmpImage->height) ||
  850. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) > SIZE_MAX / 3U)
  851. {
  852. delete tmpImage;
  853. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded dimensions do not match target image");
  854. return ESP_FAIL;
  855. }
  856. const size_t expectedBytes =
  857. static_cast<size_t>(tmpImage->width) * static_cast<size_t>(tmpImage->height) * 3U;
  858. if (expectedBytes > static_cast<size_t>(INT_MAX))
  859. {
  860. delete tmpImage;
  861. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image is too large");
  862. return ESP_FAIL;
  863. }
  864. uint8_t *source = tmpImage->RGBImageLock();
  865. if (source == NULL)
  866. {
  867. delete tmpImage;
  868. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: decoded image lock failed");
  869. return ESP_FAIL;
  870. }
  871. const bool copied = _Image->CopyFromMemory(source, static_cast<int>(expectedBytes));
  872. tmpImage->RGBImageRelease();
  873. delete tmpImage;
  874. #ifdef DEBUG_DETAIL_ON
  875. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  876. #endif
  877. return copied ? ESP_OK : ESP_FAIL;
  878. }
  879. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  880. {
  881. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  882. if (!operationLock.acquired())
  883. {
  884. ESP_LOGW(TAG, "CaptureToFile: camera operation lock unavailable");
  885. return ESP_ERR_TIMEOUT;
  886. }
  887. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  888. if (restoreResult != ESP_OK) return restoreResult;
  889. const CameraSettings captureSettings = static_cast<const CameraSettings &>(CCstatus);
  890. ScopedCameraCaptureIndicators indicators(*this, true, delay > 0);
  891. if (delay > 0) vTaskDelay(pdMS_TO_TICKS(delay));
  892. camera_fb_t *fb = NULL;
  893. {
  894. ScopedCameraLock cameraLock(m_cameraMutex);
  895. if (!cameraLock.acquired()) return ESP_ERR_TIMEOUT;
  896. {
  897. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  898. }
  899. fb = esp_camera_fb_get();
  900. }
  901. if (fb == NULL)
  902. {
  903. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  904. "Check camera module and/or proper electrical connection");
  905. return ESP_FAIL;
  906. }
  907. ScopedCameraFrame frame(fb, m_cameraMutex);
  908. #ifdef DEBUG_DETAIL_ON
  909. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  910. #endif
  911. nm = FormatFileName(nm);
  912. #ifdef DEBUG_DETAIL_ON
  913. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  914. #endif
  915. const string fileType = toUpper(getFileType(nm));
  916. uint8_t *buffer = NULL;
  917. size_t bufferLength = 0;
  918. bool bufferNeedsFree = false;
  919. bool captureOkay = false;
  920. if (fileType == "BMP")
  921. {
  922. bufferNeedsFree = true;
  923. captureOkay = frame2bmp(fb, &buffer, &bufferLength) &&
  924. buffer != NULL && bufferLength > 0;
  925. }
  926. else if (fileType == "JPG")
  927. {
  928. if (fb->format == PIXFORMAT_JPEG)
  929. {
  930. buffer = fb->buf;
  931. bufferLength = fb->len;
  932. captureOkay = buffer != NULL && bufferLength > 0;
  933. }
  934. else
  935. {
  936. bufferNeedsFree = true;
  937. captureOkay = frame2jpg(fb, captureSettings.ImageQuality, &buffer, &bufferLength) &&
  938. buffer != NULL && bufferLength > 0;
  939. if (!captureOkay) ESP_LOGE(TAG, "JPEG compression failed");
  940. }
  941. }
  942. if (captureOkay)
  943. {
  944. FILE *fp = fopen(nm.c_str(), "wb");
  945. if (fp == NULL)
  946. {
  947. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  948. captureOkay = false;
  949. }
  950. else
  951. {
  952. const size_t written = fwrite(buffer, 1, bufferLength, fp);
  953. const int closeResult = fclose(fp);
  954. if (written != bufferLength || closeResult != 0)
  955. {
  956. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: incomplete write to " + nm);
  957. captureOkay = false;
  958. }
  959. }
  960. }
  961. else
  962. {
  963. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: unsupported image format or conversion failed");
  964. }
  965. if (bufferNeedsFree && buffer != NULL) free(buffer);
  966. // Return the frame under the short driver lock; SD access above does not
  967. // need to hold that lock.
  968. frame.release();
  969. return captureOkay ? ESP_OK : ESP_FAIL;
  970. }
  971. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay, bool previewCapture)
  972. {
  973. ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
  974. if (!frameLease.acquired()) return ESP_ERR_TIMEOUT;
  975. ScopedCameraLock cameraLock(m_cameraMutex);
  976. if (!cameraLock.acquired())
  977. {
  978. ESP_LOGW(TAG, "CaptureToHTTP: camera mutex unavailable");
  979. httpd_resp_set_status(req, "503 Service Unavailable");
  980. httpd_resp_send(req, "Camera is busy", HTTPD_RESP_USE_STRLEN);
  981. return ESP_ERR_TIMEOUT;
  982. }
  983. const bool useTemporaryPreview = previewCapture && m_temporarySettingsActive && m_previewCapturePending;
  984. if (useTemporaryPreview)
  985. {
  986. delay = m_previewCaptureDelayMs;
  987. }
  988. else
  989. {
  990. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  991. if (restoreResult != ESP_OK) return restoreResult;
  992. if (previewCapture)
  993. {
  994. const int waitSeconds = std::max(0, CCstatus.WaitBeforePicture);
  995. delay = waitSeconds > INT_MAX / 1000 ? INT_MAX : waitSeconds * 1000;
  996. }
  997. }
  998. esp_err_t res = ESP_OK;
  999. size_t fb_len = 0;
  1000. int64_t fr_start = esp_timer_get_time();
  1001. LEDOnOff(true); // Status-LED on
  1002. if (delay > 0)
  1003. {
  1004. LightOnOff(true); // Flash-LED on
  1005. vTaskDelay(pdMS_TO_TICKS(delay));
  1006. }
  1007. {
  1008. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1009. }
  1010. camera_fb_t *fb = esp_camera_fb_get();
  1011. if (!fb)
  1012. {
  1013. LEDOnOff(false); // Status-LED off
  1014. LightOnOff(false); // Flash-LED off
  1015. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  1016. "Check camera module and/or proper electrical connection");
  1017. httpd_resp_send_500(req);
  1018. // doReboot();
  1019. return ESP_FAIL;
  1020. }
  1021. ScopedCameraFrame frame(fb, m_cameraMutex);
  1022. LEDOnOff(false); // Status-LED off
  1023. res = httpd_resp_set_type(req, "image/jpeg");
  1024. if (res == ESP_OK)
  1025. {
  1026. res = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  1027. }
  1028. if (res == ESP_OK)
  1029. {
  1030. if (CCstatus.DemoMode)
  1031. {
  1032. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  1033. uint8_t *demoData = NULL;
  1034. size_t demoLength = 0;
  1035. if (loadNextDemoImage(&demoData, &demoLength)) {
  1036. fb_len = demoLength;
  1037. res = httpd_resp_send(req, (const char *)demoData, demoLength);
  1038. free_psram_heap("Demo image HTTP frame", demoData);
  1039. } else {
  1040. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToHTTP: could not load demo image");
  1041. res = ESP_FAIL;
  1042. }
  1043. }
  1044. else
  1045. {
  1046. if (fb->format == PIXFORMAT_JPEG)
  1047. {
  1048. fb_len = fb->len;
  1049. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  1050. }
  1051. else
  1052. {
  1053. jpg_chunking_t jchunk = {req, 0};
  1054. res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk) ? ESP_OK : ESP_FAIL;
  1055. if (res == ESP_OK)
  1056. {
  1057. res = httpd_resp_send_chunk(req, NULL, 0);
  1058. }
  1059. fb_len = jchunk.len;
  1060. }
  1061. }
  1062. }
  1063. frame.release();
  1064. if (res == ESP_OK && useTemporaryPreview) m_previewCapturePending = false;
  1065. int64_t fr_end = esp_timer_get_time();
  1066. ESP_LOGI(TAG, "JPG: %dKB %dms", (int)(fb_len / 1024), (int)((fr_end - fr_start) / 1000));
  1067. if (delay > 0)
  1068. {
  1069. LightOnOff(false); // Flash-LED off
  1070. }
  1071. return res;
  1072. }
  1073. esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
  1074. {
  1075. esp_err_t res = ESP_OK;
  1076. size_t fb_len = 0;
  1077. int64_t fr_start = 0;
  1078. char part_buf[64];
  1079. {
  1080. ScopedCameraLock settingsLock(m_cameraMutex);
  1081. if (!settingsLock.acquired()) return ESP_ERR_TIMEOUT;
  1082. const esp_err_t restoreResult = RestoreCommittedSettingsIfNeeded();
  1083. if (restoreResult != ESP_OK) return restoreResult;
  1084. }
  1085. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
  1086. if (FlashlightOn)
  1087. {
  1088. LEDOnOff(true);
  1089. LightOnOff(true);
  1090. }
  1091. res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  1092. if (res == ESP_OK)
  1093. {
  1094. res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1095. }
  1096. // Discard one initial frame so that exposure and white balance can settle.
  1097. if (res == ESP_OK)
  1098. {
  1099. ScopedCameraOperationLock warmupLease(m_cameraOperationMutex);
  1100. if (!warmupLease.acquired())
  1101. {
  1102. res = ESP_ERR_TIMEOUT;
  1103. }
  1104. else
  1105. {
  1106. ScopedCameraLock warmupLock(m_cameraMutex);
  1107. if (!warmupLock.acquired())
  1108. {
  1109. res = ESP_ERR_TIMEOUT;
  1110. }
  1111. else
  1112. {
  1113. ScopedCameraFrame warmupFrame(esp_camera_fb_get(), m_cameraMutex);
  1114. }
  1115. }
  1116. }
  1117. while (res == ESP_OK)
  1118. {
  1119. fr_start = esp_timer_get_time();
  1120. ScopedCameraOperationLock frameLease(m_cameraOperationMutex);
  1121. if (!frameLease.acquired())
  1122. {
  1123. res = ESP_ERR_TIMEOUT;
  1124. }
  1125. else
  1126. {
  1127. ScopedCameraFrame frame;
  1128. {
  1129. // Only serialize access to the camera driver while acquiring the frame.
  1130. // Keep the framebuffer lease, not the driver mutex, during network I/O.
  1131. ScopedCameraLock frameLock(m_cameraMutex);
  1132. if (!frameLock.acquired())
  1133. {
  1134. res = ESP_ERR_TIMEOUT;
  1135. }
  1136. else
  1137. {
  1138. frame.set(esp_camera_fb_get());
  1139. if (frame.get() == NULL)
  1140. {
  1141. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
  1142. res = ESP_FAIL;
  1143. }
  1144. }
  1145. }
  1146. if (res == ESP_OK)
  1147. {
  1148. camera_fb_t *fb = frame.get();
  1149. fb_len = fb->len;
  1150. const int headerLength = snprintf(part_buf, sizeof(part_buf), _STREAM_PART,
  1151. static_cast<unsigned int>(fb_len));
  1152. if (headerLength < 0 || static_cast<size_t>(headerLength) >= sizeof(part_buf))
  1153. {
  1154. res = ESP_FAIL;
  1155. }
  1156. else
  1157. {
  1158. res = httpd_resp_send_chunk(req, part_buf, static_cast<size_t>(headerLength));
  1159. }
  1160. if (res == ESP_OK) res = httpd_resp_send_chunk(req, (const char *)fb->buf, fb_len);
  1161. if (res == ESP_OK) res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  1162. }
  1163. }
  1164. if (res != ESP_OK)
  1165. {
  1166. break;
  1167. }
  1168. const int64_t fr_end = esp_timer_get_time();
  1169. ESP_LOGD(TAG, "JPG: %dKB %dms", (int)(fb_len / 1024), (int)((fr_end - fr_start) / 1000));
  1170. const int64_t fr_delta_ms = (fr_end - fr_start) / 1000;
  1171. if (CAM_LIVESTREAM_REFRESHRATE > fr_delta_ms)
  1172. {
  1173. const TickType_t xDelay = pdMS_TO_TICKS(CAM_LIVESTREAM_REFRESHRATE - fr_delta_ms);
  1174. ESP_LOGD(TAG, "Stream: sleep for: %lu ticks", (unsigned long)xDelay);
  1175. vTaskDelay(xDelay);
  1176. }
  1177. }
  1178. if (FlashlightOn)
  1179. {
  1180. LEDOnOff(false);
  1181. LightOnOff(false);
  1182. }
  1183. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
  1184. return res;
  1185. }
  1186. void CCamera::UpdateFlashOutputLocked(void)
  1187. {
  1188. const bool active = m_manualFlashOn || m_captureFlashUsers > 0;
  1189. #ifdef USE_PWM_LEDFLASH
  1190. const uint32_t duty = active ? static_cast<uint32_t>(LedIntensity) : 0U;
  1191. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty));
  1192. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  1193. #else
  1194. // The camera owns the board flash LED independently of the user GPIO handler.
  1195. gpio_pad_select_gpio(FLASH_GPIO);
  1196. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  1197. gpio_set_level(FLASH_GPIO, active ? 1 : 0);
  1198. #endif
  1199. }
  1200. void CCamera::UpdateStatusLedOutputLocked(void)
  1201. {
  1202. if (xHandle_task_StatusLED != NULL) return;
  1203. const bool active = m_manualStatusLedOn || m_captureStatusLedUsers > 0;
  1204. gpio_pad_select_gpio(BLINK_GPIO);
  1205. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  1206. // The on-board status LED is active-low.
  1207. gpio_set_level(BLINK_GPIO, active ? 0 : 1);
  1208. }
  1209. void CCamera::SetCaptureFlashActive(bool active)
  1210. {
  1211. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1212. if (!operationLock.acquired()) return;
  1213. ScopedCameraLock cameraLock(m_cameraMutex);
  1214. if (!cameraLock.acquired()) return;
  1215. if (active)
  1216. {
  1217. if (m_captureFlashUsers < UINT32_MAX) ++m_captureFlashUsers;
  1218. }
  1219. else if (m_captureFlashUsers > 0)
  1220. {
  1221. --m_captureFlashUsers;
  1222. }
  1223. UpdateFlashOutputLocked();
  1224. }
  1225. void CCamera::SetCaptureStatusLedActive(bool active)
  1226. {
  1227. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1228. if (!operationLock.acquired()) return;
  1229. ScopedCameraLock cameraLock(m_cameraMutex);
  1230. if (!cameraLock.acquired()) return;
  1231. if (active)
  1232. {
  1233. if (m_captureStatusLedUsers < UINT32_MAX) ++m_captureStatusLedUsers;
  1234. }
  1235. else if (m_captureStatusLedUsers > 0)
  1236. {
  1237. --m_captureStatusLedUsers;
  1238. }
  1239. UpdateStatusLedOutputLocked();
  1240. }
  1241. void CCamera::LightOnOff(bool status)
  1242. {
  1243. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1244. if (!operationLock.acquired()) return;
  1245. ScopedCameraLock cameraLock(m_cameraMutex);
  1246. if (!cameraLock.acquired())
  1247. {
  1248. ESP_LOGW(TAG, "LightOnOff: camera mutex unavailable");
  1249. return;
  1250. }
  1251. m_manualFlashOn = status;
  1252. UpdateFlashOutputLocked();
  1253. }
  1254. void CCamera::LEDOnOff(bool status)
  1255. {
  1256. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1257. if (!operationLock.acquired()) return;
  1258. ScopedCameraLock cameraLock(m_cameraMutex);
  1259. if (!cameraLock.acquired()) return;
  1260. m_manualStatusLedOn = status;
  1261. UpdateStatusLedOutputLocked();
  1262. }
  1263. void CCamera::SetImageWidthHeightFromResolution(CameraSettings &settings)
  1264. {
  1265. switch (settings.ImageFrameSize)
  1266. {
  1267. case FRAMESIZE_QVGA:
  1268. settings.ImageWidth = 320;
  1269. settings.ImageHeight = 240;
  1270. break;
  1271. case FRAMESIZE_VGA:
  1272. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1273. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1274. break;
  1275. default:
  1276. // Higher resolutions overload the ESP32 image-processing pipeline.
  1277. // Zoom is implemented by sensor-side windowing, while the output stays VGA.
  1278. ESP_LOGW(TAG, "Frame size %d exceeds the supported VGA limit; forcing VGA",
  1279. static_cast<int>(settings.ImageFrameSize));
  1280. settings.ImageFrameSize = FRAMESIZE_VGA;
  1281. settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
  1282. settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
  1283. break;
  1284. }
  1285. }
  1286. void CCamera::useDemoMode(void)
  1287. {
  1288. ScopedCameraOperationLock operationLock(m_cameraOperationMutex);
  1289. if (!operationLock.acquired()) return;
  1290. char line[50];
  1291. m_demoFiles.clear();
  1292. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  1293. if (fd == NULL) {
  1294. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: '/sdcard/demo/files.txt' is missing!");
  1295. CCstatus.DemoMode = false;
  1296. return;
  1297. }
  1298. while (fgets(line, sizeof(line), fd) != NULL) {
  1299. size_t length = strlen(line);
  1300. while (length > 0 && (line[length-1] == '\n' || line[length-1] == '\r')) line[--length] = '\0';
  1301. if (length > 0) m_demoFiles.push_back(line);
  1302. }
  1303. fclose(fd);
  1304. if (m_demoFiles.empty()) {
  1305. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode: files.txt contains no image names");
  1306. CCstatus.DemoMode = false;
  1307. return;
  1308. }
  1309. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(m_demoFiles.size()) + " files) instead of real camera image!");
  1310. for (const auto& file : m_demoFiles) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  1311. CCstatus.DemoMode = true;
  1312. }
  1313. bool CCamera::loadNextDemoImage(uint8_t **data, size_t *length)
  1314. {
  1315. if (data == NULL || length == NULL || m_demoFiles.empty()) return false;
  1316. *data = NULL;
  1317. *length = 0;
  1318. const size_t index = static_cast<size_t>(getCountFlowRounds()) % m_demoFiles.size();
  1319. const std::string filename = "/sdcard/demo/" + m_demoFiles[index];
  1320. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + filename + " as demo image");
  1321. FILE *fp = fopen(filename.c_str(), "rb");
  1322. if (fp == NULL) return false;
  1323. const long fileSize = GetFileSize(filename);
  1324. if (fileSize <= 0 || fileSize > DEMO_IMAGE_SIZE) {
  1325. fclose(fp);
  1326. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image has invalid size: " + std::to_string(fileSize));
  1327. return false;
  1328. }
  1329. uint8_t *buffer = static_cast<uint8_t*>(malloc_psram_heap(
  1330. "Demo image frame", static_cast<size_t>(fileSize), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  1331. if (buffer == NULL) {
  1332. fclose(fp);
  1333. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Demo image PSRAM allocation failed");
  1334. return false;
  1335. }
  1336. const size_t readBytes = fread(buffer, 1, static_cast<size_t>(fileSize), fp);
  1337. const bool readOkay = (readBytes == static_cast<size_t>(fileSize)) && (ferror(fp) == 0);
  1338. fclose(fp);
  1339. if (!readOkay) {
  1340. free_psram_heap("Demo image frame (short read)", buffer);
  1341. return false;
  1342. }
  1343. *data = buffer;
  1344. *length = readBytes;
  1345. return true;
  1346. }
  1347. long CCamera::GetFileSize(std::string filename)
  1348. {
  1349. struct stat stat_buf;
  1350. long rc = stat(filename.c_str(), &stat_buf);
  1351. return rc == 0 ? stat_buf.st_size : -1;
  1352. }