// Camera 实现 — V4L2 multiplanar 采集(RKISP mainpath, NV12)
#include "camera/camera.h"

#include "common/log.h"

#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

namespace {

int xioctl(int fd, unsigned long req, void* arg) {
    int r;
    do {
        r = ioctl(fd, req, arg);
    } while (r == -1 && errno == EINTR);
    return r;
}

uint32_t fourcc_nv12() { return V4L2_PIX_FMT_NV12; }

}  // namespace

Camera::~Camera() { Close(); }

bool Camera::Open(const CameraConfig& cfg) {
    cfg_ = cfg;
    if (cfg_.pixelformat == 0) cfg_.pixelformat = fourcc_nv12();

    fd_ = ::open(cfg_.device.c_str(), O_RDWR | O_NONBLOCK, 0);
    if (fd_ < 0) {
        HW_ERR("camera: 打开 %s 失败: %s", cfg_.device.c_str(), strerror(errno));
        return false;
    }

    // 查询能力, 确认是 capture multiplanar 设备
    struct v4l2_capability cap = {};
    if (xioctl(fd_, VIDIOC_QUERYCAP, &cap) < 0) {
        HW_ERR("camera: VIDIOC_QUERYCAP 失败: %s", strerror(errno));
        Close();
        return false;
    }
    uint32_t caps = cap.capabilities;
    if (!(caps & V4L2_CAP_STREAMING) || !(caps & V4L2_CAP_VIDEO_CAPTURE_MPLANE)) {
        HW_ERR("camera: %s 不支持 capture-mplane+streaming (caps=0x%x)", cfg_.device.c_str(),
               caps);
        Close();
        return false;
    }
    HW_LOG("camera: %s (%s / %s) 打开成功", cfg_.device.c_str(), cap.driver, cap.card);

    // 设置格式: NV12
    struct v4l2_format fmt = {};
    fmt.type                       = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    fmt.fmt.pix_mp.width           = cfg_.width;
    fmt.fmt.pix_mp.height          = cfg_.height;
    fmt.fmt.pix_mp.pixelformat     = cfg_.pixelformat;
    fmt.fmt.pix_mp.field           = V4L2_FIELD_NONE;
    fmt.fmt.pix_mp.num_planes      = 1;
    if (xioctl(fd_, VIDIOC_S_FMT, &fmt) < 0) {
        HW_ERR("camera: VIDIOC_S_FMT 失败: %s", strerror(errno));
        Close();
        return false;
    }
    // 回读实际格式(驱动可能调整)
    cfg_.width       = fmt.fmt.pix_mp.width;
    cfg_.height      = fmt.fmt.pix_mp.height;
    wstride_         = fmt.fmt.pix_mp.plane_fmt[0].bytesperline;
    frame_size_      = fmt.fmt.pix_mp.plane_fmt[0].sizeimage;
    HW_LOG("camera: fmt %ux%u fourcc=0x%08x stride=%u size=%u planes=%u", cfg_.width,
           cfg_.height, fmt.fmt.pix_mp.pixelformat, wstride_, frame_size_,
           fmt.fmt.pix_mp.num_planes);

    // 申请缓冲
    struct v4l2_requestbuffers req = {};
    req.count  = (uint32_t)cfg_.buf_count;
    req.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    req.memory = V4L2_MEMORY_MMAP;
    if (xioctl(fd_, VIDIOC_REQBUFS, &req) < 0) {
        HW_ERR("camera: VIDIOC_REQBUFS 失败: %s", strerror(errno));
        Close();
        return false;
    }
    if (req.count < 2) {
        HW_ERR("camera: 缓冲不足 (%u)", req.count);
        Close();
        return false;
    }
    cfg_.buf_count = (int)req.count;
    return MapBuffers();
}

bool Camera::MapBuffers() {
    bufs_.resize(cfg_.buf_count);

    for (int i = 0; i < cfg_.buf_count; ++i) {
        struct v4l2_buffer buf = {};
        struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
        buf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buf.memory   = V4L2_MEMORY_MMAP;
        buf.index    = (uint32_t)i;
        buf.m.planes = planes;
        buf.length   = VIDEO_MAX_PLANES;
        if (xioctl(fd_, VIDIOC_QUERYBUF, &buf) < 0) {
            HW_ERR("camera: QUERYBUF(%d) 失败: %s", i, strerror(errno));
            return false;
        }
        Buf& b    = bufs_[i];
        b.planes  = buf.length;
        for (uint32_t p = 0; p < b.planes; ++p) {
            b.len[p] = planes[p].length;
            b.addr[p] =
                mmap(nullptr, planes[p].length, PROT_READ | PROT_WRITE, MAP_SHARED, fd_,
                     planes[p].m.mem_offset);
            if (b.addr[p] == MAP_FAILED) {
                HW_ERR("camera: mmap buf%d plane%u 失败: %s", i, p, strerror(errno));
                b.addr[p] = nullptr;
                return false;
            }
            // 尝试导出 dma-buf fd(失败不致命, 退化到虚拟地址路径)
            b.fds[p] = -1;
            if (cfg_.export_dmabuf) {
                struct v4l2_exportbuffer exp = {};
                exp.type  = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
                exp.index = (uint32_t)i;
                exp.plane = p;
                exp.flags = O_RDWR | O_CLOEXEC;
                if (xioctl(fd_, VIDIOC_EXPBUF, &exp) == 0) {
                    b.fds[p] = exp.fd;
                } else {
                    HW_WARN("camera: EXPBUF buf%d plane%u 不可用(%s), 用 vaddr 路径", i, p,
                            strerror(errno));
                }
            }
        }
    }
    HW_LOG("camera: 映射 %d 块缓冲 (dmabuf_fd=%s)", cfg_.buf_count,
           bufs_[0].fds[0] >= 0 ? "yes" : "no");
    return true;
}

