ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
mipi_csi.cpp
Go to the documentation of this file.
1#include "mipi_csi.h"
2
3#ifdef USE_ESP32_VARIANT_ESP32P4
4
5#include <algorithm>
6#include <cerrno>
7#include <cinttypes>
8#include <cstring>
9#include <fcntl.h>
10#include <sys/ioctl.h>
11#include <sys/mman.h>
12#include <unistd.h>
13
14#include <driver/i2c_master.h>
15#include <esp_cam_sensor_xclk.h>
16#include <esp_video_device.h>
17#include <esp_video_init.h>
18#include <esp_video_ioctl.h>
19#include <linux/videodev2.h>
20
22#include "esphome/core/log.h"
23
24namespace esphome::mipi_csi {
25
26ESPHOME_LOG_TAG(TAG, "mipi_csi");
27
28static constexpr uint32_t CAPTURE_TASK_STACK_SIZE = 4096;
29static constexpr UBaseType_t CAPTURE_TASK_PRIORITY = 1;
30#if CONFIG_FREERTOS_UNICORE
31static constexpr BaseType_t CAPTURE_TASK_CORE = tskNO_AFFINITY;
32#else
33static constexpr BaseType_t CAPTURE_TASK_CORE = 1;
34#endif
36static constexpr uint32_t CAPTURE_RETRY_DELAY_MS = 100;
37
38/* ---------------- MipiCsiCamera: setup ---------------- */
39
41 setup_output_pin(this->power_pin_, true);
42 // Sensors need their clock running while they come out of reset
43 if (!this->start_external_clock_()) {
44 this->fail_(LOG_STR("Failed to start external clock"));
45 return;
46 }
47 pulse_reset(this->reset_pin_, {.low_ms = 10, .high_after_ms = 20});
48 if (!this->init_video_()) {
49 this->fail_(LOG_STR("Failed to initialize video pipeline"));
50 return;
51 }
52 const size_t frame_size = this->configure_device_();
53 if (frame_size == 0) {
54 this->fail_(LOG_STR("Failed to configure video device"));
55 return;
56 }
57
58 this->reusable_image_ = std::make_shared<MipiCsiImage>();
59 this->result_queue_ = xQueueCreate(1, sizeof(size_t));
60 if (this->result_queue_ == nullptr) {
61 this->fail_(LOG_STR("Failed to create frame queue"));
62 return;
63 }
64 if (!this->start_streaming_(frame_size)) {
65 this->fail_(LOG_STR("Failed to start video stream"));
66 return;
67 }
68 if (xTaskCreatePinnedToCore(&MipiCsiCamera::capture_task, "mipi_csi", CAPTURE_TASK_STACK_SIZE, this,
69 CAPTURE_TASK_PRIORITY, nullptr, CAPTURE_TASK_CORE) != pdPASS) {
70 this->fail_(LOG_STR("Failed to start capture task"));
71 return;
72 }
73}
74
76 if (this->xclk_pin_ < 0)
77 return true;
78
79#if CONFIG_CAMERA_XCLK_USE_ESP_CLOCK_ROUTER
80 esp_cam_sensor_xclk_handle_t handle = nullptr;
81 esp_err_t err = esp_cam_sensor_xclk_allocate(ESP_CAM_SENSOR_XCLK_ESP_CLOCK_ROUTER, &handle);
82 if (err != ESP_OK) {
83 ESP_LOGE(TAG, "Allocating the sensor clock failed: %s", esp_err_to_name(err));
84 return false;
85 }
86
87 esp_cam_sensor_xclk_config_t config{};
88 config.esp_clock_router_cfg.xclk_pin = static_cast<gpio_num_t>(this->xclk_pin_);
89 config.esp_clock_router_cfg.xclk_freq_hz = this->xclk_frequency_;
90 err = esp_cam_sensor_xclk_start(handle, &config);
91 if (err != ESP_OK) {
92 ESP_LOGE(TAG, "Starting the sensor clock failed: %s", esp_err_to_name(err));
93 return false;
94 }
95 return true;
96#else
97 ESP_LOGE(TAG, "Sensor clock output is not available in this build");
98 return false;
99#endif
100}
101
103 i2c_master_bus_handle_t i2c_handle = nullptr;
104 esp_err_t err = i2c_master_get_bus_handle(this->i2c_bus_->get_port(), &i2c_handle);
105 if (err != ESP_OK) {
106 ESP_LOGE(TAG, "Could not use I2C port %d for the sensor: %s", this->i2c_bus_->get_port(), esp_err_to_name(err));
107 return false;
108 }
109
110 esp_video_init_csi_config_t csi_config{};
111 csi_config.sccb_config.init_sccb = false;
112 csi_config.sccb_config.i2c_handle = i2c_handle;
113 csi_config.sccb_config.freq = this->sccb_frequency_;
114 csi_config.reset_pin = GPIO_NUM_NC;
115 csi_config.pwdn_pin = GPIO_NUM_NC;
116#ifdef USE_MIPI_CSI_EXTERNAL_LDO
117 csi_config.dont_init_ldo = true;
118#endif
119
120 esp_video_init_config_t video_config{};
121 video_config.csi = &csi_config;
122
123 // esp_video routes RAW sensors through the ISP and bypasses it for RGB/YUV ones
124 err = esp_video_init_with_flags(&video_config, ESP_VIDEO_INIT_FLAGS_MIPI_CSI | ESP_VIDEO_INIT_FLAGS_ISP);
125 if (err != ESP_OK) {
126 ESP_LOGE(TAG, "Camera sensor initialization failed: %s", esp_err_to_name(err));
127 return false;
128 }
129 return true;
130}
131
132template<typename F> void MipiCsiCamera::for_each_sensor_format_(F &&fn) {
133 v4l2_sensor_format_enum enumerator{};
134 for (enumerator.index = 0; ioctl(this->fd_, VIDIOC_ENUM_SENSOR_FMT, &enumerator) == 0; enumerator.index++) {
135 if (enumerator.format.port == ESP_CAM_SENSOR_MIPI_CSI)
136 fn(enumerator.format);
137 }
138}
139
141 esp_cam_sensor_format_t chosen{};
142
143 if (this->width_ == 0) {
144 // No resolution configured, so keep the format the sensor driver starts up with.
145 if (ioctl(this->fd_, VIDIOC_G_SENSOR_FMT, &chosen) != 0) {
146 ESP_LOGE(TAG, "Reading the sensor's current format failed: %s", strerror(errno));
147 return false;
148 }
149 } else {
150 bool found = false;
151 this->for_each_sensor_format_([&](const esp_cam_sensor_format_t &candidate) {
152 if (candidate.width != this->width_ || candidate.height != this->height_)
153 return;
154 if (!found || this->is_better_sensor_format_(candidate, chosen)) {
155 chosen = candidate;
156 found = true;
157 }
158 });
159
160 if (!found) {
161 ESP_LOGE(TAG, "The sensor cannot capture %ux%u. Supported resolutions are:", this->width_, this->height_);
162 this->for_each_sensor_format_([](const esp_cam_sensor_format_t &format) {
163 ESP_LOGE(TAG, " %ux%u at %u fps (%s)", format.width, format.height, format.fps,
164 format.name != nullptr ? format.name : LOG_STR_LITERAL("unnamed"));
165 });
166 return false;
167 }
168
169 // The resolution belongs to the sensor, so it has to be selected here. VIDIOC_S_FMT only picks
170 // the pixel format and rejects every resolution other than the sensor's current one.
171 if (ioctl(this->fd_, VIDIOC_S_SENSOR_FMT, &chosen) != 0) {
172 ESP_LOGE(TAG, "Switching the sensor to %ux%u failed: %s", this->width_, this->height_, strerror(errno));
173 return false;
174 }
175 }
176
177 this->width_ = chosen.width;
178 this->height_ = chosen.height;
179 this->framerate_ = this->resolve_framerate_(chosen.fps);
180 ESP_LOGD(TAG, "Sensor format '%s': %ux%u at %u fps, %s",
181 chosen.name != nullptr ? chosen.name : LOG_STR_LITERAL("unnamed"), chosen.width, chosen.height, chosen.fps,
182 chosen.isp_info != nullptr ? LOG_STR_LITERAL("processed by the ISP")
183 : LOG_STR_LITERAL("used as the sensor delivers it"));
184 return true;
185}
186
187bool MipiCsiCamera::is_better_sensor_format_(const esp_cam_sensor_format_t &candidate,
188 const esp_cam_sensor_format_t &current) const {
189 // Formats that carry ISP information are the RAW ones, and only those let the ISP run the image
190 // tuning algorithms, so they are always preferred.
191 if ((candidate.isp_info != nullptr) != (current.isp_info != nullptr))
192 return candidate.isp_info != nullptr;
193 // Without the ISP, only a sensor output in the configured pixel format works on every chip revision
194 if ((candidate.format == this->sensor_format_) != (current.format == this->sensor_format_))
195 return candidate.format == this->sensor_format_;
196
197 // Prefer the rate closest to the configured one that the driver can reach by dropping frames
198 return this->reachable_framerate_(candidate.fps) > this->reachable_framerate_(current.fps);
199}
200
201uint8_t MipiCsiCamera::reachable_framerate_(uint8_t sensor_fps) const {
202 if (sensor_fps == 0)
203 return this->framerate_;
204 // The driver can only divide the sensor's rate
205 uint8_t fps = std::min(this->framerate_, sensor_fps);
206 while (sensor_fps % fps != 0)
207 fps--;
208 return fps;
209}
210
211uint8_t MipiCsiCamera::resolve_framerate_(uint8_t sensor_fps) const {
212 const uint8_t fps = this->reachable_framerate_(sensor_fps);
213 if (fps != this->framerate_) {
214 ESP_LOGW(TAG, "The sensor runs at %u fps, so %u fps is used instead of %u fps", sensor_fps, fps, this->framerate_);
215 }
216 return fps;
217}
218
220 this->fd_ = open(ESP_VIDEO_MIPI_CSI_DEVICE_NAME, O_RDWR);
221 if (this->fd_ < 0) {
222 ESP_LOGE(TAG, "Opening %s failed: %s", ESP_VIDEO_MIPI_CSI_DEVICE_NAME, strerror(errno));
223 return 0;
224 }
225
226 if (!this->select_sensor_format_())
227 return 0;
228
229 v4l2_format format{};
230 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
231 format.fmt.pix.width = this->width_;
232 format.fmt.pix.height = this->height_;
233 format.fmt.pix.pixelformat = this->fourcc_;
234 if (ioctl(this->fd_, VIDIOC_S_FMT, &format) != 0) {
235 ESP_LOGE(TAG, "The camera cannot deliver '%.4s' at %ux%u: %s", reinterpret_cast<const char *>(&this->fourcc_),
236 this->width_, this->height_, strerror(errno));
237 return 0;
238 }
239
240 // Must come after the format has been set, and not every sensor offers a choice of frame rates.
241 v4l2_streamparm stream_param{};
242 stream_param.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
243 stream_param.parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
244 stream_param.parm.capture.timeperframe.numerator = 1;
245 stream_param.parm.capture.timeperframe.denominator = this->framerate_;
246 if (ioctl(this->fd_, VIDIOC_S_PARM, &stream_param) != 0) {
247 ESP_LOGW(TAG, "The sensor kept its own frame rate: %s", strerror(errno));
248 }
249
251 this->apply_control_(V4L2_CID_HFLIP, (this->flip_flags_ & FLIP_HORIZONTAL_ON) != 0, LOG_STR("horizontal flip"));
252 if (this->flip_flags_ & FLIP_VERTICAL_SET)
253 this->apply_control_(V4L2_CID_VFLIP, (this->flip_flags_ & FLIP_VERTICAL_ON) != 0, LOG_STR("vertical flip"));
254
255 if (!this->read_back_format_())
256 return 0;
257
258 const size_t frame_size = static_cast<size_t>(this->width_) * this->height_ * this->bytes_per_pixel_;
259 return this->encoder_.init(this->width_, this->height_, frame_size) ? frame_size : 0;
260}
261
263 v4l2_format actual{};
264 actual.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
265 if (ioctl(this->fd_, VIDIOC_G_FMT, &actual) != 0) {
266 ESP_LOGE(TAG, "Reading back the capture format failed: %s", strerror(errno));
267 return false;
268 }
269
270 // The driver is free to settle on something other than what was asked for, and the encoder has to
271 // be set up for what actually comes out, not for what was requested. Only the geometry and the
272 // pixel format are meaningful here: esp_video hands back the very struct it was given, so its
273 // bytesperline and sizeimage fields stay at whatever the caller left them.
274 const char *actual_fourcc = reinterpret_cast<const char *>(&actual.fmt.pix.pixelformat);
275 ESP_LOGD(TAG, "Capture format: %" PRIu32 "x%" PRIu32 " '%.4s'", actual.fmt.pix.width, actual.fmt.pix.height,
276 actual_fourcc);
277
278 // A different pixel format means every byte of the frame would be read with the wrong layout, so
279 // the encoder would turn out a corrupted picture rather than a wrong-looking one.
280 if (actual.fmt.pix.pixelformat != this->fourcc_) {
281 ESP_LOGE(TAG, "The camera delivers '%.4s' instead of the configured '%.4s'; pick another 'pixel_format'",
282 actual_fourcc, reinterpret_cast<const char *>(&this->fourcc_));
283 return false;
284 }
285
286 this->width_ = actual.fmt.pix.width;
287 this->height_ = actual.fmt.pix.height;
288 return true;
289}
290
291void MipiCsiCamera::apply_control_(uint32_t id, int32_t value, const LogString *name) {
292 v4l2_ext_control control{};
293 control.id = id;
294 control.value = value;
295
296 v4l2_ext_controls controls{};
297 controls.ctrl_class = V4L2_CTRL_CLASS_USER;
298 controls.count = 1;
299 controls.controls = &control;
300
301 if (ioctl(this->fd_, VIDIOC_S_EXT_CTRLS, &controls) != 0) {
302 ESP_LOGW(TAG, "Setting %s failed: %s", LOG_STR_ARG(name), strerror(errno));
303 }
304}
305
306bool MipiCsiCamera::start_streaming_(size_t frame_size) {
307 v4l2_requestbuffers request{};
308 request.count = this->frame_buffer_count_;
309 request.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
310 request.memory = V4L2_MEMORY_MMAP;
311 if (ioctl(this->fd_, VIDIOC_REQBUFS, &request) != 0) {
312 ESP_LOGE(TAG, "Requesting %u frame buffers failed: %s", this->frame_buffer_count_, strerror(errno));
313 return false;
314 }
315
316 if (!this->buffers_.try_init(request.count)) {
317 ESP_LOGE(TAG, "Not enough memory to track %" PRIu32 " frame buffers", request.count);
318 return false;
319 }
320
321 for (uint32_t i = 0; i < request.count; i++) {
322 v4l2_buffer buffer{};
323 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
324 buffer.memory = V4L2_MEMORY_MMAP;
325 buffer.index = i;
326 if (ioctl(this->fd_, VIDIOC_QUERYBUF, &buffer) != 0) {
327 ESP_LOGE(TAG, "Querying frame buffer %" PRIu32 " failed: %s", i, strerror(errno));
328 return false;
329 }
330
331 void *data = mmap(nullptr, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, this->fd_, buffer.m.offset);
332 if (data == MAP_FAILED) {
333 ESP_LOGE(TAG, "Mapping frame buffer %" PRIu32 " failed: %s", i, strerror(errno));
334 return false;
335 }
336 this->buffers_.push_back({static_cast<uint8_t *>(data), buffer.length});
337
338 if (buffer.length < frame_size) {
339 ESP_LOGE(TAG, "Frame buffer %" PRIu32 " holds %" PRIu32 " bytes but a frame needs %zu", i, buffer.length,
340 frame_size);
341 return false;
342 }
343
344 if (ioctl(this->fd_, VIDIOC_QBUF, &buffer) != 0) {
345 ESP_LOGE(TAG, "Queueing frame buffer %" PRIu32 " failed: %s", i, strerror(errno));
346 return false;
347 }
348 }
349
350 int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
351 if (ioctl(this->fd_, VIDIOC_STREAMON, &type) != 0) {
352 ESP_LOGE(TAG, "Starting the video stream failed: %s", strerror(errno));
353 return false;
354 }
355 return true;
356}
357
358void MipiCsiCamera::fail_(const LogString *reason) {
359 if (this->result_queue_ != nullptr) {
360 vQueueDelete(this->result_queue_);
361 this->result_queue_ = nullptr;
362 }
363
364 if (this->fd_ >= 0) {
365 // Ignored if the stream was never turned on: VIDIOC_STREAMOFF then just reports an error.
366 int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
367 ioctl(this->fd_, VIDIOC_STREAMOFF, &type);
368
369 for (auto &buffer : this->buffers_) {
370 munmap(buffer.data, buffer.length);
371 }
372 this->buffers_.release();
373
374 close(this->fd_);
375 this->fd_ = -1;
376 }
377 this->mark_failed(reason);
378}
379
380static const LogString *flip_state(uint8_t flags, uint8_t set_bit, uint8_t on_bit) {
381 if ((flags & set_bit) == 0)
382 return LOG_STR("default");
383 return (flags & on_bit) != 0 ? LOG_STR("on") : LOG_STR("off");
384}
385
387 ESP_LOGCONFIG(TAG,
388 "MIPI-CSI camera '%s':\n"
389 " Sensor: %s\n"
390 " Resolution: %ux%u\n"
391 " Capture format: %.4s\n"
392 " JPEG quality: %u\n"
393 " Frame rate: %u fps\n"
394 " Frame buffers: %u\n"
395 " Flip: horizontal %s, vertical %s",
396 LOG_STR_ARG(this->get_log_name()), this->sensor_name_, this->width_, this->height_,
397 reinterpret_cast<const char *>(&this->fourcc_), this->encoder_.get_quality(), this->framerate_,
398 this->frame_buffer_count_,
399 LOG_STR_ARG(flip_state(this->flip_flags_, FLIP_HORIZONTAL_SET, FLIP_HORIZONTAL_ON)),
400 LOG_STR_ARG(flip_state(this->flip_flags_, FLIP_VERTICAL_SET, FLIP_VERTICAL_ON)));
401 if (this->xclk_pin_ >= 0) {
402 ESP_LOGCONFIG(TAG, " External clock: GPIO%d at %" PRIu32 " Hz", this->xclk_pin_, this->xclk_frequency_);
403 }
404 LOG_PIN(" Reset Pin: ", this->reset_pin_);
405 LOG_PIN(" Power Pin: ", this->power_pin_);
406}
407
408/* ---------------- MipiCsiCamera: capture ---------------- */
409
411 auto *self = static_cast<MipiCsiCamera *>(param);
412
413 // The stream runs continuously so that the ISP's auto exposure and white balance stay converged.
414 // Frames nobody asked for are simply handed straight back to the driver.
415 while (true) {
416 v4l2_buffer buffer{};
417 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
418 buffer.memory = V4L2_MEMORY_MMAP;
419 if (ioctl(self->fd_, VIDIOC_DQBUF, &buffer) != 0) {
420 ESP_LOGW(TAG, "Dequeueing a frame failed: %s", strerror(errno));
421 vTaskDelay(pdMS_TO_TICKS(CAPTURE_RETRY_DELAY_MS));
422 continue;
423 }
424
425 if (self->frame_wanted_.load() && (buffer.flags & V4L2_BUF_FLAG_ERROR) == 0) {
426 // The encoder is handed the whole mapped buffer, as Espressif's reference does: the length is
427 // what bounds the cache invalidation before the JPEG engine's DMA reads it, so anything short
428 // of the region the camera wrote leaves stale data in the picture.
429 //
430 // buffer.bytesused is not worth checking here. The CSI driver sets it to the configured frame
431 // size rather than to the number of bytes it actually received, so it can never reveal a
432 // short frame.
433 const FrameBuffer &mapped = self->buffers_[buffer.index];
434 size_t length = self->encoder_.encode(mapped.data, mapped.length);
435 // Reported even when encoding failed: a length of zero tells the main loop that the request
436 // it recorded was not served, so that a still image request is not silently dropped.
437 xQueueSend(self->result_queue_, &length, portMAX_DELAY);
439 // Cleared last, so that an unset flag always means the result is already on the queue.
440 self->frame_wanted_.store(false);
441 }
442
443 if (ioctl(self->fd_, VIDIOC_QBUF, &buffer) != 0) {
444 ESP_LOGW(TAG, "Returning a frame buffer failed: %s", strerror(errno));
445 }
446 }
447}
448
451
452 // Release the previous image once every consumer has finished reading it, which frees the
453 // encoder's output buffer for the next frame.
454 if (this->current_image_ && this->current_image_.use_count() == 2) {
455 this->current_image_.reset();
456 }
457
458 // Publish a frame the capture task has finished encoding.
459 if (!this->current_image_) {
460 size_t length;
461 if (xQueueReceive(this->result_queue_, &length, 0) == pdTRUE) {
462 if (length == 0) {
463 // Encoding failed. Hand the one-shot requests back so the clients waiting for a still image
464 // are served by the next frame instead of waiting forever. Streams ask again on their own.
465 this->single_requesters_ |= static_cast<uint8_t>(this->pending_requesters_ & ~this->stream_requesters_.load());
466 this->pending_requesters_ = 0;
467 return;
468 }
469 this->reusable_image_->set_frame(this->encoder_.get_output_buffer(), length, this->pending_requesters_);
470 this->current_image_ = this->reusable_image_;
471 this->pending_requesters_ = 0;
472 for (uint8_t i = 0; i < this->listener_count_; i++) {
473 auto *listener = this->listeners_[i];
474 listener->on_camera_image(this->current_image_);
475 }
476#ifdef USE_MIPI_CSI_IMAGE_CALLBACK
477 this->image_callback_.call(CameraImageData{this->current_image_->get_data_buffer(), length});
478#endif
479 return;
480 }
481 }
482
483 // Ask Home Assistant's still image to refresh every so often even when nobody is watching.
484 if (!this->has_requested_image_() && this->idle_update_interval_ != 0 &&
485 now - this->last_idle_request_ >= this->idle_update_interval_) {
486 this->last_idle_request_ = now;
488 }
489
490 // Ask the capture task for the next frame. Not while an image is still in flight, because both
491 // share the encoder's single output buffer.
492 if (this->current_image_ || this->frame_wanted_.load() || uxQueueMessagesWaiting(this->result_queue_) != 0 ||
493 !this->has_requested_image_())
494 return;
496 return;
497
498 this->pending_requesters_ = this->single_requesters_.exchange(0) | this->stream_requesters_.load();
499 this->last_request_ = now;
500 this->frame_wanted_.store(true);
501}
502
503/* ---------------- MipiCsiCamera: requests ---------------- */
504
505// Called from the web server's task too: wake the loop so a long loop interval does not delay the frame
507 this->single_requesters_ |= (1U << requester);
509}
510
512 this->defer([this]() {
513 for (uint8_t i = 0; i < this->listener_count_; i++) {
514 auto *listener = this->listeners_[i];
515 listener->on_stream_start();
516 }
517#ifdef USE_MIPI_CSI_STREAM_CALLBACK
518 this->stream_callback_.call(true);
519#endif
520 });
521 this->stream_requesters_ |= (1U << requester);
523}
524
526 this->defer([this]() {
527 for (uint8_t i = 0; i < this->listener_count_; i++) {
528 auto *listener = this->listeners_[i];
529 listener->on_stream_stop();
530 }
531#ifdef USE_MIPI_CSI_STREAM_CALLBACK
532 this->stream_callback_.call(false);
533#endif
534 });
535 this->stream_requesters_ &= ~(1U << requester);
536}
537
538/* ---------------- MipiCsiImageReader ---------------- */
539
540void MipiCsiImageReader::set_image(std::shared_ptr<camera::CameraImage> image) {
541 this->image_ = std::move(image);
542 this->offset_ = 0;
543}
544
546 if (!this->image_)
547 return 0;
548 return this->image_->get_data_length() - this->offset_;
549}
550
551uint8_t *MipiCsiImageReader::peek_data_buffer() { return this->image_->get_data_buffer() + this->offset_; }
552
553void MipiCsiImageReader::consume_data(size_t consumed) { this->offset_ += consumed; }
554
556
557} // namespace esphome::mipi_csi
558
559#endif
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
void defer(const char *name, SchedulerCallback &&f)
Defer a callback to the next loop() call with a const char* name.
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
virtual void on_stream_stop()
Definition camera.h:50
virtual void on_stream_start()
Definition camera.h:49
virtual void on_camera_image(const std::shared_ptr< CameraImage > &image)
Definition camera.h:48
virtual int get_port() const =0
Returns the I2C port number.
uint8_t * get_output_buffer() const
Returns the buffer holding the most recently encoded image.
bool init(uint16_t width, uint16_t height, size_t frame_size)
Allocates the encoder engine and its output buffer.
MIPI-CSI camera on the ESP32-P4: V4L2 capture through esp_video, JPEG by the hardware encoder.
Definition mipi_csi.h:69
std::shared_ptr< MipiCsiImage > current_image_
Definition mipi_csi.h:178
i2c::InternalI2CBus * i2c_bus_
Definition mipi_csi.h:166
void fail_(const LogString *reason)
Releases everything setup() acquired and marks the component failed.
Definition mipi_csi.cpp:358
CallbackManager< void(bool)> stream_callback_
Definition mipi_csi.h:185
void request_image(camera::CameraRequester requester) override
Definition mipi_csi.cpp:506
FixedVector< FrameBuffer > buffers_
Definition mipi_csi.h:174
static constexpr uint8_t FLIP_VERTICAL_ON
Definition mipi_csi.h:140
std::atomic< uint8_t > single_requesters_
Definition mipi_csi.h:201
CallbackManager< void(CameraImageData)> image_callback_
Definition mipi_csi.h:182
std::shared_ptr< MipiCsiImage > reusable_image_
Definition mipi_csi.h:177
camera::CameraListener ** listeners_
Definition mipi_csi.h:179
std::atomic< bool > frame_wanted_
Set by the main loop to ask the capture task for one frame, cleared by the task when done.
Definition mipi_csi.h:204
static constexpr uint8_t FLIP_HORIZONTAL_SET
Definition mipi_csi.h:137
void start_stream(camera::CameraRequester requester) override
Definition mipi_csi.cpp:511
std::atomic< uint8_t > stream_requesters_
Definition mipi_csi.h:202
void for_each_sensor_format_(F &&fn)
Calls fn with every MIPI-CSI format the sensor offers.
Definition mipi_csi.cpp:132
uint8_t pending_requesters_
Requesters recorded when the frame currently being captured was asked for.
Definition mipi_csi.h:200
bool start_streaming_(size_t frame_size)
Definition mipi_csi.cpp:306
size_t configure_device_()
Returns the size of one raw frame, or 0 on failure.
Definition mipi_csi.cpp:219
bool is_better_sensor_format_(const esp_cam_sensor_format_t &candidate, const esp_cam_sensor_format_t &current) const
Ranks two sensor formats of the same resolution against each other.
Definition mipi_csi.cpp:187
static void capture_task(void *param)
Definition mipi_csi.cpp:410
void stop_stream(camera::CameraRequester requester) override
Definition mipi_csi.cpp:525
bool read_back_format_()
Reads back the format the driver settled on, which the JPEG encoder has to match exactly.
Definition mipi_csi.cpp:262
uint8_t resolve_framerate_(uint8_t sensor_fps) const
Reduces the configured frame rate to one the driver can actually produce.
Definition mipi_csi.cpp:211
uint8_t reachable_framerate_(uint8_t sensor_fps) const
Definition mipi_csi.cpp:201
void apply_control_(uint32_t id, int32_t value, const LogString *name)
Applies a V4L2 user control, logging a warning if the sensor does not support it.
Definition mipi_csi.cpp:291
uint8_t sensor_format_
The sensor output that needs no conversion for the configured pixel format.
Definition mipi_csi.h:196
static constexpr uint8_t FLIP_HORIZONTAL_ON
Definition mipi_csi.h:138
static constexpr uint8_t FLIP_VERTICAL_SET
Definition mipi_csi.h:139
size_t available() const override
Definition mipi_csi.cpp:545
void set_image(std::shared_ptr< camera::CameraImage > image) override
Definition mipi_csi.cpp:540
void consume_data(size_t consumed) override
Definition mipi_csi.cpp:553
std::shared_ptr< camera::CameraImage > image_
Definition mipi_csi.h:64
uint8_t * peek_data_buffer() override
Definition mipi_csi.cpp:551
uint16_t flags
uint16_t id
uint8_t type
uint32_t buffer
Definition gif.cpp:50
CameraRequester
Different sources for filtering.
Definition camera.h:16
ESPHOME_LOG_TAG(TAG, "mipi_csi.jpeg")
uint32_t value
Definition hal.cpp:59
void const char int const char * format
Definition log.h:110
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:44
Application App
Global storage of Application pointer - only one Application can exist.
ESPHOME_ALWAYS_INLINE void pulse_reset(GPIOPin *pin, ResetPulse pulse)
Set up an active-low reset pin and drive it through pulse.
Definition gpio_pin.h:214
static void uint32_t
Payload handed to the on_image automation.
Definition mipi_csi.h:28
One V4L2 capture buffer mapped into our address space.
Definition mipi_csi.h:132
spi_device_handle_t handle