3#ifdef USE_ESP32_VARIANT_ESP32P4
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>
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;
33static constexpr BaseType_t CAPTURE_TASK_CORE = 1;
36static constexpr uint32_t CAPTURE_RETRY_DELAY_MS = 100;
44 this->
fail_(LOG_STR(
"Failed to start external clock"));
49 this->
fail_(LOG_STR(
"Failed to initialize video pipeline"));
53 if (frame_size == 0) {
54 this->
fail_(LOG_STR(
"Failed to configure video device"));
61 this->
fail_(LOG_STR(
"Failed to create frame queue"));
65 this->
fail_(LOG_STR(
"Failed to start video stream"));
69 CAPTURE_TASK_PRIORITY,
nullptr, CAPTURE_TASK_CORE) != pdPASS) {
70 this->
fail_(LOG_STR(
"Failed to start capture task"));
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);
83 ESP_LOGE(TAG,
"Allocating the sensor clock failed: %s", esp_err_to_name(err));
87 esp_cam_sensor_xclk_config_t config{};
88 config.esp_clock_router_cfg.xclk_pin =
static_cast<gpio_num_t
>(this->
xclk_pin_);
90 err = esp_cam_sensor_xclk_start(
handle, &config);
92 ESP_LOGE(TAG,
"Starting the sensor clock failed: %s", esp_err_to_name(err));
97 ESP_LOGE(TAG,
"Sensor clock output is not available in this build");
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);
106 ESP_LOGE(TAG,
"Could not use I2C port %d for the sensor: %s", this->
i2c_bus_->
get_port(), esp_err_to_name(err));
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;
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;
120 esp_video_init_config_t video_config{};
121 video_config.csi = &csi_config;
124 err = esp_video_init_with_flags(&video_config, ESP_VIDEO_INIT_FLAGS_MIPI_CSI | ESP_VIDEO_INIT_FLAGS_ISP);
126 ESP_LOGE(TAG,
"Camera sensor initialization failed: %s", esp_err_to_name(err));
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);
141 esp_cam_sensor_format_t chosen{};
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));
152 if (candidate.width != this->width_ || candidate.height != this->height_)
161 ESP_LOGE(TAG,
"The sensor cannot capture %ux%u. Supported resolutions are:", this->
width_, this->
height_);
164 format.name !=
nullptr ?
format.name : LOG_STR_LITERAL(
"unnamed"));
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));
177 this->
width_ = chosen.width;
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"));
188 const esp_cam_sensor_format_t ¤t)
const {
191 if ((candidate.isp_info !=
nullptr) != (current.isp_info !=
nullptr))
192 return candidate.isp_info !=
nullptr;
194 if ((candidate.format == this->sensor_format_) != (current.format == this->sensor_format_))
205 uint8_t fps = std::min(this->
framerate_, sensor_fps);
206 while (sensor_fps % fps != 0)
214 ESP_LOGW(TAG,
"The sensor runs at %u fps, so %u fps is used instead of %u fps", sensor_fps, fps, this->
framerate_);
220 this->
fd_ = open(ESP_VIDEO_MIPI_CSI_DEVICE_NAME, O_RDWR);
222 ESP_LOGE(TAG,
"Opening %s failed: %s", ESP_VIDEO_MIPI_CSI_DEVICE_NAME, strerror(errno));
230 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
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_),
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));
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));
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,
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_));
286 this->
width_ = actual.fmt.pix.width;
287 this->
height_ = actual.fmt.pix.height;
292 v4l2_ext_control control{};
294 control.value =
value;
296 v4l2_ext_controls controls{};
297 controls.ctrl_class = V4L2_CTRL_CLASS_USER;
299 controls.controls = &control;
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));
307 v4l2_requestbuffers request{};
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));
316 if (!this->
buffers_.try_init(request.count)) {
317 ESP_LOGE(TAG,
"Not enough memory to track %" PRIu32
" frame buffers", request.count);
321 for (
uint32_t i = 0; i < request.count; i++) {
323 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
324 buffer.memory = V4L2_MEMORY_MMAP;
326 if (ioctl(this->
fd_, VIDIOC_QUERYBUF, &
buffer) != 0) {
327 ESP_LOGE(TAG,
"Querying frame buffer %" PRIu32
" failed: %s", i, strerror(errno));
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));
336 this->
buffers_.push_back({
static_cast<uint8_t *
>(data),
buffer.length});
338 if (
buffer.length < frame_size) {
339 ESP_LOGE(TAG,
"Frame buffer %" PRIu32
" holds %" PRIu32
" bytes but a frame needs %zu", i,
buffer.length,
344 if (ioctl(this->
fd_, VIDIOC_QBUF, &
buffer) != 0) {
345 ESP_LOGE(TAG,
"Queueing frame buffer %" PRIu32
" failed: %s", i, strerror(errno));
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));
364 if (this->
fd_ >= 0) {
366 int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
367 ioctl(this->
fd_, VIDIOC_STREAMOFF, &
type);
372 this->buffers_.release();
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");
388 "MIPI-CSI camera '%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",
398 this->frame_buffer_count_,
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));
425 if (self->frame_wanted_.load() && (
buffer.flags & V4L2_BUF_FLAG_ERROR) == 0) {
437 xQueueSend(self->result_queue_, &
length, portMAX_DELAY);
440 self->frame_wanted_.store(
false);
443 if (ioctl(self->fd_, VIDIOC_QBUF, &
buffer) != 0) {
444 ESP_LOGW(TAG,
"Returning a frame buffer failed: %s", strerror(errno));
461 if (xQueueReceive(this->
result_queue_, &length, 0) == pdTRUE) {
476#ifdef USE_MIPI_CSI_IMAGE_CALLBACK
512 this->
defer([
this]() {
517#ifdef USE_MIPI_CSI_STREAM_CALLBACK
526 this->
defer([
this]() {
531#ifdef USE_MIPI_CSI_STREAM_CALLBACK
541 this->
image_ = std::move(image);
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()
virtual void on_stream_start()
virtual void on_camera_image(const std::shared_ptr< CameraImage > &image)
virtual int get_port() const =0
Returns the I2C port number.
uint8_t get_quality() const
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.
const char * sensor_name_
std::shared_ptr< MipiCsiImage > current_image_
i2c::InternalI2CBus * i2c_bus_
void fail_(const LogString *reason)
Releases everything setup() acquired and marks the component failed.
CallbackManager< void(bool)> stream_callback_
uint32_t last_idle_request_
void request_image(camera::CameraRequester requester) override
FixedVector< FrameBuffer > buffers_
static constexpr uint8_t FLIP_VERTICAL_ON
std::atomic< uint8_t > single_requesters_
CallbackManager< void(CameraImageData)> image_callback_
std::shared_ptr< MipiCsiImage > reusable_image_
camera::CameraListener ** listeners_
std::atomic< bool > frame_wanted_
Set by the main loop to ask the capture task for one frame, cleared by the task when done.
static constexpr uint8_t FLIP_HORIZONTAL_SET
void start_stream(camera::CameraRequester requester) override
std::atomic< uint8_t > stream_requesters_
void for_each_sensor_format_(F &&fn)
Calls fn with every MIPI-CSI format the sensor offers.
uint8_t pending_requesters_
Requesters recorded when the frame currently being captured was asked for.
bool has_requested_image_() const
bool start_streaming_(size_t frame_size)
QueueHandle_t result_queue_
size_t configure_device_()
Returns the size of one raw frame, or 0 on failure.
bool is_better_sensor_format_(const esp_cam_sensor_format_t &candidate, const esp_cam_sensor_format_t ¤t) const
Ranks two sensor formats of the same resolution against each other.
static void capture_task(void *param)
void stop_stream(camera::CameraRequester requester) override
bool read_back_format_()
Reads back the format the driver settled on, which the JPEG encoder has to match exactly.
bool select_sensor_format_()
uint8_t resolve_framerate_(uint8_t sensor_fps) const
Reduces the configured frame rate to one the driver can actually produce.
bool start_external_clock_()
uint8_t reachable_framerate_(uint8_t sensor_fps) const
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.
uint8_t sensor_format_
The sensor output that needs no conversion for the configured pixel format.
void dump_config() override
uint32_t idle_update_interval_
static constexpr uint8_t FLIP_HORIZONTAL_ON
uint8_t frame_buffer_count_
static constexpr uint8_t FLIP_VERTICAL_SET
size_t available() const override
void return_image() override
void set_image(std::shared_ptr< camera::CameraImage > image) override
void consume_data(size_t consumed) override
std::shared_ptr< camera::CameraImage > image_
uint8_t * peek_data_buffer() override
CameraRequester
Different sources for filtering.
ESPHOME_LOG_TAG(TAG, "mipi_csi.jpeg")
void const char int const char * format
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.
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.
Payload handed to the on_image automation.
One V4L2 capture buffer mapped into our address space.
spi_device_handle_t handle