void Camera::UnmapBuffers() {
    for (auto& b : bufs_) {
        for (uint32_t p = 0; p < 3; ++p) {
            if (b.addr[p]) munmap(b.addr[p], b.len[p]);
            if (b.fds[p] >= 0) ::close(b.fds[p]);
        }
    }
    bufs_.clear();
}

bool Camera::Start() {
    if (fd_ < 0 || bufs_.empty()) return false;
    for (int i = 0; i < cfg_.buf_count; ++i) {
        struct v4l2_buffer buf = {};
        struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
        buf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buf.memory   = V4L2_MEMORY_MMAP;
        buf.index    = (uint32_t)i;
        buf.m.planes = planes;
        buf.length   = VIDEO_MAX_PLANES;
        if (xioctl(fd_, VIDIOC_QBUF, &buf) < 0) {
            HW_ERR("camera: 初始 QBUF(%d) 失败: %s", i, strerror(errno));
            return false;
        }
    }
    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    if (xioctl(fd_, VIDIOC_STREAMON, &type) < 0) {
        HW_ERR("camera: STREAMON 失败: %s", strerror(errno));
        return false;
    }
    streaming_ = true;
    return true;
}

bool Camera::GetFrame(CameraFrame* out, int timeout_ms) {
    if (!streaming_ || !out) return false;

    struct pollfd pfd = {fd_, POLLIN | POLLPRI, 0};
    int pr = poll(&pfd, 1, timeout_ms);
    if (pr <= 0) {
        if (pr == 0) {
            consecutive_timeouts_++;
            // 连续超时达阈值: ISP/3A 会话切换卡死时的自愈(STREAMOFF/STREAMON)
            if (consecutive_timeouts_ >= 3 && recover_count_ < 3) {
                recover_count_++;
                HW_WARN("camera: 连续 %d 次取帧超时, 尝试重启流(%d/3)", consecutive_timeouts_,
                        recover_count_);
                RestartStream();
            }
        } else {
            HW_ERR("camera: poll 失败: %s", strerror(errno));
        }
        return false;
    }

    struct v4l2_buffer buf = {};
    struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
    buf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory   = V4L2_MEMORY_MMAP;
    buf.m.planes = planes;
    buf.length   = VIDEO_MAX_PLANES;
    if (xioctl(fd_, VIDIOC_DQBUF, &buf) < 0) {
        if (errno != EAGAIN) HW_ERR("camera: DQBUF 失败: %s", strerror(errno));
        return false;
    }
    if (buf.index >= bufs_.size()) return false;
    consecutive_timeouts_ = 0;   // 成功取帧, 清零超时计数

    Buf& b        = bufs_[buf.index];
    out->vaddr    = b.addr[0];
    out->dmabuf_fd = b.fds[0];
    out->size     = b.len[0];
    out->width    = cfg_.width;
    out->height   = cfg_.height;
    out->wstride  = wstride_;
    out->pixfmt   = cfg_.pixelformat;
    out->timestamp_us = (uint64_t)buf.timestamp.tv_sec * 1000000ull + buf.timestamp.tv_usec;
    out->index    = (int)buf.index;
    return true;
}

bool Camera::PutFrame(const CameraFrame& f) {
    if (!streaming_ || f.index < 0) return false;
    struct v4l2_buffer buf = {};
    struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
    buf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory   = V4L2_MEMORY_MMAP;
    buf.index    = (uint32_t)f.index;
    buf.m.planes = planes;
    buf.length   = VIDEO_MAX_PLANES;
    if (xioctl(fd_, VIDIOC_QBUF, &buf) < 0) {
        HW_ERR("camera: QBUF(%d) 失败: %s", f.index, strerror(errno));
        return false;
    }
    return true;
}

void Camera::Stop() {
    if (streaming_ && fd_ >= 0) {
        enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        xioctl(fd_, VIDIOC_STREAMOFF, &type);
        streaming_ = false;
    }
}

// 重建流: STREAMOFF → 重新 QBUF 全部缓冲 → STREAMON
bool Camera::RestartStream() {
    if (fd_ < 0 || bufs_.empty()) return false;
    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    xioctl(fd_, VIDIOC_STREAMOFF, &type);
    streaming_ = false;

    for (int i = 0; i < cfg_.buf_count; ++i) {
        struct v4l2_buffer buf = {};
        struct v4l2_plane planes[VIDEO_MAX_PLANES] = {};
        buf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buf.memory   = V4L2_MEMORY_MMAP;
        buf.index    = (uint32_t)i;
        buf.m.planes = planes;
        buf.length   = VIDEO_MAX_PLANES;
        if (xioctl(fd_, VIDIOC_QBUF, &buf) < 0) {
            HW_ERR("camera: restart QBUF(%d) 失败: %s", i, strerror(errno));
            return false;
        }
    }
    if (xioctl(fd_, VIDIOC_STREAMON, &type) < 0) {
        HW_ERR("camera: restart STREAMON 失败: %s", strerror(errno));
        return false;
    }
    streaming_           = true;
    consecutive_timeouts_ = 0;
    return true;
}

void Camera::Close() {
    Stop();
    UnmapBuffers();
    if (fd_ >= 0) {
        ::close(fd_);
        fd_ = -1;
    }
}
